Вышел Модуль интеграций 2.0 для MedusaЧитать анонс
Odoo logo

Odoo

Двусторонняя интеграция с Odoo ERP (Odoo 14–19+, JSON-RPC 2.0 и JSON-2 API) для Medusa v2. Товары и варианты, остатки на нескольких складах со сверкой расхождений, заказы, счета и платежи, клиенты, резолвер штрихкодов для POS и склада, повторная отправка офлайн-транзакций POS.

npm install @vicacha-devs/medusa-plugin-odoo
Категория
ERP
Создано
Vicacha-devs
Версия
0.1.1
Ежемесячные загрузки
Загрузка данных
Последнее обновление

The Complete Bidirectional Odoo ERP (Odoo 14–19+ JSON-RPC 2.0 & JSON-2 API) Integration, Multi-Warehouse Inventory Drift Reconciliation, Automated Order/Invoice/Payment Accounting, POS Barcode Resolver & Offline POS Replay Suite for Medusa v2 ().

unifies and supersedes two separate Medusa ecosystem packages— and —into a single self-contained, zero-external-SaaS-proxy Medusa v2 plugin with native support for both legacy Odoo 14–18 JSON-RPC 2.0 and modern Odoo 19+ JSON-2 REST/RPC APIs.


Table of Contents

  1. Overview & Ecosystem Comparison
  2. Architecture Overview
  3. Installation & Configuration
  4. Bidirectional Sync Capabilities
  5. Database Schema ( Models)
  6. Medusa v2 Workflows & Compensation
  7. Subscribers & Scheduled Jobs
  8. Complete REST API Reference
  9. Typed SDK () & React Hooks ()
  10. Decoupled Admin UI, Widgets & 10-Locale i18n
  11. Security Architecture
  12. Development & Testing Commands

1. Overview & Ecosystem Comparison

Feature / Capability
Medusa Versionv2 ()v2 ()v2 ()
External SaaS Proxy RequiredNoYes (Requires external connector proxy)No (100% self-hosted inside Medusa)
Odoo Protocol SupportJSON-RPC 2.0 onlyProxy-dependentDual Protocol: JSON-RPC 2.0 (Odoo 14–18) & JSON-2 API (Odoo 19+)
Resilience & Rate LimitingBasic Proxy-dependentToken-Bucket Rate Limiter, Circuit Breaker (//) & Exponential Backoff
Product & Variant SyncOne-way importBasic catalog syncBidirectional (, , ) + non-destructive variant reconciliation
Multi-Warehouse InventorySingle stock locationBasic stock syncMulti-Warehouse ↔ (), & modes
Inventory Drift ReconciliationNoneNoneAutomated & manual drift detection (, , ) + point-in-time snapshots
Orders, Invoices & PaymentsBasic Basic Idempotent + invoice creation/posting (, , ) +
Two-Way Customer SyncOrder partner onlyOrder partner onlyTwo-way ↔ Medusa Customer sync with B2B Company/VAT & addresses
POS Barcode Resolver & Offline ReplayNoneNoneSub-10ms resolver (, , , ) + Offline POS transaction queue
Inbound Webhooks & ObservabilityNoneBasic webhookTiming-safe HMAC-SHA256 with event deduplication + OpenMetrics/Prometheus
Admin UI & i18nMinimal pageSettings form5-Route Admin Control Center (), Order & Product Widgets, 18 modular components ( lines), 10 locales

2. Architecture Overview

Core Architectural Layers

  1. Multi-Protocol ():
    • JSON-RPC 2.0 (): Authenticates via (, ) and executes model methods via , for Odoo 14, 15, 16, 17, and 18.
    • Odoo 19+ JSON-2 API (): Executes RESTful RPC calls against using and optional .
    • Resilience Primitives: Built-in token-bucket rate limiter (), 3-state circuit breaker ( → → ), and exponential backoff retry loop ().
  2. ():
    • Extends with full lifecycle management for connection settings, section configurations, bidirectional entity synchronization, drift reconciliation, barcode resolution, offline POS replay, and webhook processing.
  3. 10 DML Models with Prefix ():
    • Stores all ERP state in isolated PostgreSQL tables (, , , , , , , , , ).
  4. Compatibility Alias ():
    • Exposes as a drop-in compatibility alias for projects migrating from .

3. Installation & Configuration

Step 1: Install the Package

Step 2: Configure

Register the plugin in and the module in (using either or the compatibility alias ):

Step 3: Run Database Migrations

npx medusa db:migrate

4. Bidirectional Sync Capabilities

4.1 Products & Variants ( ↔ & ↔ )

  • Odoo → Medusa Import: Fetches and records, maps attributes to Medusa options/variants, converts base64 images into data URLs or file attachments, deduplicates product handles via , and performs non-destructive variant reconciliation (matching existing variants by , , or without destroying historical IDs).
  • Medusa → Odoo Export: Pushes Medusa products and variants to Odoo / , computes SHA-256 payload checksums (), and updates to prevent circular subscriber loops.

4.2 Multi-Warehouse Inventory & Drift Reconciliation ( / )

  • Location Mapping: Maps Medusa IDs to Odoo () records.
  • Quantity Modes: Supports both On-Hand ( / ) and Forecasted () inventory quantities.
  • Automated Drift Reconciliation: Compares Medusa inventory levels against Odoo stock quants across all mapped variants and warehouses, recording point-in-time rows and resolving discrepancies using:
    • : Automatically updates Medusa inventory levels to match Odoo.
    • : Automatically writes Odoo inventory adjustments to match Medusa.
    • : Opens an record for human review in .

4.3 Orders, Invoices & Payments (, , )

  • Order Sync: Triggered automatically on or manually from the Order widget / API. Resolves or creates the customer , maps line items by SKU/ERP mapping, creates + , and optionally confirms the quotation ().
  • Invoicing & Payment Registration: When is enabled and the order satisfies (, , or ), creates and posts the Odoo invoice ( / ) and optionally registers payment via against the configured .

4.4 Customers ()

  • Two-Way Partner Sync: Matches Medusa customers and Odoo records via and normalized email addresses, syncing names, phone numbers, street/city/zip/country addresses, and B2B company/VAT fields.

4.5 POS & Warehouse Barcode Resolver + Offline POS Replay

  • Sub-10ms Barcode Lookup (): Resolves , , , or across four operational contexts (, , , ) using an in-memory TTL cache → → Medusa database → live Odoo RPC fallback, logging every scan to .
  • Offline POS Transaction Queue (): Enqueues offline POS checkouts with idempotent deduplication and replays them into Medusa orders and Odoo records once connectivity is restored.

4.6 Inbound Webhooks () & Prometheus Metrics ()

  • Inbound Webhooks: Verifies / against the raw request body using , deduplicates events by in , and dispatches real-time product, stock, customer, or order updates.
  • Prometheus Metrics: Exposes counters and gauges (, , , , , , , ) in both JSON and OpenMetrics text format ().

5. Database Schema ( Models)

All 10 DML models are defined in and created by :

Model ExportTable NamePrimary Purpose & Key Columns
Key-value JSON configuration store ( unique index, JSONB) for connection credentials and per-section settings (, , , , , , ).
Cross-system entity link table (, , , , , , , , ).
Execution audit log for sync runs (, , , , , , , , , , ).
Dead-letter queue for failed entity sync operations (, , , , , , , , , , ).
Point-in-time stock comparison records (, , , , , , , , , , , ).
Summary log for inventory drift reconciliation runs (, , , , , , , , , , , ).
Manual review queue for stock or field conflicts (, , , , , , , , , , ).
Telemetry log for POS & warehouse barcode scans (, , , , , , , ).
Durable queue for offline POS orders ( unique index, , , , , , , , , , , ).
Idempotency ledger for inbound Odoo webhooks ( unique index, , , , , , , ).

6. Medusa v2 Workflows & Compensation

Defined in and orchestrated with :

Workflow / OperationWorkflow ID / Service MethodStep(s)Trigger & Compensation Behavior
()Triggered via , subscriber, or scheduled cron. Records in and logs per-item failures to .
()Triggered via , subscriber, or scheduled cron. Syncs multi-warehouse stock and returns .
( → )Triggered via subscriber or . Queries order graph, creates/updates Odoo + optional invoice & payment, and writes / back to order metadata.
() ()Triggered via , subscriber, or scheduled cron. Syncs Medusa customers ↔ Odoo .
() ()Triggered via or cron job. Captures rows and applies , , or .
() ()Triggered via (). Replays queued offline POS transactions into Medusa and Odoo idempotently.
Barcode Scan Resolution ( / )Cache → → Medusa DB → Odoo RPCTriggered via . Resolves barcode in , , , or context and records .
Inbound Webhook Processing ( / )HMAC Verify → Deduplicate → Dispatch SyncTriggered via . Validates HMAC-SHA256 signature, records , and updates mapped entities.

7. Subscribers & Scheduled Jobs

Event Subscribers ()

FileSubscriber IDEvents Listened ToBehavior & Loop Prevention
Invokes to create the Odoo , invoice, and payment when is enabled.
, Checks section settings ( and in / ) and exports updated products using SHA-256 checksum comparison () to prevent infinite sync loops.
Checks section settings ( and in / ) and exports stock deltas to Odoo warehouses.
, Checks section settings ( and in / ) and syncs customer changes to .

Scheduled Jobs ()

FileJob NameCron ScheduleDescription
(configurable; e.g. )Verifies connection credentials are configured, then sequentially runs , , and with .
(configurable; e.g. )Verifies connection credentials and , then executes .

8. Complete REST API Reference

Admin Endpoints ()

MethodPathValidator SchemaDescription
—Returns connection status (, , ), active protocol, circuit breaker state, Odoo server version, and entity counters.
—Returns the current connection configuration with secrets (, , ) masked via .
Validates URL safety (), preserves existing secrets when omitted, and saves connection settings to .
Tests live connectivity against Odoo and returns , , , , , and .
—Reads section settings for , , , , , , or .
—Merges and persists partial settings for the specified .
—Fetches Medusa , , and alongside Odoo , , , and .
Triggers manual sync for , , , , or .
—Manually syncs a specific Medusa order ID to Odoo (with optional invoice and payment).
—Lists rows filtered by optional and .
Creates or updates an explicit link between a Medusa ID and an Odoo ID.
—Returns recent runs, runs, and records.
—Lists dead-letter records filtered by .
Marks a dead-letter record as resolved.
—Lists records filtered by ( / ).
Resolves an inventory drift conflict using , , or .
—Lists offline POS transactions ().
Enqueues () or replays () an offline POS transaction.
—Returns Prometheus text exposition when is passed, or JSON metrics plus Prometheus string otherwise.

Store & Webhook Endpoints

MethodPathValidator SchemaDescription
Resolves a scanned barcode/EAN-13/SKU for , , , or context. Returns when found or when unmatched.
()Verifies / via HMAC-SHA256, deduplicates , and processes inbound Odoo events.

9. Typed SDK () & React Hooks ()

Typed SDK Usage

React Hooks Usage

All hooks are exported from and built on lightweight, zero-boilerplate query/mutation primitives (, ) with automatic cache invalidation:

  • Query Hooks: , , , , , , , , .
  • Mutation Hooks: , , , , , , , .

10. Decoupled Admin UI, Widgets & 10-Locale i18n

5 Admin Routes ()

  • (): Main overview dashboard featuring , 4 KPI s, a 2×2 grid linking to sub-routes, and manual bidirectional sync controls.
  • (): Two-column layout with ( credentials, protocol selector, private-network toggle) in and in .
  • (): Two-column layout with & in , and & in .
  • (): Single-column observability view rendering , , and .
  • (): Two-column POS & warehouse tool pairing with .

2 Admin Detail Widgets ()

  • (): Displays with Odoo and invoice badges plus one-click manual order sync / re-verification.
  • (): Displays the linked Odoo ID badge and one-click catalog sync button.

18 Modular Components ( lines each) & 10-Locale i18n

  • Every component under is strictly under 170 lines and uses primitives (, , , , , , , , , , , ).
  • Full 10-locale Admin internationalization (, , , , , , , , , and with RTL support) under .

11. Security Architecture

Implemented in :

  1. SSRF Protection ():
    • Enforces or protocols only.
    • Rejects URLs with embedded or credentials.
    • Blocks cloud metadata endpoints (, , , , , ).
    • Blocks loopback and private RFC1918/RFC6598/IPv6 ULA ranges (, , , , , , , , , , ) unless is explicitly enabled for local development.
  2. Credential Redaction ( & ):
    • Masks , , and ( or ) before returning configuration objects from while providing boolean , , and indicators.
  3. Timing-Safe Webhook Verification ():
    • Computes over the unparsed buffer ( in ) and compares hex digests using .
  4. Rate Limiting & Circuit Breaker ():
    • Token-bucket throttling () prevents overwhelming Odoo worker processes, while the circuit breaker trips to after consecutive failures and probes recovery in after .

12. Development & Testing Commands