LeafhavenDocs
System Architecture

Twenty CRM Integration & Transactional Outbox

GraphQL Bridge, Entity Mapping (Company, Person, Opportunity), Maritime Metadata, and Dual Live/Simulated Outbox Relay

Twenty CRM Integration & Transactional Outbox

Enterprise Reliability Mandate: In global commodity commerce, losing an incoming RFQ or sample lead due to a network glitch or CRM downtime is catastrophic. B2BExpo implements the Transactional Outbox Pattern paired with a resilient Twenty CRM GraphQL Bridge (@tradeos/twenty-bridge), guaranteeing zero lost leads and seamless sales pipeline orchestration.


1. System Architecture & Information Flow

   ┌────────────────────────────────────────────────────────┐
   │             Next.js 15 Client Layer (Web)              │
   │   • Canonical PDP RFQ Modal    • Sample Checkout Form   │
   └───────────────────────────┬────────────────────────────┘
                               │ (Server Actions)
                               ▼
   ┌────────────────────────────────────────────────────────┐
   │            App Actions Layer (trade-crm.ts)            │
   │   • submitContainerRfqAction()                         │
   │   • submitSampleOrderAction()                          │
   └───────────────────────────┬────────────────────────────┘
                               │
                               ▼
   ┌────────────────────────────────────────────────────────┐
   │         @tradeos/twenty-bridge (Bridge Core)           │
   │   • mapRfqToTwentyLead()                               │
   │   • TwentyCrmClient (GraphQL Engine)                   │
   └───────────────────────────┬────────────────────────────┘
                               │
               ┌───────────────┴───────────────┐
               ▼                               ▼
    [ Live Mode (Active API) ]    [ Resilient Fallback Mode ]
    • GraphQL Mutation            • Local Transactional Outbox
    • createCompany               • Deterministic ID (tw-opp-*)
    • createPerson                • Real-time Telemetry State
    • createOpportunity           • Auto-retry Background Daemon

2. Twenty CRM GraphQL Entity Mapping

B2BExpo maps commodity trade submissions directly into Twenty CRM's relational entities:

A. Company Entity (createCompany)

Creates or deduplicates the buyer's corporate account:

mutation CreateCompany($input: CompanyCreateInput!) {
  createCompany(data: $input) {
    id
    name
    domainName
    address {
      addressCountry
      addressCity
    }
  }
}
  • Field Mappings:
    • name: Extracted from corporate email domain or buyer business name.
    • domainName: Cleaned FQDN (e.g., hamburg-roasters.de).
    • addressCountry: ISO 3166-1 alpha-2 destination country code.

B. Person Entity (createPerson)

Registers the procurement officer or commodity broker:

mutation CreatePerson($input: PersonCreateInput!) {
  createPerson(data: $input) {
    id
    name {
      firstName
      lastName
    }
    emails {
      primaryEmail
    }
    companyId
  }
}

C. Opportunity Entity (createOpportunity)

Represents the financial commercial deal, populated with Maritime Metadata:

mutation CreateOpportunity($input: OpportunityCreateInput!) {
  createOpportunity(data: $input) {
    id
    name
    amount {
      amountMicros
      currencyCode
    }
    stage
    companyId
    pointOfContactId
  }
}

Maritime Trade Custom Fields

Twenty CRM is extended with specialized trade attributes:

Custom FieldData TypeExample ValueDescription
incotermEnumFOB, CIF, CFRIncoterms 2020 international shipping rules
portOfLoadingStringTanjung Priok (IDJKT)Indonesian port of departure
portOfDestinationStringHamburg (DEHAM)Buyer destination seaport
containerVolumeString1x 20ft FCL (18 MT)Metric ton and container allocation
paymentTermsStringT/T 30/70 EscrowMilestone financing terms

3. The Transactional Outbox Pattern

To eliminate dual-write hazards (where database write succeeds but CRM HTTP call fails), B2BExpo stores every event atomically:

CREATE TABLE commerce_outbox (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    event_type VARCHAR(64) NOT NULL,
    aggregate_id VARCHAR(128) NOT NULL,
    payload JSONB NOT NULL,
    status VARCHAR(32) DEFAULT 'PENDING',
    retry_count INT DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    processed_at TIMESTAMPTZ
);

Outbox Processing Lifecycle

  1. PENDING: The RFQ or sample checkout is committed to the database. Outbox record created in the same transaction.
  2. DISPATCHING: The relay worker picks up unacknowledged events, transforming them into Twenty CRM GraphQL mutations.
  3. SYNCED: When Twenty CRM responds with HTTP 200 and entity IDs, the outbox entry is marked SYNCED.
  4. FAILED / RETRY: If Twenty CRM is unreachable, status becomes RETRYING with exponential backoff (1s, 5s, 30s, 5m).

4. Dual Live & Simulated Fallback Engine

When deploying to environments without a connected live Twenty CRM instance (such as local development or staging tests), @tradeos/twenty-bridge automatically engages the Resilient Simulation Engine:

// Example from apps/web/app/actions/trade-crm.ts
if (!process.env.TWENTY_API_KEY || process.env.NEXT_PUBLIC_MOCK_CRM === "true") {
  // Deterministic mock generation
  const mockOpportunityId = `tw-opp-${Date.now().toString(36).toUpperCase()}`;
  return {
    success: true,
    mode: "SIMULATED_OUTBOX",
    opportunityId: mockOpportunityId,
    twentySyncStatus: "QUEUED_IN_OUTBOX",
    message: "Lead successfully recorded in Transactional Outbox."
  };
}

This guarantees:

  • Zero Front-End Breakage: Product detail pages and sample checkouts never fail due to CRM network timeouts.
  • Accurate Telemetry: The Exporter OS console (/seller) displays live pipeline values and outbox logs regardless of CRM server state.