ArchitectureData Model Reference
Architecture

Data Model Reference — Jules

Entity relationships, key Prisma models, and the multi-tenant schema architecture for Jules (Harold).

Data Model Reference — Jules

Developer documentation — Key entities, relationships, and multi-tenant architecture for the Jules backend.


Table of Contents

  1. Multi-Tenant Architecture
  2. Core Trading Entities
  3. Operations
  4. Containers
  5. Allocations
  6. Logistics
  7. Commercial & Contracts
  8. Financial & Invoicing
  9. Hedging
  10. Companies, Sites & Contacts
  11. Configuration & Reference Data
  12. Users & Auth
  13. Key Design Patterns

Multi-Tenant Architecture

Jules uses per-organization PostgreSQL schemas for data isolation. Each client organization has its own schema:

{client}_lotr_extr

For example: garfield_lotr_extr, demirdokum_lotr_extr.

All business data (operations, containers, invoices, etc.) lives in the organization schema. Prisma applies the schema prefix at runtime based on the authenticated user's organization.

Consequences:

  • No cross-org queries are possible by design
  • Each org's schema is independent — migrations run per org
  • The public schema holds only auth/org-level tables

Core Trading Entities


Operations

The Operation model is the central commercial entity.

Key fields

FieldTypeDescription
idUUIDPrimary key
haroldNumberStringHuman-readable unique reference (e.g., OP-2026-001)
typeEnumBUY or SELL
statusEnumIN_PROGRESS, CONFIRMED, CLOSED, CANCELLED
marketTypeEnumEXPORT or LOCAL
companyIdFKCounterparty company
siteIdFKCounterparty site
contractIdFKLinked contract (optional)
isWarehouseBooleanWhether this is a warehouse operation
createdByIdFKCreating user
createdAtDateTime

OperationQuality

Each operation has one or more quality lines (the material grades being traded):

FieldTypeDescription
operationIdFKParent operation
qualityIdFKMaterial grade
quantityDecimalContracted volume
priceDecimalPrice per unit
incotermEnumFOB, CFR, CIF, EXW, etc.
priceTypeEnumSPOT, INDEX, TREATMENT
paymentTermsString
portOfLoadingIdFK
portOfDestinationIdFK
hedgingStatusEnumREQUIRED, PARTIALLY_HEDGED, HEDGED

Containers

Container

FieldTypeDescription
idUUIDPrimary key
haroldNumberStringe.g., CTN-2026-001234
referenceNumberStringPhysical container ID (e.g., CLHU1234567)
sealedNumberStringSecurity seal number
blNumberStringBill of Lading number
operationIdFKParent operation
followUpStatusEnumUNPLANNED, PLANNED, LOADED, DELIVERED, CLOSED
bookingStatusEnumBOOKING_REQUESTED, PC_BOOKED, FREIGHT_BOOKED, ALL_BOOKED
netWeightDecimalWeight of commodity
grossWeightDecimalTotal weight incl. tare
tareWeightDecimalEmpty container weight
weightSlipDecimalWeight at destination
dateOfLoadingDateTime
dateOfDeliveryDateTime
estimatedMarginDecimalPre-invoicing margin estimate
finalMarginDecimalPost-invoicing margin
isPurchaseInvoicingClosedBoolean
isSaleInvoicingClosedBoolean
bookingIdFKFreight booking
shipmentIdFKShipment

ContainerToOperationQuality

Junction table tracking quantities per quality within a container:

FieldDescription
containerIdFK → Container
operationQualityIdFK → OperationQuality
plannedQuantityIntended quantity at creation
loadedQuantityActual weight at loading
deliveredQuantityWeight at destination

ContainerInvoicingLine

One row per cost/revenue element per container:

FieldDescription
containerIdFK → Container
elementTypeBUY, SELL, or PROVIDER
costElementEnum (FREIGHT_COST, PRECARRIAGE, AGENT_COMMISSION, etc.)
statusPLANNED, LOADED, DELIVERED, CLOSED
invoicingStatusPENDING or INVOICED
estimatedAmountFrom rate card
actualAmountFrom invoice
currency

Allocations

Allocation

FieldTypeDescription
idUUID
haroldNumberStringe.g., ALLOC-2026-0012
statusEnumDRAFT, CONFIRMED
buyOperationQualityIdFKBuy side quality line
sellOperationQualityIdFKSell side quality line
referenceNumberStringExternal reference
trackingStatusEnumLOADED → SHIPPED → ARRIVED → RECOVERED
annex7StatusEnumPENDING → SIGNED_AND_UPLOADED
bookingFulfilmentStatusEnumPENDING → ALL_BOOKING_OK
customsStatusEnumPENDING → SENT_TO_CARRIER
loadReportStatusEnumPENDING → SENT_TO_DOCS_TEAM
isVGMSubmittedBoolean
marginPerTonDecimalEstimated margin/T

Containers are linked to allocations via a many-to-many (Allocation ↔ Container).


Logistics

Booking

FieldDescription
typeFREIGHT or CARGO_BULK
statusREQUESTED, IN_PROGRESS, CONFIRMED, CANCELLED
shippingLineIdFK → ShippingLine
logisticForwarderIdFK → LogisticForwarder
portOfLoadingIdFK → Port
portOfDestinationIdFK → Port
numberOfBookedContainersInteger
freightCostIdFK → FreightRate
vesselName / voyageNumberFor cargo bulk
charterPartyDateFor cargo bulk
quantityAllowanceTypeMOLOO / CHOPT / MOLCHOP (bulk)

BookingToPort (bulk bookings)

Multi-port loading/destination per voyage:

FieldDescription
bookingIdFK → Booking
portIdFK → Port
directionLOADING or DISCHARGE
sequencePort call order

Shipment

FieldDescription
haroldNumbere.g., SHIP-2026-0441
blNumberBill of Lading number
locationStatusAT_ORIGIN → IN_TRANSIT → COMPLETED
timingStatusON_TIME / DELAYED / EARLY_ARRIVAL
documentationStatusTO_START → SENT_TO_CLIENT
releaseTypeBL release method
currentEta / originalEta
actualSailingDate
letterOfCreditIdFK → LetterOfCredit (optional)
trackedContainerIdReference container for tracking

FreightRate / PreCarriageRate

Rate cards used for logistics cost estimation:

EntityKey fields
FreightRateshippingLineId, portOfLoadingId, portOfDestinationId, cost, logisticMaterialId, validityStart/End
PreCarriageRatepreCarriageLineId, preCarriageAreaId, portOfLoadingId, mode (ROAD/RAIL/BARGE), cost

Both have validationStatus: NOT_VALIDATED, VALIDATED, UNCHECKED.


Commercial & Contracts

Contract

FieldDescription
typeTRADING, WM_SPOT, WM_RECURRING
directionBUY or SELL
statusIN_PROGRESS → CONFIRMED → CLOSED
companyIdCounterparty
siteIdCounterparty site
marketTypeEXPORT or LOCAL
startDate / endDateContract period

ContractStream

Quality lines within a contract:

FieldDescription
contractIdFK → Contract
qualityIdMaterial grade
quantityContracted volume
priceAgreed price
priceTypeSPOT / INDEX / TREATMENT
incoterm
toleranceRateAllowed quantity deviation
mqcMinimum quality commitment per container

Goal

FieldDescription
qualityIdTargeted material
quantityVolume target
targetPricePrice objective
priceTypeBUY or SELL
startDate / dueDateTime window
fulfilledQuantityVolume achieved through operations

Financial & Invoicing

Invoice

FieldDescription
haroldNumber
typeBUY_INVOICE, SELL_INVOICE, PROVIDER_INVOICE, etc.
statusDRAFT → CONFIRMED → PAID
companyIdCounterparty
totalAmount
currency
operationIdLinked operation
shipmentIdLinked shipment (optional)

Budget

FieldDescription
nameBudget identifier
templateIdFK → BudgetTemplate
statusPENDING, APPROVED, REJECTED
overdraftPeriodDays of negative cash

BudgetElement

One cost line per budget:

FieldDescription
budgetIdFK → Budget
elementIdFK → cost element
costTypeFLAT / PERCENTAGE / LOGISTICS_RATE
priceAmount
costPercentageFor percentage-based
percentageOfPURCHASE / SALE / TURNOVER

Hedging

HedgingContract

FieldDescription
haroldNumber
typePURCHASE / SALE / PURCHASE_AVG_PRICE / SALE_AVG_PRICE / PURCHASE_DEHEDGE / SALE_DEHEDGE / BORROWING / LENDING / etc.
marketLME or COMEX
commodityHedged commodity
quantityTotal hedge volume
tradeDateWhen executed
promptDateSettlement date on exchange
statusOPEN / PARTIALLY_CLOSED / CLOSED / PAST
allocatedQuantityVolume allocated to containers
dehedgedQuantityVolume closed out
parentIdFK → HedgingContract (for de-hedges/carry)

ContainerQualityHedging

Links a hedging contract to a specific container quality:

FieldDescription
hedgingContractIdFK → HedgingContract
containerIdFK → Container
operationQualityIdFK → OperationQuality
hedgedQuantityTonnes covered
loadedWeightActual container weight
recoveryPercentageFor recovery-formula hedges

Companies, Sites & Contacts

Company

FieldDescription
name
typeSUPPLIER / CUSTOMER / BOTH / INTERNAL
isBlockedBlocked from new operations
erpId / erpValueExternal ERP identifiers

Site

FieldDescription
companyIdFK → Company
name
siteTypeWAREHOUSE / SUPPLIER / CUSTOMER / PORT
isWarehouseWarehouse mode flag
address
portOfLoadingIdDefault port (for supplier sites)
portOfDestinationIdDefault port (for customer sites)
erpId / erpCompanyIdExternal identifiers

SiteToCompany

Multiple companies can be linked to a site (e.g., a port used by many companies). Tracks the primary company relationship.

Contact

FieldDescription
firstName / lastName
email
phone
companyIdPrimary company
isPrimaryPrimary contact flag

Configuration & Reference Data

Quality (material grade)

FieldDescription
namee.g., "HMS 1&2"
familyIdFK → QualityFamily
groupIdFK → QualityGroup
defaultVolumeDefault quantity unit
defaultPriceVolumeDefault price unit
isDeletedSoft delete flag

LogisticMaterial (container type)

FieldDescription
namee.g., "40' HC"
capacityStandard capacity in tonnes

ShippingLine / LogisticForwarder / PreCarriageLine

Reference entities for logistics providers. All support contact linking.

Port

FieldDescription
namePort name
country
typeLOADING or DESTINATION or BOTH

Users & Auth

User (in org schema)

FieldDescription
email
firstName / lastName
roleUser role within the organization
departmentIdFK → Department

UserToCompany

Links internal users to counterparty companies they manage:

FieldDescription
userIdFK → User
companyIdFK → Company

ExternalUser (portal users)

FieldDescription
email
companyIdThe counterparty company they represent
typeSUPPLIER_PORTAL or CUSTOMER_PORTAL
isActive

Key Design Patterns

1. Harold numbers

Every key entity gets a system-generated human-readable identifier (haroldNumber) in addition to the UUID primary key. Format: {PREFIX}-{YEAR}-{SEQUENCE} (e.g., OP-2026-001234).

2. Soft deletes

Most reference data (qualities, sites, companies) uses isDeleted = true rather than hard deletes, to preserve referential integrity.

3. Estimated vs actual amounts

Most financial fields exist in pairs:

  • estimatedFreightCost / actualFreightCost
  • estimatedMargin / finalMargin

Estimated values come from rate cards at creation. Actual values come from invoicing.

4. ERP sync fields

Entities that sync with external ERPs carry erpId, erpValue, erpCompanyId fields (nullable). Sync status is tracked per entity.

5. Watchers pattern

Multiple entities (allocations, shipments, operations) support a watchers relation — a list of users who receive notifications about changes.

6. Multi-currency

Financial amounts always carry a currency field. Margin calculations normalize all amounts to the sale currency before computing.