/** * src/adapters/odoo-bills-adapter.ts * ===================================== * `WritebackAdapter` (../adapters/writeback-adapter.ts) implementation for * Odoo Vendor Bills (`account.move`, `move_type: 'in_invoice'`) -- * registered under `adapterId: "odoo_bills"` onto an * `ExternalWritebackService` (../services/external-writeback-service.ts). * * PORTED FROM v0-datahub's `lib/odoo/invoice-bridge.ts` (read in full before * writing this file), generalized as one WritebackAdapter implementation * rather than a standalone module with its own Supabase-coupled pipeline * function (`processInboxToOdoo`). What is a DIRECT PORT of proven logic, * vs. what is NEW/GENERALIZED, stated precisely: * * DIRECT PORT (same behavior, same guard order, same reasoning): * - `isReminder`/`duplicateFlag` guard -- invoice-bridge.ts's * `processInboxToOdoo`: "if (invoice.is_reminder || invoice.duplicate_flag) * return { ok:false, error: ... }" (a reminder or a detected duplicate is * NEVER posted to Odoo). Ported verbatim as this adapter's first guard in * `write()`. * - "already posted, skip" guard -- invoice-bridge.ts: "if * (invoice.odoo_move_id) { ...hoppar över...; return { ok:true, odoo_id: * invoice.odoo_move_id } }". Ported as the `existingExternalId` check -- * this adapter's own idempotency defense-in-depth layer, complementing * (not replacing) `ExternalWritebackService`'s own in-memory claim -- see * that service's own module doc comment and writeback-adapter.ts's * `WritebackAdapter.write` doc comment for why BOTH layers exist. * - Partner matching by org-nr -- invoice-bridge.ts's * `matchInvoiceToOdooPartner`: digits-only comparison against * `odoo_export__res_partner.vat` so "556xxx-xxxx", "SE556xxxxxxxx01", and * "5561234567" all match the same partner. Ported as * `matchPartnerViaFabric` below, with ONE necessary substitution: the * original queried via v0-datahub's own `@/lib/warehouse/client` * (Next.js-app-local, not importable from this repo) -- this port uses * 0pt's own already-built, equally generic * `../adapters/fabric-onelake-adapter.ts` (built this same pass, for * 0pt.document_ocr's own needs) against the SAME table name * (`odoo_export__res_partner`) and the SAME digits-only `LIKE` query * shape, parameterized instead of string-interpolated. * - Vendor Bill request shape -- invoice-bridge.ts's `pushInvoiceToOdoo`: * POSTs `{ model: "account.move", invoice: { partner_id, ref, * invoice_date, invoice_date_due, invoice_line_ids: [...] } }` to * `/api/odoo/invoices/write`. Ported verbatim as this adapter's own POST * body -- same endpoint path convention, same field names, so an existing * `/api/odoo/invoices/write` deployment needs no change to accept calls * from this adapter. * - Line synthesis fallback -- invoice-bridge.ts's `processInboxToOdoo` * builds a single summary `invoice_line_ids` entry * (`description: subject||vendor||"Faktura {number}"`, `quantity: 1, * unit_price: amount_excl_vat`) when no itemized lines exist. Ported as * `synthesizeSummaryLine` below, used only when `payload.lines` is absent. * * GENERALIZED / NEW (did not exist in the original, or could not be ported * 1:1): * - The Supabase read/claim/update-status statements in * `processInboxToOdoo` (the `invoice_inbox` table CRUD, and its own * atomic `UPDATE ... WHERE odoo_move_id IS NULL` claim) are NOT ported * here -- that is `ExternalWritebackService`'s job now (its own * adapter-agnostic in-memory claim, see that service's module doc * comment), not this adapter's. This adapter is stateless per call. * - `baseUrl`/`apiKey`/the Fabric credentials are all constructor * parameters -- the original hardcoded `process.env.ODOO_BASE_URL`/ * `process.env.NEXT_PUBLIC_APP_URL`/etc as module-level env reads (v0- * datahub is a single-tenant app; this repo is a SIAX platform capability * any customer's tenant can register their own Odoo instance against, the * same "nothing hardcoded, everything a caller-supplied credential" * doctrine ../adapters/fabric-onelake-adapter.ts's own header already * documents for the identical reason). * - `fetchImpl`/`matchPartner` are injectable (default to the real `fetch` * / `matchPartnerViaFabric`) purely so tests never make a real network * call -- the original had no test coverage for this path at all * (v0-datahub's invoice-bridge.ts has no accompanying test file); this * port is genuinely tested (see tests/p0/odoo-bills-adapter.test.ts). */ import type { WritebackAdapter, WritebackAdapterContext, WritebackRequest, WritebackResult } from "./writeback-adapter"; import { FabricOneLakeAdapter, type FabricOneLakeConnectionConfig } from "./fabric-onelake-adapter"; /** One itemized Vendor Bill line -- same shape as invoice-bridge.ts's `InvoiceForOdoo.lines`. */ export interface OdooBillLine { description: string; quantity: number; unit_price: number; vat_rate?: number; account_bas?: number; } /** * The structured record this adapter expects as `WritebackRequest.payload` * -- same field set as invoice-bridge.ts's `InvoiceForOdoo`, plus the guard * fields (`is_reminder`/`duplicate_flag`/`existing_external_id`) that * `processInboxToOdoo` read directly off its own `invoice_inbox` row (this * adapter has no row of its own to read them from, so the caller supplies * them on the payload instead). */ export interface OdooBillPayload { vendor_name: string; vendor_org_nr?: string; /** Pre-resolved Odoo res.partner id -- when absent and `vendor_org_nr` is set, this adapter * attempts to resolve one via partner matching (see this file's module doc comment). */ partner_id?: number; invoice_number: string; ocr?: string; amount_gross: number; amount_excl_vat?: number; vat?: number; currency: string; invoice_date: string; due_date?: string; description?: string; lines?: readonly OdooBillLine[]; /** Mirrors invoice_inbox.is_reminder -- a payment reminder must never be posted as a new Bill. */ is_reminder?: boolean; /** Mirrors invoice_inbox.duplicate_flag -- a detected duplicate must never be posted. */ duplicate_flag?: boolean; /** When the caller already knows this record was posted (e.g. re-delivering a webhook), pass * the known Odoo id here -- this adapter treats it as already-done and returns it unchanged, * exactly mirroring invoice-bridge.ts's own `invoice.odoo_move_id` early-return. */ existing_external_id?: string; } export type OdooPartnerMatcher = ( orgNr: string, ctx: WritebackAdapterContext, ) => Promise<{ partner_id?: number; partner_name?: string }>; export interface OdooBillsAdapterConfig { /** Base URL of the deployment exposing `/api/odoo/invoices/write` (same route shape as * v0-datahub's own `/api/odoo/invoices/write` this was ported from). */ baseUrl: string; /** Bearer credential for that route. Optional ONLY when `allowUnauthenticated` is explicitly * set (e.g. a route that authenticates by network policy instead) -- see `isConfigured`. */ apiKey?: string; allowUnauthenticated?: boolean; /** Fabric/OneLake connection used for org-nr -> Odoo partner matching (this file's own * `matchPartnerViaFabric`), when `matchPartner` is not explicitly supplied. Optional -- * without it (and without an explicit `matchPartner`), partner matching is skipped entirely * and the Bill is posted without a partner link, mirroring invoice-bridge.ts's own * `matchInvoiceToOdooPartner` catch-all ("Ingen partner match — skickar utan * partner-koppling"). */ fabric?: FabricOneLakeConnectionConfig; /** Table name for the partner lookup query -- defaults to `odoo_export__res_partner`, the * exact table invoice-bridge.ts's own `matchInvoiceToOdooPartner` queried. */ partnerTable?: string; /** Injectable partner matcher, for tests or a caller with its own partner-resolution source. * When supplied, this takes priority over `fabric`. */ matchPartner?: OdooPartnerMatcher; /** Injectable `fetch`, so tests never make a real network call. */ fetchImpl?: typeof fetch; } /** * Digits-only org-nr -> Odoo partner match, ported 1:1 from invoice-bridge.ts's * `matchInvoiceToOdooPartner` (see this file's module doc comment). The only * substitution is the query transport: `FabricOneLakeAdapter.query` instead * of v0-datahub's `@/lib/warehouse/client` -- same table, same digits-only * `LIKE` comparison so "556xxx-xxxx"/"SE556xxxxxxxx01"/"5561234567" all * resolve to the same partner, now parameterized instead of string-interpolated. */ export async function matchPartnerViaFabric( fabric: FabricOneLakeAdapter, orgNr: string, partnerTable: string = "odoo_export__res_partner", ): Promise<{ partner_id?: number; partner_name?: string }> { const digits = orgNr.replace(/[^0-9]/g, ""); if (!digits) return {}; try { const result = await fabric.query<{ id: number; name: string; vat: string }>( `SELECT TOP 1 id, name, vat FROM ${partnerTable} WHERE REPLACE(REPLACE(vat,'-',''),' ','') LIKE '%' + @digits + '%'`, { digits }, ); if (result.rows.length > 0) { return { partner_id: result.rows[0]!.id, partner_name: result.rows[0]!.name }; } return {}; } catch { // Same catch-all as invoice-bridge.ts's own matchInvoiceToOdooPartner: an unreachable/ // misconfigured warehouse must never fail the whole write -- it degrades to "post without // a partner link", not a thrown error. return {}; } } /** Builds the single synthesized `invoice_line_ids` entry used when `payload.lines` is absent * -- ported verbatim from invoice-bridge.ts's `processInboxToOdoo` line-synthesis block. */ function synthesizeSummaryLine(payload: OdooBillPayload): OdooBillLine { const exclVat = payload.amount_excl_vat ?? payload.amount_gross; const description = (payload.description || payload.vendor_name || `Faktura ${payload.invoice_number}`).trim(); return { description, quantity: 1, unit_price: exclVat }; } function isOdooBillPayload(payload: Readonly>): payload is OdooBillPayload & Record { return ( typeof payload.vendor_name === "string" && typeof payload.invoice_number === "string" && typeof payload.amount_gross === "number" && typeof payload.currency === "string" && typeof payload.invoice_date === "string" ); } export class OdooBillsAdapter implements WritebackAdapter { readonly adapterId = "odoo_bills"; private fabricAdapter: FabricOneLakeAdapter | null; constructor(private config: OdooBillsAdapterConfig) { this.fabricAdapter = config.fabric ? new FabricOneLakeAdapter(config.fabric, config.fetchImpl) : null; } isConfigured(): boolean { return !!this.config.baseUrl && (!!this.config.apiKey || this.config.allowUnauthenticated === true); } async write(request: WritebackRequest, ctx: WritebackAdapterContext): Promise { if (!this.isConfigured()) { return { ok: false, error: "odoo_not_configured" }; } if (!isOdooBillPayload(request.payload)) { return { ok: false, error: "invalid_payload_missing_required_fields" }; } const payload = request.payload as unknown as OdooBillPayload; // Guard 1: reminders/duplicates are never posted -- ported verbatim from // invoice-bridge.ts's processInboxToOdoo (see this file's module doc comment). if (payload.is_reminder) return { ok: false, error: "is_reminder" }; if (payload.duplicate_flag) return { ok: false, error: "duplicate" }; // Guard 2: already posted -- idempotent no-op, ported verbatim. if (payload.existing_external_id) { return { ok: true, externalId: payload.existing_external_id }; } // Partner match (best-effort, never fails the write) -- ported verbatim in spirit. let partnerId = payload.partner_id; if (!partnerId && payload.vendor_org_nr) { if (this.config.matchPartner) { const matched = await this.config.matchPartner(payload.vendor_org_nr, ctx); partnerId = matched.partner_id; } else if (this.fabricAdapter) { const matched = await matchPartnerViaFabric(this.fabricAdapter, payload.vendor_org_nr, this.config.partnerTable); partnerId = matched.partner_id; } } const lines = payload.lines && payload.lines.length > 0 ? payload.lines : [synthesizeSummaryLine(payload)]; const fetchImpl = this.config.fetchImpl ?? fetch; let res: Response; try { res = await fetchImpl(`${this.config.baseUrl}/api/odoo/invoices/write`, { method: "POST", headers: { "Content-Type": "application/json", ...(this.config.apiKey ? { Authorization: `Bearer ${this.config.apiKey}` } : {}), }, body: JSON.stringify({ model: "account.move", invoice: { partner_id: partnerId, ref: payload.invoice_number, invoice_date: payload.invoice_date, invoice_date_due: payload.due_date, invoice_line_ids: lines.map((l) => ({ name: l.description, quantity: l.quantity, price_unit: l.unit_price })), }, }), }); } catch (e) { return { ok: false, error: `odoo_network_error: ${e instanceof Error ? e.message : String(e)}` }; } if (!res.ok) { return { ok: false, error: `odoo_http_${res.status}` }; } const result: { ok?: boolean; odoo_id?: number; error?: string } = await res.json(); if (!result.ok || !result.odoo_id) { return { ok: false, error: result.error ?? "odoo_write_failed" }; } return { ok: true, externalId: String(result.odoo_id) }; } }