패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.7.1

odoo_rpc

스트림을 통한 세션 변경 사항 추적 기능이 있는 Dart용 Odoo RPC 클라이언트 라이브러리.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.6천
좋아요
73
Pub 점수
150

패키지 설치

flutter pub add odoo_rpc

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

odoo_rpc 패키지는 RPC(원격 프로시저 호출)를 사용하여 Odoo ERP 시스템과 원활한 통신을 가능하게 하는 Dart 라이브러리입니다. 스트림을 통해 실시간 추적 기능을 갖춘 세션 관리를 지원하여 개발자가 인증 상태와 세션 변경 사항을 동적으로 모니터링할 수 있습니다. 크로스플랫폼 사용을 위해 설계되어 Android, iOS, 웹, macOS, Windows, Linux에서 모두 작동합니다. Odoo의 백엔드 서비스와의 통합을 간소화하여 Odoo 데이터 및 워크플로우와 상호작용하는 네이티브 또는 웹 애플리케이션 개발에 이상적입니다.

사용 사례

  • Flutter 앱을 Odoo ERP와 통합하기
  • 기업 애플리케이션에서의 실시간 세션 모니터링
  • Odoo 백엔드를 사용하여 CRM 또는 재고 도구 구축
  • Flutter 앱과 Odoo 간의 데이터 동기화
  • 모바일 클라이언트에서 Odoo 작업 자동화

주요 기능

  • 스트림 기반 세션 변경 추적
  • 크로스 플랫폼 호환성
  • Odoo와의 안전한 RPC 통신
  • 인증 및 세션 지속성 지원
  • Flutter pub add 명령을 통한 간편한 설정

적합한 대상

  • ERP 통합 앱을 구축하는 Flutter 개발자
  • Odoo를 백엔드로 사용하는 기업용 앱 팀
  • 실시간 세션 업데이트가 필요한 개발자
  • Odoo 연결이 필요한 모바일 및 데스크톱 앱
  • Odoo 기반 비즈니스 솔루션을 개발하는 팀

고려 사항

  • RPC가 활성화된 활성 Odoo 서버가 필요합니다
  • 인증 설정은 신중하게 처리되어야 합니다
  • 기본 사용법 외에 문서가 제한적
  • Odoo에 안정적인 네트워크 연결이 필요합니다
  • 비-Odoo 백엔드 통합에는 적합하지 않습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Odoo RPC Client Library

Odoo RPC Client Library for Dart.

Features

  • Initialize client with previously stored Odoo Session.
  • Authenticate via database name, login and password.
  • Issue JSON-RPC requests to JSON controllers.
  • Execute public methods via CallKw.
  • Get Odoo Session updates via stream.
  • Terminate session (logout).
  • Catch exceptions when session expires.

Usage

To use this plugin, add odoo_rpc as a dependency in your pubspec.yaml file. For example:

dependencies:
  odoo_rpc: <latest_version>

Examples

Basic RPC-call

import 'dart:io';
import 'package:odoo_rpc/odoo_rpc.dart'

main() async {
  final client = OdooClient('https://my-db.odoo.com');
  try {
    await client.authenticate('my-db', 'admin', 'admin');
    final res = await client.callRPC('/web/session/modules', 'call', {});
    print('Installed modules: \n' + res.toString());
  } on OdooException catch (e) {
    print(e);
    client.close();
    exit(-1);
  }
  client.close();
}

RPC-Calls with tracking session changes. Odoo server will issue new session_id on each call.

import 'dart:io';
import 'package:odoo_rpc/odoo_rpc.dart'


sessionChanged(OdooSession sessionId) async {
  print('We got new session ID: ' + sessionId.id);
  store_session_somehow(sessionId);
}


main() async {
  var prev_session = restore_session_somehow();
  var client = OdooClient("https://my-db.odoo.com", sessionId: prev_session);

  // Subscribe to session changes to store most recent one
  var subscription = client.sessionStream.listen(sessionChanged);

  try {
    final session = await client.authenticate('my-db', 'admin', 'admin');
    var res = await client.callRPC('/web/session/modules', 'call', {});
    print('Installed modules: \n' + res.toString());

    // logout
    await client.destroySession();
  } on OdooException catch (e) {
    print(e);
    subscription.cancel();
    client.close();
    exit(-1);
  }

  try {
    await client.checkSession();
  } on OdooSessionExpiredException {
    print('Session expired');
  }

  subscription.cancel();
  client.close();
}

Flutter example using FutureBuilder.

import 'package:flutter/material.dart';
import 'package:odoo_rpc/odoo_rpc.dart';

final orpc = OdooClient('https://my-odoo-instance.com');
void main() async {
  await orpc.authenticate('odoo-db', 'admin', 'admin');
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  Future<dynamic> fetchContacts() {
    return orpc.callKw({
      'model': 'res.partner',
      'method': 'search_read',
      'args': [],
      'kwargs': {
        'context': {'bin_size': true},
        'domain': [],
        'fields': ['id', 'name', 'email', '__last_update', 'image_128'],
        'limit': 80,
      },
    });
  }

  Widget buildListItem(Map<String, dynamic> record) {
    var unique = record['__last_update'] as String;
    unique = unique.replaceAll(RegExp(r'[^0-9]'), '');
    final avatarUrl =
        '${orpc.baseURL}/web/image?model=res.partner&field=image_128&id=${record["id"]}&unique=$unique';
    return ListTile(
      leading: CircleAvatar(backgroundImage: NetworkImage(avatarUrl)),
      title: Text(record['name']),
      subtitle: Text(record['email'] is String ? record['email'] : ''),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Contacts'),
      ),
      body: Center(
        child: FutureBuilder(
            future: fetchContacts(),
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      final record =
                          snapshot.data[index] as Map<String, dynamic>;
                      return buildListItem(record);
                    });
              } else {
                if (snapshot.hasError) return Text('Unable to fetch data');
                return CircularProgressIndicator();
              }
            }),
      ),
    );
  }
}

For more complex usage consider odoo_repository as abstraction layer between your flutter app and Odoo backend.

Web platform notice

This package intentionally uses http package instead of dart:io so web platform could be supported. However RPC calls via web client (dart js) that is hosted on separate domain will not work due to CORS requests currently are not correctly handled by Odoo. See https://github.com/odoo/odoo/pull/37853 for the details.

To make it work from different host we must follow the rules of CORS. Make sure your odoo server has these CORS headers:

Access-Control-Allow-Methods: GET, OPTIONS, PUT, POST
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Origin: https://{YOUR_FLUTTER_APP_DOMAIN}
Access-Control-Allow-Credentials: true // This is super important

And for WebApp you must use BrowserClient or something similar. The withCredentials = true is crucial. It allows the httpClient to carry on cookies from Browser. On Web browser, it won't allow you to directly access set-cookie header. As it is a forbidden header: https://fetch.spec.whatwg.org/#forbidden-request-header But it will automatically add this cookie to the BrowserClient whenever you make rpc call to your odoo server once authenticated.

OdooClient(BASE_URL,
  sessionId: ODOO_SESSION,
  httpClient: BrowserClient()..withCredentials = true,
  isWebPlatform = true,
)

For Web always listen to loginStream stream in order to get if user logged in or logged out. As session_id will be unaccesible on Web platform.

Issues

Please file any issues, bugs or feature requests as an issue on our GitHub page.

Want to contribute

If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug or adding a cool new feature), please send us your pull request.

Author

Odoo RPC Client Library is developed by ERP Ukraine.

카테고리

의존성

의존성 목록 2 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.