@open-mercato/core 0.10.1-develop.7775.1.2a1f553826 → 0.10.1-develop.7776.1.3032ea0741
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/sales/api/order-lines/batch/route.js +227 -0
- package/dist/modules/sales/api/order-lines/batch/route.js.map +7 -0
- package/dist/modules/sales/commands/documents.js +356 -129
- package/dist/modules/sales/commands/documents.js.map +2 -2
- package/dist/modules/sales/data/validators.js +53 -0
- package/dist/modules/sales/data/validators.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/sales/api/order-lines/batch/route.ts +312 -0
- package/src/modules/sales/commands/documents.ts +504 -179
- package/src/modules/sales/data/validators.ts +71 -0
- package/src/modules/sales/i18n/de.json +9 -0
- package/src/modules/sales/i18n/en.json +9 -0
- package/src/modules/sales/i18n/es.json +9 -0
- package/src/modules/sales/i18n/ko.json +9 -0
- package/src/modules/sales/i18n/pl.json +9 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/sales/commands/documents.ts"],
|
|
4
|
-
"sourcesContent": ["// @ts-nocheck\n\nimport { randomUUID } from \"crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\nimport { registerCommand } from \"@open-mercato/shared/lib/commands\";\nimport type { CommandHandler, CommandRuntimeContext } from \"@open-mercato/shared/lib/commands\";\nimport { withAtomicFlush } from \"@open-mercato/shared/lib/commands/flush\";\nimport {\n buildChanges,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n requireId,\n type CrudEventsConfig,\n} from \"@open-mercato/shared/lib/commands/helpers\";\nimport { LockMode } from \"@mikro-orm/core\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport type { EventBus } from \"@open-mercato/events\";\nimport type { DataEngine } from \"@open-mercato/shared/lib/data/engine\";\nimport { CrudHttpError, notFound } from \"@open-mercato/shared/lib/crud/errors\";\nimport {\n deriveResourceFromCommandId,\n invalidateCrudCache,\n} from \"@open-mercato/shared/lib/crud/cache\";\nimport { resolveTranslations } from \"@open-mercato/shared/lib/i18n/server\";\nimport { resolveNotificationService } from \"../../notifications/lib/notificationService\";\nimport { buildFeatureNotificationFromType } from \"../../notifications/lib/notificationBuilder\";\nimport { emitSalesEvent } from \"../events\";\nimport { setRecordCustomFields } from \"@open-mercato/core/modules/entities/lib/helpers\";\nimport { loadCustomFieldValues } from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport {\n normalizeCustomFieldResponse,\n normalizeCustomFieldValues,\n} from \"@open-mercato/shared/lib/custom-fields/normalize\";\nimport { E } from \"#generated/entities.ids.generated\";\nimport { findWithDecryption, findOneWithDecryption } from \"@open-mercato/shared/lib/encryption/find\";\nimport {\n SalesQuote,\n SalesQuoteLine,\n SalesQuoteAdjustment,\n SalesOrder,\n SalesOrderLine,\n SalesOrderAdjustment,\n SalesShipment,\n SalesShipmentItem,\n SalesPayment,\n SalesPaymentAllocation,\n SalesInvoice,\n SalesInvoiceLine,\n SalesCreditMemo,\n SalesCreditMemoLine,\n SalesDocumentAddress,\n SalesNote,\n SalesChannel,\n SalesShippingMethod,\n SalesDeliveryWindow,\n SalesPaymentMethod,\n SalesDocumentTag,\n SalesDocumentTagAssignment,\n SalesReturn,\n type SalesLineKind,\n type SalesAdjustmentKind,\n type SalesSettings,\n} from \"../data/entities\";\nimport {\n CatalogProduct,\n CatalogProductUnitConversion,\n} from \"../../catalog/data/entities\";\nimport { Dictionary, DictionaryEntry } from \"../../dictionaries/data/entities\";\nimport { CustomFieldValue } from \"@open-mercato/core/modules/entities/data/entities\";\nimport {\n CustomerAddress,\n CustomerEntity,\n CustomerPersonProfile,\n} from \"../../customers/data/entities\";\nimport {\n enforceAdjustmentSign,\n validateReturnAdjustmentWithinRemaining,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n quoteCreateSchema,\n quoteLineCreateSchema,\n quoteAdjustmentCreateSchema,\n orderCreateSchema,\n ORDER_PAYMENT_LEDGER_WARNING_CODE,\n resolveSuppliedOrderPaymentLedgerFields,\n amountsModeSchema,\n orderLineCreateSchema,\n orderHeaderTotalsSchema,\n orderAdjustmentCreateSchema,\n invoiceCreateSchema,\n invoiceUpdateSchema,\n creditMemoCreateSchema,\n creditMemoUpdateSchema,\n customerSnapshotSchema,\n type QuoteCreateInput,\n type QuoteLineCreateInput,\n type QuoteAdjustmentCreateInput,\n type OrderCreateInput,\n type OrderPaymentLedgerWarning,\n type OrderLineCreateInput,\n type OrderAdjustmentCreateInput,\n type InvoiceCreateInput,\n type CreditMemoCreateInput,\n} from \"../data/validators\";\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n toNumericString,\n reconcileLinePersistedTotals,\n deriveLineNetFromGross,\n enforceSalesDocumentOptimisticLock,\n lockSalesDocumentRow,\n SALES_RESOURCE_KIND_ORDER,\n SALES_RESOURCE_KIND_QUOTE,\n} from \"./shared\";\nimport {\n loadShipmentSnapshot,\n restoreShipmentSnapshot,\n type ShipmentSnapshot,\n} from \"./shipments\";\nimport {\n loadPaymentSnapshot,\n restorePaymentSnapshot,\n type PaymentSnapshot,\n} from \"./payments\";\nimport { resolveConvertedOrderFeeTotals } from \"../lib/convertedOrderTotals\";\nimport type { SalesCalculationService } from \"../services/salesCalculationService\";\nimport type { TaxCalculationService } from \"../services/taxCalculationService\";\nimport type {\n PaymentMethodContext,\n ShippingMethodContext,\n} from \"../lib/providers\";\nimport {\n type SalesAmountsMode,\n type SalesLineSnapshot,\n type SalesLineUomSnapshot,\n type SalesAdjustmentDraft,\n type SalesDocumentAmounts,\n type SalesLineCalculationResult,\n type SalesDocumentCalculationResult,\n} from \"../lib/types\";\nimport {\n mapOrderLineEntityToSnapshot,\n mapQuoteLineEntityToSnapshot,\n resolveUpsertDiscountFields,\n resolveUpsertTotalsOrigin,\n resolveUpsertCalculatedAmounts,\n} from \"../lib/lineSnapshots\";\nimport {\n assertAmountsModeUnsupportedOnQuote,\n assertExternalHeaderComplete,\n assertExternalLineComplete,\n assertUniformAmountsMode,\n buildExternalHeaderTotals,\n hasAnySuppliedHeaderTotal,\n readPersistedHeaderTotals,\n refuseOnExternalOrder,\n requireOrderTotalsForExternalWrite,\n} from \"../lib/externalAmounts\";\nimport { isExternalAmountsMode } from \"../lib/calculations\";\nimport { loadShippedQuantityByLine } from \"../lib/shipments/snapshots\";\nimport { resolveDictionaryEntryValue, resolveCachedDictionaryEntryValue } from \"../lib/dictionaries\";\nimport { assertOrderCanBeCancelled, isCancelledOrderStatus } from \"../lib/orderCancellationGuard\";\nimport type { CacheStrategy } from \"@open-mercato/cache\";\nimport { resolveStatusEntryIdByValue } from \"../lib/statusHelpers\";\nimport { SalesDocumentNumberGenerator } from \"../services/salesDocumentNumberGenerator\";\nimport { loadSalesSettings } from \"./settings\";\nimport { notificationTypes } from \"../notifications\";\nimport {\n REFERENCE_UNIT_CODES,\n canonicalizeUnitCode,\n toUnitLookupKey,\n} from \"@open-mercato/shared/lib/units/unitCodes\";\nimport type { AuthContext } from \"@open-mercato/shared/lib/auth/server\";\nimport type { TranslateWithFallbackFn } from \"@open-mercato/shared/lib/i18n/translate\";\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('sales')\nlet warnedDeprecatedOrderPaymentLedgerInput = false\n\n// CRUD events configuration for workflow triggers\nconst orderCrudEvents: CrudEventsConfig<SalesOrder> = {\n module: \"sales\",\n entity: \"order\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n userId: ctx.actorUserId ?? null,\n }),\n};\n\nconst quoteCrudEvents: CrudEventsConfig<SalesQuote> = {\n module: \"sales\",\n entity: \"quote\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n userId: ctx.actorUserId ?? null,\n }),\n};\n\ntype DocumentAddressSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n customerAddressId: string | null;\n name: string | null;\n purpose: string | null;\n companyName: string | null;\n addressLine1: string;\n addressLine2: string | null;\n city: string | null;\n region: string | null;\n postalCode: string | null;\n country: string | null;\n buildingNumber: string | null;\n flatNumber: string | null;\n latitude: number | null;\n longitude: number | null;\n};\n\ntype NoteSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n contextType: \"order\" | \"quote\";\n contextId: string;\n orderId: string | null;\n quoteId: string | null;\n body: string;\n authorUserId: string | null;\n appearanceIcon: string | null;\n appearanceColor: string | null;\n};\n\ntype TagAssignmentSnapshot = {\n id: string;\n tagId: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n};\n\ntype QuoteGraphSnapshot = {\n quote: {\n id: string;\n organizationId: string;\n tenantId: string;\n quoteNumber: string;\n statusEntryId: string | null;\n status: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n validFrom: string | null;\n validUntil: string | null;\n comments: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n };\n lines: QuoteLineSnapshot[];\n adjustments: QuoteAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n};\n\ntype QuoteLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype QuoteAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n quoteLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderGraphSnapshot = {\n order: {\n id: string;\n organizationId: string;\n tenantId: string;\n orderNumber: string;\n statusEntryId: string | null;\n status: string | null;\n fulfillmentStatusEntryId: string | null;\n fulfillmentStatus: string | null;\n paymentStatusEntryId: string | null;\n paymentStatus: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n exchangeRate: string | null;\n taxStrategyKey: string | null;\n discountStrategyKey: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n placedAt: string | null;\n expectedDeliveryAt: string | null;\n dueAt: string | null;\n comments: string | null;\n internalNotes: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n shippingNetAmount: string;\n shippingGrossAmount: string;\n surchargeTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n refundedTotalAmount: string;\n outstandingAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n totalsMode: SalesAmountsMode;\n };\n lines: OrderLineSnapshot[];\n adjustments: OrderAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n shipments: ShipmentSnapshot[];\n payments: PaymentSnapshot[];\n};\n\ntype OrderLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n reservedQuantity: string;\n fulfilledQuantity: string;\n invoicedQuantity: string;\n returnedQuantity: string;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n amountsMode: SalesAmountsMode;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n orderLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderUndoPayload = {\n before?: OrderGraphSnapshot | null;\n after?: OrderGraphSnapshot | null;\n};\n\ntype QuoteUndoPayload = {\n before?: QuoteGraphSnapshot | null;\n after?: QuoteGraphSnapshot | null;\n};\n\ntype QuoteConvertUndoPayload = {\n quote?: QuoteGraphSnapshot | null;\n order?: OrderGraphSnapshot | null;\n};\n\ntype InvoiceGraphSnapshot = {\n invoice: {\n id: string;\n organizationId: string;\n tenantId: string;\n invoiceNumber: string;\n orderId: string | null;\n statusEntryId: string | null;\n status: string | null;\n issueDate: string | Date | null;\n dueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n outstandingAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: InvoiceLineSnapshot[];\n};\n\ntype InvoiceLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n kind: string;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype CreditMemoGraphSnapshot = {\n creditMemo: {\n id: string;\n organizationId: string;\n tenantId: string;\n creditMemoNumber: string;\n orderId: string | null;\n invoiceId: string | null;\n statusEntryId: string | null;\n status: string | null;\n reason: string | null;\n issueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: CreditMemoLineSnapshot[];\n};\n\ntype CreditMemoLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype InvoiceUndoPayload = {\n before?: InvoiceGraphSnapshot | null;\n after?: InvoiceGraphSnapshot | null;\n};\n\ntype CreditMemoUndoPayload = {\n before?: CreditMemoGraphSnapshot | null;\n after?: CreditMemoGraphSnapshot | null;\n};\n\nconst currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, { message: \"currency_code_invalid\" });\n\nconst dateOnlySchema = z\n .string()\n .trim()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, { message: \"invalid_date\" })\n .refine((value) => !Number.isNaN(new Date(value).getTime()), {\n message: \"invalid_date\",\n });\n\nconst addressSnapshotSchema = z\n .record(z.string(), z.unknown())\n .nullable()\n .optional();\n\n// Mirrors the create schema's `decimal({ min: 0 })` (data/validators.ts). `null`\n// comes first in the union below because the coercion accepts it \u2014 `Number(null)`\n// is 0 \u2014 and would turn a clear into a written zero.\nconst exchangeRateSchema = z.coerce.number().min(0);\n\nconst documentUpdateFieldsSchema = z\n .object({\n id: z.string().uuid(),\n customerEntityId: z.string().uuid().nullable().optional(),\n customerContactId: z.string().uuid().nullable().optional(),\n customerSnapshot: customerSnapshotSchema.nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n customerReference: z.string().nullable().optional(),\n externalReference: z.string().nullable().optional(),\n comment: z.string().nullable().optional(),\n // Same names and limits as the create schema (data/validators.ts), so a\n // caller can send one payload shape to create and update. Nullable here\n // because an update \u2014 unlike a create \u2014 has an existing value to clear.\n comments: z.string().trim().max(4000).nullable().optional(),\n internalNotes: z.string().trim().max(4000).nullable().optional(),\n orderNumber: z.string().trim().min(1).max(191).optional(),\n quoteNumber: z.string().trim().min(1).max(191).optional(),\n currencyCode: currencyCodeSchema.optional(),\n // Order-only columns \u2014 SalesQuote declares none of them. Declared here\n // because the create schema declares them and a caller reusing its create\n // payload on an update otherwise lost them silently; `applyDocumentUpdate`\n // rejects each with a 400 on a quote rather than dropping it.\n exchangeRate: z.union([z.null(), exchangeRateSchema]).optional(),\n paymentStatusEntryId: z.string().uuid().nullable().optional(),\n fulfillmentStatusEntryId: z.string().uuid().nullable().optional(),\n channelId: z.string().uuid().nullable().optional(),\n statusEntryId: z.string().uuid().nullable().optional(),\n placedAt: z.union([dateOnlySchema, z.null()]).optional(),\n expectedDeliveryAt: z.union([dateOnlySchema, z.null()]).optional(),\n shippingAddressId: z.string().uuid().nullable().optional(),\n billingAddressId: z.string().uuid().nullable().optional(),\n shippingAddressSnapshot: addressSnapshotSchema,\n billingAddressSnapshot: addressSnapshotSchema,\n shippingMethodId: z.string().uuid().nullable().optional(),\n shippingMethodCode: z.string().nullable().optional(),\n shippingMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n paymentMethodId: z.string().uuid().nullable().optional(),\n paymentMethodCode: z.string().nullable().optional(),\n paymentMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n tags: z.array(z.string().uuid()).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n customFieldSetId: z.string().uuid().nullable().optional(),\n totalsMode: amountsModeSchema.optional(),\n ...orderHeaderTotalsSchema.shape,\n });\n\ntype DocumentUpdateFields = z.infer<typeof documentUpdateFieldsSchema>;\n\nfunction carriesDocumentEdit(input: DocumentUpdateFields): boolean {\n return (\n typeof input.currencyCode === \"string\" ||\n input.placedAt !== undefined ||\n input.expectedDeliveryAt !== undefined ||\n input.channelId !== undefined ||\n input.statusEntryId !== undefined ||\n input.exchangeRate !== undefined ||\n input.paymentStatusEntryId !== undefined ||\n input.fulfillmentStatusEntryId !== undefined ||\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined ||\n input.customerReference !== undefined ||\n input.externalReference !== undefined ||\n input.comment !== undefined ||\n input.comments !== undefined ||\n input.internalNotes !== undefined ||\n input.orderNumber !== undefined ||\n input.quoteNumber !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined ||\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.tags !== undefined ||\n input.customFields !== undefined ||\n input.customFieldSetId !== undefined\n );\n}\n\n// The route cannot see an order's persisted mode, so it lets header totals count\n// as an edit; each command re-applies `documentEditSchema` once it can. An empty\n// update must not reach a quote: execution reverts a `sent` quote to draft.\nexport const documentUpdateSchema = documentUpdateFieldsSchema.refine(\n (input) =>\n carriesDocumentEdit(input) ||\n input.totalsMode !== undefined ||\n hasAnySuppliedHeaderTotal(input),\n { message: \"update_payload_empty\" },\n);\n\nconst documentEditSchema = documentUpdateFieldsSchema.refine(carriesDocumentEdit, {\n message: \"update_payload_empty\",\n});\n\nexport type DocumentUpdateInput = z.infer<typeof documentUpdateSchema>;\n\ntype DocumentLineCreateInput = QuoteLineCreateInput | OrderLineCreateInput;\ntype DocumentAdjustmentCreateInput =\n | QuoteAdjustmentCreateInput\n | OrderAdjustmentCreateInput;\n\nfunction cloneJson<T>(value: T): T {\n if (value === null || value === undefined) return value;\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/**\n * Graph snapshots load custom fields through `loadCustomFieldValues`, which keys\n * them `cf_<key>`. Writing those keys back verbatim stores a new `cf_<key>` row\n * instead of restoring `<key>`, so restores strip the prefix first.\n */\nfunction toSnapshotCustomFieldWriteValues(\n values: Record<string, unknown>,\n): ReturnType<typeof normalizeCustomFieldValues> {\n return normalizeCustomFieldValues(normalizeCustomFieldResponse(values) ?? {});\n}\n\n/**\n * Persists document-level custom fields supplied on a create input.\n *\n * Order and quote creates used to accept `customFields` at the HTTP boundary\n * (`splitCustomFieldPayload` folds `cf_*` keys into it) and then drop the values\n * on the floor, because the create schemas never declared the key and the\n * handlers never wrote it \u2014 only updates did. Callers therefore had to create,\n * then immediately update, to get custom fields to stick.\n */\nasync function setDocumentCustomFieldsIfSupplied(\n em: EntityManager,\n params: {\n entityId: string;\n recordId: string;\n organizationId: string;\n tenantId: string;\n customFields: unknown;\n },\n): Promise<void> {\n const { customFields } = params;\n if (customFields === undefined || customFields === null) return;\n const values =\n typeof customFields === \"object\" && !Array.isArray(customFields)\n ? (customFields as Record<string, unknown>)\n : {};\n if (!Object.keys(values).length) return;\n await setRecordCustomFields(em, {\n entityId: params.entityId,\n recordId: params.recordId,\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n values: normalizeCustomFieldValues(values),\n });\n}\n\nasync function resolveCustomerSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n customerEntityId?: string | null,\n customerContactId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!customerEntityId) return null;\n const customer = await em.findOne(\n CustomerEntity,\n { id: customerEntityId, organizationId, tenantId },\n { populate: [\"personProfile\", \"companyProfile\"] },\n );\n if (!customer) return null;\n\n const contact = customerContactId\n ? await em.findOne(CustomerPersonProfile, {\n id: customerContactId,\n organizationId,\n tenantId,\n })\n : null;\n\n return {\n customer: {\n id: customer.id,\n kind: customer.kind,\n displayName: customer.displayName,\n primaryEmail: customer.primaryEmail ?? null,\n primaryPhone: customer.primaryPhone ?? null,\n personProfile: customer.personProfile\n ? {\n id: customer.personProfile.id,\n firstName: customer.personProfile.firstName ?? null,\n lastName: customer.personProfile.lastName ?? null,\n preferredName: customer.personProfile.preferredName ?? null,\n }\n : null,\n companyProfile: customer.companyProfile\n ? {\n id: customer.companyProfile.id,\n legalName: customer.companyProfile.legalName ?? null,\n brandName: customer.companyProfile.brandName ?? null,\n domain: customer.companyProfile.domain ?? null,\n websiteUrl: customer.companyProfile.websiteUrl ?? null,\n }\n : null,\n },\n contact: contact\n ? {\n id: contact.id,\n firstName: contact.firstName ?? null,\n lastName: contact.lastName ?? null,\n preferredName: contact.preferredName ?? null,\n jobTitle: contact.jobTitle ?? null,\n department: contact.department ?? null,\n }\n : null,\n };\n}\n\nasync function resolveAddressSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n addressId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!addressId) return null;\n const address = await findOneWithDecryption(\n em,\n CustomerAddress,\n { id: addressId, organizationId, tenantId },\n undefined,\n { tenantId, organizationId },\n );\n if (!address) return null;\n\n return {\n id: address.id,\n name: address.name ?? null,\n purpose: address.purpose ?? null,\n companyName: address.companyName ?? null,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? null,\n buildingNumber: address.buildingNumber ?? null,\n flatNumber: address.flatNumber ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n postalCode: address.postalCode ?? null,\n country: address.country ?? null,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n isPrimary: address.isPrimary,\n };\n}\n\nasync function resolveDocumentReferences(\n em: EntityManager,\n parsed: {\n organizationId: string;\n tenantId: string;\n customerEntityId?: string | null;\n customerContactId?: string | null;\n customerSnapshot?: Record<string, unknown> | null;\n billingAddressId?: string | null;\n shippingAddressId?: string | null;\n billingAddressSnapshot?: Record<string, unknown> | null;\n shippingAddressSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n deliveryWindowId?: string | null;\n paymentMethodId?: string | null;\n },\n): Promise<{\n customerSnapshot: Record<string, unknown> | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n shippingMethod: SalesShippingMethod | null;\n deliveryWindow: SalesDeliveryWindow | null;\n paymentMethod: SalesPaymentMethod | null;\n}> {\n const [\n resolvedCustomerSnapshot,\n resolvedBillingSnapshot,\n resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n ] = await Promise.all([\n parsed.customerSnapshot\n ? Promise.resolve(cloneJson(parsed.customerSnapshot))\n : resolveCustomerSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.customerEntityId ?? null,\n parsed.customerContactId ?? null,\n ),\n parsed.billingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.billingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.billingAddressId ?? null,\n ),\n parsed.shippingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.shippingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.shippingAddressId ?? null,\n ),\n parsed.shippingMethodId\n ? em.findOne(SalesShippingMethod, {\n id: parsed.shippingMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.deliveryWindowId\n ? em.findOne(SalesDeliveryWindow, {\n id: parsed.deliveryWindowId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.paymentMethodId\n ? em.findOne(SalesPaymentMethod, {\n id: parsed.paymentMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n ]);\n\n return {\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n shippingMethod: shippingMethod ?? null,\n deliveryWindow: deliveryWindow ?? null,\n paymentMethod: paymentMethod ?? null,\n };\n}\n\nfunction normalizeStatusValue(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length ? trimmed : null;\n}\n\nfunction isConfirmedOrderStatus(status: string | null): boolean {\n return status === \"confirmed\";\n}\n\nasync function emitOrderLifecycleEvent(input: {\n eventId: \"sales.order.confirmed\" | \"sales.order.cancelled\";\n order: SalesOrder;\n previousStatus: string | null;\n}): Promise<void> {\n await emitSalesEvent(input.eventId, {\n id: input.order.id,\n orderId: input.order.id,\n orderNumber: input.order.orderNumber,\n previousStatus: input.previousStatus,\n status: normalizeStatusValue(input.order.status),\n tenantId: input.order.tenantId,\n organizationId: input.order.organizationId,\n });\n}\n\nfunction emitOrderLifecycleEventsForTransition(input: {\n order: SalesOrder;\n previousStatus: string | null;\n}): void {\n const nextStatus = normalizeStatusValue(input.order.status);\n if (input.previousStatus === nextStatus) return;\n\n if (isConfirmedOrderStatus(nextStatus)) {\n void emitOrderLifecycleEvent({\n eventId: \"sales.order.confirmed\",\n order: input.order,\n previousStatus: input.previousStatus,\n }).catch((err) => {\n // Surface as warning so downstream automations (e.g. WMS reservation\n // subscriber) failing to register/persist their own follow-up state is\n // observable in logs instead of being silently dropped. The order\n // status transition itself is already committed at this point.\n logger.warn(\"order lifecycle event emit failed\", {\n eventId: \"sales.order.confirmed\",\n orderId: input.order.id,\n err,\n });\n });\n }\n\n if (isCancelledOrderStatus(nextStatus)) {\n void emitOrderLifecycleEvent({\n eventId: \"sales.order.cancelled\",\n order: input.order,\n previousStatus: input.previousStatus,\n }).catch((err) => {\n logger.warn(\"order lifecycle event emit failed\", {\n eventId: \"sales.order.cancelled\",\n orderId: input.order.id,\n err,\n });\n });\n }\n}\n\nfunction resolveNoteAuthorFromAuth(auth: AuthContext | null): string | null {\n if (!auth || auth.isApiKey) return null;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n const uuidRegex =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;\n return uuidRegex.test(sub) ? sub : null;\n}\n\nfunction resolveStatusChangeActor(auth: AuthContext | null, translate: TranslateWithFallbackFn): string {\n const unknownLabel = translate(\n \"sales.orders.status_change.actor_unknown\",\n \"unknown user\",\n );\n if (!auth) return unknownLabel;\n if (auth.isApiKey) {\n const keyName = typeof auth.keyName === \"string\" ? auth.keyName.trim() : \"\";\n const keyId = typeof auth.keyId === \"string\" ? auth.keyId.trim() : \"\";\n const label =\n keyName || keyId || (typeof auth.sub === \"string\" ? auth.sub : \"\");\n return label\n ? translate(\n \"sales.orders.status_change.actor_api_key\",\n \"API key {name}\",\n { name: label },\n )\n : unknownLabel;\n }\n const email = typeof auth.email === \"string\" ? auth.email.trim() : \"\";\n if (email) return email;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n if (sub) return sub;\n return unknownLabel;\n}\n\nfunction formatStatusLabel(status: string | null, translate: TranslateWithFallbackFn): string {\n if (status && status.trim().length) return status.trim();\n return translate(\"sales.orders.status_change.empty\", \"unset\");\n}\n\nasync function appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth,\n}: {\n em: EntityManager;\n order: SalesOrder;\n previousStatus: string | null;\n auth: AuthContext | null;\n}): Promise<SalesNote | null> {\n const nextStatus = normalizeStatusValue(order.status);\n if (previousStatus === nextStatus) return null;\n const { translate } = await resolveTranslations();\n const body = translate(\n \"sales.orders.status_change.note\",\n \"Status changed from {from} to {to} by {actor}.\",\n {\n from: formatStatusLabel(previousStatus, translate),\n to: formatStatusLabel(nextStatus, translate),\n actor: resolveStatusChangeActor(auth, translate),\n },\n );\n const note = em.create(SalesNote, {\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n authorUserId: resolveNoteAuthorFromAuth(auth),\n appearanceIcon: null,\n appearanceColor: null,\n body,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(note);\n return note;\n}\n\nasync function applyDocumentUpdate({\n kind,\n entity,\n input,\n em,\n}: {\n kind: \"order\" | \"quote\";\n entity: SalesOrder | SalesQuote;\n input: DocumentUpdateInput;\n em: EntityManager;\n}): Promise<void> {\n const organizationId = (entity as any).organizationId as string;\n const tenantId = (entity as any).tenantId as string;\n const status =\n typeof (entity as any).status === \"string\" ? (entity as any).status : null;\n const { translate } = await resolveTranslations();\n\n const wantsCustomerChange =\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined;\n const wantsAddressChange =\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined;\n\n let settings: SalesSettings | null = null;\n if (kind === \"order\" && (wantsCustomerChange || wantsAddressChange)) {\n settings = await loadSalesSettings(em, { organizationId, tenantId });\n }\n\n const guardStatus = (\n allowed: string[] | null | undefined,\n errorKey: string,\n fallback: string,\n ) => {\n if (!Array.isArray(allowed)) return;\n if (allowed.length === 0) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n if (!status || !allowed.includes(status)) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n };\n\n if (kind === \"order\" && wantsCustomerChange) {\n guardStatus(\n settings?.orderCustomerEditableStatuses ?? null,\n \"sales.orders.edit_customer_blocked\",\n \"Editing the customer is blocked for this status.\",\n );\n }\n if (kind === \"order\" && wantsAddressChange) {\n guardStatus(\n settings?.orderAddressEditableStatuses ?? null,\n \"sales.orders.edit_addresses_blocked\",\n \"Editing addresses is blocked for this status.\",\n );\n }\n\n if (kind === \"order\" && typeof input.orderNumber === \"string\") {\n (entity as SalesOrder).orderNumber = input.orderNumber;\n }\n if (kind === \"quote\" && typeof input.quoteNumber === \"string\") {\n (entity as SalesQuote).quoteNumber = input.quoteNumber;\n }\n\n if (input.customerEntityId !== undefined) {\n const nextCustomerEntityId = input.customerEntityId ?? null;\n const customerChanged =\n (nextCustomerEntityId?.toLowerCase() ?? null) !==\n (entity.customerEntityId?.toLowerCase() ?? null);\n const snapshotContactId =\n input.customerContactId !== undefined\n ? input.customerContactId\n : customerChanged\n ? null\n : entity.customerContactId ?? null;\n if (customerChanged) {\n entity.customerEntityId = nextCustomerEntityId;\n }\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n entity.customerEntityId ?? null,\n snapshotContactId,\n );\n if (customerChanged) {\n entity.customerContactId = input.customerContactId ?? null;\n entity.billingAddressId = null;\n entity.shippingAddressId = null;\n entity.billingAddressSnapshot = null;\n entity.shippingAddressSnapshot = null;\n }\n }\n if (input.customerContactId !== undefined) {\n entity.customerContactId = input.customerContactId ?? null;\n if (entity.customerEntityId) {\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n entity.customerEntityId,\n input.customerContactId,\n );\n }\n }\n if (input.customerSnapshot !== undefined) {\n entity.customerSnapshot = input.customerSnapshot ?? null;\n }\n if (input.metadata !== undefined) {\n entity.metadata = input.metadata ?? null;\n }\n if (input.externalReference !== undefined) {\n const normalized =\n typeof input.externalReference === \"string\"\n ? input.externalReference.trim()\n : \"\";\n entity.externalReference = normalized.length ? normalized : null;\n }\n if (input.customerReference !== undefined) {\n const normalized =\n typeof input.customerReference === \"string\"\n ? input.customerReference.trim()\n : \"\";\n entity.customerReference = normalized.length ? normalized : null;\n }\n if (input.comment !== undefined) {\n const normalized =\n typeof input.comment === \"string\" ? input.comment.trim() : \"\";\n entity.comments = normalized.length ? normalized : null;\n }\n // After `comment`, so the canonical name wins when a payload carries both.\n if (input.comments !== undefined) {\n const normalized =\n typeof input.comments === \"string\" ? input.comments.trim() : \"\";\n entity.comments = normalized.length ? normalized : null;\n }\n // Orders only \u2014 SalesQuote has no internalNotes column. Reject rather than\n // ignore it on a quote: the field now satisfies the schema's refine on its\n // own, so silently dropping it would let an otherwise-empty payload run the\n // update, and a quote in `sent` status loses its acceptance token and reverts\n // to draft on any update that reaches execution.\n if (kind === \"quote\" && input.internalNotes !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.internal_notes_unsupported\",\n \"Internal notes are not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.internalNotes !== undefined) {\n const normalized =\n typeof input.internalNotes === \"string\" ? input.internalNotes.trim() : \"\";\n (entity as SalesOrder).internalNotes = normalized.length\n ? normalized\n : null;\n }\n if (typeof input.currencyCode === \"string\") {\n entity.currencyCode = input.currencyCode;\n }\n // Orders only \u2014 SalesQuote has no exchange_rate column, so the field is\n // rejected rather than ignored for the same reason as internalNotes above.\n if (kind === \"quote\" && input.exchangeRate !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.exchange_rate_unsupported\",\n \"Exchange rate is not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.exchangeRate !== undefined) {\n (entity as SalesOrder).exchangeRate = toNumericString(input.exchangeRate);\n }\n if (input.channelId !== undefined) {\n if (input.channelId === null) {\n entity.channelId = null;\n } else {\n const channel = await findOneWithDecryption(\n em,\n SalesChannel,\n {\n id: input.channelId,\n organizationId,\n tenantId,\n deletedAt: null,\n },\n {},\n { tenantId, organizationId },\n );\n if (!channel) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.channelInvalid\",\n \"Selected channel could not be found.\",\n ),\n });\n }\n entity.channelId = channel.id;\n }\n }\n if (input.statusEntryId !== undefined) {\n const statusValue = await resolveDictionaryEntryValue(\n em,\n input.statusEntryId,\n { tenantId },\n );\n if (input.statusEntryId && !statusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n (entity as any).statusEntryId = input.statusEntryId ?? null;\n (entity as any).status = statusValue;\n }\n // Orders only \u2014 SalesQuote has neither the entry-id nor the derived text\n // column for payment and fulfillment status, so both are rejected on a quote.\n if (kind === \"quote\" && input.paymentStatusEntryId !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.payment_status_unsupported\",\n \"Payment status is not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.paymentStatusEntryId !== undefined) {\n const paymentStatusValue = await resolveDictionaryEntryValue(\n em,\n input.paymentStatusEntryId,\n { tenantId },\n );\n if (input.paymentStatusEntryId && !paymentStatusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n // Both columns, like the statusEntryId branch above and like order create:\n // moving the id without its derived text leaves a self-contradicting row.\n (entity as SalesOrder).paymentStatusEntryId =\n input.paymentStatusEntryId ?? null;\n (entity as SalesOrder).paymentStatus = paymentStatusValue;\n }\n if (kind === \"quote\" && input.fulfillmentStatusEntryId !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.fulfillment_status_unsupported\",\n \"Fulfillment status is not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.fulfillmentStatusEntryId !== undefined) {\n const fulfillmentStatusValue = await resolveDictionaryEntryValue(\n em,\n input.fulfillmentStatusEntryId,\n { tenantId },\n );\n if (input.fulfillmentStatusEntryId && !fulfillmentStatusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n (entity as SalesOrder).fulfillmentStatusEntryId =\n input.fulfillmentStatusEntryId ?? null;\n (entity as SalesOrder).fulfillmentStatus = fulfillmentStatusValue;\n }\n if (input.placedAt !== undefined) {\n if (input.placedAt === null) {\n entity.placedAt = null;\n } else {\n const parsed = new Date(input.placedAt);\n entity.placedAt = Number.isNaN(parsed.getTime())\n ? entity.placedAt\n : parsed;\n }\n }\n if (\n input.expectedDeliveryAt !== undefined &&\n \"expectedDeliveryAt\" in entity\n ) {\n if (input.expectedDeliveryAt === null) {\n (entity as SalesOrder).expectedDeliveryAt = null;\n } else {\n const parsed = new Date(input.expectedDeliveryAt);\n (entity as SalesOrder).expectedDeliveryAt = Number.isNaN(parsed.getTime())\n ? (entity as SalesOrder).expectedDeliveryAt\n : parsed;\n }\n }\n if (input.shippingAddressId !== undefined) {\n entity.shippingAddressId = input.shippingAddressId ?? null;\n if (input.shippingAddressSnapshot === undefined) {\n entity.shippingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.shippingAddressId,\n );\n }\n }\n if (input.billingAddressId !== undefined) {\n entity.billingAddressId = input.billingAddressId ?? null;\n if (input.billingAddressSnapshot === undefined) {\n entity.billingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.billingAddressId,\n );\n }\n }\n if (input.shippingAddressSnapshot !== undefined) {\n entity.shippingAddressSnapshot = input.shippingAddressSnapshot ?? null;\n }\n if (input.billingAddressSnapshot !== undefined) {\n entity.billingAddressSnapshot = input.billingAddressSnapshot ?? null;\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.shippingMethodCode !== undefined\n ) {\n let shippingMethod: SalesShippingMethod | null = null;\n if (input.shippingMethodId) {\n shippingMethod = await em.findOne(SalesShippingMethod, {\n id: input.shippingMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!shippingMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.shippingMethodInvalid\",\n \"Selected shipping method could not be found.\",\n ),\n });\n }\n }\n (entity as any).shippingMethodId = input.shippingMethodId ?? null;\n (entity as any).shippingMethod = shippingMethod ?? null;\n (entity as any).shippingMethodCode =\n input.shippingMethodCode ?? shippingMethod?.code ?? null;\n if (input.shippingMethodSnapshot !== undefined) {\n (entity as any).shippingMethodSnapshot =\n input.shippingMethodSnapshot ?? null;\n } else {\n (entity as any).shippingMethodSnapshot = shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.paymentMethodCode !== undefined\n ) {\n let paymentMethod: SalesPaymentMethod | null = null;\n if (input.paymentMethodId) {\n paymentMethod = await em.findOne(SalesPaymentMethod, {\n id: input.paymentMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!paymentMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.paymentMethodInvalid\",\n \"Selected payment method could not be found.\",\n ),\n });\n }\n }\n (entity as any).paymentMethodId = input.paymentMethodId ?? null;\n (entity as any).paymentMethod = paymentMethod ?? null;\n (entity as any).paymentMethodCode =\n input.paymentMethodCode ?? paymentMethod?.code ?? null;\n if (input.paymentMethodSnapshot !== undefined) {\n (entity as any).paymentMethodSnapshot =\n input.paymentMethodSnapshot ?? null;\n } else {\n (entity as any).paymentMethodSnapshot = paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n\n if (input.tags !== undefined) {\n await syncSalesDocumentTags(em, {\n documentId: entity.id,\n kind,\n organizationId,\n tenantId,\n tagIds: input.tags,\n });\n }\n\n if (input.customFieldSetId !== undefined) {\n (entity as any).customFieldSetId = input.customFieldSetId ?? null;\n }\n\n if (input.customFields !== undefined) {\n const values =\n input.customFields &&\n typeof input.customFields === \"object\" &&\n !Array.isArray(input.customFields)\n ? (input.customFields as Record<string, unknown>)\n : {};\n // Same normalize path as create (`setDocumentCustomFieldsIfSupplied`) so\n // update and create agree on key/value shapes written to EAV.\n await setRecordCustomFields(em, {\n entityId: kind === \"order\" ? E.sales.sales_order : E.sales.sales_quote,\n recordId: entity.id,\n organizationId,\n tenantId,\n values: normalizeCustomFieldValues(values),\n });\n }\n}\n\nasync function loadQuoteSnapshot(\n em: EntityManager,\n id: string,\n): Promise<QuoteGraphSnapshot | null> {\n const quote = await findOneWithDecryption(em, SalesQuote, { id, deletedAt: null });\n if (!quote) return null;\n const decryptionScope = { tenantId: quote.tenantId, organizationId: quote.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n quoteCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"quote\" },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"quote\" },\n { populate: [\"tag\"] },\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [quote.id],\n tenantIdByRecord: { [quote.id]: quote.tenantId },\n organizationIdByRecord: { [quote.id]: quote.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"quote\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n quote: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteNumber: quote.quoteNumber,\n statusEntryId: quote.statusEntryId ?? null,\n status: quote.status ?? null,\n customerEntityId: quote.customerEntityId ?? null,\n customerContactId: quote.customerContactId ?? null,\n customerSnapshot: quote.customerSnapshot\n ? cloneJson(quote.customerSnapshot)\n : null,\n billingAddressId: quote.billingAddressId ?? null,\n shippingAddressId: quote.shippingAddressId ?? null,\n billingAddressSnapshot: quote.billingAddressSnapshot\n ? cloneJson(quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: quote.shippingAddressSnapshot\n ? cloneJson(quote.shippingAddressSnapshot)\n : null,\n currencyCode: quote.currencyCode,\n validFrom: quote.validFrom ? quote.validFrom.toISOString() : null,\n validUntil: quote.validUntil ? quote.validUntil.toISOString() : null,\n comments: quote.comments ?? null,\n taxInfo: quote.taxInfo ? cloneJson(quote.taxInfo) : null,\n shippingMethodId: quote.shippingMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n deliveryWindowId: quote.deliveryWindowId ?? null,\n deliveryWindowCode: quote.deliveryWindowCode ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n channelId: quote.channelId ?? null,\n shippingMethodSnapshot: quote.shippingMethodSnapshot\n ? cloneJson(quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: quote.deliveryWindowSnapshot\n ? cloneJson(quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: quote.paymentMethodSnapshot\n ? cloneJson(quote.paymentMethodSnapshot)\n : null,\n metadata: quote.metadata ? cloneJson(quote.metadata) : null,\n customFieldSetId: quote.customFieldSetId ?? null,\n customFields: quoteCustomFields[quote.id]\n ? cloneJson(quoteCustomFields[quote.id])\n : null,\n subtotalNetAmount: quote.subtotalNetAmount,\n subtotalGrossAmount: quote.subtotalGrossAmount,\n discountTotalAmount: quote.discountTotalAmount,\n taxTotalAmount: quote.taxTotalAmount,\n grandTotalNetAmount: quote.grandTotalNetAmount,\n grandTotalGrossAmount: quote.grandTotalGrossAmount,\n totalsSnapshot: quote.totalsSnapshot\n ? cloneJson(quote.totalsSnapshot)\n : null,\n lineItemCount: quote.lineItemCount,\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n quoteLineId:\n typeof adj.quoteLine === \"string\"\n ? adj.quoteLine\n : (adj.quoteLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n };\n}\n\nasync function loadOrderSnapshot(\n em: EntityManager,\n id: string,\n): Promise<OrderGraphSnapshot | null> {\n const order = await findOneWithDecryption(em, SalesOrder, { id, deletedAt: null });\n if (!order) return null;\n const decryptionScope = { tenantId: order.tenantId, organizationId: order.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n shipments,\n payments,\n orderCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"order\" },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"order\" },\n { populate: [\"tag\"] },\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesShipment, { order: order }),\n em.find(SalesPayment, { order: order }),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order,\n recordIds: [order.id],\n tenantIdByRecord: { [order.id]: order.tenantId },\n organizationIdByRecord: { [order.id]: order.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const shipmentSnapshots = (\n await Promise.all(\n shipments.map((entry) => loadShipmentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is ShipmentSnapshot => !!entry);\n const paymentSnapshots = (\n await Promise.all(\n payments.map((entry) => loadPaymentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is PaymentSnapshot => !!entry);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"order\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n order: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderNumber: order.orderNumber,\n statusEntryId: order.statusEntryId ?? null,\n status: order.status ?? null,\n fulfillmentStatusEntryId: order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: order.fulfillmentStatus ?? null,\n paymentStatusEntryId: order.paymentStatusEntryId ?? null,\n paymentStatus: order.paymentStatus ?? null,\n customerEntityId: order.customerEntityId ?? null,\n customerContactId: order.customerContactId ?? null,\n customerSnapshot: order.customerSnapshot\n ? cloneJson(order.customerSnapshot)\n : null,\n billingAddressId: order.billingAddressId ?? null,\n shippingAddressId: order.shippingAddressId ?? null,\n billingAddressSnapshot: order.billingAddressSnapshot\n ? cloneJson(order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: order.shippingAddressSnapshot\n ? cloneJson(order.shippingAddressSnapshot)\n : null,\n currencyCode: order.currencyCode,\n exchangeRate: order.exchangeRate ?? null,\n taxStrategyKey: order.taxStrategyKey ?? null,\n discountStrategyKey: order.discountStrategyKey ?? null,\n taxInfo: order.taxInfo ? cloneJson(order.taxInfo) : null,\n shippingMethodId: order.shippingMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n deliveryWindowId: order.deliveryWindowId ?? null,\n deliveryWindowCode: order.deliveryWindowCode ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n channelId: order.channelId ?? null,\n placedAt: order.placedAt ? order.placedAt.toISOString() : null,\n expectedDeliveryAt: order.expectedDeliveryAt\n ? order.expectedDeliveryAt.toISOString()\n : null,\n dueAt: order.dueAt ? order.dueAt.toISOString() : null,\n comments: order.comments ?? null,\n internalNotes: order.internalNotes ?? null,\n shippingMethodSnapshot: order.shippingMethodSnapshot\n ? cloneJson(order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: order.deliveryWindowSnapshot\n ? cloneJson(order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: order.paymentMethodSnapshot\n ? cloneJson(order.paymentMethodSnapshot)\n : null,\n metadata: order.metadata ? cloneJson(order.metadata) : null,\n customFieldSetId: order.customFieldSetId ?? null,\n customFields: orderCustomFields[order.id]\n ? cloneJson(orderCustomFields[order.id])\n : null,\n subtotalNetAmount: order.subtotalNetAmount,\n subtotalGrossAmount: order.subtotalGrossAmount,\n discountTotalAmount: order.discountTotalAmount,\n taxTotalAmount: order.taxTotalAmount,\n shippingNetAmount: order.shippingNetAmount,\n shippingGrossAmount: order.shippingGrossAmount,\n surchargeTotalAmount: order.surchargeTotalAmount,\n grandTotalNetAmount: order.grandTotalNetAmount,\n grandTotalGrossAmount: order.grandTotalGrossAmount,\n paidTotalAmount: order.paidTotalAmount,\n refundedTotalAmount: order.refundedTotalAmount,\n outstandingAmount: order.outstandingAmount,\n totalsSnapshot: order.totalsSnapshot\n ? cloneJson(order.totalsSnapshot)\n : null,\n lineItemCount: order.lineItemCount,\n totalsMode: order.totalsMode ?? \"computed\",\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n amountsMode: line.amountsMode ?? \"computed\",\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n orderLineId:\n typeof adj.orderLine === \"string\"\n ? adj.orderLine\n : (adj.orderLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n shipments: shipmentSnapshots,\n payments: paymentSnapshots,\n };\n}\n\nasync function loadInvoiceSnapshot(\n em: EntityManager,\n id: string,\n): Promise<InvoiceGraphSnapshot | null> {\n const invoice = await em.findOne(SalesInvoice, { id, deletedAt: null });\n if (!invoice) return null;\n const lines = await em.find(\n SalesInvoiceLine,\n { invoice: invoice },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [invoiceCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_invoice,\n recordIds: [invoice.id],\n tenantIdByRecord: { [invoice.id]: invoice.tenantId },\n organizationIdByRecord: { [invoice.id]: invoice.organizationId },\n }),\n ]);\n return {\n invoice: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n invoiceNumber: invoice.invoiceNumber,\n orderId: invoice.orderId ?? null,\n statusEntryId: invoice.statusEntryId ?? null,\n status: invoice.status ?? null,\n issueDate: invoice.issueDate ?? null,\n dueDate: invoice.dueDate ?? null,\n currencyCode: invoice.currencyCode,\n subtotalNetAmount: String(invoice.subtotalNetAmount),\n subtotalGrossAmount: String(invoice.subtotalGrossAmount),\n discountTotalAmount: String(invoice.discountTotalAmount),\n taxTotalAmount: String(invoice.taxTotalAmount),\n grandTotalNetAmount: String(invoice.grandTotalNetAmount),\n grandTotalGrossAmount: String(invoice.grandTotalGrossAmount),\n paidTotalAmount: String(invoice.paidTotalAmount),\n outstandingAmount: String(invoice.outstandingAmount),\n metadata: invoice.metadata ?? null,\n customFieldSetId: invoice.customFieldSetId ?? null,\n customFields: invoiceCustomFields[invoice.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n discountAmount: String(line.discountAmount),\n discountPercent: String(line.discountPercent),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\nasync function loadCreditMemoSnapshot(\n em: EntityManager,\n id: string,\n): Promise<CreditMemoGraphSnapshot | null> {\n const creditMemo = await em.findOne(SalesCreditMemo, { id, deletedAt: null });\n if (!creditMemo) return null;\n const lines = await em.find(\n SalesCreditMemoLine,\n { creditMemo: creditMemo },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [creditMemoCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_credit_memo,\n recordIds: [creditMemo.id],\n tenantIdByRecord: { [creditMemo.id]: creditMemo.tenantId },\n organizationIdByRecord: { [creditMemo.id]: creditMemo.organizationId },\n }),\n ]);\n return {\n creditMemo: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n creditMemoNumber: creditMemo.creditMemoNumber,\n orderId: creditMemo.order?.id ?? null,\n invoiceId: creditMemo.invoice?.id ?? null,\n statusEntryId: creditMemo.statusEntryId ?? null,\n status: creditMemo.status ?? null,\n reason: creditMemo.reason ?? null,\n issueDate: creditMemo.issueDate ?? null,\n currencyCode: creditMemo.currencyCode,\n subtotalNetAmount: String(creditMemo.subtotalNetAmount),\n subtotalGrossAmount: String(creditMemo.subtotalGrossAmount),\n taxTotalAmount: String(creditMemo.taxTotalAmount),\n grandTotalNetAmount: String(creditMemo.grandTotalNetAmount),\n grandTotalGrossAmount: String(creditMemo.grandTotalGrossAmount),\n metadata: creditMemo.metadata ?? null,\n customFieldSetId: creditMemo.customFieldSetId ?? null,\n customFields: creditMemoCustomFields[creditMemo.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\ntype DeletableEntity = {\n id?: string;\n organizationId?: string | null;\n tenantId?: string | null;\n};\n\nasync function queueDeletionSideEffects(\n dataEngine: DataEngine,\n entities: DeletableEntity[] | DeletableEntity | null | undefined,\n entityType: string,\n): Promise<void> {\n if (!entities) return;\n const list = Array.isArray(entities) ? entities : [entities];\n const tasks: Array<Promise<void>> = [];\n for (const entity of list) {\n if (!entity) continue;\n const id = typeof entity.id === \"string\" ? entity.id : null;\n if (!id) continue;\n tasks.push(\n emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity,\n identifiers: {\n id,\n organizationId: entity.organizationId ?? null,\n tenantId: entity.tenantId ?? null,\n },\n indexer: { entityType },\n }),\n );\n }\n if (tasks.length) await Promise.all(tasks);\n}\n\nfunction toNumeric(value: string | number | null | undefined): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n if (!Number.isNaN(parsed)) return parsed;\n }\n return 0;\n}\n\nconst UNIT_DICTIONARY_KEYS = [\"unit\", \"units\", \"measurement_units\"] as const;\nconst UOM_REFERENCE_UNITS = new Set<string>(REFERENCE_UNIT_CODES);\nconst UOM_NORMALIZED_SCALE = 6;\nconst UOM_NORMALIZED_MAX = 1_000_000_000_000;\nconst UNIT_PRICE_AUTOCONVERT_SCALE = 4;\n\ntype ProductUomState = {\n productId: string;\n baseUnitCode: string | null;\n defaultSalesUnit: string | null;\n unitPriceEnabled: boolean;\n unitPriceReferenceUnit: \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null;\n unitPriceBaseQuantity: string | null;\n conversionsByUnitKey: Map<string, CatalogProductUnitConversion>;\n};\n\ntype UomResolver = {\n dictionaryPromise: Promise<Dictionary | null> | null;\n unitExistsCache: Map<string, boolean>;\n productCache: Map<string, ProductUomState | null>;\n};\n\ntype NormalizeLineUomInput = {\n em: EntityManager;\n resolver: UomResolver;\n organizationId: string;\n tenantId: string;\n line: {\n productId?: string | null;\n productVariantId?: string | null;\n quantity?: number | string | null;\n quantityUnit?: string | null;\n unitPriceNet?: number | null;\n unitPriceGross?: number | null;\n normalizedQuantity?: number | string | null;\n normalizedUnit?: string | null;\n uomSnapshot?: Record<string, unknown> | null;\n };\n};\n\nfunction createUomResolver(): UomResolver {\n return {\n dictionaryPromise: null,\n unitExistsCache: new Map<string, boolean>(),\n productCache: new Map<string, ProductUomState | null>(),\n };\n}\n\nfunction normalizeUnitCode(value: unknown): string | null {\n return canonicalizeUnitCode(value);\n}\n\nfunction unitLookupKey(value: string | null | undefined): string | null {\n return toUnitLookupKey(value);\n}\n\nfunction roundNormalizedQuantity(value: number): number {\n const factor = 10 ** UOM_NORMALIZED_SCALE;\n if (!Number.isFinite(value)) return 0;\n return Math.round(value * factor) / factor;\n}\n\nfunction assertNormalizedPrecision(value: number) {\n if (!Number.isFinite(value) || Math.abs(value) >= UOM_NORMALIZED_MAX) {\n throw new CrudHttpError(422, { error: \"uom.precision_overflow\" });\n }\n}\n\nfunction toOptionalNumber(value: unknown): number | null {\n if (value === null || value === undefined) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n}\n\nfunction resolveSnapshotToBaseFactor(snapshot: unknown): number {\n if (!snapshot || typeof snapshot !== \"object\") return 1;\n const payload = snapshot as Record<string, unknown>;\n const factor = toOptionalNumber(payload.toBaseFactor ?? payload.to_base_factor);\n if (!Number.isFinite(factor) || !factor || factor <= 0) return 1;\n return factor;\n}\n\nfunction roundAutoConvertedUnitPrice(value: number): number | null {\n if (!Number.isFinite(value) || value < 0) return null;\n const factor = 10 ** UNIT_PRICE_AUTOCONVERT_SCALE;\n const rounded = Math.round((value + Number.EPSILON) * factor) / factor;\n return Number.isFinite(rounded) ? rounded : null;\n}\n\nfunction convertLineUnitPricesOnUnitChange(params: {\n existingSnapshot: SalesLineSnapshot | null;\n nextQuantityUnit: string | null;\n nextUomSnapshot: SalesLineUomSnapshot | Record<string, unknown> | null;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}): {\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n didConvert: boolean;\n} {\n if (!params.existingSnapshot) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const existingUnitPriceNet =\n typeof params.existingSnapshot.unitPriceNet === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceNet)\n ? params.existingSnapshot.unitPriceNet\n : null;\n const existingUnitPriceGross =\n typeof params.existingSnapshot.unitPriceGross === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceGross)\n ? params.existingSnapshot.unitPriceGross\n : null;\n const sameNumber = (left: number | null, right: number | null): boolean => {\n if (left === null || right === null) return left === right;\n return Math.abs(left - right) < 0.000001;\n };\n const shouldConvertNet =\n params.unitPriceNet === null ||\n sameNumber(params.unitPriceNet, existingUnitPriceNet);\n const shouldConvertGross =\n params.unitPriceGross === null ||\n sameNumber(params.unitPriceGross, existingUnitPriceGross);\n if (!shouldConvertNet && !shouldConvertGross) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousUnit = normalizeUnitCode(params.existingSnapshot?.quantityUnit ?? null);\n const nextUnit = normalizeUnitCode(params.nextQuantityUnit);\n if (!previousUnit || !nextUnit || previousUnit === nextUnit) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousFactor = resolveSnapshotToBaseFactor(\n params.existingSnapshot?.uomSnapshot ?? null,\n );\n const nextFactor = resolveSnapshotToBaseFactor(params.nextUomSnapshot);\n if (\n !Number.isFinite(previousFactor) ||\n previousFactor <= 0 ||\n !Number.isFinite(nextFactor) ||\n nextFactor <= 0\n ) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const convertAmount = (\n value: number | null,\n shouldConvert: boolean,\n ): number | null => {\n if (!shouldConvert) return value;\n if (value === null || !Number.isFinite(value)) return value;\n const converted = roundAutoConvertedUnitPrice((value / previousFactor) * nextFactor);\n return converted ?? value;\n };\n const nextUnitPriceNet = convertAmount(params.unitPriceNet, shouldConvertNet);\n const nextUnitPriceGross = convertAmount(\n params.unitPriceGross,\n shouldConvertGross,\n );\n const didConvert =\n nextUnitPriceNet !== params.unitPriceNet ||\n nextUnitPriceGross !== params.unitPriceGross;\n return {\n unitPriceNet: nextUnitPriceNet,\n unitPriceGross: nextUnitPriceGross,\n didConvert,\n };\n}\n\nfunction resolveReferenceUnit(\n value: unknown,\n): \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null {\n const normalized = toUnitLookupKey(value);\n if (!normalized) return null;\n if (!UOM_REFERENCE_UNITS.has(normalized)) return null;\n return normalized as \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\";\n}\n\nasync function resolveUnitDictionaryScoped(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n): Promise<Dictionary | null> {\n return findOneWithDecryption(\n em,\n Dictionary,\n {\n organizationId,\n tenantId,\n key: { $in: [...UNIT_DICTIONARY_KEYS] },\n deletedAt: null,\n isActive: true,\n },\n { orderBy: { createdAt: \"asc\" } },\n );\n}\n\nasync function assertUnitExists(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n unitCode: string,\n): Promise<void> {\n const normalizedCode = unitLookupKey(unitCode);\n if (!normalizedCode) return;\n const rawUnitCode = unitCode.trim();\n if (!resolver.dictionaryPromise) {\n resolver.dictionaryPromise = resolveUnitDictionaryScoped(\n em,\n organizationId,\n tenantId,\n );\n }\n const dictionary = await resolver.dictionaryPromise;\n if (!dictionary) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n const cacheKey = `${dictionary.id}:${normalizedCode}`;\n if (resolver.unitExistsCache.has(cacheKey)) {\n if (!resolver.unitExistsCache.get(cacheKey)) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n return;\n }\n const entry = await findOneWithDecryption(em, DictionaryEntry, {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n $or: [{ normalizedValue: normalizedCode }, { value: rawUnitCode }],\n });\n const exists = !!entry;\n resolver.unitExistsCache.set(cacheKey, exists);\n if (!exists) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n}\n\nasync function resolveProductUomState(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n productId: string,\n): Promise<ProductUomState | null> {\n if (resolver.productCache.has(productId)) {\n return resolver.productCache.get(productId) ?? null;\n }\n const product = await findOneWithDecryption(em, CatalogProduct, {\n id: productId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!product) {\n resolver.productCache.set(productId, null);\n return null;\n }\n const conversions = await findWithDecryption(em, CatalogProductUnitConversion, {\n product: product.id,\n organizationId,\n tenantId,\n deletedAt: null,\n isActive: true,\n });\n const conversionsByUnitKey = new Map<string, CatalogProductUnitConversion>();\n for (const conversion of conversions) {\n const key = unitLookupKey(conversion.unitCode);\n if (!key) continue;\n conversionsByUnitKey.set(key, conversion);\n }\n const state: ProductUomState = {\n productId: product.id,\n baseUnitCode: normalizeUnitCode(product.defaultUnit ?? null),\n defaultSalesUnit: normalizeUnitCode(product.defaultSalesUnit ?? null),\n unitPriceEnabled: Boolean(product.unitPriceEnabled),\n unitPriceReferenceUnit: resolveReferenceUnit(\n product.unitPriceReferenceUnit,\n ),\n unitPriceBaseQuantity: product.unitPriceBaseQuantity ?? null,\n conversionsByUnitKey,\n };\n resolver.productCache.set(productId, state);\n return state;\n}\n\nfunction buildUnitPriceReferenceSnapshot(params: {\n product: ProductUomState;\n toBaseFactor: number;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}) {\n if (!params.product.unitPriceEnabled) return undefined;\n const baseQuantityNumber = toNumeric(params.product.unitPriceBaseQuantity);\n const output: NonNullable<SalesLineUomSnapshot[\"unitPriceReference\"]> = {\n enabled: true,\n referenceUnitCode: params.product.unitPriceReferenceUnit ?? null,\n baseQuantity: params.product.unitPriceBaseQuantity ?? null,\n };\n if (\n !params.product.unitPriceReferenceUnit ||\n params.toBaseFactor <= 0 ||\n baseQuantityNumber <= 0\n ) {\n return output;\n }\n if (\n typeof params.unitPriceGross === \"number\" &&\n Number.isFinite(params.unitPriceGross)\n ) {\n output.grossPerReference = toNumericString(\n (params.unitPriceGross / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n if (\n typeof params.unitPriceNet === \"number\" &&\n Number.isFinite(params.unitPriceNet)\n ) {\n output.netPerReference = toNumericString(\n (params.unitPriceNet / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n return output;\n}\n\nasync function normalizeLineUom(input: NormalizeLineUomInput): Promise<{\n quantity: number;\n quantityUnit: string | null;\n normalizedQuantity: number;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n}> {\n const quantity = toNumeric(input.line.quantity);\n const existingSnapshot =\n input.line.uomSnapshot && typeof input.line.uomSnapshot === \"object\"\n ? (cloneJson(input.line.uomSnapshot) as SalesLineUomSnapshot)\n : null;\n const productId =\n typeof input.line.productId === \"string\" ? input.line.productId : null;\n const variantId =\n typeof input.line.productVariantId === \"string\"\n ? input.line.productVariantId\n : null;\n const enteredUnitInput = normalizeUnitCode(input.line.quantityUnit);\n if (!productId) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot ?? {\n version: 1,\n productId: null,\n productVariantId: variantId,\n baseUnitCode:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n enteredUnitCode: enteredUnitInput,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: { mode: \"half_up\", scale: UOM_NORMALIZED_SCALE },\n source: { conversionId: null, resolvedAt: new Date().toISOString() },\n },\n };\n }\n\n const productState = await resolveProductUomState(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n productId,\n );\n if (!productState) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const baseUnitCode = productState.baseUnitCode;\n const enteredUnitCode =\n enteredUnitInput ??\n productState.defaultSalesUnit ??\n baseUnitCode ??\n normalizeUnitCode(input.line.normalizedUnit);\n if (enteredUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitCode,\n );\n }\n if (baseUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n baseUnitCode,\n );\n }\n\n if (!baseUnitCode) {\n const requiresBase =\n Boolean(enteredUnitCode) ||\n productState.conversionsByUnitKey.size > 0 ||\n Boolean(productState.defaultSalesUnit);\n if (requiresBase) {\n throw new CrudHttpError(400, { error: \"uom.default_unit_missing\" });\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitCode ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ?? enteredUnitCode ?? null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const resolvedEnteredUnit = enteredUnitCode ?? baseUnitCode;\n const enteredKey = unitLookupKey(resolvedEnteredUnit);\n const baseKey = unitLookupKey(baseUnitCode);\n let toBaseFactor = 1;\n let conversionId: string | null = null;\n if (enteredKey && baseKey && enteredKey !== baseKey) {\n const conversion = productState.conversionsByUnitKey.get(enteredKey);\n if (!conversion) {\n throw new CrudHttpError(400, { error: \"uom.conversion_not_found\" });\n }\n toBaseFactor = toNumeric(conversion.toBaseFactor);\n conversionId = conversion.id;\n }\n if (!Number.isFinite(toBaseFactor) || toBaseFactor <= 0) {\n throw new CrudHttpError(400, { error: \"uom.invalid_factor\" });\n }\n const normalizedQuantity = roundNormalizedQuantity(quantity * toBaseFactor);\n assertNormalizedPrecision(normalizedQuantity);\n const unitPriceReference = buildUnitPriceReferenceSnapshot({\n product: productState,\n toBaseFactor,\n unitPriceNet: toOptionalNumber(input.line.unitPriceNet),\n unitPriceGross: toOptionalNumber(input.line.unitPriceGross),\n });\n const snapshot: SalesLineUomSnapshot = {\n version: 1,\n productId,\n productVariantId: variantId,\n baseUnitCode,\n enteredUnitCode: resolvedEnteredUnit,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: toNumericString(toBaseFactor) ?? \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: {\n mode: \"half_up\",\n scale: UOM_NORMALIZED_SCALE,\n },\n source: {\n conversionId,\n resolvedAt: new Date().toISOString(),\n },\n ...(unitPriceReference ? { unitPriceReference } : {}),\n };\n\n return {\n quantity,\n quantityUnit: resolvedEnteredUnit,\n normalizedQuantity,\n normalizedUnit: baseUnitCode,\n uomSnapshot: snapshot,\n };\n}\n\nfunction normalizeShippingMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n currencyCode?: string,\n): ShippingMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n currencyCode:\n typeof (snapshot as Record<string, unknown>).currencyCode === \"string\"\n ? ((snapshot as Record<string, unknown>).currencyCode as string)\n : (currencyCode ?? null),\n baseRateNet: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateNet ??\n (snapshot as Record<string, unknown>).base_rate_net) as\n | string\n | number\n | null,\n ),\n baseRateGross: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateGross ??\n (snapshot as Record<string, unknown>).base_rate_gross) as\n | string\n | number\n | null,\n ),\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction normalizePaymentMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n): PaymentMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n terms:\n typeof (snapshot as Record<string, unknown>).terms === \"string\"\n ? ((snapshot as Record<string, unknown>).terms as string)\n : null,\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction buildProviderContext(params: {\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n currencyCode: string;\n}) {\n return {\n shippingMethod: normalizeShippingMethodContext(\n params.shippingSnapshot,\n params.shippingMethodId,\n params.shippingMethodCode,\n params.currencyCode,\n ),\n paymentMethod: normalizePaymentMethodContext(\n params.paymentSnapshot,\n params.paymentMethodId,\n params.paymentMethodCode,\n ),\n };\n}\n\nfunction buildCalculationContext(params: {\n tenantId: string;\n organizationId: string;\n currencyCode: string;\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n}) {\n return {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n currencyCode: params.currencyCode,\n metadata: buildProviderContext({\n shippingSnapshot: params.shippingSnapshot,\n paymentSnapshot: params.paymentSnapshot,\n shippingMethodId: params.shippingMethodId,\n paymentMethodId: params.paymentMethodId,\n shippingMethodCode: params.shippingMethodCode,\n paymentMethodCode: params.paymentMethodCode,\n currencyCode: params.currencyCode,\n }),\n };\n}\n\nfunction mapOrderAdjustmentToDraft(\n adjustment: SalesOrderAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction mapQuoteAdjustmentToDraft(\n adjustment: SalesQuoteAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nasync function emitTotalsCalculated(\n eventBus: EventBus | null | undefined,\n payload: {\n documentKind: SalesDocumentKind;\n documentId: string;\n organizationId: string;\n tenantId: string;\n customerId?: string | null;\n totals: SalesDocumentCalculationResult[\"totals\"];\n lineCount: number;\n },\n): Promise<void> {\n if (!eventBus) return;\n await eventBus.emitEvent(\"sales.document.totals.calculated\", payload);\n}\n\nfunction isStoredRowSourcedLine(line: DocumentLineCreateInput): boolean {\n return (\n (line as Pick<SalesLineSnapshot, \"discountAmountFromStoredRow\">)\n .discountAmountFromStoredRow === true\n );\n}\n\nfunction isStoredRowSourcedTotalsLine(line: DocumentLineCreateInput): boolean {\n return (\n (line as Pick<SalesLineSnapshot, \"totalsFromStoredRow\">)\n .totalsFromStoredRow === true\n );\n}\n\nfunction createLineSnapshotFromInput(\n line: DocumentLineCreateInput,\n lineNumber: number,\n): SalesLineSnapshot {\n const quantity = Number(line.quantity ?? 0);\n const normalizedQuantity = toNumeric(\n line.normalizedQuantity ?? quantity,\n );\n return {\n lineNumber,\n kind: line.kind ?? \"product\",\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity,\n normalizedUnit:\n typeof line.normalizedUnit === \"string\"\n ? line.normalizedUnit\n : (line.quantityUnit ?? null),\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet ?? null,\n unitPriceGross: line.unitPriceGross ?? null,\n discountAmount: line.discountAmount ?? null,\n // Several callers re-run an already-mapped snapshot through here \u2014 the line\n // upsert and delete paths rebuild every line of the document, not just the\n // one being edited. Those inputs already carry a line total from a stored\n // row, so their origin must survive rather than be overwritten with the\n // caller default, or the untouched lines get re-inflated by quantity on\n // every write. Exactly one of the two origin fields is ever set, which is\n // the invariant the calculation engine relies on.\n ...(isStoredRowSourcedLine(line)\n ? { discountAmountFromStoredRow: true }\n : { discountAmountBasis: line.discountAmountBasis ?? \"unit\" }),\n // Carried independently of the discount origin above: a line upsert can\n // take its discount from the caller while its totals still come off the\n // stored row, and only the caller half is worth reconciling (#5644).\n ...(isStoredRowSourcedTotalsLine(line) ? { totalsFromStoredRow: true } : {}),\n discountPercent: line.discountPercent ?? null,\n taxRate: line.taxRate ?? null,\n taxAmount: line.taxAmount ?? null,\n totalNetAmount: line.totalNetAmount ?? null,\n totalGrossAmount: line.totalGrossAmount ?? null,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId:\n \"customFieldSetId\" in line\n ? ((line as any).customFieldSetId ?? null)\n : null,\n customFields:\n \"customFields\" in line && line.customFields\n ? cloneJson((line as any).customFields)\n : null,\n amountsMode: (line as { amountsMode?: SalesAmountsMode | null }).amountsMode ?? null,\n };\n}\n\nfunction createAdjustmentDraftFromInput(\n adjustment: DocumentAdjustmentCreateInput & { id?: string | null },\n): SalesAdjustmentDraft {\n const lineRef =\n \"quoteLineId\" in adjustment\n ? (adjustment as any).quoteLineId\n : (adjustment as any).orderLineId;\n if (adjustment.scope === \"line\" && lineRef) {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n return {\n id: typeof adjustment.id === \"string\" ? adjustment.id : undefined,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate ?? null,\n amountNet: adjustment.amountNet ?? null,\n amountGross: adjustment.amountGross ?? null,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction convertLineCalculationToEntityInput(\n lineResult: SalesLineCalculationResult,\n sourceLine: DocumentLineCreateInput,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const line = lineResult.line;\n // The gross-derived net repair heals core-owned rows; on an external line a\n // zero net is the caller's figure, not a defect to correct.\n const persistTotals = isExternalAmountsMode(line.amountsMode)\n ? <T,>(payload: T): T => payload\n : reconcileLinePersistedTotals;\n return persistTotals({\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind ?? \"product\",\n statusEntryId: sourceLine.statusEntryId ?? null,\n productId: sourceLine.productId ?? null,\n productVariantId: sourceLine.productVariantId ?? null,\n catalogSnapshot: sourceLine.catalogSnapshot\n ? cloneJson(sourceLine.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumericString(line.quantity) ?? \"0\",\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity:\n toNumericString(line.normalizedQuantity ?? line.quantity) ?? \"0\",\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet:\n toNumericString(\n line.unitPriceNet ??\n lineResult.netAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n unitPriceGross:\n toNumericString(\n line.unitPriceGross ??\n lineResult.grossAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n discountAmount: toNumericString(lineResult.discountAmount) ?? \"0\",\n discountPercent: toNumericString(line.discountPercent) ?? \"0\",\n taxRate: toNumericString(line.taxRate) ?? \"0\",\n taxAmount: toNumericString(lineResult.taxAmount) ?? \"0\",\n totalNetAmount: toNumericString(lineResult.netAmount) ?? \"0\",\n totalGrossAmount: toNumericString(lineResult.grossAmount) ?? \"0\",\n // Conditional: this converter also serves quote lines, which have no column.\n ...(line.amountsMode ? { amountsMode: line.amountsMode } : {}),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: sourceLine.promotionSnapshot\n ? cloneJson(sourceLine.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: sourceLine.customFieldSetId ?? null,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n });\n}\n\nfunction convertAdjustmentResultToEntityInput(\n adjustment: SalesAdjustmentDraft,\n sourceAdjustment: DocumentAdjustmentCreateInput | null,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const metadata = adjustment.metadata ? cloneJson(adjustment.metadata) : null;\n const resolvedPosition =\n sourceAdjustment?.position ??\n (adjustment.position !== null && adjustment.position !== undefined\n ? adjustment.position\n : index);\n return {\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumericString(adjustment.rate) ?? \"0\",\n amountNet: toNumericString(adjustment.amountNet) ?? \"0\",\n amountGross:\n toNumericString(adjustment.amountGross ?? adjustment.amountNet) ?? \"0\",\n currencyCode: adjustment.currencyCode ?? null,\n metadata,\n position: resolvedPosition,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n };\n}\n\nasync function applyOrderLineResults(params: {\n em: EntityManager;\n order: SalesOrder;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesOrderLine[];\n}): Promise<void> {\n const { em, order, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: order.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesOrderLine, {\n order,\n id: sourceLine.id ?? undefined,\n reservedQuantity: existing?.reservedQuantity ?? \"0\",\n fulfilledQuantity: existing?.fulfilledQuantity ?? \"0\",\n invoicedQuantity: existing?.invoicedQuantity ?? \"0\",\n returnedQuantity: existing?.returnedQuantity ?? \"0\",\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n order,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function applyQuoteLineResults(params: {\n em: EntityManager;\n quote: SalesQuote;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesQuoteLine[];\n}): Promise<void> {\n const { em, quote, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: quote.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesQuoteLine, {\n quote,\n id: sourceLine.id ?? undefined,\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n quote,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function replaceQuoteLines(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n lineInputs: QuoteLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: quote.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesQuoteLine, {\n quote,\n ...entityInput,\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceQuoteAdjustments(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: QuoteAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesQuoteAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n quote,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesQuoteAdjustment, {\n id: adjustmentId,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? quote.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.quoteLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustmentId,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nasync function replaceOrderLines(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n lineInputs: OrderLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: order.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesOrderLine, {\n order,\n ...entityInput,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceOrderAdjustments(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: OrderAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesOrderAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n order,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesOrderAdjustment, {\n id: adjustmentId,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? order.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.orderLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustmentId,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nfunction applyQuoteTotals(\n quote: SalesQuote,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n quote.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n quote.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n quote.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n quote.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n quote.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n quote.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n quote.totalsSnapshot = cloneJson(totals);\n quote.lineItemCount = lineCount;\n}\n\nfunction applyOrderTotals(\n order: SalesOrder,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n order.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n order.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n order.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n order.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n order.shippingNetAmount = toNumericString(totals.shippingNetAmount) ?? \"0\";\n order.shippingGrossAmount =\n toNumericString(totals.shippingGrossAmount) ?? \"0\";\n order.surchargeTotalAmount =\n toNumericString(totals.surchargeTotalAmount) ?? \"0\";\n order.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n order.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n order.paidTotalAmount = toNumericString(totals.paidTotalAmount) ?? \"0\";\n order.refundedTotalAmount =\n toNumericString(totals.refundedTotalAmount) ?? \"0\";\n order.outstandingAmount = toNumericString(totals.outstandingAmount) ?? \"0\";\n order.totalsSnapshot = cloneJson(totals);\n order.lineItemCount = lineCount;\n}\n\nfunction applyOrderLineAmountsFromCalculation(params: {\n em: EntityManager;\n lines: SalesOrderLine[];\n calculation: SalesDocumentCalculationResult;\n amountsMode: SalesAmountsMode;\n}): void {\n const { em, lines, calculation, amountsMode } = params;\n lines.forEach((line, index) => {\n const result = calculation.lines[index];\n if (!result) return;\n line.amountsMode = amountsMode;\n line.discountAmount = toNumericString(result.discountAmount) ?? \"0\";\n line.taxAmount = toNumericString(result.taxAmount) ?? \"0\";\n line.totalNetAmount = toNumericString(result.netAmount) ?? \"0\";\n line.totalGrossAmount = toNumericString(result.grossAmount) ?? \"0\";\n em.persist(line);\n });\n}\n\nfunction normalizePaymentTotal(value: unknown): number {\n if (typeof value === \"number\" && Number.isFinite(value))\n return Math.max(value, 0);\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? Math.max(parsed, 0) : 0;\n }\n return 0;\n}\n\nfunction resolveExistingPaymentTotals(order: SalesOrder) {\n return {\n paidTotalAmount: normalizePaymentTotal(order.paidTotalAmount),\n refundedTotalAmount: normalizePaymentTotal(order.refundedTotalAmount),\n };\n}\n\nfunction ensureQuoteScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction ensureOrderScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction normalizeTagIds(tags?: Array<string | null | undefined>): string[] {\n if (!Array.isArray(tags)) return [];\n const set = new Set<string>();\n tags.forEach((id) => {\n if (typeof id === \"string\" && id.trim().length > 0) set.add(id.trim());\n });\n return Array.from(set);\n}\n\n// A loaded assignment exposes its tag as an entity, an unwrapped id or the raw\n// column depending on how it was fetched; the snapshot loaders read it the same\n// defensive way. Returns null when the id cannot be determined, which callers\n// must treat as \"unrecognised\" rather than as a match.\nfunction readAssignmentTagId(assignment: {\n tag?: unknown;\n}): string | null {\n const tag = (assignment as { tag?: unknown }).tag;\n if (typeof tag === \"string\") return tag;\n return (\n (tag as { id?: string } | null | undefined)?.id ??\n (assignment as { tag_id?: string }).tag_id ??\n null\n );\n}\n\nfunction buildTagChange(\n beforeTags: TagAssignmentSnapshot[] | undefined,\n afterTags: TagAssignmentSnapshot[] | undefined,\n): { from: string[]; to: string[] } | null {\n const beforeIds = normalizeTagIds(beforeTags?.map((tag) => tag.tagId));\n const afterIds = normalizeTagIds(afterTags?.map((tag) => tag.tagId));\n beforeIds.sort((a, b) => a.localeCompare(b));\n afterIds.sort((a, b) => a.localeCompare(b));\n if (\n beforeIds.length === afterIds.length &&\n beforeIds.every((id, index) => id === afterIds[index])\n ) {\n return null;\n }\n return { from: beforeIds, to: afterIds };\n}\n\nfunction buildDocumentUpdateChangeKeys(kind: SalesDocumentKind, input: DocumentUpdateInput): string[] {\n const keys = new Set<string>();\n if (kind === \"order\") {\n if (input.orderNumber !== undefined) keys.add(\"orderNumber\");\n } else {\n if (input.quoteNumber !== undefined) keys.add(\"quoteNumber\");\n }\n if (input.statusEntryId !== undefined) {\n keys.add(\"statusEntryId\");\n keys.add(\"status\");\n }\n if (input.customerEntityId !== undefined) {\n keys.add(\"customerEntityId\");\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n keys.add(\"billingAddressId\");\n keys.add(\"shippingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (input.customerContactId !== undefined) {\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n }\n if (input.customerSnapshot !== undefined) keys.add(\"customerSnapshot\");\n if (input.metadata !== undefined) keys.add(\"metadata\");\n if (input.comment !== undefined) keys.add(\"comments\");\n if (input.comments !== undefined) keys.add(\"comments\");\n if (input.currencyCode !== undefined) keys.add(\"currencyCode\");\n if (input.channelId !== undefined) keys.add(\"channelId\");\n if (kind === \"order\") {\n if (input.internalNotes !== undefined) keys.add(\"internalNotes\");\n if (input.placedAt !== undefined) keys.add(\"placedAt\");\n if (input.expectedDeliveryAt !== undefined) keys.add(\"expectedDeliveryAt\");\n if (input.exchangeRate !== undefined) keys.add(\"exchangeRate\");\n if (input.paymentStatusEntryId !== undefined) {\n keys.add(\"paymentStatusEntryId\");\n keys.add(\"paymentStatus\");\n }\n if (input.fulfillmentStatusEntryId !== undefined) {\n keys.add(\"fulfillmentStatusEntryId\");\n keys.add(\"fulfillmentStatus\");\n }\n }\n if (\n input.shippingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined\n ) {\n keys.add(\"shippingAddressId\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (\n input.billingAddressId !== undefined ||\n input.billingAddressSnapshot !== undefined\n ) {\n keys.add(\"billingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined\n ) {\n keys.add(\"shippingMethodId\");\n keys.add(\"shippingMethodCode\");\n keys.add(\"shippingMethodSnapshot\");\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined\n ) {\n keys.add(\"paymentMethodId\");\n keys.add(\"paymentMethodCode\");\n keys.add(\"paymentMethodSnapshot\");\n }\n if (input.customFieldSetId !== undefined) keys.add(\"customFieldSetId\");\n if (input.customFields !== undefined) keys.add(\"customFields\");\n return Array.from(keys);\n}\n\n// Writes only the difference between the stored and the incoming tag set, and\n// no-ops when they are equal. The previous delete-all-then-reinsert rewrote an\n// unchanged set on every save that carried `tags`: on a large\n// sales_document_tag_assignments that delete was the dominant cost of a bulk\n// import, and it also reset each assignment's id/created_at, churned the unique\n// index and left two dead tuples per document per save.\n//\n// Semantics are unchanged \u2014 a tag removed out of band still differs from the\n// incoming set and is still restored. Removals go through the UnitOfWork rather\n// than nativeDelete because the assignments are loaded (managed) here; a native\n// delete would leave stale identities behind. The add and remove sets are\n// disjoint by construction, so MikroORM's insert-before-delete commit order can\n// never transiently violate the unique (tag_id, document_id, document_kind).\n//\n// The assignment read below is deliberately scoped by document only, with no\n// organization/tenant predicate \u2014 unlike the display reads in\n// api/documents/factory.ts, and unlike the tag-scope check above. It has to\n// match the scope of the unique constraint it reconciles against, which spans\n// (tag_id, document_id, document_kind) and no scope columns. Narrowing the read\n// would hide a mis-scoped row from the diff, put its tag in the add set, and\n// turn the insert into a unique-constraint violation. The document itself is\n// already scope-checked by the caller before this runs.\nasync function syncSalesDocumentTags(\n em: EntityManager,\n params: {\n documentId: string;\n kind: SalesDocumentKind;\n organizationId: string;\n tenantId: string;\n tagIds?: Array<string | null | undefined> | null;\n },\n) {\n if (params.tagIds === undefined) return;\n const tagIds = normalizeTagIds(params.tagIds);\n const byId = new Map<string, SalesDocumentTag>();\n if (tagIds.length > 0) {\n const tagsInScope = await em.find(SalesDocumentTag, {\n id: { $in: tagIds },\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n });\n if (tagsInScope.length !== tagIds.length) {\n throw new CrudHttpError(400, {\n error: \"One or more tags not found for this scope\",\n });\n }\n tagsInScope.forEach((tag) => byId.set(tag.id, tag));\n }\n const existing = await em.find(SalesDocumentTagAssignment, {\n documentId: params.documentId,\n documentKind: params.kind,\n });\n const existingByTagId = new Map<string, (typeof existing)[number]>();\n existing.forEach((assignment) => {\n const tagId = readAssignmentTagId(assignment);\n if (tagId) existingByTagId.set(tagId, assignment);\n });\n const wanted = new Set(tagIds);\n const toRemove = existing.filter((assignment) => {\n const tagId = readAssignmentTagId(assignment);\n return tagId === null || !wanted.has(tagId);\n });\n const toAdd = tagIds.filter((tagId) => !existingByTagId.has(tagId));\n if (toRemove.length === 0 && toAdd.length === 0) return;\n toRemove.forEach((assignment) => em.remove(assignment));\n for (const tagId of toAdd) {\n const tag = byId.get(tagId);\n if (!tag) continue;\n const assignment = em.create(SalesDocumentTagAssignment, {\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n documentId: params.documentId,\n documentKind: params.kind,\n tag,\n order:\n params.kind === \"order\"\n ? em.getReference(SalesOrder, params.documentId)\n : null,\n quote:\n params.kind === \"quote\"\n ? em.getReference(SalesQuote, params.documentId)\n : null,\n });\n em.persist(assignment);\n }\n}\n\nfunction applyQuoteSnapshot(\n quote: SalesQuote,\n snapshot: QuoteGraphSnapshot[\"quote\"],\n): void {\n quote.organizationId = snapshot.organizationId;\n quote.tenantId = snapshot.tenantId;\n quote.quoteNumber = snapshot.quoteNumber;\n quote.statusEntryId = snapshot.statusEntryId ?? null;\n quote.status = snapshot.status ?? null;\n quote.customerEntityId = snapshot.customerEntityId ?? null;\n quote.customerContactId = snapshot.customerContactId ?? null;\n quote.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n quote.billingAddressId = snapshot.billingAddressId ?? null;\n quote.shippingAddressId = snapshot.shippingAddressId ?? null;\n quote.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n quote.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n quote.currencyCode = snapshot.currencyCode;\n quote.validFrom = snapshot.validFrom ? new Date(snapshot.validFrom) : null;\n quote.validUntil = snapshot.validUntil ? new Date(snapshot.validUntil) : null;\n quote.comments = snapshot.comments ?? null;\n quote.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n quote.shippingMethodId = snapshot.shippingMethodId ?? null;\n quote.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n quote.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n quote.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n quote.paymentMethodId = snapshot.paymentMethodId ?? null;\n quote.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n quote.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n quote.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n quote.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n quote.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n quote.channelId = snapshot.channelId ?? null;\n quote.customFieldSetId = snapshot.customFieldSetId ?? null;\n quote.subtotalNetAmount = snapshot.subtotalNetAmount;\n quote.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n quote.discountTotalAmount = snapshot.discountTotalAmount;\n quote.taxTotalAmount = snapshot.taxTotalAmount;\n quote.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n quote.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n quote.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n quote.lineItemCount = snapshot.lineItemCount;\n}\n\nfunction applyOrderSnapshot(\n order: SalesOrder,\n snapshot: OrderGraphSnapshot[\"order\"],\n): void {\n order.organizationId = snapshot.organizationId;\n order.tenantId = snapshot.tenantId;\n order.orderNumber = snapshot.orderNumber;\n order.statusEntryId = snapshot.statusEntryId ?? null;\n order.status = snapshot.status ?? null;\n order.fulfillmentStatusEntryId = snapshot.fulfillmentStatusEntryId ?? null;\n order.fulfillmentStatus = snapshot.fulfillmentStatus ?? null;\n order.paymentStatusEntryId = snapshot.paymentStatusEntryId ?? null;\n order.paymentStatus = snapshot.paymentStatus ?? null;\n order.customerEntityId = snapshot.customerEntityId ?? null;\n order.customerContactId = snapshot.customerContactId ?? null;\n order.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n order.billingAddressId = snapshot.billingAddressId ?? null;\n order.shippingAddressId = snapshot.shippingAddressId ?? null;\n order.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n order.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n order.currencyCode = snapshot.currencyCode;\n order.exchangeRate = snapshot.exchangeRate ?? null;\n order.taxStrategyKey = snapshot.taxStrategyKey ?? null;\n order.discountStrategyKey = snapshot.discountStrategyKey ?? null;\n order.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n order.shippingMethodId = snapshot.shippingMethodId ?? null;\n order.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n order.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n order.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n order.paymentMethodId = snapshot.paymentMethodId ?? null;\n order.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n order.channelId = snapshot.channelId ?? null;\n order.placedAt = snapshot.placedAt ? new Date(snapshot.placedAt) : null;\n order.expectedDeliveryAt = snapshot.expectedDeliveryAt\n ? new Date(snapshot.expectedDeliveryAt)\n : null;\n order.dueAt = snapshot.dueAt ? new Date(snapshot.dueAt) : null;\n order.comments = snapshot.comments ?? null;\n order.internalNotes = snapshot.internalNotes ?? null;\n order.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n order.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n order.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n order.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n order.customFieldSetId = snapshot.customFieldSetId ?? null;\n order.subtotalNetAmount = snapshot.subtotalNetAmount;\n order.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n order.discountTotalAmount = snapshot.discountTotalAmount;\n order.taxTotalAmount = snapshot.taxTotalAmount;\n order.shippingNetAmount = snapshot.shippingNetAmount;\n order.shippingGrossAmount = snapshot.shippingGrossAmount;\n order.surchargeTotalAmount = snapshot.surchargeTotalAmount;\n order.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n order.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n order.paidTotalAmount = snapshot.paidTotalAmount;\n order.refundedTotalAmount = snapshot.refundedTotalAmount;\n order.outstandingAmount = snapshot.outstandingAmount;\n order.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n order.lineItemCount = snapshot.lineItemCount;\n // Restored with the amounts, never separately: the lines come back with their\n // own mode, so omitting this leaves a mixed document the next write recomputes.\n order.totalsMode = snapshot.totalsMode ?? \"computed\";\n}\n\nasync function assertQuoteGraphUndoCurrent(\n em: EntityManager,\n quoteId: string,\n expected: QuoteGraphSnapshot,\n): Promise<void> {\n const current = await loadQuoteSnapshot(em, quoteId);\n const unchanged =\n !!current &&\n sameIds(current.lines, expected.lines) &&\n sameIds(current.adjustments, expected.adjustments) &&\n sameRecords(current.notes, expected.notes) &&\n sameRecords(current.tags, expected.tags) &&\n sameRecords(current.addresses, expected.addresses);\n if (!unchanged) return throwDocumentUndoStale(\"quote\");\n}\n\nasync function undoQuoteGraph(\n ctx: CommandRuntimeContext,\n before: QuoteGraphSnapshot,\n after: QuoteGraphSnapshot | null | undefined,\n): Promise<void> {\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n let restored: SalesQuote | undefined;\n await em.transactional(async (tx) => {\n const quote = await findOneWithDecryption(\n tx,\n SalesQuote,\n { id: before.quote.id },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n { tenantId: before.quote.tenantId, organizationId: before.quote.organizationId },\n );\n if (after) {\n if (!quote) return throwDocumentUndoStale(\"quote\");\n await assertQuoteGraphUndoCurrent(tx, quote.id, after);\n tx.clear();\n }\n restored = await restoreQuoteGraph(tx, before, quote && after ? after : null);\n await tx.flush();\n });\n if (!restored) return;\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudUndoSideEffects({\n dataEngine,\n action: \"updated\",\n entity: restored,\n identifiers: {\n id: restored.id,\n organizationId: restored.organizationId,\n tenantId: restored.tenantId,\n },\n indexer: { entityType: E.sales.sales_quote },\n });\n}\n\nasync function restoreQuoteGraph(\n em: EntityManager,\n snapshot: QuoteGraphSnapshot,\n verified: QuoteGraphSnapshot | null = null,\n): Promise<SalesQuote> {\n let quote = await findOneWithDecryption(\n em,\n SalesQuote,\n { id: snapshot.quote.id },\n {},\n {\n tenantId: snapshot.quote.tenantId,\n organizationId: snapshot.quote.organizationId,\n },\n );\n if (!quote) {\n quote = em.create(SalesQuote, {\n id: snapshot.quote.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n quoteNumber: snapshot.quote.quoteNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n validFrom: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : null,\n validUntil: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n comments: snapshot.quote.comments ?? null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n channelId: snapshot.quote.channelId ?? null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(quote);\n }\n applyQuoteSnapshot(quote, snapshot.quote);\n await em.flush();\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n const existingAdjustments = await em.find(\n SalesQuoteAdjustment,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n const verifiedIds = (entries: ReadonlyArray<{ id: string }> | undefined) =>\n verified ? { id: { $in: (entries ?? []).map((entry) => entry.id) } } : {};\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n ...verifiedIds(verified?.addresses),\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n ...verifiedIds(verified?.notes),\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n ...verifiedIds(verified?.tags),\n });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesQuoteLine, {\n id: line.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesQuoteAdjustment, {\n id: adjustment.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.quoteLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"quote\",\n contextId: quote.id,\n order: null,\n quote,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n tag,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.quote.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: toSnapshotCustomFieldWriteValues(snapshot.quote.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: line.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: toSnapshotCustomFieldWriteValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustment.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: toSnapshotCustomFieldWriteValues(adjustment.customFields),\n });\n }\n\n return quote;\n}\n\nasync function throwDocumentUndoStale(kind: \"order\" | \"quote\"): Promise<never> {\n const { translate } = await resolveTranslations();\n throw new CrudHttpError(409, {\n error:\n kind === \"order\"\n ? translate(\n \"sales.documents.errors.undoStaleOrder\",\n \"This change can no longer be undone because the order was changed afterwards.\",\n )\n : translate(\n \"sales.documents.errors.undoStaleQuote\",\n \"This change can no longer be undone because the quote was changed afterwards.\",\n ),\n });\n}\n\nfunction canonicalizeForComparison(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value\n .map(canonicalizeForComparison)\n .map((entry) => ({ entry, key: JSON.stringify(entry) }))\n .sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0))\n .map(({ entry }) => entry);\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))\n .map((key) => [key, canonicalizeForComparison((value as Record<string, unknown>)[key])]),\n );\n }\n return value;\n}\n\nfunction toComparableRecords(\n entries: ReadonlyArray<{ id: string }> | null | undefined,\n): Map<string, unknown> {\n const records = new Map<string, unknown>();\n for (const entry of entries ?? []) {\n records.set(entry.id, canonicalizeForComparison(JSON.parse(JSON.stringify(entry))));\n }\n return records;\n}\n\nfunction withoutAllocationIds(\n payments: ReadonlyArray<PaymentSnapshot> | null | undefined,\n): Array<PaymentSnapshot> {\n return (payments ?? []).map((payment) => ({\n ...payment,\n allocations: (payment.allocations ?? []).map((allocation) =>\n Object.fromEntries(Object.entries(allocation).filter(([key]) => key !== \"id\")),\n ),\n }));\n}\n\nfunction sameRecords(\n current: ReadonlyArray<{ id: string }> | null | undefined,\n expected: ReadonlyArray<{ id: string }> | null | undefined,\n): boolean {\n const currentRecords = toComparableRecords(current);\n const expectedRecords = toComparableRecords(expected);\n if (currentRecords.size !== expectedRecords.size) return false;\n for (const [id, record] of expectedRecords) {\n if (!currentRecords.has(id)) return false;\n if (!isDeepStrictEqual(currentRecords.get(id), record)) return false;\n }\n return true;\n}\n\nfunction sameIds(\n current: ReadonlyArray<{ id: string }> | null | undefined,\n expected: ReadonlyArray<{ id: string }> | null | undefined,\n): boolean {\n const currentIds = new Set((current ?? []).map((entry) => entry.id));\n const expectedIds = (expected ?? []).map((entry) => entry.id);\n return (\n currentIds.size === expectedIds.length &&\n expectedIds.every((id) => currentIds.has(id))\n );\n}\n\nfunction sameLineProgress(\n current: ReadonlyArray<SalesLineSnapshot>,\n expected: ReadonlyArray<SalesLineSnapshot> | null | undefined,\n): boolean {\n if (!sameIds(current, expected)) return false;\n const expectedById = new Map((expected ?? []).map((line) => [line.id, line]));\n return current.every((line) => {\n const target = expectedById.get(line.id);\n return (\n !!target &&\n Number(line.fulfilledQuantity ?? 0) === Number(target.fulfilledQuantity ?? 0) &&\n Number(line.returnedQuantity ?? 0) === Number(target.returnedQuantity ?? 0)\n );\n });\n}\n\nasync function assertOrderGraphUndoCurrent(\n em: EntityManager,\n orderId: string,\n expected: OrderGraphSnapshot,\n): Promise<void> {\n const current = await loadOrderSnapshot(em, orderId);\n if (!current) return throwDocumentUndoStale(\"order\");\n const lineIds = current.lines.map((line) => line.id);\n const [returnCount, invoiceLineCount, creditMemoLineCount] = await Promise.all([\n em.count(SalesReturn, { order: orderId }),\n lineIds.length\n ? em.count(SalesInvoiceLine, { orderLine: { $in: lineIds } })\n : Promise.resolve(0),\n lineIds.length\n ? em.count(SalesCreditMemoLine, { orderLine: { $in: lineIds } })\n : Promise.resolve(0),\n ]);\n if (returnCount > 0 || invoiceLineCount > 0 || creditMemoLineCount > 0) {\n return throwDocumentUndoStale(\"order\");\n }\n const unchanged =\n sameLineProgress(current.lines, expected.lines) &&\n sameIds(current.adjustments, expected.adjustments) &&\n sameRecords(current.shipments, expected.shipments) &&\n sameRecords(withoutAllocationIds(current.payments), withoutAllocationIds(expected.payments)) &&\n sameRecords(current.notes, expected.notes) &&\n sameRecords(current.tags, expected.tags) &&\n sameRecords(current.addresses, expected.addresses);\n if (!unchanged) return throwDocumentUndoStale(\"order\");\n}\n\nasync function lockOrderForUndo(\n em: EntityManager,\n orderId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<boolean> {\n const order = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: orderId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n );\n if (!order) return false;\n await em.find(\n SalesOrderLine,\n { order: orderId },\n { lockMode: LockMode.PESSIMISTIC_WRITE, orderBy: { id: \"asc\" } },\n );\n return true;\n}\n\nasync function withVerifiedOrderGraph(\n ctx: CommandRuntimeContext,\n expected: OrderGraphSnapshot | null | undefined,\n scope: { orderId: string; tenantId: string; organizationId: string },\n work: (tx: EntityManager, exists: boolean) => Promise<void>,\n): Promise<void> {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n await em.transactional(async (tx) => {\n const exists = await lockOrderForUndo(tx, scope.orderId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n });\n if (exists && expected) {\n await assertOrderGraphUndoCurrent(tx, scope.orderId, expected);\n tx.clear();\n }\n await work(tx, exists);\n });\n}\n\nasync function undoOrderGraph(\n ctx: CommandRuntimeContext,\n before: OrderGraphSnapshot,\n after: OrderGraphSnapshot | null | undefined,\n): Promise<void> {\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n let restored: SalesOrder | undefined;\n await withVerifiedOrderGraph(\n ctx,\n after,\n {\n orderId: before.order.id,\n tenantId: before.order.tenantId,\n organizationId: before.order.organizationId,\n },\n async (tx, exists) => {\n if (!exists && after) await throwDocumentUndoStale(\"order\");\n restored = await restoreOrderGraph(tx, before, exists ? after : null);\n await tx.flush();\n },\n );\n if (!restored) return;\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudUndoSideEffects({\n dataEngine,\n action: \"updated\",\n entity: restored,\n identifiers: {\n id: restored.id,\n organizationId: restored.organizationId,\n tenantId: restored.tenantId,\n },\n indexer: { entityType: E.sales.sales_order },\n });\n}\n\nasync function restoreOrderGraph(\n em: EntityManager,\n snapshot: OrderGraphSnapshot,\n verified: OrderGraphSnapshot | null = null,\n): Promise<SalesOrder> {\n let order = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: snapshot.order.id },\n {},\n {\n tenantId: snapshot.order.tenantId,\n organizationId: snapshot.order.organizationId,\n },\n );\n let existingLines: SalesOrderLine[] = [];\n if (order) {\n existingLines = await em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n );\n await assertShippedOrderGraphRestorable(\n em,\n order,\n existingLines,\n snapshot,\n );\n }\n if (!order) {\n order = em.create(SalesOrder, {\n id: snapshot.order.id,\n organizationId: snapshot.order.organizationId,\n tenantId: snapshot.order.tenantId,\n orderNumber: snapshot.order.orderNumber,\n statusEntryId: snapshot.order.statusEntryId ?? null,\n status: snapshot.order.status ?? null,\n fulfillmentStatusEntryId: snapshot.order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: snapshot.order.fulfillmentStatus ?? null,\n paymentStatusEntryId: snapshot.order.paymentStatusEntryId ?? null,\n paymentStatus: snapshot.order.paymentStatus ?? null,\n customerEntityId: snapshot.order.customerEntityId ?? null,\n customerContactId: snapshot.order.customerContactId ?? null,\n customerSnapshot: snapshot.order.customerSnapshot\n ? cloneJson(snapshot.order.customerSnapshot)\n : null,\n billingAddressId: snapshot.order.billingAddressId ?? null,\n shippingAddressId: snapshot.order.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.order.billingAddressSnapshot\n ? cloneJson(snapshot.order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.order.shippingAddressSnapshot\n ? cloneJson(snapshot.order.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.order.currencyCode,\n exchangeRate: snapshot.order.exchangeRate ?? null,\n taxStrategyKey: snapshot.order.taxStrategyKey ?? null,\n discountStrategyKey: snapshot.order.discountStrategyKey ?? null,\n taxInfo: snapshot.order.taxInfo\n ? cloneJson(snapshot.order.taxInfo)\n : null,\n shippingMethodId: snapshot.order.shippingMethodId ?? null,\n shippingMethodCode: snapshot.order.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.order.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.order.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.order.paymentMethodId ?? null,\n paymentMethodCode: snapshot.order.paymentMethodCode ?? null,\n channelId: snapshot.order.channelId ?? null,\n placedAt: snapshot.order.placedAt\n ? new Date(snapshot.order.placedAt)\n : null,\n expectedDeliveryAt: snapshot.order.expectedDeliveryAt\n ? new Date(snapshot.order.expectedDeliveryAt)\n : null,\n dueAt: snapshot.order.dueAt ? new Date(snapshot.order.dueAt) : null,\n comments: snapshot.order.comments ?? null,\n internalNotes: snapshot.order.internalNotes ?? null,\n shippingMethodSnapshot: snapshot.order.shippingMethodSnapshot\n ? cloneJson(snapshot.order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.order.deliveryWindowSnapshot\n ? cloneJson(snapshot.order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.order.paymentMethodSnapshot\n ? cloneJson(snapshot.order.paymentMethodSnapshot)\n : null,\n metadata: snapshot.order.metadata\n ? cloneJson(snapshot.order.metadata)\n : null,\n customFieldSetId: snapshot.order.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.order.subtotalNetAmount,\n subtotalGrossAmount: snapshot.order.subtotalGrossAmount,\n discountTotalAmount: snapshot.order.discountTotalAmount,\n taxTotalAmount: snapshot.order.taxTotalAmount,\n shippingNetAmount: snapshot.order.shippingNetAmount,\n shippingGrossAmount: snapshot.order.shippingGrossAmount,\n surchargeTotalAmount: snapshot.order.surchargeTotalAmount,\n grandTotalNetAmount: snapshot.order.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.order.grandTotalGrossAmount,\n paidTotalAmount: snapshot.order.paidTotalAmount,\n refundedTotalAmount: snapshot.order.refundedTotalAmount,\n outstandingAmount: snapshot.order.outstandingAmount,\n totalsSnapshot: snapshot.order.totalsSnapshot\n ? cloneJson(snapshot.order.totalsSnapshot)\n : null,\n lineItemCount: snapshot.order.lineItemCount,\n totalsMode: snapshot.order.totalsMode ?? \"computed\",\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n }\n applyOrderSnapshot(order, snapshot.order);\n await em.flush();\n const existingAdjustments = await em.find(\n SalesOrderAdjustment,\n { order: order.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n const shipmentSnapshots = Array.isArray(snapshot.shipments)\n ? snapshot.shipments\n : [];\n const paymentSnapshots = Array.isArray(snapshot.payments)\n ? snapshot.payments\n : [];\n const existingShipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = existingShipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n existingShipments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n const verifiedIds = (entries: ReadonlyArray<{ id: string }> | undefined) =>\n verified ? { id: { $in: (entries ?? []).map((entry) => entry.id) } } : {};\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n ...verifiedIds(verified?.addresses),\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n ...verifiedIds(verified?.notes),\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n ...verifiedIds(verified?.tags),\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n // Not repaired from gross: an external line's net is the caller's figure.\n totalNetAmount: isExternalAmountsMode(line.amountsMode)\n ? line.totalNetAmount\n : toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n amountsMode: line.amountsMode ?? \"computed\",\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesOrderAdjustment, {\n id: adjustment.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.orderLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n quote: null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n tag,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.order.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: toSnapshotCustomFieldWriteValues(snapshot.order.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: line.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: toSnapshotCustomFieldWriteValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustment.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: toSnapshotCustomFieldWriteValues(adjustment.customFields),\n });\n }\n\n for (const shipment of shipmentSnapshots) {\n await restoreShipmentSnapshot(em, shipment);\n }\n\n for (const payment of paymentSnapshots) {\n await restorePaymentSnapshot(em, payment);\n }\n\n return order;\n}\n\nconst createQuoteCommand: CommandHandler<\n QuoteCreateInput,\n { quoteId: string }\n> = {\n id: \"sales.quotes.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = quoteCreateSchema.parse(rawInput ?? {});\n const quoteNumber =\n typeof initial.quoteNumber === \"string\" &&\n initial.quoteNumber.trim().length\n ? initial.quoteNumber.trim()\n : (\n await generator.generate({\n kind: \"quote\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = quoteCreateSchema.parse({ ...initial, quoteNumber });\n const ensuredQuoteNumber = parsed.quoteNumber ?? quoteNumber;\n if (!ensuredQuoteNumber) {\n throw new CrudHttpError(400, { error: \"Quote number is required.\" });\n }\n ensureQuoteScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n const quoteStatus = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n const quoteId = randomUUID();\n const quote = em.create(SalesQuote, {\n id: quoteId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteNumber: ensuredQuoteNumber,\n statusEntryId: parsed.statusEntryId ?? null,\n status: quoteStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n validFrom: parsed.validFrom ?? null,\n validUntil: parsed.validUntil ?? null,\n comments: parsed.comments ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n channelId: parsed.channelId ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n await assertAmountsModeUnsupportedOnQuote(parsed.lines ?? []);\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n quoteLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n quoteAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n }),\n )\n : null;\n\n const lineSnapshots: SalesLineSnapshot[] = normalizedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the quote header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(quote);\n await replaceQuoteLines(em, quote, calculation, normalizedLineInputs);\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: quote.id,\n kind: \"quote\",\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n tagIds: parsed.tags,\n });\n await setDocumentCustomFieldsIfSupplied(em, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customFields: parsed.customFields,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.quotes.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.quote.created\",\n );\n if (typeDef) {\n const totalAmount =\n quote.grandTotalGrossAmount && quote.currencyCode\n ? `${quote.grandTotalGrossAmount} ${quote.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.quotes.manage\",\n bodyVariables: {\n quoteNumber: quote.quoteNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:quote\",\n sourceEntityId: quote.id,\n linkHref: `/backend/sales/quotes/${quote.id}`,\n });\n\n // Bulk-import backfills opt out of the per-record notification fan-out (and its inline\n // e-mail delivery); interactive creates are unaffected.\n if (!ctx.bulkImport?.skipNotifications) {\n await notificationService.createForFeature(notificationInput, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId ?? null,\n });\n }\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n logger.error(\"sales.quotes.create failed to create notification\", { err });\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: quote,\n identifiers: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n events: quoteCrudEvents,\n indexer: { entityType: E.sales.sales_quote },\n actorUserId: ctx.auth?.sub ?? null,\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { quoteId: quote.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.create\", \"Create sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n ensureQuoteScope(ctx, after.quote.organizationId, after.quote.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n await em.transactional(async (tx) => {\n const quote = await findOneWithDecryption(\n tx,\n SalesQuote,\n { id: after.quote.id },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n {\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n },\n );\n if (!quote) return;\n await assertQuoteGraphUndoCurrent(tx, quote.id, after);\n await tx.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await tx.nativeDelete(SalesQuoteLine, { quote: quote.id });\n tx.remove(quote);\n await tx.flush();\n });\n },\n};\n\nconst deleteQuoteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string }\n> = {\n id: \"sales.quotes.delete\",\n async prepare(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await findOneWithDecryption(em, SalesQuote, { id });\n if (!quote)\n throw notFound(\"Sales quote not found\");\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const [addresses, notes, tags, adjustments, lines] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: quote.id,\n documentKind: \"quote\",\n },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: quote.id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n }),\n em.find(SalesQuoteAdjustment, { quote: quote.id }),\n em.find(SalesQuoteLine, { quote: quote.id }),\n ]);\n // Delete the quote and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n em.remove(quote);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, quote, E.sales.sales_quote),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_quote_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_quote_adjustment,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { quoteId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.delete\", \"Delete sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: before.quote.id,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\ntype TotalsCalculatedPayload = Parameters<typeof emitTotalsCalculated>[1];\ntype LockedGraphWrite<TResult> = {\n result: TResult;\n calculation: SalesDocumentCalculationResult;\n};\ntype LockedGraphSnapshots<TSnapshot> = {\n before: TSnapshot | null;\n after: TSnapshot | null;\n};\ntype LockedGraphKind<TDocument, TSnapshot> = {\n documentKind: SalesDocumentKind;\n lock: (\n em: EntityManager,\n ctx: CommandRuntimeContext,\n documentId: string,\n missingMessage: string,\n ) => Promise<TDocument>;\n loadSnapshot: (em: EntityManager, documentId: string) => Promise<TSnapshot | null>;\n snapshots: WeakMap<object, LockedGraphSnapshots<TSnapshot>>;\n};\n\nconst lockedGraphWriteInputs = new WeakSet<object>();\nconst lockedOrderGraphSnapshots = new WeakMap<object, LockedGraphSnapshots<OrderGraphSnapshot>>();\nconst lockedQuoteGraphSnapshots = new WeakMap<object, LockedGraphSnapshots<QuoteGraphSnapshot>>();\n\nfunction resolveRequestDecryptionScope(ctx: CommandRuntimeContext) {\n return {\n tenantId: ctx.auth?.tenantId ?? undefined,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? undefined,\n };\n}\n\nasync function lockOrderForTotalsWrite(\n em: EntityManager,\n ctx: CommandRuntimeContext,\n orderId: string,\n missingOrderMessage: string,\n): Promise<SalesOrder> {\n const existingOrder = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: orderId, deletedAt: null },\n {},\n resolveRequestDecryptionScope(ctx),\n );\n if (!existingOrder) throw notFound(missingOrderMessage);\n ensureOrderScope(ctx, existingOrder.organizationId, existingOrder.tenantId);\n const scope = {\n tenantId: existingOrder.tenantId,\n organizationId: existingOrder.organizationId,\n };\n if (!(await lockSalesDocumentRow(em, \"sales_orders\", orderId, scope))) {\n throw notFound(missingOrderMessage);\n }\n const order = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: orderId, deletedAt: null, ...scope },\n { refresh: true },\n scope,\n );\n if (!order) throw notFound(missingOrderMessage);\n await enforceSalesDocumentOptimisticLock(ctx, order, SALES_RESOURCE_KIND_ORDER);\n return order;\n}\n\nasync function lockQuoteForTotalsWrite(\n em: EntityManager,\n ctx: CommandRuntimeContext,\n quoteId: string,\n missingQuoteMessage: string,\n): Promise<SalesQuote> {\n const existingQuote = await findOneWithDecryption(\n em,\n SalesQuote,\n { id: quoteId, deletedAt: null },\n {},\n resolveRequestDecryptionScope(ctx),\n );\n if (!existingQuote) throw notFound(missingQuoteMessage);\n ensureQuoteScope(ctx, existingQuote.organizationId, existingQuote.tenantId);\n const scope = {\n tenantId: existingQuote.tenantId,\n organizationId: existingQuote.organizationId,\n };\n if (!(await lockSalesDocumentRow(em, \"sales_quotes\", quoteId, scope))) {\n throw notFound(missingQuoteMessage);\n }\n const quote = await findOneWithDecryption(\n em,\n SalesQuote,\n { id: quoteId, deletedAt: null, ...scope },\n { refresh: true },\n scope,\n );\n if (!quote) throw notFound(missingQuoteMessage);\n await enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n return quote;\n}\n\nfunction buildTotalsCalculatedPayload(\n documentKind: SalesDocumentKind,\n document: SalesOrder | SalesQuote,\n calculation: SalesDocumentCalculationResult,\n): TotalsCalculatedPayload {\n return {\n documentKind,\n documentId: document.id,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n customerId: document.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n };\n}\n\nasync function emitCommittedTotalsCalculated(\n ctx: CommandRuntimeContext,\n payload: TotalsCalculatedPayload | null,\n): Promise<void> {\n if (!payload) return;\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n await emitTotalsCalculated(eventBus, payload);\n}\n\nconst lockedOrderGraphKind: LockedGraphKind<SalesOrder, OrderGraphSnapshot> = {\n documentKind: \"order\",\n lock: lockOrderForTotalsWrite,\n loadSnapshot: loadOrderSnapshot,\n snapshots: lockedOrderGraphSnapshots,\n};\n\nconst lockedQuoteGraphKind: LockedGraphKind<SalesQuote, QuoteGraphSnapshot> = {\n documentKind: \"quote\",\n lock: lockQuoteForTotalsWrite,\n loadSnapshot: loadQuoteSnapshot,\n snapshots: lockedQuoteGraphSnapshots,\n};\n\nfunction markLockedGraphWrite(input: object): Record<string, never> {\n lockedGraphWriteInputs.add(input);\n return {};\n}\n\nasync function writeLockedDocumentGraph<\n TDocument extends SalesOrder | SalesQuote,\n TSnapshot,\n TResult extends object,\n>(\n kind: LockedGraphKind<TDocument, TSnapshot>,\n input: object,\n ctx: CommandRuntimeContext,\n documentId: string,\n missingMessage: string,\n write: (em: EntityManager, document: TDocument) => Promise<LockedGraphWrite<TResult>>,\n): Promise<TResult> {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const captureSnapshots = lockedGraphWriteInputs.has(input);\n let written!: LockedGraphWrite<TResult>;\n let totalsEvent!: TotalsCalculatedPayload;\n let before: TSnapshot | null = null;\n let after: TSnapshot | null = null;\n await withAtomicFlush(\n em,\n [\n async () => {\n const document = await kind.lock(em, ctx, documentId, missingMessage);\n if (captureSnapshots) before = await kind.loadSnapshot(em, document.id);\n written = await write(em, document);\n totalsEvent = buildTotalsCalculatedPayload(\n kind.documentKind,\n document,\n written.calculation,\n );\n },\n ...(captureSnapshots\n ? [\n async () => {\n em.clear();\n after = await kind.loadSnapshot(em, documentId);\n },\n ]\n : []),\n ],\n { transaction: true },\n );\n if (captureSnapshots) kind.snapshots.set(written.result, { before, after });\n await emitCommittedTotalsCalculated(ctx, totalsEvent);\n return written.result;\n}\n\nfunction writeLockedOrderGraph<TResult extends object>(\n input: object,\n ctx: CommandRuntimeContext,\n orderId: string,\n missingOrderMessage: string,\n write: (em: EntityManager, order: SalesOrder) => Promise<LockedGraphWrite<TResult>>,\n): Promise<TResult> {\n return writeLockedDocumentGraph(lockedOrderGraphKind, input, ctx, orderId, missingOrderMessage, write);\n}\n\nfunction writeLockedQuoteGraph<TResult extends object>(\n input: object,\n ctx: CommandRuntimeContext,\n quoteId: string,\n missingQuoteMessage: string,\n write: (em: EntityManager, quote: SalesQuote) => Promise<LockedGraphWrite<TResult>>,\n): Promise<TResult> {\n return writeLockedDocumentGraph(lockedQuoteGraphKind, input, ctx, quoteId, missingQuoteMessage, write);\n}\n\nfunction resolveLockedOrderGraphBefore(\n result: object,\n preparedBefore: unknown,\n): OrderGraphSnapshot | undefined {\n return (\n lockedOrderGraphSnapshots.get(result)?.before ??\n (preparedBefore as OrderGraphSnapshot | undefined)\n );\n}\n\nfunction resolveLockedQuoteGraphBefore(\n result: object,\n preparedBefore: unknown,\n): QuoteGraphSnapshot | undefined {\n return (\n lockedQuoteGraphSnapshots.get(result)?.before ??\n (preparedBefore as QuoteGraphSnapshot | undefined)\n );\n}\n\nasync function captureLockedOrderGraphAfter(\n ctx: CommandRuntimeContext,\n result: object,\n orderId: string,\n): Promise<OrderGraphSnapshot | null> {\n const locked = lockedOrderGraphSnapshots.get(result);\n if (locked) return locked.after;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, orderId);\n}\n\nasync function captureLockedQuoteGraphAfter(\n ctx: CommandRuntimeContext,\n result: object,\n quoteId: string,\n): Promise<QuoteGraphSnapshot | null> {\n const locked = lockedQuoteGraphSnapshots.get(result);\n if (locked) return locked.after;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, quoteId);\n}\n\nconst updateQuoteCommand: CommandHandler<\n DocumentUpdateInput,\n { quote: SalesQuote }\n> = {\n id: \"sales.quotes.update\",\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, parsed.id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n await assertAmountsModeUnsupportedOnQuote([parsed]);\n documentEditSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n let quote!: SalesQuote;\n let totalsEvent: TotalsCalculatedPayload | null = null;\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, optional sent-token reset, and totals recalc\n // atomically. applyDocumentUpdate/replace*/setRecordCustomFields flush\n // mid-build, so without a transaction a later failure would leave a\n // half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n quote = await lockQuoteForTotalsWrite(em, ctx, parsed.id, \"Sales quote not found\");\n const shouldInvalidateSentToken = (quote.status ?? null) === \"sent\";\n await applyDocumentUpdate({\n kind: \"quote\",\n entity: quote,\n input: parsed,\n em,\n });\n // After applyDocumentUpdate, not before it: the reset must not happen\n // for an update that turns out to be invalid, or a rejected payload\n // still strips a sent quote of its acceptance link.\n if (shouldInvalidateSentToken) {\n quote.acceptanceToken = null;\n quote.sentAt = null;\n quote.status = \"draft\";\n quote.statusEntryId = await resolveStatusEntryIdByValue(em, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n value: \"draft\",\n });\n }\n },\n // Scalar mutations above are persisted by withAtomicFlush's per-phase\n // flush boundary before the recalc reads below run any query on the same\n // EntityManager. MikroORM v7 would otherwise silently discard pending\n // scalar changes on `quote` when the `em.find` line/adjustment lookups\n // reset the changeset (see SPEC-018).\n async () => {\n if (shouldRecalculateTotals) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n totalsEvent = buildTotalsCalculatedPayload(\"quote\", quote, calculation);\n }\n quote.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n await emitCommittedTotalsCalculated(ctx, totalsEvent);\n // Same as sales.orders.update (#6217): refresh the query-index projection so\n // customFields written in applyDocumentUpdate are visible on the next list GET.\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: quote,\n identifiers: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n indexer: { entityType: E.sales.sales_quote },\n actorUserId: ctx.auth?.sub ?? null,\n });\n const resourceKind =\n deriveResourceFromCommandId(updateQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { quote };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quote.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.quote as unknown as Record<string, unknown>,\n after.quote as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"quote\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.quotes.update\", \"Update sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quote.id,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\n/**\n * Output contracts for the order commands, consumed by the workflows context\n * ledger through `commandRegistry.outputSchemaOf`.\n *\n * `sales.orders.update` genuinely returns the mutated `SalesOrder` entity, not\n * an id \u2014 so the schema describes the entity's own scalar columns. It is a\n * curated subset, not the whole entity: relation properties (`channel`,\n * `shippingMethod`, `lines`) are ORM references that do not survive the JSON\n * context column, and the jsonb snapshot blobs carry no pickable shape. Zod\n * objects do not claim exhaustiveness, so naming a subset stays honest while\n * keeping the variable picker readable.\n */\nconst orderEntityOutputSchema = z.object({\n id: z.string().uuid(),\n organizationId: z.string().uuid(),\n tenantId: z.string().uuid(),\n orderNumber: z.string(),\n channelId: z.string().uuid().nullable().optional(),\n customerEntityId: z.string().uuid().nullable().optional(),\n currencyCode: z.string(),\n status: z.string().nullable().optional(),\n statusEntryId: z.string().uuid().nullable().optional(),\n fulfillmentStatus: z.string().nullable().optional(),\n paymentStatus: z.string().nullable().optional(),\n subtotalNetAmount: z.string(),\n subtotalGrossAmount: z.string(),\n discountTotalAmount: z.string(),\n taxTotalAmount: z.string(),\n grandTotalNetAmount: z.string(),\n grandTotalGrossAmount: z.string(),\n paidTotalAmount: z.string(),\n outstandingAmount: z.string(),\n lineItemCount: z.number(),\n placedAt: z.date().nullable().optional(),\n dueAt: z.date().nullable().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nconst orderUpdateOutputSchema = z.object({ order: orderEntityOutputSchema });\n\nconst orderIdOutputSchema = z.object({ orderId: z.string().uuid() });\n\nconst updateOrderCommand: CommandHandler<\n DocumentUpdateInput,\n { order: SalesOrder }\n> = {\n id: \"sales.orders.update\",\n outputSchema: orderUpdateOutputSchema,\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, parsed.id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n let order!: SalesOrder;\n let previousStatus: string | null = null;\n let nextTotalsMode: SalesAmountsMode = \"computed\";\n let totalsModeChanged = false;\n let externalHeaderSupplied = false;\n let suppliedTotals: Partial<SalesDocumentAmounts> | null = null;\n let statusChangeNote: SalesNote | null = null;\n let totalsEvent: TotalsCalculatedPayload | null = null;\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, totals recalc, and status-change note atomically.\n // applyDocumentUpdate/replace*/setRecordCustomFields flush mid-build, so\n // without a transaction a later failure would leave a half-updated order\n // committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n order = await lockOrderForTotalsWrite(em, ctx, parsed.id, \"Sales order not found\");\n const currentTotalsMode: SalesAmountsMode = order.totalsMode ?? \"computed\";\n nextTotalsMode = parsed.totalsMode ?? currentTotalsMode;\n totalsModeChanged = nextTotalsMode !== currentTotalsMode;\n externalHeaderSupplied =\n isExternalAmountsMode(nextTotalsMode) && hasAnySuppliedHeaderTotal(parsed);\n if (!totalsModeChanged && !externalHeaderSupplied) {\n documentEditSchema.parse(rawInput ?? {});\n }\n if (isExternalAmountsMode(nextTotalsMode) && (totalsModeChanged || externalHeaderSupplied)) {\n await requireOrderTotalsForExternalWrite(parsed);\n }\n suppliedTotals = isExternalAmountsMode(nextTotalsMode)\n ? externalHeaderSupplied\n ? buildExternalHeaderTotals(parsed)\n : readPersistedHeaderTotals(order)\n : null;\n previousStatus = normalizeStatusValue(order.status);\n if (parsed.statusEntryId && !isCancelledOrderStatus(previousStatus)) {\n const requestedStatus = normalizeStatusValue(\n await resolveDictionaryEntryValue(em, parsed.statusEntryId, {\n tenantId: order.tenantId,\n }),\n );\n if (isCancelledOrderStatus(requestedStatus)) {\n await assertOrderCanBeCancelled(em, order);\n }\n }\n await applyDocumentUpdate({\n kind: \"order\",\n entity: order,\n input: parsed,\n em,\n });\n },\n // Scalar mutations above are persisted by withAtomicFlush's per-phase\n // flush boundary before the recalc reads and the status-change-note\n // lookup below run any query on the same EntityManager. MikroORM v7 would\n // otherwise silently discard pending scalar changes on `order` when the\n // `em.find` lines/adjustments or appendOrderStatusChangeNote queries\n // reset the changeset (see SPEC-018).\n async () => {\n if (shouldRecalculateTotals || totalsModeChanged || externalHeaderSupplied) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n // Leaving external: the stored tax and gross are the source's figures,\n // and the computed path honours both verbatim while it re-derives net,\n // so they must be re-derived too or net + tax \u2260 gross (#7925).\n const leavingExternal =\n totalsModeChanged && !isExternalAmountsMode(nextTotalsMode);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n ...(leavingExternal ? { taxAmount: null, totalGrossAmount: null } : {}),\n amountsMode: nextTotalsMode,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode: nextTotalsMode,\n suppliedTotals,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n if (totalsModeChanged) {\n applyOrderLineAmountsFromCalculation({\n em,\n lines: existingLines,\n calculation,\n amountsMode: nextTotalsMode,\n });\n order.totalsMode = nextTotalsMode;\n }\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n totalsEvent = buildTotalsCalculatedPayload(\"order\", order, calculation);\n }\n statusChangeNote = await appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth: ctx.auth ?? null,\n });\n order.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n await emitCommittedTotalsCalculated(ctx, totalsEvent);\n emitOrderLifecycleEventsForTransition({ order, previousStatus });\n // Refresh the query-index projection (including customValues). Create already\n // did this; update used to only invalidate the HTTP CRUD cache, so a PUT that\n // wrote EAV custom fields still returned the pre-update values on the next\n // GET `/api/sales/orders?id=` (list reads cf_* from the index, #6217).\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: order,\n identifiers: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n indexer: { entityType: E.sales.sales_order },\n actorUserId: ctx.auth?.sub ?? null,\n });\n if (statusChangeNote) {\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: statusChangeNote,\n identifiers: {\n id: statusChangeNote.id,\n organizationId: statusChangeNote.organizationId,\n tenantId: statusChangeNote.tenantId,\n },\n indexer: { entityType: E.sales.sales_note },\n });\n }\n const resourceKind =\n deriveResourceFromCommandId(updateOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { order };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.order.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.order as unknown as Record<string, unknown>,\n after.order as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"order\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.orders.update\", \"Update sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.order.id,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst createOrderCommand: CommandHandler<\n OrderCreateInput,\n { orderId: string; warnings?: OrderPaymentLedgerWarning[] }\n> = {\n id: \"sales.orders.create\",\n outputSchema: orderIdOutputSchema,\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const deprecatedPaymentLedgerFields = resolveSuppliedOrderPaymentLedgerFields(rawInput)\n const initial = orderCreateSchema.parse(rawInput ?? {});\n if (deprecatedPaymentLedgerFields.length && !warnedDeprecatedOrderPaymentLedgerInput) {\n warnedDeprecatedOrderPaymentLedgerInput = true\n logger.warn(\"sales.orders.create ignored deprecated payment ledger input\", {\n code: ORDER_PAYMENT_LEDGER_WARNING_CODE,\n fields: deprecatedPaymentLedgerFields,\n })\n }\n const orderNumber =\n typeof initial.orderNumber === \"string\" &&\n initial.orderNumber.trim().length\n ? initial.orderNumber.trim()\n : (\n await generator.generate({\n kind: \"order\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = orderCreateSchema.parse({ ...initial, orderNumber });\n const ensuredOrderNumber = parsed.orderNumber ?? orderNumber;\n if (!ensuredOrderNumber) {\n throw new CrudHttpError(400, { error: \"Order number is required.\" });\n }\n ensureOrderScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n // Soft-resolve the cache so the per-order status/fulfillment/payment dictionary lookups are\n // memoized across a bulk import; degrades to a straight EM read when no cache is registered.\n const dictionaryCache = ctx.container.resolve(\"cache\", { allowUnregistered: true }) as\n | CacheStrategy\n | undefined;\n const [status, fulfillmentStatus, paymentStatus] = await Promise.all([\n resolveCachedDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: parsed.tenantId }, dictionaryCache),\n resolveCachedDictionaryEntryValue(em, parsed.fulfillmentStatusEntryId ?? null, { tenantId: parsed.tenantId }, dictionaryCache),\n resolveCachedDictionaryEntryValue(em, parsed.paymentStatusEntryId ?? null, { tenantId: parsed.tenantId }, dictionaryCache),\n ]);\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n\n const orderId = randomUUID()\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderNumber: ensuredOrderNumber,\n externalReference: parsed.externalReference ?? null,\n customerReference: parsed.customerReference ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n fulfillmentStatusEntryId: parsed.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus,\n paymentStatusEntryId: parsed.paymentStatusEntryId ?? null,\n paymentStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n exchangeRate:\n typeof parsed.exchangeRate === \"number\"\n ? toNumericString(parsed.exchangeRate)\n : null,\n taxStrategyKey: parsed.taxStrategyKey ?? null,\n discountStrategyKey: parsed.discountStrategyKey ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n channelId: parsed.channelId ?? null,\n placedAt: parsed.placedAt ?? null,\n expectedDeliveryAt: parsed.expectedDeliveryAt ?? null,\n dueAt: parsed.dueAt ?? null,\n comments: parsed.comments ?? null,\n internalNotes: parsed.internalNotes ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n shippingNetAmount: \"0\",\n shippingGrossAmount: \"0\",\n surchargeTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n orderLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n orderAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n }),\n )\n : null;\n\n const totalsMode: SalesAmountsMode = parsed.totalsMode ?? \"computed\";\n await assertUniformAmountsMode(totalsMode, normalizedLineInputs);\n const modedLineInputs = normalizedLineInputs.map((line) => ({\n ...line,\n amountsMode: totalsMode,\n }));\n if (isExternalAmountsMode(totalsMode)) {\n await assertExternalHeaderComplete(parsed);\n for (const [index, line] of modedLineInputs.entries()) {\n await assertExternalLineComplete(line, line.lineNumber ?? index + 1);\n }\n }\n order.totalsMode = totalsMode;\n const suppliedTotals: Partial<SalesDocumentAmounts> | null = isExternalAmountsMode(totalsMode)\n ? buildExternalHeaderTotals(parsed)\n : null;\n const lineSnapshots: SalesLineSnapshot[] = modedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode,\n suppliedTotals,\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the order header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(order);\n await replaceOrderLines(em, order, calculation, modedLineInputs);\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: order.id,\n kind: \"order\",\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n tagIds: parsed.tags,\n });\n await setDocumentCustomFieldsIfSupplied(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customFields: parsed.customFields,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.orders.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.order.created\",\n );\n if (typeDef) {\n const totalAmount =\n order.grandTotalGrossAmount && order.currencyCode\n ? `${order.grandTotalGrossAmount} ${order.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.orders.manage\",\n bodyVariables: {\n orderNumber: order.orderNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:order\",\n sourceEntityId: order.id,\n linkHref: `/backend/sales/orders/${order.id}`,\n });\n\n // Bulk-import backfills opt out of the per-record notification fan-out (and its inline\n // e-mail delivery); interactive creates are unaffected.\n if (!ctx.bulkImport?.skipNotifications) {\n await notificationService.createForFeature(notificationInput, {\n tenantId: order.tenantId,\n organizationId: order.organizationId ?? null,\n });\n }\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n logger.error(\"sales.orders.create failed to create notification\", { err });\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: order,\n identifiers: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n events: orderCrudEvents,\n indexer: { entityType: E.sales.sales_order },\n actorUserId: ctx.auth?.sub ?? null,\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n emitOrderLifecycleEventsForTransition({\n order,\n previousStatus: null,\n });\n\n return {\n orderId: order.id,\n ...(deprecatedPaymentLedgerFields.length\n ? {\n warnings: [\n {\n code: ORDER_PAYMENT_LEDGER_WARNING_CODE,\n fields: deprecatedPaymentLedgerFields,\n },\n ],\n }\n : {}),\n };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.create\", \"Create sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n ensureOrderScope(ctx, after.order.organizationId, after.order.tenantId);\n await withVerifiedOrderGraph(\n ctx,\n after,\n {\n orderId: after.order.id,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n },\n async (tx, exists) => {\n if (!exists) return;\n const order = await findOneWithDecryption(\n tx,\n SalesOrder,\n { id: after.order.id },\n {},\n {\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n },\n );\n if (!order) return;\n await tx.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await tx.nativeDelete(SalesOrderLine, { order: order.id });\n tx.remove(order);\n await tx.flush();\n },\n );\n },\n};\n\nconst deleteOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.orders.delete\",\n outputSchema: orderIdOutputSchema,\n async prepare(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await findOneWithDecryption(em, SalesOrder, { id });\n if (!order)\n throw notFound(\"Sales order not found\");\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n const shipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = shipments.map((entry) => entry.id);\n const [\n shipmentItems,\n payments,\n paymentAllocations,\n addresses,\n notes,\n tags,\n adjustments,\n lines,\n ] = await Promise.all([\n shipmentIds.length\n ? em.find(SalesShipmentItem, { shipment: { $in: shipmentIds } })\n : Promise.resolve([]),\n em.find(SalesPayment, { order: order.id }),\n em.find(SalesPaymentAllocation, { order: order.id }),\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: order.id,\n documentKind: \"order\",\n },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: order.id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n }),\n em.find(SalesOrderAdjustment, { order: order.id }),\n em.find(SalesOrderLine, { order: order.id }),\n ]);\n // Delete the order and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n em.remove(order);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, order, E.sales.sales_order),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_order_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_order_adjustment,\n ),\n queueDeletionSideEffects(dataEngine, shipments, E.sales.sales_shipment),\n queueDeletionSideEffects(\n dataEngine,\n shipmentItems,\n E.sales.sales_shipment_item,\n ),\n queueDeletionSideEffects(dataEngine, payments, E.sales.sales_payment),\n queueDeletionSideEffects(\n dataEngine,\n paymentAllocations,\n E.sales.sales_payment_allocation,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { orderId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.delete\", \"Delete sales order\"),\n resourceKind: \"sales.order\",\n resourceId: before.order.id,\n tenantId: before.order.tenantId,\n organizationId: before.order.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteConvertToOrderSchema = z.object({\n quoteId: z.string().uuid(),\n orderId: z.string().uuid().optional(),\n orderNumber: z.string().trim().max(191).optional(),\n});\n\nconst convertQuoteToOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.quotes.convert_to_order\",\n async prepare(input, ctx) {\n const parsed = quoteConvertToOrderSchema.safeParse(input ?? {});\n const quoteId = parsed.success\n ? parsed.data.quoteId\n : typeof (input as any)?.quoteId === \"string\"\n ? (input as any).quoteId\n : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const payload = quoteConvertToOrderSchema.parse(rawInput ?? {});\n // When the caller supplies an existing transactional EntityManager, reuse it\n // (and its row locks) so the quote status flip and the order materialization\n // commit or roll back as one atomic unit \u2014 no out-of-band compensating write.\n const callerEm = ctx.transactionalEm;\n const rootEm =\n callerEm ?? (ctx.container.resolve(\"em\") as EntityManager).fork();\n const transactionalEm = rootEm as EntityManager & {\n transactional?: <TResult>(\n callback: (trx: EntityManager) => Promise<TResult>,\n ) => Promise<TResult>;\n };\n const runConversion = async (em: EntityManager) => {\n const quote = await findOneWithDecryption(\n em,\n SalesQuote,\n {\n id: payload.quoteId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n );\n const { translate } = await resolveTranslations();\n if (!quote)\n throw notFound(translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ));\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n await enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n const snapshot = await loadQuoteSnapshot(em, payload.quoteId);\n if (!snapshot)\n throw notFound(translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ));\n const orderId = payload.orderId ?? quote.id;\n const existingOrder = await findOneWithDecryption(em, SalesOrder, {\n id: orderId,\n deletedAt: null,\n }, undefined, { tenantId: quote.tenantId, organizationId: quote.organizationId });\n if (existingOrder) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.detail.convertExists\",\n \"Order already exists for this quote.\",\n ),\n });\n }\n\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const generatedNumber = (\n await generator.generate({\n kind: \"order\",\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n })\n ).number;\n const orderNumber =\n typeof payload.orderNumber === \"string\" &&\n payload.orderNumber.trim().length\n ? payload.orderNumber.trim()\n : generatedNumber;\n\n const [quoteCustomFields, quoteLineCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [snapshot.quote.id],\n tenantIdByRecord: { [snapshot.quote.id]: snapshot.quote.tenantId },\n organizationIdByRecord: {\n [snapshot.quote.id]: snapshot.quote.organizationId,\n },\n }),\n snapshot.lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: snapshot.lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [line.id, snapshot.quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [\n line.id,\n snapshot.quote.organizationId,\n ]),\n ),\n })\n : Promise.resolve({}),\n ]);\n\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n orderNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n fulfillmentStatusEntryId: null,\n fulfillmentStatus: null,\n paymentStatusEntryId: null,\n paymentStatus: null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n exchangeRate: null,\n taxStrategyKey: null,\n discountStrategyKey: null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n channelId: snapshot.quote.channelId ?? null,\n placedAt: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : quote.createdAt,\n expectedDeliveryAt: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n dueAt: null,\n comments: snapshot.quote.comments ?? null,\n internalNotes: null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n ...resolveConvertedOrderFeeTotals({\n totalsSnapshot: snapshot.quote.totalsSnapshot,\n currencyCode: snapshot.quote.currencyCode,\n adjustments: snapshot.adjustments,\n }),\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n\n const orderLineMap = new Map<string, SalesOrderLine>();\n snapshot.lines.forEach((line, index) => {\n const orderLine = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind as SalesLineKind,\n statusEntryId: (line as any).statusEntryId ?? null,\n status: (line as any).status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration\n ? cloneJson(line.configuration)\n : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(orderLine);\n orderLineMap.set(orderLine.id, orderLine);\n });\n\n snapshot.adjustments.forEach((adj, index) => {\n const orderLineId = adj.quoteLineId ?? null;\n const orderLine = orderLineId\n ? (orderLineMap.get(orderLineId) ?? null)\n : null;\n const entity = em.create(SalesOrderAdjustment, {\n id: adj.id,\n order,\n orderLine: orderLine ?? null,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n scope: adj.scope,\n kind: adj.kind as SalesAdjustmentKind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n const [addresses, notes, tags] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n },\n {},\n {\n tenantId: snapshot.quote.tenantId,\n organizationId: snapshot.quote.organizationId,\n },\n ),\n findWithDecryption(\n em,\n SalesNote,\n {\n contextType: \"quote\",\n contextId: snapshot.quote.id,\n },\n {},\n {\n tenantId: snapshot.quote.tenantId,\n organizationId: snapshot.quote.organizationId,\n },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n }),\n ]);\n addresses.forEach((entry) => {\n entry.documentKind = \"order\";\n entry.documentId = order.id;\n entry.order = order;\n entry.quote = null;\n entry.updatedAt = new Date();\n });\n notes.forEach((note) => {\n note.contextType = \"order\";\n note.contextId = order.id;\n note.order = order;\n note.quote = null;\n note.updatedAt = new Date();\n });\n tags.forEach((assignment) => {\n assignment.documentKind = \"order\";\n assignment.documentId = order.id;\n assignment.order = order;\n assignment.quote = null;\n assignment.updatedAt = new Date();\n });\n\n const documentCustomValues = quoteCustomFields[snapshot.quote.id];\n if (documentCustomValues && Object.keys(documentCustomValues).length) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values: documentCustomValues,\n });\n }\n const lineCustomEntries = quoteLineCustomFields as Record<\n string,\n Record<string, unknown>\n >;\n if (lineCustomEntries && Object.keys(lineCustomEntries).length) {\n for (const [lineId, values] of Object.entries(lineCustomEntries)) {\n if (!values || !Object.keys(values).length) continue;\n if (!orderLineMap.has(lineId)) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values,\n });\n }\n }\n\n await em.nativeDelete(SalesQuoteAdjustment, { quote: snapshot.quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: snapshot.quote.id });\n em.remove(quote);\n await em.flush();\n\n return { orderId: order.id };\n };\n if (callerEm) {\n // Already inside the caller's transaction \u2014 run directly so the whole flow\n // stays a single transaction (no nested savepoint).\n return runConversion(callerEm);\n }\n return typeof transactionalEm.transactional === \"function\"\n ? transactionalEm.transactional((trx) => runConversion(trx))\n : runConversion(rootEm);\n },\n captureAfter: async (_input, result, ctx) => {\n // Prefer the caller's transactional EM so the just-created (still\n // uncommitted) order is visible when building the audit \"after\" snapshot.\n const em =\n ctx.transactionalEm ??\n (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.convert\",\n \"Convert quote to order\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n quote: before,\n order: after ?? null,\n } satisfies QuoteConvertUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteConvertUndoPayload>(logEntry);\n const quoteSnapshot = payload?.quote;\n const orderSnapshot = payload?.order;\n if (!quoteSnapshot) return;\n ensureQuoteScope(\n ctx,\n quoteSnapshot.quote.organizationId,\n quoteSnapshot.quote.tenantId,\n );\n const revertConversion = async (em: EntityManager, orderExists: boolean) => {\n if (orderSnapshot) {\n const orderId = orderSnapshot.order.id;\n const orderLineIds = orderSnapshot.lines.map((line) => line.id);\n const existingOrder = orderExists\n ? await findOneWithDecryption(em, SalesOrder, { id: orderId }, undefined, { tenantId: quoteSnapshot.quote.tenantId, organizationId: quoteSnapshot.quote.organizationId })\n : null;\n if (existingOrder) {\n const shipments = await em.find(SalesShipment, { order: orderId });\n const shipmentIds = shipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: orderId });\n await em.nativeDelete(SalesPayment, { order: orderId });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: orderId });\n await em.nativeDelete(SalesOrderLine, { order: orderId });\n em.remove(existingOrder);\n }\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: orderId,\n });\n if (orderLineIds.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: orderLineIds } as any,\n });\n }\n }\n const noteIds = quoteSnapshot.notes.map((note) => note.id);\n if (noteIds.length) {\n await em.nativeDelete(SalesNote, { id: { $in: noteIds } });\n }\n await restoreQuoteGraph(em, quoteSnapshot);\n await em.flush();\n };\n if (orderSnapshot) {\n await withVerifiedOrderGraph(\n ctx,\n orderSnapshot,\n {\n orderId: orderSnapshot.order.id,\n tenantId: orderSnapshot.order.tenantId,\n organizationId: orderSnapshot.order.organizationId,\n },\n revertConversion,\n );\n return;\n }\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n await em.transactional((tx) => revertConversion(tx, false));\n },\n};\n\n// Nested rather than spread flat: a line payload already has a `totalNetAmount`\n// that means the line's, not the document's.\nconst orderLineUpsertSchema = orderLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n orderTotals: orderHeaderTotalsSchema.optional(),\n});\n\nconst orderLineDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n orderTotals: orderHeaderTotalsSchema.optional(),\n});\n\nconst quoteLineUpsertSchema = quoteLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n});\n\nconst quoteLineDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst orderAdjustmentUpsertSchema = orderAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst orderAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n});\n\nconst quoteAdjustmentUpsertSchema = quoteAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst quoteAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst SHIPPED_QUANTITY_TOLERANCE = 1e-6;\n\n// Locked outright on a shipped line: none of these may move at all.\nconst SHIPPED_LINE_NUMERIC_PRICING_FIELDS = [\n \"unitPriceNet\",\n \"unitPriceGross\",\n \"discountAmount\",\n \"discountPercent\",\n \"taxRate\",\n] as const;\n\n// Line totals are derived, not authored: clients recompute and echo them on every\n// submit, so raising the quantity of a shipped line legitimately changes them. They\n// are still writable straight through, so they cannot simply be ignored either.\n// The invariant that separates a quantity edit from moving money is the per-unit\n// economics \u2014 total per unit must stay put, whatever the quantity does. That also\n// keeps discounted lines working, since a proportional total scales with quantity.\nconst SHIPPED_LINE_DERIVED_TOTAL_FIELDS = [\n \"totalNetAmount\",\n \"totalGrossAmount\",\n] as const;\n\ntype ShippedLineComparable = Pick<\n SalesLineSnapshot,\n | \"quantity\"\n | \"quantityUnit\"\n | (typeof SHIPPED_LINE_NUMERIC_PRICING_FIELDS)[number]\n | (typeof SHIPPED_LINE_DERIVED_TOTAL_FIELDS)[number]\n>;\n\nconst hasNumericChange = (\n next: number | null | undefined,\n previous: number | null | undefined,\n): boolean => {\n if (next === undefined || next === null) return false;\n if (previous === undefined || previous === null) return true;\n return Math.abs(next - previous) > SHIPPED_QUANTITY_TOLERANCE;\n};\n\nconst hasExactNumericChange = (\n next: number | null | undefined,\n previous: number | null | undefined,\n): boolean => {\n if (next === undefined || next === null) {\n return previous !== undefined && previous !== null;\n }\n if (previous === undefined || previous === null) return true;\n return Math.abs(next - previous) > SHIPPED_QUANTITY_TOLERANCE;\n};\n\nconst hasUnitChange = (\n next: string | null | undefined,\n previous: string | null | undefined,\n): boolean => {\n if (next === undefined || next === null) return false;\n const normalizedPrevious = (previous ?? \"\").trim().toLowerCase();\n if (!normalizedPrevious) return false;\n return next.trim().toLowerCase() !== normalizedPrevious;\n};\n\nconst hasExactUnitChange = (\n next: string | null | undefined,\n previous: string | null | undefined,\n): boolean =>\n (next ?? \"\").trim().toLowerCase() !==\n (previous ?? \"\").trim().toLowerCase();\n\nfunction hasShippedLineTotalChange(\n next: Partial<ShippedLineComparable>,\n previous: ShippedLineComparable,\n nextQuantity: number | null | undefined,\n exact: boolean,\n): boolean {\n const numericChange = exact ? hasExactNumericChange : hasNumericChange;\n const previousQuantity = previous.quantity;\n const canScale =\n typeof previousQuantity === \"number\" &&\n Math.abs(previousQuantity) > SHIPPED_QUANTITY_TOLERANCE &&\n typeof nextQuantity === \"number\";\n\n return SHIPPED_LINE_DERIVED_TOTAL_FIELDS.some((field) => {\n const nextTotal = next[field];\n const previousTotal = previous[field];\n // Without a scalable quantity pair there is nothing to derive the expected\n // total from, so fall back to locking the value outright.\n if (!canScale || typeof previousTotal !== \"number\") {\n return numericChange(nextTotal, previousTotal);\n }\n if (nextTotal === undefined || nextTotal === null) {\n return exact ? numericChange(nextTotal, previousTotal) : false;\n }\n const expectedTotal =\n (previousTotal / (previousQuantity as number)) * (nextQuantity as number);\n // Scale the tolerance with magnitude: a fixed 1e-6 is below the float noise\n // floor once totals reach six figures.\n const tolerance = Math.max(\n SHIPPED_QUANTITY_TOLERANCE,\n Math.abs(expectedTotal) * 1e-9,\n );\n return Math.abs(nextTotal - expectedTotal) > tolerance;\n });\n}\n\nfunction hasShippedLinePricingChange(\n next: Partial<ShippedLineComparable>,\n previous: ShippedLineComparable,\n nextQuantity: number | null | undefined,\n exact: boolean,\n): boolean {\n const numericChange = exact ? hasExactNumericChange : hasNumericChange;\n return (\n SHIPPED_LINE_NUMERIC_PRICING_FIELDS.some((field) =>\n numericChange(next[field], previous[field]),\n ) ||\n hasShippedLineTotalChange(next, previous, nextQuantity, exact) ||\n (exact\n ? hasExactUnitChange(next.quantityUnit, previous.quantityUnit)\n : hasUnitChange(next.quantityUnit, previous.quantityUnit))\n );\n}\n\nasync function assertShippedOrderLineChangeAllowed(\n existingSnapshot: SalesLineSnapshot,\n nextSnapshot: Partial<ShippedLineComparable> | null,\n shippedQuantity: number,\n exact: boolean,\n): Promise<void> {\n if (shippedQuantity <= 0) return;\n\n const nextQuantity = nextSnapshot\n ? exact\n ? nextSnapshot.quantity\n : (nextSnapshot.quantity ?? existingSnapshot.quantity)\n : 0;\n const quantityInvalid =\n nextQuantity === undefined ||\n nextQuantity < shippedQuantity - SHIPPED_QUANTITY_TOLERANCE;\n const pricingChanged =\n nextSnapshot !== null &&\n hasShippedLinePricingChange(\n nextSnapshot,\n existingSnapshot,\n nextQuantity,\n exact,\n );\n if (!quantityInvalid && !pricingChanged) return;\n\n const { translate } = await resolveTranslations();\n if (quantityInvalid) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorQuantityBelowShipped\",\n \"You cannot lower the quantity below the {{shipped}} already shipped.\",\n { shipped: shippedQuantity },\n ),\n });\n }\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorPriceShipped\",\n \"You cannot change the price or unit of a line that has shipped items.\",\n ),\n });\n}\n\nasync function assertShippedOrderLineEditable(\n em: EntityManager,\n order: SalesOrder,\n existingSnapshot: SalesLineSnapshot | null,\n parsed: z.infer<typeof orderLineUpsertSchema>,\n): Promise<void> {\n const lineId = existingSnapshot?.id;\n if (!existingSnapshot || !lineId) return;\n const shippedByLine = await loadShippedQuantityByLine(em, order.id, {\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n });\n const shippedQuantity = shippedByLine.get(lineId) ?? 0;\n await assertShippedOrderLineChangeAllowed(\n existingSnapshot,\n parsed,\n shippedQuantity,\n false,\n );\n}\n\nasync function assertShippedOrderGraphRestorable(\n em: EntityManager,\n order: SalesOrder,\n existingLines: SalesOrderLine[],\n snapshot: OrderGraphSnapshot,\n): Promise<void> {\n const shippedByLine = await loadShippedQuantityByLine(em, order.id, {\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n });\n if (shippedByLine.size === 0) return;\n\n const snapshotLinesById = new Map(\n snapshot.lines.flatMap((line) => (line.id ? [[line.id, line] as const] : [])),\n );\n for (const line of existingLines) {\n const shippedQuantity = shippedByLine.get(line.id) ?? 0;\n if (shippedQuantity <= 0) continue;\n await assertShippedOrderLineChangeAllowed(\n mapOrderLineEntityToSnapshot(line),\n snapshotLinesById.get(line.id) ?? null,\n shippedQuantity,\n true,\n );\n }\n}\n\nconst FULFILLED_ORDER_STATUS = \"fulfilled\";\n\nconst isFulfilledOrder = (order: SalesOrder): boolean => {\n const normalize = (value: string | null | undefined): string =>\n (value ?? \"\").trim().toLowerCase();\n return (\n normalize(order.status) === FULFILLED_ORDER_STATUS ||\n normalize(order.fulfillmentStatus) === FULFILLED_ORDER_STATUS\n );\n};\n\nasync function assertOrderAcceptsNewLine(\n order: SalesOrder,\n existingSnapshot: SalesLineSnapshot | null,\n): Promise<void> {\n if (existingSnapshot) return;\n if (!isFulfilledOrder(order)) return;\n const { translate } = await resolveTranslations();\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorAddToFulfilled\",\n \"You cannot add a new item to a fulfilled order. Change the order status first.\",\n ),\n });\n}\n\nconst orderLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = orderLineUpsertSchema.parse(rawBody);\n return writeLockedOrderGraph(input, ctx, parsed.orderId, \"Sales order not found\", async (em, order) => {\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const totalsMode: SalesAmountsMode = order.totalsMode ?? \"computed\";\n await assertUniformAmountsMode(totalsMode, [parsed]);\n if (isExternalAmountsMode(totalsMode)) {\n await requireOrderTotalsForExternalWrite(parsed.orderTotals);\n }\n const suppliedTotals: Partial<SalesDocumentAmounts> | null = isExternalAmountsMode(totalsMode)\n ? buildExternalHeaderTotals(parsed.orderTotals)\n : null;\n await assertOrderAcceptsNewLine(order, existingSnapshot);\n await assertShippedOrderLineEditable(em, order, existingSnapshot, parsed);\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n const unitPriceSupplied = unitPriceNet !== null || unitPriceGross !== null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n let taxService: TaxCalculationService | null = null;\n try {\n taxService = ctx.container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n taxService = null;\n }\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? (existingSnapshot as any)?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n const uomResolver = createUomResolver();\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesLineSnapshot & {\n statusEntryId?: string | null;\n catalogSnapshot?: Record<string, unknown> | null;\n promotionSnapshot?: Record<string, unknown> | null;\n } = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n lineSnapshots.length + 1,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n order.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n ...resolveUpsertDiscountFields(\n parsed.discountAmount,\n parsed.discountAmountBasis,\n existingSnapshot,\n ),\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n ...resolveUpsertTotalsOrigin(parsed.totalNetAmount, existingSnapshot),\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : ((existingSnapshot as any)?.customFields ?? null),\n amountsMode: totalsMode,\n };\n Object.assign(\n updatedSnapshot,\n resolveUpsertCalculatedAmounts(parsed, updatedSnapshot, existingSnapshot),\n );\n // After the line above, never before: tax and gross only exist once it runs,\n // and it nulls them when pricing changed, which an external line must restate.\n // The unit price is checked as resolved, not as defaulted to zero above,\n // and a price the tax service derived from no source price counts as absent.\n if (isExternalAmountsMode(totalsMode)) {\n await assertExternalLineComplete(\n {\n ...(updatedSnapshot as Record<string, unknown>),\n unitPriceNet: unitPriceSupplied ? unitPriceNet : null,\n },\n updatedSnapshot.lineNumber ?? 1,\n );\n }\n (updatedSnapshot as any).statusEntryId = statusEntryId;\n (updatedSnapshot as any).catalogSnapshot =\n parsed.catalogSnapshot ??\n (existingSnapshot as any)?.catalogSnapshot ??\n null;\n (updatedSnapshot as any).promotionSnapshot =\n parsed.promotionSnapshot ??\n (existingSnapshot as any)?.promotionSnapshot ??\n null;\n\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode,\n suppliedTotals,\n });\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n return { result: { orderId: order.id, lineId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.upsert\",\n \"Upsert order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst orderLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const { translate } = await resolveTranslations();\n const parsed = orderLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedOrderGraph(input, ctx, parsed.orderId, translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ), async (em, order) => {\n const shipmentCount = await em.count(SalesShipmentItem, {\n orderLine: parsed.id,\n shipment: { deletedAt: null },\n });\n if (shipmentCount > 0) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteShipped\",\n \"Cannot delete a line that has shipped items.\",\n ),\n });\n }\n const existingLines = await em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw notFound(translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ));\n }\n if (filtered.length === 0) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteLast\",\n \"An order must contain at least one line item.\",\n ),\n });\n }\n const totalsMode: SalesAmountsMode = order.totalsMode ?? \"computed\";\n if (isExternalAmountsMode(totalsMode)) {\n await requireOrderTotalsForExternalWrite(parsed.orderTotals);\n }\n const suppliedTotals: Partial<SalesDocumentAmounts> | null = isExternalAmountsMode(totalsMode)\n ? buildExternalHeaderTotals(parsed.orderTotals)\n : null;\n const sourceInputs = filtered.map((line, index) => ({\n ...mapOrderLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode,\n suppliedTotals,\n });\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n return { result: { orderId: order.id, lineId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.delete\",\n \"Delete order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = quoteLineUpsertSchema.parse(rawBody);\n await assertAmountsModeUnsupportedOnQuote([parsed]);\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n let taxService: TaxCalculationService | null = null;\n try {\n taxService = ctx.container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n taxService = null;\n }\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? (existingSnapshot as any)?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n const uomResolver = createUomResolver();\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesLineSnapshot & {\n statusEntryId?: string | null;\n catalogSnapshot?: Record<string, unknown> | null;\n promotionSnapshot?: Record<string, unknown> | null;\n } = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n lineSnapshots.length + 1,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n quote.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n ...resolveUpsertDiscountFields(\n parsed.discountAmount,\n parsed.discountAmountBasis,\n existingSnapshot,\n ),\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n ...resolveUpsertTotalsOrigin(parsed.totalNetAmount, existingSnapshot),\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : ((existingSnapshot as any)?.customFields ?? null),\n };\n Object.assign(\n updatedSnapshot,\n resolveUpsertCalculatedAmounts(parsed, updatedSnapshot, existingSnapshot),\n );\n (updatedSnapshot as any).statusEntryId = statusEntryId;\n (updatedSnapshot as any).catalogSnapshot =\n parsed.catalogSnapshot ??\n (existingSnapshot as any)?.catalogSnapshot ??\n null;\n (updatedSnapshot as any).promotionSnapshot =\n parsed.promotionSnapshot ??\n (existingSnapshot as any)?.promotionSnapshot ??\n null;\n\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n return { result: { quoteId: quote.id, lineId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.upsert\",\n \"Upsert quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = quoteLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw notFound(\"Quote line not found\");\n }\n const sourceInputs = filtered.map((line, index) => ({\n ...mapQuoteLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n return { result: { quoteId: quote.id, lineId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.delete\",\n \"Delete quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\nconst orderAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedOrderGraph(input, ctx, parsed.orderId, \"Sales order not found\", async (em, order) => {\n if (isExternalAmountsMode(order.totalsMode ?? \"computed\")) await refuseOnExternalOrder();\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapOrderAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? order.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? order.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n return { result: { orderId: order.id, adjustmentId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.upsert\",\n \"Upsert order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst orderAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedOrderGraph(input, ctx, parsed.orderId, \"Sales order not found\", async (em, order) => {\n if (isExternalAmountsMode(order.totalsMode ?? \"computed\")) await refuseOnExternalOrder();\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw notFound(\"Adjustment not found\");\n }\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n return { result: { orderId: order.id, adjustmentId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.delete\",\n \"Delete order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapQuoteAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? quote.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? quote.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n return { result: { quoteId: quote.id, adjustmentId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.upsert\",\n \"Upsert quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw notFound(\"Adjustment not found\");\n }\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n return { result: { quoteId: quote.id, adjustmentId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.delete\",\n \"Delete quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Invoice CRUD commands\n// ---------------------------------------------------------------------------\n\nconst invoiceCrudEvents: CrudEventsConfig<SalesInvoice> = {\n module: \"sales\",\n entity: \"invoice\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createInvoiceCommand: CommandHandler<\n InvoiceCreateInput,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = invoiceCreateSchema.parse(rawInput ?? {});\n const invoiceNumber =\n typeof initial.invoiceNumber === \"string\" &&\n initial.invoiceNumber.trim().length\n ? initial.invoiceNumber.trim()\n : (\n await generator.generate({\n kind: \"invoice\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = invoiceCreateSchema.parse({ ...initial, invoiceNumber });\n const ensuredInvoiceNumber = parsed.invoiceNumber ?? invoiceNumber;\n if (!ensuredInvoiceNumber) {\n throw new CrudHttpError(400, { error: \"Invoice number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await findOneWithDecryption(\n em,\n SalesOrder,\n {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n );\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n const invoiceId = randomUUID();\n const invoice = em.create(SalesInvoice, {\n id: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n invoiceNumber: ensuredInvoiceNumber,\n orderId: parsed.orderId ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n issueDate: parsed.issueDate ?? new Date(),\n dueDate: parsed.dueDate ?? null,\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n discountTotalAmount: toNumericString(parsed.discountTotalAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n paidTotalAmount: toNumericString(parsed.paidTotalAmount ?? 0),\n outstandingAmount: toNumericString(parsed.outstandingAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(invoice);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesInvoiceLine, {\n id: randomUUID(),\n invoice,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n discountAmount: toNumericString(line.discountAmount ?? 0),\n discountPercent: toNumericString(line.discountPercent ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount ?? 0, line.totalGrossAmount ?? 0, line.taxRate ?? 0),\n ),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_invoice,\n recordId: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.create\", \"Create invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: after.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n await em.nativeDelete(SalesInvoiceLine, { invoice: invoice.id });\n em.remove(invoice);\n await em.flush();\n },\n};\n\nconst invoiceUpdateChangeKeys = [\n \"invoiceNumber\",\n \"statusEntryId\",\n \"status\",\n \"issueDate\",\n \"dueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"discountTotalAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"paidTotalAmount\",\n \"outstandingAmount\",\n \"metadata\",\n] as const;\n\nfunction toAuditISOString(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString();\n }\n if (typeof value === \"string\") {\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();\n }\n return null;\n}\n\nfunction auditValuesEqual(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true;\n if (left instanceof Date || right instanceof Date) {\n const leftIso = toAuditISOString(left);\n const rightIso = toAuditISOString(right);\n return leftIso !== null && rightIso !== null && leftIso === rightIso;\n }\n return isDeepStrictEqual(left, right);\n}\n\nfunction buildAuditChanges(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n keys: readonly string[],\n): Record<string, { from: unknown; to: unknown }> {\n const changedKeys = keys.filter((key) => !auditValuesEqual(before[key], after[key]));\n return buildChanges(before, after, changedKeys);\n}\n\nfunction selectInvoiceUpdateChangeKeys(\n input: z.infer<typeof invoiceUpdateSchema>,\n): Array<(typeof invoiceUpdateChangeKeys)[number]> {\n return invoiceUpdateChangeKeys.filter((key) =>\n key === \"status\"\n ? input.statusEntryId !== undefined\n : input[key as keyof z.infer<typeof invoiceUpdateSchema>] !== undefined,\n );\n}\n\nfunction applyInvoiceHeaderUpdate(\n invoice: SalesInvoice,\n input: z.infer<typeof invoiceUpdateSchema>,\n resolvedStatus: string | null | undefined,\n): void {\n if (input.invoiceNumber !== undefined) invoice.invoiceNumber = input.invoiceNumber;\n if (input.statusEntryId !== undefined) {\n invoice.statusEntryId = input.statusEntryId;\n invoice.status = resolvedStatus ?? null;\n }\n if (input.issueDate !== undefined) invoice.issueDate = input.issueDate;\n if (input.dueDate !== undefined) invoice.dueDate = input.dueDate;\n if (input.currencyCode !== undefined) invoice.currencyCode = input.currencyCode;\n if (input.subtotalNetAmount !== undefined) invoice.subtotalNetAmount = toNumericString(input.subtotalNetAmount);\n if (input.subtotalGrossAmount !== undefined) invoice.subtotalGrossAmount = toNumericString(input.subtotalGrossAmount);\n if (input.discountTotalAmount !== undefined) invoice.discountTotalAmount = toNumericString(input.discountTotalAmount);\n if (input.taxTotalAmount !== undefined) invoice.taxTotalAmount = toNumericString(input.taxTotalAmount);\n if (input.grandTotalNetAmount !== undefined) invoice.grandTotalNetAmount = toNumericString(input.grandTotalNetAmount);\n if (input.grandTotalGrossAmount !== undefined) invoice.grandTotalGrossAmount = toNumericString(input.grandTotalGrossAmount);\n if (input.paidTotalAmount !== undefined) invoice.paidTotalAmount = toNumericString(input.paidTotalAmount);\n if (input.outstandingAmount !== undefined) invoice.outstandingAmount = toNumericString(input.outstandingAmount);\n if (input.metadata !== undefined) invoice.metadata = input.metadata;\n}\n\nconst updateInvoiceCommand: CommandHandler<\n z.infer<typeof invoiceUpdateSchema>,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = invoiceUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n let resolvedStatus: string | null | undefined;\n if (parsed.statusEntryId !== undefined) {\n resolvedStatus = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: invoice.tenantId });\n }\n\n applyInvoiceHeaderUpdate(invoice, parsed, resolvedStatus);\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ input, result, snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildAuditChanges(\n before.invoice as unknown as Record<string, unknown>,\n after.invoice as unknown as Record<string, unknown>,\n selectInvoiceUpdateChangeKeys(input),\n )\n : {};\n return {\n actionLabel: translate(\"sales.audit.invoices.update\", \"Update invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: { before, after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: before.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n invoice.invoiceNumber = before.invoice.invoiceNumber;\n invoice.orderId = before.invoice.orderId;\n invoice.statusEntryId = before.invoice.statusEntryId;\n invoice.status = before.invoice.status;\n invoice.issueDate = before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : null;\n invoice.dueDate = before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null;\n invoice.currencyCode = before.invoice.currencyCode;\n invoice.subtotalNetAmount = before.invoice.subtotalNetAmount;\n invoice.subtotalGrossAmount = before.invoice.subtotalGrossAmount;\n invoice.discountTotalAmount = before.invoice.discountTotalAmount;\n invoice.taxTotalAmount = before.invoice.taxTotalAmount;\n invoice.grandTotalNetAmount = before.invoice.grandTotalNetAmount;\n invoice.grandTotalGrossAmount = before.invoice.grandTotalGrossAmount;\n invoice.paidTotalAmount = before.invoice.paidTotalAmount;\n invoice.outstandingAmount = before.invoice.outstandingAmount;\n invoice.metadata = before.invoice.metadata;\n invoice.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteInvoiceCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { invoiceId: string }\n> = {\n id: \"sales.invoices.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n invoice.deletedAt = new Date();\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { invoiceId: invoice.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.delete\", \"Delete invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: before.invoice.id,\n tenantId: before.invoice.tenantId,\n organizationId: before.invoice.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.invoice.organizationId);\n ensureTenantScope(ctx, before.invoice.tenantId);\n const restored = em.create(SalesInvoice, {\n id: before.invoice.id,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n invoiceNumber: before.invoice.invoiceNumber,\n orderId: before.invoice.orderId,\n statusEntryId: before.invoice.statusEntryId,\n status: before.invoice.status,\n issueDate: before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : new Date(),\n dueDate: before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null,\n currencyCode: before.invoice.currencyCode,\n subtotalNetAmount: before.invoice.subtotalNetAmount,\n subtotalGrossAmount: before.invoice.subtotalGrossAmount,\n discountTotalAmount: before.invoice.discountTotalAmount,\n taxTotalAmount: before.invoice.taxTotalAmount,\n grandTotalNetAmount: before.invoice.grandTotalNetAmount,\n grandTotalGrossAmount: before.invoice.grandTotalGrossAmount,\n paidTotalAmount: before.invoice.paidTotalAmount,\n outstandingAmount: before.invoice.outstandingAmount,\n metadata: before.invoice.metadata,\n customFieldSetId: before.invoice.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesInvoiceLine, {\n id: line.id,\n invoice: restored,\n orderLineId: line.orderLineId,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\n// ---------------------------------------------------------------------------\n// Credit Memo CRUD commands\n// ---------------------------------------------------------------------------\n\nconst creditMemoCrudEvents: CrudEventsConfig<SalesCreditMemo> = {\n module: \"sales\",\n entity: \"credit_memo\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createCreditMemoCommand: CommandHandler<\n CreditMemoCreateInput,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = creditMemoCreateSchema.parse(rawInput ?? {});\n const creditMemoNumber =\n typeof initial.creditMemoNumber === \"string\" &&\n initial.creditMemoNumber.trim().length\n ? initial.creditMemoNumber.trim()\n : (\n await generator.generate({\n kind: \"credit_memo\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = creditMemoCreateSchema.parse({ ...initial, creditMemoNumber });\n const ensuredCreditMemoNumber = parsed.creditMemoNumber ?? creditMemoNumber;\n if (!ensuredCreditMemoNumber) {\n throw new CrudHttpError(400, { error: \"Credit memo number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await findOneWithDecryption(\n em,\n SalesOrder,\n {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n );\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n // Validate invoiceId belongs to same org/tenant\n if (parsed.invoiceId) {\n const invoiceExists = await em.findOne(SalesInvoice, {\n id: parsed.invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!invoiceExists) {\n throw new CrudHttpError(400, { error: \"Referenced invoice not found in current scope.\" });\n }\n }\n\n const creditMemoId = randomUUID();\n const creditMemo = em.create(SalesCreditMemo, {\n id: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n creditMemoNumber: ensuredCreditMemoNumber,\n order: parsed.orderId ? em.getReference(SalesOrder, parsed.orderId) : null,\n invoice: parsed.invoiceId ? em.getReference(SalesInvoice, parsed.invoiceId) : null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n reason: parsed.reason ?? null,\n issueDate: parsed.issueDate ?? new Date(),\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(creditMemo);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesCreditMemoLine, {\n id: randomUUID(),\n creditMemo,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount ?? 0, line.totalGrossAmount ?? 0, line.taxRate ?? 0),\n ),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_credit_memo,\n recordId: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.create\", \"Create credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: after.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n await em.nativeDelete(SalesCreditMemoLine, { creditMemo: creditMemo.id });\n em.remove(creditMemo);\n await em.flush();\n },\n};\n\nconst creditMemoUpdateChangeKeys = [\n \"creditMemoNumber\",\n \"statusEntryId\",\n \"status\",\n \"reason\",\n \"issueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"metadata\",\n] as const;\n\nfunction selectCreditMemoUpdateChangeKeys(\n input: z.infer<typeof creditMemoUpdateSchema>,\n): Array<(typeof creditMemoUpdateChangeKeys)[number]> {\n return creditMemoUpdateChangeKeys.filter((key) =>\n key === \"status\"\n ? input.statusEntryId !== undefined\n : input[key as keyof z.infer<typeof creditMemoUpdateSchema>] !== undefined,\n );\n}\n\nfunction applyCreditMemoHeaderUpdate(\n creditMemo: SalesCreditMemo,\n input: z.infer<typeof creditMemoUpdateSchema>,\n resolvedStatus: string | null | undefined,\n): void {\n if (input.creditMemoNumber !== undefined) creditMemo.creditMemoNumber = input.creditMemoNumber;\n if (input.statusEntryId !== undefined) {\n creditMemo.statusEntryId = input.statusEntryId;\n creditMemo.status = resolvedStatus ?? null;\n }\n if (input.reason !== undefined) creditMemo.reason = input.reason;\n if (input.issueDate !== undefined) creditMemo.issueDate = input.issueDate;\n if (input.currencyCode !== undefined) creditMemo.currencyCode = input.currencyCode;\n if (input.subtotalNetAmount !== undefined) creditMemo.subtotalNetAmount = toNumericString(input.subtotalNetAmount);\n if (input.subtotalGrossAmount !== undefined) creditMemo.subtotalGrossAmount = toNumericString(input.subtotalGrossAmount);\n if (input.taxTotalAmount !== undefined) creditMemo.taxTotalAmount = toNumericString(input.taxTotalAmount);\n if (input.grandTotalNetAmount !== undefined) creditMemo.grandTotalNetAmount = toNumericString(input.grandTotalNetAmount);\n if (input.grandTotalGrossAmount !== undefined) creditMemo.grandTotalGrossAmount = toNumericString(input.grandTotalGrossAmount);\n if (input.metadata !== undefined) creditMemo.metadata = input.metadata;\n}\n\nconst updateCreditMemoCommand: CommandHandler<\n z.infer<typeof creditMemoUpdateSchema>,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = creditMemoUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n let resolvedStatus: string | null | undefined;\n if (parsed.statusEntryId !== undefined) {\n resolvedStatus = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: creditMemo.tenantId });\n }\n\n applyCreditMemoHeaderUpdate(creditMemo, parsed, resolvedStatus);\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ input, result, snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildAuditChanges(\n before.creditMemo as unknown as Record<string, unknown>,\n after.creditMemo as unknown as Record<string, unknown>,\n selectCreditMemoUpdateChangeKeys(input),\n )\n : {};\n return {\n actionLabel: translate(\"sales.audit.credit_memos.update\", \"Update credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: { before, after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: before.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n creditMemo.creditMemoNumber = before.creditMemo.creditMemoNumber;\n creditMemo.order = before.creditMemo.orderId\n ? em.getReference(SalesOrder, before.creditMemo.orderId)\n : null;\n creditMemo.invoice = before.creditMemo.invoiceId\n ? em.getReference(SalesInvoice, before.creditMemo.invoiceId)\n : null;\n creditMemo.statusEntryId = before.creditMemo.statusEntryId;\n creditMemo.status = before.creditMemo.status;\n creditMemo.reason = before.creditMemo.reason;\n creditMemo.issueDate = before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : null;\n creditMemo.currencyCode = before.creditMemo.currencyCode;\n creditMemo.subtotalNetAmount = before.creditMemo.subtotalNetAmount;\n creditMemo.subtotalGrossAmount = before.creditMemo.subtotalGrossAmount;\n creditMemo.taxTotalAmount = before.creditMemo.taxTotalAmount;\n creditMemo.grandTotalNetAmount = before.creditMemo.grandTotalNetAmount;\n creditMemo.grandTotalGrossAmount = before.creditMemo.grandTotalGrossAmount;\n creditMemo.metadata = before.creditMemo.metadata;\n creditMemo.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteCreditMemoCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n creditMemo.deletedAt = new Date();\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.delete\", \"Delete credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: before.creditMemo.id,\n tenantId: before.creditMemo.tenantId,\n organizationId: before.creditMemo.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.creditMemo.organizationId);\n ensureTenantScope(ctx, before.creditMemo.tenantId);\n const restored = em.create(SalesCreditMemo, {\n id: before.creditMemo.id,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n creditMemoNumber: before.creditMemo.creditMemoNumber,\n order: before.creditMemo.orderId\n ? em.getReference(SalesOrder, before.creditMemo.orderId)\n : null,\n invoice: before.creditMemo.invoiceId\n ? em.getReference(SalesInvoice, before.creditMemo.invoiceId)\n : null,\n statusEntryId: before.creditMemo.statusEntryId,\n status: before.creditMemo.status,\n reason: before.creditMemo.reason,\n issueDate: before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : new Date(),\n currencyCode: before.creditMemo.currencyCode,\n subtotalNetAmount: before.creditMemo.subtotalNetAmount,\n subtotalGrossAmount: before.creditMemo.subtotalGrossAmount,\n taxTotalAmount: before.creditMemo.taxTotalAmount,\n grandTotalNetAmount: before.creditMemo.grandTotalNetAmount,\n grandTotalGrossAmount: before.creditMemo.grandTotalGrossAmount,\n metadata: before.creditMemo.metadata,\n customFieldSetId: before.creditMemo.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesCreditMemoLine, {\n id: line.id,\n creditMemo: restored,\n orderLineId: line.orderLineId,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n lineNumber: line.lineNumber,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\nregisterCommand(updateQuoteCommand);\nregisterCommand(createQuoteCommand);\nregisterCommand(deleteQuoteCommand);\nregisterCommand(convertQuoteToOrderCommand);\nregisterCommand(updateOrderCommand);\nregisterCommand(createOrderCommand);\nregisterCommand(deleteOrderCommand);\nregisterCommand(orderLineUpsertCommand);\nregisterCommand(orderLineDeleteCommand);\nregisterCommand(quoteLineUpsertCommand);\nregisterCommand(quoteLineDeleteCommand);\nregisterCommand(orderAdjustmentUpsertCommand);\nregisterCommand(orderAdjustmentDeleteCommand);\nregisterCommand(quoteAdjustmentUpsertCommand);\nregisterCommand(quoteAdjustmentDeleteCommand);\nregisterCommand(createInvoiceCommand);\nregisterCommand(updateInvoiceCommand);\nregisterCommand(deleteInvoiceCommand);\nregisterCommand(createCreditMemoCommand);\nregisterCommand(updateCreditMemoCommand);\nregisterCommand(deleteCreditMemoCommand);\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;AAClC,SAAS,SAAS;AAClB,SAAS,uBAAuB;AAEhC,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,gBAAgB;AAIzB,SAAS,eAAe,gBAAgB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAC3C,SAAS,wCAAwC;AACjD,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAClB,SAAS,oBAAoB,6BAA6B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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IACJ;AACA,UAAM,GAAG,MAAM;AAAA,EACjB;AACF;AAEA,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,0BAA0B;AAC1C,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,sBAAsB;AACtC,gBAAgB,sBAAsB;AACtC,gBAAgB,sBAAsB;AACtC,gBAAgB,sBAAsB;AACtC,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,uBAAuB;AACvC,gBAAgB,uBAAuB;AACvC,gBAAgB,uBAAuB;",
|
|
4
|
+
"sourcesContent": ["// @ts-nocheck\n\nimport { randomUUID } from \"crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\nimport { registerCommand } from \"@open-mercato/shared/lib/commands\";\nimport type { CommandHandler, CommandRuntimeContext } from \"@open-mercato/shared/lib/commands\";\nimport { withAtomicFlush } from \"@open-mercato/shared/lib/commands/flush\";\nimport {\n buildChanges,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n requireId,\n type CrudEventsConfig,\n} from \"@open-mercato/shared/lib/commands/helpers\";\nimport { LockMode } from \"@mikro-orm/core\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport type { EventBus } from \"@open-mercato/events\";\nimport type { DataEngine } from \"@open-mercato/shared/lib/data/engine\";\nimport { CrudHttpError, notFound } from \"@open-mercato/shared/lib/crud/errors\";\nimport {\n deriveResourceFromCommandId,\n invalidateCrudCache,\n} from \"@open-mercato/shared/lib/crud/cache\";\nimport { resolveTranslations } from \"@open-mercato/shared/lib/i18n/server\";\nimport { resolveNotificationService } from \"../../notifications/lib/notificationService\";\nimport { buildFeatureNotificationFromType } from \"../../notifications/lib/notificationBuilder\";\nimport { emitSalesEvent } from \"../events\";\nimport { setRecordCustomFields } from \"@open-mercato/core/modules/entities/lib/helpers\";\nimport { loadCustomFieldValues } from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport {\n normalizeCustomFieldResponse,\n normalizeCustomFieldValues,\n} from \"@open-mercato/shared/lib/custom-fields/normalize\";\nimport { E } from \"#generated/entities.ids.generated\";\nimport { findWithDecryption, findOneWithDecryption } from \"@open-mercato/shared/lib/encryption/find\";\nimport {\n SalesQuote,\n SalesQuoteLine,\n SalesQuoteAdjustment,\n SalesOrder,\n SalesOrderLine,\n SalesOrderAdjustment,\n SalesShipment,\n SalesShipmentItem,\n SalesPayment,\n SalesPaymentAllocation,\n SalesInvoice,\n SalesInvoiceLine,\n SalesCreditMemo,\n SalesCreditMemoLine,\n SalesDocumentAddress,\n SalesNote,\n SalesChannel,\n SalesShippingMethod,\n SalesDeliveryWindow,\n SalesPaymentMethod,\n SalesDocumentTag,\n SalesDocumentTagAssignment,\n SalesReturn,\n type SalesLineKind,\n type SalesAdjustmentKind,\n type SalesSettings,\n} from \"../data/entities\";\nimport {\n CatalogProduct,\n CatalogProductUnitConversion,\n} from \"../../catalog/data/entities\";\nimport { Dictionary, DictionaryEntry } from \"../../dictionaries/data/entities\";\nimport { CustomFieldValue } from \"@open-mercato/core/modules/entities/data/entities\";\nimport {\n CustomerAddress,\n CustomerEntity,\n CustomerPersonProfile,\n} from \"../../customers/data/entities\";\nimport {\n enforceAdjustmentSign,\n validateReturnAdjustmentWithinRemaining,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n quoteCreateSchema,\n quoteLineCreateSchema,\n quoteAdjustmentCreateSchema,\n orderCreateSchema,\n ORDER_PAYMENT_LEDGER_WARNING_CODE,\n resolveSuppliedOrderPaymentLedgerFields,\n amountsModeSchema,\n orderLineCreateSchema,\n orderLineBulkUpsertSchema,\n orderHeaderTotalsSchema,\n orderAdjustmentCreateSchema,\n invoiceCreateSchema,\n invoiceUpdateSchema,\n creditMemoCreateSchema,\n creditMemoUpdateSchema,\n customerSnapshotSchema,\n type QuoteCreateInput,\n type QuoteLineCreateInput,\n type QuoteAdjustmentCreateInput,\n type OrderCreateInput,\n type OrderPaymentLedgerWarning,\n type OrderLineCreateInput,\n type OrderAdjustmentCreateInput,\n type InvoiceCreateInput,\n type CreditMemoCreateInput,\n} from \"../data/validators\";\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n toNumericString,\n reconcileLinePersistedTotals,\n deriveLineNetFromGross,\n enforceSalesDocumentOptimisticLock,\n lockSalesDocumentRow,\n SALES_RESOURCE_KIND_ORDER,\n SALES_RESOURCE_KIND_QUOTE,\n} from \"./shared\";\nimport {\n loadShipmentSnapshot,\n restoreShipmentSnapshot,\n type ShipmentSnapshot,\n} from \"./shipments\";\nimport {\n loadPaymentSnapshot,\n restorePaymentSnapshot,\n type PaymentSnapshot,\n} from \"./payments\";\nimport { resolveConvertedOrderFeeTotals } from \"../lib/convertedOrderTotals\";\nimport type { SalesCalculationService } from \"../services/salesCalculationService\";\nimport type { TaxCalculationService } from \"../services/taxCalculationService\";\nimport type {\n PaymentMethodContext,\n ShippingMethodContext,\n} from \"../lib/providers\";\nimport {\n type SalesAmountsMode,\n type SalesLineSnapshot,\n type SalesLineUomSnapshot,\n type SalesAdjustmentDraft,\n type SalesDocumentAmounts,\n type SalesLineCalculationResult,\n type SalesDocumentCalculationResult,\n} from \"../lib/types\";\nimport {\n mapOrderLineEntityToSnapshot,\n mapQuoteLineEntityToSnapshot,\n resolveUpsertDiscountFields,\n resolveUpsertTotalsOrigin,\n resolveUpsertCalculatedAmounts,\n type SalesPersistedLineSnapshot,\n} from \"../lib/lineSnapshots\";\nimport {\n assertAmountsModeUnsupportedOnQuote,\n assertExternalHeaderComplete,\n assertExternalLineComplete,\n assertUniformAmountsMode,\n buildExternalHeaderTotals,\n hasAnySuppliedHeaderTotal,\n readPersistedHeaderTotals,\n refuseOnExternalOrder,\n requireOrderTotalsForExternalWrite,\n} from \"../lib/externalAmounts\";\nimport { isExternalAmountsMode } from \"../lib/calculations\";\nimport { loadShippedQuantityByLine } from \"../lib/shipments/snapshots\";\nimport { resolveDictionaryEntryValue, resolveCachedDictionaryEntryValue } from \"../lib/dictionaries\";\nimport { assertOrderCanBeCancelled, isCancelledOrderStatus } from \"../lib/orderCancellationGuard\";\nimport type { CacheStrategy } from \"@open-mercato/cache\";\nimport { resolveStatusEntryIdByValue } from \"../lib/statusHelpers\";\nimport { SalesDocumentNumberGenerator } from \"../services/salesDocumentNumberGenerator\";\nimport { loadSalesSettings } from \"./settings\";\nimport { notificationTypes } from \"../notifications\";\nimport {\n REFERENCE_UNIT_CODES,\n canonicalizeUnitCode,\n toUnitLookupKey,\n} from \"@open-mercato/shared/lib/units/unitCodes\";\nimport type { AuthContext } from \"@open-mercato/shared/lib/auth/server\";\nimport type { TranslateWithFallbackFn } from \"@open-mercato/shared/lib/i18n/translate\";\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('sales')\nlet warnedDeprecatedOrderPaymentLedgerInput = false\n\n// CRUD events configuration for workflow triggers\nconst orderCrudEvents: CrudEventsConfig<SalesOrder> = {\n module: \"sales\",\n entity: \"order\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n userId: ctx.actorUserId ?? null,\n }),\n};\n\nconst quoteCrudEvents: CrudEventsConfig<SalesQuote> = {\n module: \"sales\",\n entity: \"quote\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n userId: ctx.actorUserId ?? null,\n }),\n};\n\ntype DocumentAddressSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n customerAddressId: string | null;\n name: string | null;\n purpose: string | null;\n companyName: string | null;\n addressLine1: string;\n addressLine2: string | null;\n city: string | null;\n region: string | null;\n postalCode: string | null;\n country: string | null;\n buildingNumber: string | null;\n flatNumber: string | null;\n latitude: number | null;\n longitude: number | null;\n};\n\ntype NoteSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n contextType: \"order\" | \"quote\";\n contextId: string;\n orderId: string | null;\n quoteId: string | null;\n body: string;\n authorUserId: string | null;\n appearanceIcon: string | null;\n appearanceColor: string | null;\n};\n\ntype TagAssignmentSnapshot = {\n id: string;\n tagId: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n};\n\ntype QuoteGraphSnapshot = {\n quote: {\n id: string;\n organizationId: string;\n tenantId: string;\n quoteNumber: string;\n statusEntryId: string | null;\n status: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n validFrom: string | null;\n validUntil: string | null;\n comments: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n };\n lines: QuoteLineSnapshot[];\n adjustments: QuoteAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n};\n\ntype QuoteLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype QuoteAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n quoteLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderGraphSnapshot = {\n order: {\n id: string;\n organizationId: string;\n tenantId: string;\n orderNumber: string;\n statusEntryId: string | null;\n status: string | null;\n fulfillmentStatusEntryId: string | null;\n fulfillmentStatus: string | null;\n paymentStatusEntryId: string | null;\n paymentStatus: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n exchangeRate: string | null;\n taxStrategyKey: string | null;\n discountStrategyKey: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n placedAt: string | null;\n expectedDeliveryAt: string | null;\n dueAt: string | null;\n comments: string | null;\n internalNotes: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n shippingNetAmount: string;\n shippingGrossAmount: string;\n surchargeTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n refundedTotalAmount: string;\n outstandingAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n totalsMode: SalesAmountsMode;\n };\n lines: OrderLineSnapshot[];\n adjustments: OrderAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n shipments: ShipmentSnapshot[];\n payments: PaymentSnapshot[];\n};\n\ntype OrderLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n reservedQuantity: string;\n fulfilledQuantity: string;\n invoicedQuantity: string;\n returnedQuantity: string;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n amountsMode: SalesAmountsMode;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n orderLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderUndoPayload = {\n before?: OrderGraphSnapshot | null;\n after?: OrderGraphSnapshot | null;\n};\n\ntype QuoteUndoPayload = {\n before?: QuoteGraphSnapshot | null;\n after?: QuoteGraphSnapshot | null;\n};\n\ntype QuoteConvertUndoPayload = {\n quote?: QuoteGraphSnapshot | null;\n order?: OrderGraphSnapshot | null;\n};\n\ntype InvoiceGraphSnapshot = {\n invoice: {\n id: string;\n organizationId: string;\n tenantId: string;\n invoiceNumber: string;\n orderId: string | null;\n statusEntryId: string | null;\n status: string | null;\n issueDate: string | Date | null;\n dueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n outstandingAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: InvoiceLineSnapshot[];\n};\n\ntype InvoiceLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n kind: string;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype CreditMemoGraphSnapshot = {\n creditMemo: {\n id: string;\n organizationId: string;\n tenantId: string;\n creditMemoNumber: string;\n orderId: string | null;\n invoiceId: string | null;\n statusEntryId: string | null;\n status: string | null;\n reason: string | null;\n issueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: CreditMemoLineSnapshot[];\n};\n\ntype CreditMemoLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype InvoiceUndoPayload = {\n before?: InvoiceGraphSnapshot | null;\n after?: InvoiceGraphSnapshot | null;\n};\n\ntype CreditMemoUndoPayload = {\n before?: CreditMemoGraphSnapshot | null;\n after?: CreditMemoGraphSnapshot | null;\n};\n\nconst currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, { message: \"currency_code_invalid\" });\n\nconst dateOnlySchema = z\n .string()\n .trim()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, { message: \"invalid_date\" })\n .refine((value) => !Number.isNaN(new Date(value).getTime()), {\n message: \"invalid_date\",\n });\n\nconst addressSnapshotSchema = z\n .record(z.string(), z.unknown())\n .nullable()\n .optional();\n\n// Mirrors the create schema's `decimal({ min: 0 })` (data/validators.ts). `null`\n// comes first in the union below because the coercion accepts it \u2014 `Number(null)`\n// is 0 \u2014 and would turn a clear into a written zero.\nconst exchangeRateSchema = z.coerce.number().min(0);\n\nconst documentUpdateFieldsSchema = z\n .object({\n id: z.string().uuid(),\n customerEntityId: z.string().uuid().nullable().optional(),\n customerContactId: z.string().uuid().nullable().optional(),\n customerSnapshot: customerSnapshotSchema.nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n customerReference: z.string().nullable().optional(),\n externalReference: z.string().nullable().optional(),\n comment: z.string().nullable().optional(),\n // Same names and limits as the create schema (data/validators.ts), so a\n // caller can send one payload shape to create and update. Nullable here\n // because an update \u2014 unlike a create \u2014 has an existing value to clear.\n comments: z.string().trim().max(4000).nullable().optional(),\n internalNotes: z.string().trim().max(4000).nullable().optional(),\n orderNumber: z.string().trim().min(1).max(191).optional(),\n quoteNumber: z.string().trim().min(1).max(191).optional(),\n currencyCode: currencyCodeSchema.optional(),\n // Order-only columns \u2014 SalesQuote declares none of them. Declared here\n // because the create schema declares them and a caller reusing its create\n // payload on an update otherwise lost them silently; `applyDocumentUpdate`\n // rejects each with a 400 on a quote rather than dropping it.\n exchangeRate: z.union([z.null(), exchangeRateSchema]).optional(),\n paymentStatusEntryId: z.string().uuid().nullable().optional(),\n fulfillmentStatusEntryId: z.string().uuid().nullable().optional(),\n channelId: z.string().uuid().nullable().optional(),\n statusEntryId: z.string().uuid().nullable().optional(),\n placedAt: z.union([dateOnlySchema, z.null()]).optional(),\n expectedDeliveryAt: z.union([dateOnlySchema, z.null()]).optional(),\n shippingAddressId: z.string().uuid().nullable().optional(),\n billingAddressId: z.string().uuid().nullable().optional(),\n shippingAddressSnapshot: addressSnapshotSchema,\n billingAddressSnapshot: addressSnapshotSchema,\n shippingMethodId: z.string().uuid().nullable().optional(),\n shippingMethodCode: z.string().nullable().optional(),\n shippingMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n paymentMethodId: z.string().uuid().nullable().optional(),\n paymentMethodCode: z.string().nullable().optional(),\n paymentMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n tags: z.array(z.string().uuid()).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n customFieldSetId: z.string().uuid().nullable().optional(),\n totalsMode: amountsModeSchema.optional(),\n ...orderHeaderTotalsSchema.shape,\n });\n\ntype DocumentUpdateFields = z.infer<typeof documentUpdateFieldsSchema>;\n\nfunction carriesDocumentEdit(input: DocumentUpdateFields): boolean {\n return (\n typeof input.currencyCode === \"string\" ||\n input.placedAt !== undefined ||\n input.expectedDeliveryAt !== undefined ||\n input.channelId !== undefined ||\n input.statusEntryId !== undefined ||\n input.exchangeRate !== undefined ||\n input.paymentStatusEntryId !== undefined ||\n input.fulfillmentStatusEntryId !== undefined ||\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined ||\n input.customerReference !== undefined ||\n input.externalReference !== undefined ||\n input.comment !== undefined ||\n input.comments !== undefined ||\n input.internalNotes !== undefined ||\n input.orderNumber !== undefined ||\n input.quoteNumber !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined ||\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.tags !== undefined ||\n input.customFields !== undefined ||\n input.customFieldSetId !== undefined\n );\n}\n\n// The route cannot see an order's persisted mode, so it lets header totals count\n// as an edit; each command re-applies `documentEditSchema` once it can. An empty\n// update must not reach a quote: execution reverts a `sent` quote to draft.\nexport const documentUpdateSchema = documentUpdateFieldsSchema.refine(\n (input) =>\n carriesDocumentEdit(input) ||\n input.totalsMode !== undefined ||\n hasAnySuppliedHeaderTotal(input),\n { message: \"update_payload_empty\" },\n);\n\nconst documentEditSchema = documentUpdateFieldsSchema.refine(carriesDocumentEdit, {\n message: \"update_payload_empty\",\n});\n\nexport type DocumentUpdateInput = z.infer<typeof documentUpdateSchema>;\n\ntype DocumentLineCreateInput = QuoteLineCreateInput | OrderLineCreateInput;\ntype DocumentAdjustmentCreateInput =\n | QuoteAdjustmentCreateInput\n | OrderAdjustmentCreateInput;\n\nfunction cloneJson<T>(value: T): T {\n if (value === null || value === undefined) return value;\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/**\n * Graph snapshots load custom fields through `loadCustomFieldValues`, which keys\n * them `cf_<key>`. Writing those keys back verbatim stores a new `cf_<key>` row\n * instead of restoring `<key>`, so restores strip the prefix first.\n */\nfunction toSnapshotCustomFieldWriteValues(\n values: Record<string, unknown>,\n): ReturnType<typeof normalizeCustomFieldValues> {\n return normalizeCustomFieldValues(normalizeCustomFieldResponse(values) ?? {});\n}\n\n/**\n * Persists document-level custom fields supplied on a create input.\n *\n * Order and quote creates used to accept `customFields` at the HTTP boundary\n * (`splitCustomFieldPayload` folds `cf_*` keys into it) and then drop the values\n * on the floor, because the create schemas never declared the key and the\n * handlers never wrote it \u2014 only updates did. Callers therefore had to create,\n * then immediately update, to get custom fields to stick.\n */\nasync function setDocumentCustomFieldsIfSupplied(\n em: EntityManager,\n params: {\n entityId: string;\n recordId: string;\n organizationId: string;\n tenantId: string;\n customFields: unknown;\n },\n): Promise<void> {\n const { customFields } = params;\n if (customFields === undefined || customFields === null) return;\n const values =\n typeof customFields === \"object\" && !Array.isArray(customFields)\n ? (customFields as Record<string, unknown>)\n : {};\n if (!Object.keys(values).length) return;\n await setRecordCustomFields(em, {\n entityId: params.entityId,\n recordId: params.recordId,\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n values: normalizeCustomFieldValues(values),\n });\n}\n\nasync function resolveCustomerSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n customerEntityId?: string | null,\n customerContactId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!customerEntityId) return null;\n const customer = await em.findOne(\n CustomerEntity,\n { id: customerEntityId, organizationId, tenantId },\n { populate: [\"personProfile\", \"companyProfile\"] },\n );\n if (!customer) return null;\n\n const contact = customerContactId\n ? await em.findOne(CustomerPersonProfile, {\n id: customerContactId,\n organizationId,\n tenantId,\n })\n : null;\n\n return {\n customer: {\n id: customer.id,\n kind: customer.kind,\n displayName: customer.displayName,\n primaryEmail: customer.primaryEmail ?? null,\n primaryPhone: customer.primaryPhone ?? null,\n personProfile: customer.personProfile\n ? {\n id: customer.personProfile.id,\n firstName: customer.personProfile.firstName ?? null,\n lastName: customer.personProfile.lastName ?? null,\n preferredName: customer.personProfile.preferredName ?? null,\n }\n : null,\n companyProfile: customer.companyProfile\n ? {\n id: customer.companyProfile.id,\n legalName: customer.companyProfile.legalName ?? null,\n brandName: customer.companyProfile.brandName ?? null,\n domain: customer.companyProfile.domain ?? null,\n websiteUrl: customer.companyProfile.websiteUrl ?? null,\n }\n : null,\n },\n contact: contact\n ? {\n id: contact.id,\n firstName: contact.firstName ?? null,\n lastName: contact.lastName ?? null,\n preferredName: contact.preferredName ?? null,\n jobTitle: contact.jobTitle ?? null,\n department: contact.department ?? null,\n }\n : null,\n };\n}\n\nasync function resolveAddressSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n addressId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!addressId) return null;\n const address = await findOneWithDecryption(\n em,\n CustomerAddress,\n { id: addressId, organizationId, tenantId },\n undefined,\n { tenantId, organizationId },\n );\n if (!address) return null;\n\n return {\n id: address.id,\n name: address.name ?? null,\n purpose: address.purpose ?? null,\n companyName: address.companyName ?? null,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? null,\n buildingNumber: address.buildingNumber ?? null,\n flatNumber: address.flatNumber ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n postalCode: address.postalCode ?? null,\n country: address.country ?? null,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n isPrimary: address.isPrimary,\n };\n}\n\nasync function resolveDocumentReferences(\n em: EntityManager,\n parsed: {\n organizationId: string;\n tenantId: string;\n customerEntityId?: string | null;\n customerContactId?: string | null;\n customerSnapshot?: Record<string, unknown> | null;\n billingAddressId?: string | null;\n shippingAddressId?: string | null;\n billingAddressSnapshot?: Record<string, unknown> | null;\n shippingAddressSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n deliveryWindowId?: string | null;\n paymentMethodId?: string | null;\n },\n): Promise<{\n customerSnapshot: Record<string, unknown> | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n shippingMethod: SalesShippingMethod | null;\n deliveryWindow: SalesDeliveryWindow | null;\n paymentMethod: SalesPaymentMethod | null;\n}> {\n const [\n resolvedCustomerSnapshot,\n resolvedBillingSnapshot,\n resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n ] = await Promise.all([\n parsed.customerSnapshot\n ? Promise.resolve(cloneJson(parsed.customerSnapshot))\n : resolveCustomerSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.customerEntityId ?? null,\n parsed.customerContactId ?? null,\n ),\n parsed.billingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.billingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.billingAddressId ?? null,\n ),\n parsed.shippingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.shippingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.shippingAddressId ?? null,\n ),\n parsed.shippingMethodId\n ? em.findOne(SalesShippingMethod, {\n id: parsed.shippingMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.deliveryWindowId\n ? em.findOne(SalesDeliveryWindow, {\n id: parsed.deliveryWindowId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.paymentMethodId\n ? em.findOne(SalesPaymentMethod, {\n id: parsed.paymentMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n ]);\n\n return {\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n shippingMethod: shippingMethod ?? null,\n deliveryWindow: deliveryWindow ?? null,\n paymentMethod: paymentMethod ?? null,\n };\n}\n\nfunction normalizeStatusValue(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length ? trimmed : null;\n}\n\nfunction isConfirmedOrderStatus(status: string | null): boolean {\n return status === \"confirmed\";\n}\n\nasync function emitOrderLifecycleEvent(input: {\n eventId: \"sales.order.confirmed\" | \"sales.order.cancelled\";\n order: SalesOrder;\n previousStatus: string | null;\n}): Promise<void> {\n await emitSalesEvent(input.eventId, {\n id: input.order.id,\n orderId: input.order.id,\n orderNumber: input.order.orderNumber,\n previousStatus: input.previousStatus,\n status: normalizeStatusValue(input.order.status),\n tenantId: input.order.tenantId,\n organizationId: input.order.organizationId,\n });\n}\n\nfunction emitOrderLifecycleEventsForTransition(input: {\n order: SalesOrder;\n previousStatus: string | null;\n}): void {\n const nextStatus = normalizeStatusValue(input.order.status);\n if (input.previousStatus === nextStatus) return;\n\n if (isConfirmedOrderStatus(nextStatus)) {\n void emitOrderLifecycleEvent({\n eventId: \"sales.order.confirmed\",\n order: input.order,\n previousStatus: input.previousStatus,\n }).catch((err) => {\n // Surface as warning so downstream automations (e.g. WMS reservation\n // subscriber) failing to register/persist their own follow-up state is\n // observable in logs instead of being silently dropped. The order\n // status transition itself is already committed at this point.\n logger.warn(\"order lifecycle event emit failed\", {\n eventId: \"sales.order.confirmed\",\n orderId: input.order.id,\n err,\n });\n });\n }\n\n if (isCancelledOrderStatus(nextStatus)) {\n void emitOrderLifecycleEvent({\n eventId: \"sales.order.cancelled\",\n order: input.order,\n previousStatus: input.previousStatus,\n }).catch((err) => {\n logger.warn(\"order lifecycle event emit failed\", {\n eventId: \"sales.order.cancelled\",\n orderId: input.order.id,\n err,\n });\n });\n }\n}\n\nfunction resolveNoteAuthorFromAuth(auth: AuthContext | null): string | null {\n if (!auth || auth.isApiKey) return null;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n const uuidRegex =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;\n return uuidRegex.test(sub) ? sub : null;\n}\n\nfunction resolveStatusChangeActor(auth: AuthContext | null, translate: TranslateWithFallbackFn): string {\n const unknownLabel = translate(\n \"sales.orders.status_change.actor_unknown\",\n \"unknown user\",\n );\n if (!auth) return unknownLabel;\n if (auth.isApiKey) {\n const keyName = typeof auth.keyName === \"string\" ? auth.keyName.trim() : \"\";\n const keyId = typeof auth.keyId === \"string\" ? auth.keyId.trim() : \"\";\n const label =\n keyName || keyId || (typeof auth.sub === \"string\" ? auth.sub : \"\");\n return label\n ? translate(\n \"sales.orders.status_change.actor_api_key\",\n \"API key {name}\",\n { name: label },\n )\n : unknownLabel;\n }\n const email = typeof auth.email === \"string\" ? auth.email.trim() : \"\";\n if (email) return email;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n if (sub) return sub;\n return unknownLabel;\n}\n\nfunction formatStatusLabel(status: string | null, translate: TranslateWithFallbackFn): string {\n if (status && status.trim().length) return status.trim();\n return translate(\"sales.orders.status_change.empty\", \"unset\");\n}\n\nasync function appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth,\n}: {\n em: EntityManager;\n order: SalesOrder;\n previousStatus: string | null;\n auth: AuthContext | null;\n}): Promise<SalesNote | null> {\n const nextStatus = normalizeStatusValue(order.status);\n if (previousStatus === nextStatus) return null;\n const { translate } = await resolveTranslations();\n const body = translate(\n \"sales.orders.status_change.note\",\n \"Status changed from {from} to {to} by {actor}.\",\n {\n from: formatStatusLabel(previousStatus, translate),\n to: formatStatusLabel(nextStatus, translate),\n actor: resolveStatusChangeActor(auth, translate),\n },\n );\n const note = em.create(SalesNote, {\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n authorUserId: resolveNoteAuthorFromAuth(auth),\n appearanceIcon: null,\n appearanceColor: null,\n body,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(note);\n return note;\n}\n\nasync function applyDocumentUpdate({\n kind,\n entity,\n input,\n em,\n}: {\n kind: \"order\" | \"quote\";\n entity: SalesOrder | SalesQuote;\n input: DocumentUpdateInput;\n em: EntityManager;\n}): Promise<void> {\n const organizationId = (entity as any).organizationId as string;\n const tenantId = (entity as any).tenantId as string;\n const status =\n typeof (entity as any).status === \"string\" ? (entity as any).status : null;\n const { translate } = await resolveTranslations();\n\n const wantsCustomerChange =\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined;\n const wantsAddressChange =\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined;\n\n let settings: SalesSettings | null = null;\n if (kind === \"order\" && (wantsCustomerChange || wantsAddressChange)) {\n settings = await loadSalesSettings(em, { organizationId, tenantId });\n }\n\n const guardStatus = (\n allowed: string[] | null | undefined,\n errorKey: string,\n fallback: string,\n ) => {\n if (!Array.isArray(allowed)) return;\n if (allowed.length === 0) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n if (!status || !allowed.includes(status)) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n };\n\n if (kind === \"order\" && wantsCustomerChange) {\n guardStatus(\n settings?.orderCustomerEditableStatuses ?? null,\n \"sales.orders.edit_customer_blocked\",\n \"Editing the customer is blocked for this status.\",\n );\n }\n if (kind === \"order\" && wantsAddressChange) {\n guardStatus(\n settings?.orderAddressEditableStatuses ?? null,\n \"sales.orders.edit_addresses_blocked\",\n \"Editing addresses is blocked for this status.\",\n );\n }\n\n if (kind === \"order\" && typeof input.orderNumber === \"string\") {\n (entity as SalesOrder).orderNumber = input.orderNumber;\n }\n if (kind === \"quote\" && typeof input.quoteNumber === \"string\") {\n (entity as SalesQuote).quoteNumber = input.quoteNumber;\n }\n\n if (input.customerEntityId !== undefined) {\n const nextCustomerEntityId = input.customerEntityId ?? null;\n const customerChanged =\n (nextCustomerEntityId?.toLowerCase() ?? null) !==\n (entity.customerEntityId?.toLowerCase() ?? null);\n const snapshotContactId =\n input.customerContactId !== undefined\n ? input.customerContactId\n : customerChanged\n ? null\n : entity.customerContactId ?? null;\n if (customerChanged) {\n entity.customerEntityId = nextCustomerEntityId;\n }\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n entity.customerEntityId ?? null,\n snapshotContactId,\n );\n if (customerChanged) {\n entity.customerContactId = input.customerContactId ?? null;\n entity.billingAddressId = null;\n entity.shippingAddressId = null;\n entity.billingAddressSnapshot = null;\n entity.shippingAddressSnapshot = null;\n }\n }\n if (input.customerContactId !== undefined) {\n entity.customerContactId = input.customerContactId ?? null;\n if (entity.customerEntityId) {\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n entity.customerEntityId,\n input.customerContactId,\n );\n }\n }\n if (input.customerSnapshot !== undefined) {\n entity.customerSnapshot = input.customerSnapshot ?? null;\n }\n if (input.metadata !== undefined) {\n entity.metadata = input.metadata ?? null;\n }\n if (input.externalReference !== undefined) {\n const normalized =\n typeof input.externalReference === \"string\"\n ? input.externalReference.trim()\n : \"\";\n entity.externalReference = normalized.length ? normalized : null;\n }\n if (input.customerReference !== undefined) {\n const normalized =\n typeof input.customerReference === \"string\"\n ? input.customerReference.trim()\n : \"\";\n entity.customerReference = normalized.length ? normalized : null;\n }\n if (input.comment !== undefined) {\n const normalized =\n typeof input.comment === \"string\" ? input.comment.trim() : \"\";\n entity.comments = normalized.length ? normalized : null;\n }\n // After `comment`, so the canonical name wins when a payload carries both.\n if (input.comments !== undefined) {\n const normalized =\n typeof input.comments === \"string\" ? input.comments.trim() : \"\";\n entity.comments = normalized.length ? normalized : null;\n }\n // Orders only \u2014 SalesQuote has no internalNotes column. Reject rather than\n // ignore it on a quote: the field now satisfies the schema's refine on its\n // own, so silently dropping it would let an otherwise-empty payload run the\n // update, and a quote in `sent` status loses its acceptance token and reverts\n // to draft on any update that reaches execution.\n if (kind === \"quote\" && input.internalNotes !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.internal_notes_unsupported\",\n \"Internal notes are not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.internalNotes !== undefined) {\n const normalized =\n typeof input.internalNotes === \"string\" ? input.internalNotes.trim() : \"\";\n (entity as SalesOrder).internalNotes = normalized.length\n ? normalized\n : null;\n }\n if (typeof input.currencyCode === \"string\") {\n entity.currencyCode = input.currencyCode;\n }\n // Orders only \u2014 SalesQuote has no exchange_rate column, so the field is\n // rejected rather than ignored for the same reason as internalNotes above.\n if (kind === \"quote\" && input.exchangeRate !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.exchange_rate_unsupported\",\n \"Exchange rate is not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.exchangeRate !== undefined) {\n (entity as SalesOrder).exchangeRate = toNumericString(input.exchangeRate);\n }\n if (input.channelId !== undefined) {\n if (input.channelId === null) {\n entity.channelId = null;\n } else {\n const channel = await findOneWithDecryption(\n em,\n SalesChannel,\n {\n id: input.channelId,\n organizationId,\n tenantId,\n deletedAt: null,\n },\n {},\n { tenantId, organizationId },\n );\n if (!channel) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.channelInvalid\",\n \"Selected channel could not be found.\",\n ),\n });\n }\n entity.channelId = channel.id;\n }\n }\n if (input.statusEntryId !== undefined) {\n const statusValue = await resolveDictionaryEntryValue(\n em,\n input.statusEntryId,\n { tenantId },\n );\n if (input.statusEntryId && !statusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n (entity as any).statusEntryId = input.statusEntryId ?? null;\n (entity as any).status = statusValue;\n }\n // Orders only \u2014 SalesQuote has neither the entry-id nor the derived text\n // column for payment and fulfillment status, so both are rejected on a quote.\n if (kind === \"quote\" && input.paymentStatusEntryId !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.payment_status_unsupported\",\n \"Payment status is not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.paymentStatusEntryId !== undefined) {\n const paymentStatusValue = await resolveDictionaryEntryValue(\n em,\n input.paymentStatusEntryId,\n { tenantId },\n );\n if (input.paymentStatusEntryId && !paymentStatusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n // Both columns, like the statusEntryId branch above and like order create:\n // moving the id without its derived text leaves a self-contradicting row.\n (entity as SalesOrder).paymentStatusEntryId =\n input.paymentStatusEntryId ?? null;\n (entity as SalesOrder).paymentStatus = paymentStatusValue;\n }\n if (kind === \"quote\" && input.fulfillmentStatusEntryId !== undefined) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.quotes.fulfillment_status_unsupported\",\n \"Fulfillment status is not available on quotes.\",\n ),\n });\n }\n if (kind === \"order\" && input.fulfillmentStatusEntryId !== undefined) {\n const fulfillmentStatusValue = await resolveDictionaryEntryValue(\n em,\n input.fulfillmentStatusEntryId,\n { tenantId },\n );\n if (input.fulfillmentStatusEntryId && !fulfillmentStatusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n (entity as SalesOrder).fulfillmentStatusEntryId =\n input.fulfillmentStatusEntryId ?? null;\n (entity as SalesOrder).fulfillmentStatus = fulfillmentStatusValue;\n }\n if (input.placedAt !== undefined) {\n if (input.placedAt === null) {\n entity.placedAt = null;\n } else {\n const parsed = new Date(input.placedAt);\n entity.placedAt = Number.isNaN(parsed.getTime())\n ? entity.placedAt\n : parsed;\n }\n }\n if (\n input.expectedDeliveryAt !== undefined &&\n \"expectedDeliveryAt\" in entity\n ) {\n if (input.expectedDeliveryAt === null) {\n (entity as SalesOrder).expectedDeliveryAt = null;\n } else {\n const parsed = new Date(input.expectedDeliveryAt);\n (entity as SalesOrder).expectedDeliveryAt = Number.isNaN(parsed.getTime())\n ? (entity as SalesOrder).expectedDeliveryAt\n : parsed;\n }\n }\n if (input.shippingAddressId !== undefined) {\n entity.shippingAddressId = input.shippingAddressId ?? null;\n if (input.shippingAddressSnapshot === undefined) {\n entity.shippingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.shippingAddressId,\n );\n }\n }\n if (input.billingAddressId !== undefined) {\n entity.billingAddressId = input.billingAddressId ?? null;\n if (input.billingAddressSnapshot === undefined) {\n entity.billingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.billingAddressId,\n );\n }\n }\n if (input.shippingAddressSnapshot !== undefined) {\n entity.shippingAddressSnapshot = input.shippingAddressSnapshot ?? null;\n }\n if (input.billingAddressSnapshot !== undefined) {\n entity.billingAddressSnapshot = input.billingAddressSnapshot ?? null;\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.shippingMethodCode !== undefined\n ) {\n let shippingMethod: SalesShippingMethod | null = null;\n if (input.shippingMethodId) {\n shippingMethod = await em.findOne(SalesShippingMethod, {\n id: input.shippingMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!shippingMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.shippingMethodInvalid\",\n \"Selected shipping method could not be found.\",\n ),\n });\n }\n }\n (entity as any).shippingMethodId = input.shippingMethodId ?? null;\n (entity as any).shippingMethod = shippingMethod ?? null;\n (entity as any).shippingMethodCode =\n input.shippingMethodCode ?? shippingMethod?.code ?? null;\n if (input.shippingMethodSnapshot !== undefined) {\n (entity as any).shippingMethodSnapshot =\n input.shippingMethodSnapshot ?? null;\n } else {\n (entity as any).shippingMethodSnapshot = shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.paymentMethodCode !== undefined\n ) {\n let paymentMethod: SalesPaymentMethod | null = null;\n if (input.paymentMethodId) {\n paymentMethod = await em.findOne(SalesPaymentMethod, {\n id: input.paymentMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!paymentMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.paymentMethodInvalid\",\n \"Selected payment method could not be found.\",\n ),\n });\n }\n }\n (entity as any).paymentMethodId = input.paymentMethodId ?? null;\n (entity as any).paymentMethod = paymentMethod ?? null;\n (entity as any).paymentMethodCode =\n input.paymentMethodCode ?? paymentMethod?.code ?? null;\n if (input.paymentMethodSnapshot !== undefined) {\n (entity as any).paymentMethodSnapshot =\n input.paymentMethodSnapshot ?? null;\n } else {\n (entity as any).paymentMethodSnapshot = paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n\n if (input.tags !== undefined) {\n await syncSalesDocumentTags(em, {\n documentId: entity.id,\n kind,\n organizationId,\n tenantId,\n tagIds: input.tags,\n });\n }\n\n if (input.customFieldSetId !== undefined) {\n (entity as any).customFieldSetId = input.customFieldSetId ?? null;\n }\n\n if (input.customFields !== undefined) {\n const values =\n input.customFields &&\n typeof input.customFields === \"object\" &&\n !Array.isArray(input.customFields)\n ? (input.customFields as Record<string, unknown>)\n : {};\n // Same normalize path as create (`setDocumentCustomFieldsIfSupplied`) so\n // update and create agree on key/value shapes written to EAV.\n await setRecordCustomFields(em, {\n entityId: kind === \"order\" ? E.sales.sales_order : E.sales.sales_quote,\n recordId: entity.id,\n organizationId,\n tenantId,\n values: normalizeCustomFieldValues(values),\n });\n }\n}\n\nasync function loadQuoteSnapshot(\n em: EntityManager,\n id: string,\n): Promise<QuoteGraphSnapshot | null> {\n const quote = await findOneWithDecryption(em, SalesQuote, { id, deletedAt: null });\n if (!quote) return null;\n const decryptionScope = { tenantId: quote.tenantId, organizationId: quote.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n quoteCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"quote\" },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"quote\" },\n { populate: [\"tag\"] },\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [quote.id],\n tenantIdByRecord: { [quote.id]: quote.tenantId },\n organizationIdByRecord: { [quote.id]: quote.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"quote\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n quote: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteNumber: quote.quoteNumber,\n statusEntryId: quote.statusEntryId ?? null,\n status: quote.status ?? null,\n customerEntityId: quote.customerEntityId ?? null,\n customerContactId: quote.customerContactId ?? null,\n customerSnapshot: quote.customerSnapshot\n ? cloneJson(quote.customerSnapshot)\n : null,\n billingAddressId: quote.billingAddressId ?? null,\n shippingAddressId: quote.shippingAddressId ?? null,\n billingAddressSnapshot: quote.billingAddressSnapshot\n ? cloneJson(quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: quote.shippingAddressSnapshot\n ? cloneJson(quote.shippingAddressSnapshot)\n : null,\n currencyCode: quote.currencyCode,\n validFrom: quote.validFrom ? quote.validFrom.toISOString() : null,\n validUntil: quote.validUntil ? quote.validUntil.toISOString() : null,\n comments: quote.comments ?? null,\n taxInfo: quote.taxInfo ? cloneJson(quote.taxInfo) : null,\n shippingMethodId: quote.shippingMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n deliveryWindowId: quote.deliveryWindowId ?? null,\n deliveryWindowCode: quote.deliveryWindowCode ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n channelId: quote.channelId ?? null,\n shippingMethodSnapshot: quote.shippingMethodSnapshot\n ? cloneJson(quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: quote.deliveryWindowSnapshot\n ? cloneJson(quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: quote.paymentMethodSnapshot\n ? cloneJson(quote.paymentMethodSnapshot)\n : null,\n metadata: quote.metadata ? cloneJson(quote.metadata) : null,\n customFieldSetId: quote.customFieldSetId ?? null,\n customFields: quoteCustomFields[quote.id]\n ? cloneJson(quoteCustomFields[quote.id])\n : null,\n subtotalNetAmount: quote.subtotalNetAmount,\n subtotalGrossAmount: quote.subtotalGrossAmount,\n discountTotalAmount: quote.discountTotalAmount,\n taxTotalAmount: quote.taxTotalAmount,\n grandTotalNetAmount: quote.grandTotalNetAmount,\n grandTotalGrossAmount: quote.grandTotalGrossAmount,\n totalsSnapshot: quote.totalsSnapshot\n ? cloneJson(quote.totalsSnapshot)\n : null,\n lineItemCount: quote.lineItemCount,\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n quoteLineId:\n typeof adj.quoteLine === \"string\"\n ? adj.quoteLine\n : (adj.quoteLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n };\n}\n\nasync function loadOrderSnapshot(\n em: EntityManager,\n id: string,\n): Promise<OrderGraphSnapshot | null> {\n const order = await findOneWithDecryption(em, SalesOrder, { id, deletedAt: null });\n if (!order) return null;\n const decryptionScope = { tenantId: order.tenantId, organizationId: order.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n shipments,\n payments,\n orderCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"order\" },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"order\" },\n { populate: [\"tag\"] },\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesShipment, { order: order }),\n em.find(SalesPayment, { order: order }),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order,\n recordIds: [order.id],\n tenantIdByRecord: { [order.id]: order.tenantId },\n organizationIdByRecord: { [order.id]: order.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const shipmentSnapshots = (\n await Promise.all(\n shipments.map((entry) => loadShipmentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is ShipmentSnapshot => !!entry);\n const paymentSnapshots = (\n await Promise.all(\n payments.map((entry) => loadPaymentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is PaymentSnapshot => !!entry);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"order\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n order: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderNumber: order.orderNumber,\n statusEntryId: order.statusEntryId ?? null,\n status: order.status ?? null,\n fulfillmentStatusEntryId: order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: order.fulfillmentStatus ?? null,\n paymentStatusEntryId: order.paymentStatusEntryId ?? null,\n paymentStatus: order.paymentStatus ?? null,\n customerEntityId: order.customerEntityId ?? null,\n customerContactId: order.customerContactId ?? null,\n customerSnapshot: order.customerSnapshot\n ? cloneJson(order.customerSnapshot)\n : null,\n billingAddressId: order.billingAddressId ?? null,\n shippingAddressId: order.shippingAddressId ?? null,\n billingAddressSnapshot: order.billingAddressSnapshot\n ? cloneJson(order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: order.shippingAddressSnapshot\n ? cloneJson(order.shippingAddressSnapshot)\n : null,\n currencyCode: order.currencyCode,\n exchangeRate: order.exchangeRate ?? null,\n taxStrategyKey: order.taxStrategyKey ?? null,\n discountStrategyKey: order.discountStrategyKey ?? null,\n taxInfo: order.taxInfo ? cloneJson(order.taxInfo) : null,\n shippingMethodId: order.shippingMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n deliveryWindowId: order.deliveryWindowId ?? null,\n deliveryWindowCode: order.deliveryWindowCode ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n channelId: order.channelId ?? null,\n placedAt: order.placedAt ? order.placedAt.toISOString() : null,\n expectedDeliveryAt: order.expectedDeliveryAt\n ? order.expectedDeliveryAt.toISOString()\n : null,\n dueAt: order.dueAt ? order.dueAt.toISOString() : null,\n comments: order.comments ?? null,\n internalNotes: order.internalNotes ?? null,\n shippingMethodSnapshot: order.shippingMethodSnapshot\n ? cloneJson(order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: order.deliveryWindowSnapshot\n ? cloneJson(order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: order.paymentMethodSnapshot\n ? cloneJson(order.paymentMethodSnapshot)\n : null,\n metadata: order.metadata ? cloneJson(order.metadata) : null,\n customFieldSetId: order.customFieldSetId ?? null,\n customFields: orderCustomFields[order.id]\n ? cloneJson(orderCustomFields[order.id])\n : null,\n subtotalNetAmount: order.subtotalNetAmount,\n subtotalGrossAmount: order.subtotalGrossAmount,\n discountTotalAmount: order.discountTotalAmount,\n taxTotalAmount: order.taxTotalAmount,\n shippingNetAmount: order.shippingNetAmount,\n shippingGrossAmount: order.shippingGrossAmount,\n surchargeTotalAmount: order.surchargeTotalAmount,\n grandTotalNetAmount: order.grandTotalNetAmount,\n grandTotalGrossAmount: order.grandTotalGrossAmount,\n paidTotalAmount: order.paidTotalAmount,\n refundedTotalAmount: order.refundedTotalAmount,\n outstandingAmount: order.outstandingAmount,\n totalsSnapshot: order.totalsSnapshot\n ? cloneJson(order.totalsSnapshot)\n : null,\n lineItemCount: order.lineItemCount,\n totalsMode: order.totalsMode ?? \"computed\",\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n amountsMode: line.amountsMode ?? \"computed\",\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n orderLineId:\n typeof adj.orderLine === \"string\"\n ? adj.orderLine\n : (adj.orderLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n shipments: shipmentSnapshots,\n payments: paymentSnapshots,\n };\n}\n\nasync function loadInvoiceSnapshot(\n em: EntityManager,\n id: string,\n): Promise<InvoiceGraphSnapshot | null> {\n const invoice = await em.findOne(SalesInvoice, { id, deletedAt: null });\n if (!invoice) return null;\n const lines = await em.find(\n SalesInvoiceLine,\n { invoice: invoice },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [invoiceCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_invoice,\n recordIds: [invoice.id],\n tenantIdByRecord: { [invoice.id]: invoice.tenantId },\n organizationIdByRecord: { [invoice.id]: invoice.organizationId },\n }),\n ]);\n return {\n invoice: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n invoiceNumber: invoice.invoiceNumber,\n orderId: invoice.orderId ?? null,\n statusEntryId: invoice.statusEntryId ?? null,\n status: invoice.status ?? null,\n issueDate: invoice.issueDate ?? null,\n dueDate: invoice.dueDate ?? null,\n currencyCode: invoice.currencyCode,\n subtotalNetAmount: String(invoice.subtotalNetAmount),\n subtotalGrossAmount: String(invoice.subtotalGrossAmount),\n discountTotalAmount: String(invoice.discountTotalAmount),\n taxTotalAmount: String(invoice.taxTotalAmount),\n grandTotalNetAmount: String(invoice.grandTotalNetAmount),\n grandTotalGrossAmount: String(invoice.grandTotalGrossAmount),\n paidTotalAmount: String(invoice.paidTotalAmount),\n outstandingAmount: String(invoice.outstandingAmount),\n metadata: invoice.metadata ?? null,\n customFieldSetId: invoice.customFieldSetId ?? null,\n customFields: invoiceCustomFields[invoice.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n discountAmount: String(line.discountAmount),\n discountPercent: String(line.discountPercent),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\nasync function loadCreditMemoSnapshot(\n em: EntityManager,\n id: string,\n): Promise<CreditMemoGraphSnapshot | null> {\n const creditMemo = await em.findOne(SalesCreditMemo, { id, deletedAt: null });\n if (!creditMemo) return null;\n const lines = await em.find(\n SalesCreditMemoLine,\n { creditMemo: creditMemo },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [creditMemoCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_credit_memo,\n recordIds: [creditMemo.id],\n tenantIdByRecord: { [creditMemo.id]: creditMemo.tenantId },\n organizationIdByRecord: { [creditMemo.id]: creditMemo.organizationId },\n }),\n ]);\n return {\n creditMemo: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n creditMemoNumber: creditMemo.creditMemoNumber,\n orderId: creditMemo.order?.id ?? null,\n invoiceId: creditMemo.invoice?.id ?? null,\n statusEntryId: creditMemo.statusEntryId ?? null,\n status: creditMemo.status ?? null,\n reason: creditMemo.reason ?? null,\n issueDate: creditMemo.issueDate ?? null,\n currencyCode: creditMemo.currencyCode,\n subtotalNetAmount: String(creditMemo.subtotalNetAmount),\n subtotalGrossAmount: String(creditMemo.subtotalGrossAmount),\n taxTotalAmount: String(creditMemo.taxTotalAmount),\n grandTotalNetAmount: String(creditMemo.grandTotalNetAmount),\n grandTotalGrossAmount: String(creditMemo.grandTotalGrossAmount),\n metadata: creditMemo.metadata ?? null,\n customFieldSetId: creditMemo.customFieldSetId ?? null,\n customFields: creditMemoCustomFields[creditMemo.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\ntype DeletableEntity = {\n id?: string;\n organizationId?: string | null;\n tenantId?: string | null;\n};\n\nasync function queueDeletionSideEffects(\n dataEngine: DataEngine,\n entities: DeletableEntity[] | DeletableEntity | null | undefined,\n entityType: string,\n): Promise<void> {\n if (!entities) return;\n const list = Array.isArray(entities) ? entities : [entities];\n const tasks: Array<Promise<void>> = [];\n for (const entity of list) {\n if (!entity) continue;\n const id = typeof entity.id === \"string\" ? entity.id : null;\n if (!id) continue;\n tasks.push(\n emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity,\n identifiers: {\n id,\n organizationId: entity.organizationId ?? null,\n tenantId: entity.tenantId ?? null,\n },\n indexer: { entityType },\n }),\n );\n }\n if (tasks.length) await Promise.all(tasks);\n}\n\nfunction toNumeric(value: string | number | null | undefined): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n if (!Number.isNaN(parsed)) return parsed;\n }\n return 0;\n}\n\nconst UNIT_DICTIONARY_KEYS = [\"unit\", \"units\", \"measurement_units\"] as const;\nconst UOM_REFERENCE_UNITS = new Set<string>(REFERENCE_UNIT_CODES);\nconst UOM_NORMALIZED_SCALE = 6;\nconst UOM_NORMALIZED_MAX = 1_000_000_000_000;\nconst UNIT_PRICE_AUTOCONVERT_SCALE = 4;\n\ntype ProductUomState = {\n productId: string;\n baseUnitCode: string | null;\n defaultSalesUnit: string | null;\n unitPriceEnabled: boolean;\n unitPriceReferenceUnit: \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null;\n unitPriceBaseQuantity: string | null;\n conversionsByUnitKey: Map<string, CatalogProductUnitConversion>;\n};\n\ntype UomResolver = {\n dictionaryPromise: Promise<Dictionary | null> | null;\n unitExistsCache: Map<string, boolean>;\n productCache: Map<string, ProductUomState | null>;\n};\n\ntype NormalizeLineUomInput = {\n em: EntityManager;\n resolver: UomResolver;\n organizationId: string;\n tenantId: string;\n line: {\n productId?: string | null;\n productVariantId?: string | null;\n quantity?: number | string | null;\n quantityUnit?: string | null;\n unitPriceNet?: number | null;\n unitPriceGross?: number | null;\n normalizedQuantity?: number | string | null;\n normalizedUnit?: string | null;\n uomSnapshot?: Record<string, unknown> | null;\n };\n};\n\nfunction createUomResolver(): UomResolver {\n return {\n dictionaryPromise: null,\n unitExistsCache: new Map<string, boolean>(),\n productCache: new Map<string, ProductUomState | null>(),\n };\n}\n\nfunction normalizeUnitCode(value: unknown): string | null {\n return canonicalizeUnitCode(value);\n}\n\nfunction unitLookupKey(value: string | null | undefined): string | null {\n return toUnitLookupKey(value);\n}\n\nfunction roundNormalizedQuantity(value: number): number {\n const factor = 10 ** UOM_NORMALIZED_SCALE;\n if (!Number.isFinite(value)) return 0;\n return Math.round(value * factor) / factor;\n}\n\nfunction assertNormalizedPrecision(value: number) {\n if (!Number.isFinite(value) || Math.abs(value) >= UOM_NORMALIZED_MAX) {\n throw new CrudHttpError(422, { error: \"uom.precision_overflow\" });\n }\n}\n\nfunction toOptionalNumber(value: unknown): number | null {\n if (value === null || value === undefined) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n}\n\nfunction resolveSnapshotToBaseFactor(snapshot: unknown): number {\n if (!snapshot || typeof snapshot !== \"object\") return 1;\n const payload = snapshot as Record<string, unknown>;\n const factor = toOptionalNumber(payload.toBaseFactor ?? payload.to_base_factor);\n if (!Number.isFinite(factor) || !factor || factor <= 0) return 1;\n return factor;\n}\n\nfunction roundAutoConvertedUnitPrice(value: number): number | null {\n if (!Number.isFinite(value) || value < 0) return null;\n const factor = 10 ** UNIT_PRICE_AUTOCONVERT_SCALE;\n const rounded = Math.round((value + Number.EPSILON) * factor) / factor;\n return Number.isFinite(rounded) ? rounded : null;\n}\n\nfunction convertLineUnitPricesOnUnitChange(params: {\n existingSnapshot: SalesLineSnapshot | null;\n nextQuantityUnit: string | null;\n nextUomSnapshot: SalesLineUomSnapshot | Record<string, unknown> | null;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}): {\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n didConvert: boolean;\n} {\n if (!params.existingSnapshot) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const existingUnitPriceNet =\n typeof params.existingSnapshot.unitPriceNet === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceNet)\n ? params.existingSnapshot.unitPriceNet\n : null;\n const existingUnitPriceGross =\n typeof params.existingSnapshot.unitPriceGross === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceGross)\n ? params.existingSnapshot.unitPriceGross\n : null;\n const sameNumber = (left: number | null, right: number | null): boolean => {\n if (left === null || right === null) return left === right;\n return Math.abs(left - right) < 0.000001;\n };\n const shouldConvertNet =\n params.unitPriceNet === null ||\n sameNumber(params.unitPriceNet, existingUnitPriceNet);\n const shouldConvertGross =\n params.unitPriceGross === null ||\n sameNumber(params.unitPriceGross, existingUnitPriceGross);\n if (!shouldConvertNet && !shouldConvertGross) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousUnit = normalizeUnitCode(params.existingSnapshot?.quantityUnit ?? null);\n const nextUnit = normalizeUnitCode(params.nextQuantityUnit);\n if (!previousUnit || !nextUnit || previousUnit === nextUnit) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousFactor = resolveSnapshotToBaseFactor(\n params.existingSnapshot?.uomSnapshot ?? null,\n );\n const nextFactor = resolveSnapshotToBaseFactor(params.nextUomSnapshot);\n if (\n !Number.isFinite(previousFactor) ||\n previousFactor <= 0 ||\n !Number.isFinite(nextFactor) ||\n nextFactor <= 0\n ) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const convertAmount = (\n value: number | null,\n shouldConvert: boolean,\n ): number | null => {\n if (!shouldConvert) return value;\n if (value === null || !Number.isFinite(value)) return value;\n const converted = roundAutoConvertedUnitPrice((value / previousFactor) * nextFactor);\n return converted ?? value;\n };\n const nextUnitPriceNet = convertAmount(params.unitPriceNet, shouldConvertNet);\n const nextUnitPriceGross = convertAmount(\n params.unitPriceGross,\n shouldConvertGross,\n );\n const didConvert =\n nextUnitPriceNet !== params.unitPriceNet ||\n nextUnitPriceGross !== params.unitPriceGross;\n return {\n unitPriceNet: nextUnitPriceNet,\n unitPriceGross: nextUnitPriceGross,\n didConvert,\n };\n}\n\nfunction resolveReferenceUnit(\n value: unknown,\n): \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null {\n const normalized = toUnitLookupKey(value);\n if (!normalized) return null;\n if (!UOM_REFERENCE_UNITS.has(normalized)) return null;\n return normalized as \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\";\n}\n\nasync function resolveUnitDictionaryScoped(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n): Promise<Dictionary | null> {\n return findOneWithDecryption(\n em,\n Dictionary,\n {\n organizationId,\n tenantId,\n key: { $in: [...UNIT_DICTIONARY_KEYS] },\n deletedAt: null,\n isActive: true,\n },\n { orderBy: { createdAt: \"asc\" } },\n );\n}\n\nasync function assertUnitExists(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n unitCode: string,\n): Promise<void> {\n const normalizedCode = unitLookupKey(unitCode);\n if (!normalizedCode) return;\n const rawUnitCode = unitCode.trim();\n if (!resolver.dictionaryPromise) {\n resolver.dictionaryPromise = resolveUnitDictionaryScoped(\n em,\n organizationId,\n tenantId,\n );\n }\n const dictionary = await resolver.dictionaryPromise;\n if (!dictionary) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n const cacheKey = `${dictionary.id}:${normalizedCode}`;\n if (resolver.unitExistsCache.has(cacheKey)) {\n if (!resolver.unitExistsCache.get(cacheKey)) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n return;\n }\n const entry = await findOneWithDecryption(em, DictionaryEntry, {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n $or: [{ normalizedValue: normalizedCode }, { value: rawUnitCode }],\n });\n const exists = !!entry;\n resolver.unitExistsCache.set(cacheKey, exists);\n if (!exists) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n}\n\nasync function resolveProductUomState(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n productId: string,\n): Promise<ProductUomState | null> {\n if (resolver.productCache.has(productId)) {\n return resolver.productCache.get(productId) ?? null;\n }\n const product = await findOneWithDecryption(em, CatalogProduct, {\n id: productId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!product) {\n resolver.productCache.set(productId, null);\n return null;\n }\n const conversions = await findWithDecryption(em, CatalogProductUnitConversion, {\n product: product.id,\n organizationId,\n tenantId,\n deletedAt: null,\n isActive: true,\n });\n const conversionsByUnitKey = new Map<string, CatalogProductUnitConversion>();\n for (const conversion of conversions) {\n const key = unitLookupKey(conversion.unitCode);\n if (!key) continue;\n conversionsByUnitKey.set(key, conversion);\n }\n const state: ProductUomState = {\n productId: product.id,\n baseUnitCode: normalizeUnitCode(product.defaultUnit ?? null),\n defaultSalesUnit: normalizeUnitCode(product.defaultSalesUnit ?? null),\n unitPriceEnabled: Boolean(product.unitPriceEnabled),\n unitPriceReferenceUnit: resolveReferenceUnit(\n product.unitPriceReferenceUnit,\n ),\n unitPriceBaseQuantity: product.unitPriceBaseQuantity ?? null,\n conversionsByUnitKey,\n };\n resolver.productCache.set(productId, state);\n return state;\n}\n\nfunction buildUnitPriceReferenceSnapshot(params: {\n product: ProductUomState;\n toBaseFactor: number;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}) {\n if (!params.product.unitPriceEnabled) return undefined;\n const baseQuantityNumber = toNumeric(params.product.unitPriceBaseQuantity);\n const output: NonNullable<SalesLineUomSnapshot[\"unitPriceReference\"]> = {\n enabled: true,\n referenceUnitCode: params.product.unitPriceReferenceUnit ?? null,\n baseQuantity: params.product.unitPriceBaseQuantity ?? null,\n };\n if (\n !params.product.unitPriceReferenceUnit ||\n params.toBaseFactor <= 0 ||\n baseQuantityNumber <= 0\n ) {\n return output;\n }\n if (\n typeof params.unitPriceGross === \"number\" &&\n Number.isFinite(params.unitPriceGross)\n ) {\n output.grossPerReference = toNumericString(\n (params.unitPriceGross / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n if (\n typeof params.unitPriceNet === \"number\" &&\n Number.isFinite(params.unitPriceNet)\n ) {\n output.netPerReference = toNumericString(\n (params.unitPriceNet / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n return output;\n}\n\nasync function normalizeLineUom(input: NormalizeLineUomInput): Promise<{\n quantity: number;\n quantityUnit: string | null;\n normalizedQuantity: number;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n}> {\n const quantity = toNumeric(input.line.quantity);\n const existingSnapshot =\n input.line.uomSnapshot && typeof input.line.uomSnapshot === \"object\"\n ? (cloneJson(input.line.uomSnapshot) as SalesLineUomSnapshot)\n : null;\n const productId =\n typeof input.line.productId === \"string\" ? input.line.productId : null;\n const variantId =\n typeof input.line.productVariantId === \"string\"\n ? input.line.productVariantId\n : null;\n const enteredUnitInput = normalizeUnitCode(input.line.quantityUnit);\n if (!productId) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot ?? {\n version: 1,\n productId: null,\n productVariantId: variantId,\n baseUnitCode:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n enteredUnitCode: enteredUnitInput,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: { mode: \"half_up\", scale: UOM_NORMALIZED_SCALE },\n source: { conversionId: null, resolvedAt: new Date().toISOString() },\n },\n };\n }\n\n const productState = await resolveProductUomState(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n productId,\n );\n if (!productState) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const baseUnitCode = productState.baseUnitCode;\n const enteredUnitCode =\n enteredUnitInput ??\n productState.defaultSalesUnit ??\n baseUnitCode ??\n normalizeUnitCode(input.line.normalizedUnit);\n if (enteredUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitCode,\n );\n }\n if (baseUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n baseUnitCode,\n );\n }\n\n if (!baseUnitCode) {\n const requiresBase =\n Boolean(enteredUnitCode) ||\n productState.conversionsByUnitKey.size > 0 ||\n Boolean(productState.defaultSalesUnit);\n if (requiresBase) {\n throw new CrudHttpError(400, { error: \"uom.default_unit_missing\" });\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitCode ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ?? enteredUnitCode ?? null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const resolvedEnteredUnit = enteredUnitCode ?? baseUnitCode;\n const enteredKey = unitLookupKey(resolvedEnteredUnit);\n const baseKey = unitLookupKey(baseUnitCode);\n let toBaseFactor = 1;\n let conversionId: string | null = null;\n if (enteredKey && baseKey && enteredKey !== baseKey) {\n const conversion = productState.conversionsByUnitKey.get(enteredKey);\n if (!conversion) {\n throw new CrudHttpError(400, { error: \"uom.conversion_not_found\" });\n }\n toBaseFactor = toNumeric(conversion.toBaseFactor);\n conversionId = conversion.id;\n }\n if (!Number.isFinite(toBaseFactor) || toBaseFactor <= 0) {\n throw new CrudHttpError(400, { error: \"uom.invalid_factor\" });\n }\n const normalizedQuantity = roundNormalizedQuantity(quantity * toBaseFactor);\n assertNormalizedPrecision(normalizedQuantity);\n const unitPriceReference = buildUnitPriceReferenceSnapshot({\n product: productState,\n toBaseFactor,\n unitPriceNet: toOptionalNumber(input.line.unitPriceNet),\n unitPriceGross: toOptionalNumber(input.line.unitPriceGross),\n });\n const snapshot: SalesLineUomSnapshot = {\n version: 1,\n productId,\n productVariantId: variantId,\n baseUnitCode,\n enteredUnitCode: resolvedEnteredUnit,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: toNumericString(toBaseFactor) ?? \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: {\n mode: \"half_up\",\n scale: UOM_NORMALIZED_SCALE,\n },\n source: {\n conversionId,\n resolvedAt: new Date().toISOString(),\n },\n ...(unitPriceReference ? { unitPriceReference } : {}),\n };\n\n return {\n quantity,\n quantityUnit: resolvedEnteredUnit,\n normalizedQuantity,\n normalizedUnit: baseUnitCode,\n uomSnapshot: snapshot,\n };\n}\n\nfunction normalizeShippingMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n currencyCode?: string,\n): ShippingMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n currencyCode:\n typeof (snapshot as Record<string, unknown>).currencyCode === \"string\"\n ? ((snapshot as Record<string, unknown>).currencyCode as string)\n : (currencyCode ?? null),\n baseRateNet: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateNet ??\n (snapshot as Record<string, unknown>).base_rate_net) as\n | string\n | number\n | null,\n ),\n baseRateGross: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateGross ??\n (snapshot as Record<string, unknown>).base_rate_gross) as\n | string\n | number\n | null,\n ),\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction normalizePaymentMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n): PaymentMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n terms:\n typeof (snapshot as Record<string, unknown>).terms === \"string\"\n ? ((snapshot as Record<string, unknown>).terms as string)\n : null,\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction buildProviderContext(params: {\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n currencyCode: string;\n}) {\n return {\n shippingMethod: normalizeShippingMethodContext(\n params.shippingSnapshot,\n params.shippingMethodId,\n params.shippingMethodCode,\n params.currencyCode,\n ),\n paymentMethod: normalizePaymentMethodContext(\n params.paymentSnapshot,\n params.paymentMethodId,\n params.paymentMethodCode,\n ),\n };\n}\n\nfunction buildCalculationContext(params: {\n tenantId: string;\n organizationId: string;\n currencyCode: string;\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n}) {\n return {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n currencyCode: params.currencyCode,\n metadata: buildProviderContext({\n shippingSnapshot: params.shippingSnapshot,\n paymentSnapshot: params.paymentSnapshot,\n shippingMethodId: params.shippingMethodId,\n paymentMethodId: params.paymentMethodId,\n shippingMethodCode: params.shippingMethodCode,\n paymentMethodCode: params.paymentMethodCode,\n currencyCode: params.currencyCode,\n }),\n };\n}\n\nfunction mapOrderAdjustmentToDraft(\n adjustment: SalesOrderAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction mapQuoteAdjustmentToDraft(\n adjustment: SalesQuoteAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nasync function emitTotalsCalculated(\n eventBus: EventBus | null | undefined,\n payload: {\n documentKind: SalesDocumentKind;\n documentId: string;\n organizationId: string;\n tenantId: string;\n customerId?: string | null;\n totals: SalesDocumentCalculationResult[\"totals\"];\n lineCount: number;\n },\n): Promise<void> {\n if (!eventBus) return;\n await eventBus.emitEvent(\"sales.document.totals.calculated\", payload);\n}\n\nfunction isStoredRowSourcedLine(line: DocumentLineCreateInput): boolean {\n return (\n (line as Pick<SalesLineSnapshot, \"discountAmountFromStoredRow\">)\n .discountAmountFromStoredRow === true\n );\n}\n\nfunction isStoredRowSourcedTotalsLine(line: DocumentLineCreateInput): boolean {\n return (\n (line as Pick<SalesLineSnapshot, \"totalsFromStoredRow\">)\n .totalsFromStoredRow === true\n );\n}\n\nfunction createLineSnapshotFromInput(\n line: DocumentLineCreateInput,\n lineNumber: number,\n): SalesLineSnapshot {\n const quantity = Number(line.quantity ?? 0);\n const normalizedQuantity = toNumeric(\n line.normalizedQuantity ?? quantity,\n );\n return {\n lineNumber,\n kind: line.kind ?? \"product\",\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity,\n normalizedUnit:\n typeof line.normalizedUnit === \"string\"\n ? line.normalizedUnit\n : (line.quantityUnit ?? null),\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet ?? null,\n unitPriceGross: line.unitPriceGross ?? null,\n discountAmount: line.discountAmount ?? null,\n // Several callers re-run an already-mapped snapshot through here \u2014 the line\n // upsert and delete paths rebuild every line of the document, not just the\n // one being edited. Those inputs already carry a line total from a stored\n // row, so their origin must survive rather than be overwritten with the\n // caller default, or the untouched lines get re-inflated by quantity on\n // every write. Exactly one of the two origin fields is ever set, which is\n // the invariant the calculation engine relies on.\n ...(isStoredRowSourcedLine(line)\n ? { discountAmountFromStoredRow: true }\n : { discountAmountBasis: line.discountAmountBasis ?? \"unit\" }),\n // Carried independently of the discount origin above: a line upsert can\n // take its discount from the caller while its totals still come off the\n // stored row, and only the caller half is worth reconciling (#5644).\n ...(isStoredRowSourcedTotalsLine(line) ? { totalsFromStoredRow: true } : {}),\n discountPercent: line.discountPercent ?? null,\n taxRate: line.taxRate ?? null,\n taxAmount: line.taxAmount ?? null,\n totalNetAmount: line.totalNetAmount ?? null,\n totalGrossAmount: line.totalGrossAmount ?? null,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId:\n \"customFieldSetId\" in line\n ? ((line as any).customFieldSetId ?? null)\n : null,\n customFields:\n \"customFields\" in line && line.customFields\n ? cloneJson((line as any).customFields)\n : null,\n amountsMode: (line as { amountsMode?: SalesAmountsMode | null }).amountsMode ?? null,\n };\n}\n\nfunction createAdjustmentDraftFromInput(\n adjustment: DocumentAdjustmentCreateInput & { id?: string | null },\n): SalesAdjustmentDraft {\n const lineRef =\n \"quoteLineId\" in adjustment\n ? (adjustment as any).quoteLineId\n : (adjustment as any).orderLineId;\n if (adjustment.scope === \"line\" && lineRef) {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n return {\n id: typeof adjustment.id === \"string\" ? adjustment.id : undefined,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate ?? null,\n amountNet: adjustment.amountNet ?? null,\n amountGross: adjustment.amountGross ?? null,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction convertLineCalculationToEntityInput(\n lineResult: SalesLineCalculationResult,\n sourceLine: DocumentLineCreateInput,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const line = lineResult.line;\n // The gross-derived net repair heals core-owned rows; on an external line a\n // zero net is the caller's figure, not a defect to correct.\n const persistTotals = isExternalAmountsMode(line.amountsMode)\n ? <T,>(payload: T): T => payload\n : reconcileLinePersistedTotals;\n return persistTotals({\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind ?? \"product\",\n statusEntryId: sourceLine.statusEntryId ?? null,\n productId: sourceLine.productId ?? null,\n productVariantId: sourceLine.productVariantId ?? null,\n catalogSnapshot: sourceLine.catalogSnapshot\n ? cloneJson(sourceLine.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumericString(line.quantity) ?? \"0\",\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity:\n toNumericString(line.normalizedQuantity ?? line.quantity) ?? \"0\",\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet:\n toNumericString(\n line.unitPriceNet ??\n lineResult.netAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n unitPriceGross:\n toNumericString(\n line.unitPriceGross ??\n lineResult.grossAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n discountAmount: toNumericString(lineResult.discountAmount) ?? \"0\",\n discountPercent: toNumericString(line.discountPercent) ?? \"0\",\n taxRate: toNumericString(line.taxRate) ?? \"0\",\n taxAmount: toNumericString(lineResult.taxAmount) ?? \"0\",\n totalNetAmount: toNumericString(lineResult.netAmount) ?? \"0\",\n totalGrossAmount: toNumericString(lineResult.grossAmount) ?? \"0\",\n // Conditional: this converter also serves quote lines, which have no column.\n ...(line.amountsMode ? { amountsMode: line.amountsMode } : {}),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: sourceLine.promotionSnapshot\n ? cloneJson(sourceLine.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: sourceLine.customFieldSetId ?? null,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n });\n}\n\nfunction convertAdjustmentResultToEntityInput(\n adjustment: SalesAdjustmentDraft,\n sourceAdjustment: DocumentAdjustmentCreateInput | null,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const metadata = adjustment.metadata ? cloneJson(adjustment.metadata) : null;\n const resolvedPosition =\n sourceAdjustment?.position ??\n (adjustment.position !== null && adjustment.position !== undefined\n ? adjustment.position\n : index);\n return {\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumericString(adjustment.rate) ?? \"0\",\n amountNet: toNumericString(adjustment.amountNet) ?? \"0\",\n amountGross:\n toNumericString(adjustment.amountGross ?? adjustment.amountNet) ?? \"0\",\n currencyCode: adjustment.currencyCode ?? null,\n metadata,\n position: resolvedPosition,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n };\n}\n\nasync function applyOrderLineResults(params: {\n em: EntityManager;\n order: SalesOrder;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesOrderLine[];\n}): Promise<void> {\n const { em, order, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: order.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesOrderLine, {\n order,\n id: sourceLine.id ?? undefined,\n reservedQuantity: existing?.reservedQuantity ?? \"0\",\n fulfilledQuantity: existing?.fulfilledQuantity ?? \"0\",\n invoicedQuantity: existing?.invoicedQuantity ?? \"0\",\n returnedQuantity: existing?.returnedQuantity ?? \"0\",\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n order,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function applyQuoteLineResults(params: {\n em: EntityManager;\n quote: SalesQuote;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesQuoteLine[];\n}): Promise<void> {\n const { em, quote, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: quote.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesQuoteLine, {\n quote,\n id: sourceLine.id ?? undefined,\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n quote,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function replaceQuoteLines(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n lineInputs: QuoteLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: quote.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesQuoteLine, {\n quote,\n ...entityInput,\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceQuoteAdjustments(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: QuoteAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesQuoteAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n quote,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesQuoteAdjustment, {\n id: adjustmentId,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? quote.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.quoteLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustmentId,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nasync function replaceOrderLines(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n lineInputs: OrderLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: order.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesOrderLine, {\n order,\n ...entityInput,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceOrderAdjustments(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: OrderAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesOrderAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n order,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesOrderAdjustment, {\n id: adjustmentId,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? order.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.orderLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustmentId,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nfunction applyQuoteTotals(\n quote: SalesQuote,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n quote.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n quote.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n quote.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n quote.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n quote.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n quote.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n quote.totalsSnapshot = cloneJson(totals);\n quote.lineItemCount = lineCount;\n}\n\nfunction applyOrderTotals(\n order: SalesOrder,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n order.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n order.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n order.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n order.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n order.shippingNetAmount = toNumericString(totals.shippingNetAmount) ?? \"0\";\n order.shippingGrossAmount =\n toNumericString(totals.shippingGrossAmount) ?? \"0\";\n order.surchargeTotalAmount =\n toNumericString(totals.surchargeTotalAmount) ?? \"0\";\n order.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n order.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n order.paidTotalAmount = toNumericString(totals.paidTotalAmount) ?? \"0\";\n order.refundedTotalAmount =\n toNumericString(totals.refundedTotalAmount) ?? \"0\";\n order.outstandingAmount = toNumericString(totals.outstandingAmount) ?? \"0\";\n order.totalsSnapshot = cloneJson(totals);\n order.lineItemCount = lineCount;\n}\n\nfunction applyOrderLineAmountsFromCalculation(params: {\n em: EntityManager;\n lines: SalesOrderLine[];\n calculation: SalesDocumentCalculationResult;\n amountsMode: SalesAmountsMode;\n}): void {\n const { em, lines, calculation, amountsMode } = params;\n lines.forEach((line, index) => {\n const result = calculation.lines[index];\n if (!result) return;\n line.amountsMode = amountsMode;\n line.discountAmount = toNumericString(result.discountAmount) ?? \"0\";\n line.taxAmount = toNumericString(result.taxAmount) ?? \"0\";\n line.totalNetAmount = toNumericString(result.netAmount) ?? \"0\";\n line.totalGrossAmount = toNumericString(result.grossAmount) ?? \"0\";\n em.persist(line);\n });\n}\n\nfunction normalizePaymentTotal(value: unknown): number {\n if (typeof value === \"number\" && Number.isFinite(value))\n return Math.max(value, 0);\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? Math.max(parsed, 0) : 0;\n }\n return 0;\n}\n\nfunction resolveExistingPaymentTotals(order: SalesOrder) {\n return {\n paidTotalAmount: normalizePaymentTotal(order.paidTotalAmount),\n refundedTotalAmount: normalizePaymentTotal(order.refundedTotalAmount),\n };\n}\n\nfunction ensureQuoteScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction ensureOrderScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction normalizeTagIds(tags?: Array<string | null | undefined>): string[] {\n if (!Array.isArray(tags)) return [];\n const set = new Set<string>();\n tags.forEach((id) => {\n if (typeof id === \"string\" && id.trim().length > 0) set.add(id.trim());\n });\n return Array.from(set);\n}\n\n// A loaded assignment exposes its tag as an entity, an unwrapped id or the raw\n// column depending on how it was fetched; the snapshot loaders read it the same\n// defensive way. Returns null when the id cannot be determined, which callers\n// must treat as \"unrecognised\" rather than as a match.\nfunction readAssignmentTagId(assignment: {\n tag?: unknown;\n}): string | null {\n const tag = (assignment as { tag?: unknown }).tag;\n if (typeof tag === \"string\") return tag;\n return (\n (tag as { id?: string } | null | undefined)?.id ??\n (assignment as { tag_id?: string }).tag_id ??\n null\n );\n}\n\nfunction buildTagChange(\n beforeTags: TagAssignmentSnapshot[] | undefined,\n afterTags: TagAssignmentSnapshot[] | undefined,\n): { from: string[]; to: string[] } | null {\n const beforeIds = normalizeTagIds(beforeTags?.map((tag) => tag.tagId));\n const afterIds = normalizeTagIds(afterTags?.map((tag) => tag.tagId));\n beforeIds.sort((a, b) => a.localeCompare(b));\n afterIds.sort((a, b) => a.localeCompare(b));\n if (\n beforeIds.length === afterIds.length &&\n beforeIds.every((id, index) => id === afterIds[index])\n ) {\n return null;\n }\n return { from: beforeIds, to: afterIds };\n}\n\nfunction buildDocumentUpdateChangeKeys(kind: SalesDocumentKind, input: DocumentUpdateInput): string[] {\n const keys = new Set<string>();\n if (kind === \"order\") {\n if (input.orderNumber !== undefined) keys.add(\"orderNumber\");\n } else {\n if (input.quoteNumber !== undefined) keys.add(\"quoteNumber\");\n }\n if (input.statusEntryId !== undefined) {\n keys.add(\"statusEntryId\");\n keys.add(\"status\");\n }\n if (input.customerEntityId !== undefined) {\n keys.add(\"customerEntityId\");\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n keys.add(\"billingAddressId\");\n keys.add(\"shippingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (input.customerContactId !== undefined) {\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n }\n if (input.customerSnapshot !== undefined) keys.add(\"customerSnapshot\");\n if (input.metadata !== undefined) keys.add(\"metadata\");\n if (input.comment !== undefined) keys.add(\"comments\");\n if (input.comments !== undefined) keys.add(\"comments\");\n if (input.currencyCode !== undefined) keys.add(\"currencyCode\");\n if (input.channelId !== undefined) keys.add(\"channelId\");\n if (kind === \"order\") {\n if (input.internalNotes !== undefined) keys.add(\"internalNotes\");\n if (input.placedAt !== undefined) keys.add(\"placedAt\");\n if (input.expectedDeliveryAt !== undefined) keys.add(\"expectedDeliveryAt\");\n if (input.exchangeRate !== undefined) keys.add(\"exchangeRate\");\n if (input.paymentStatusEntryId !== undefined) {\n keys.add(\"paymentStatusEntryId\");\n keys.add(\"paymentStatus\");\n }\n if (input.fulfillmentStatusEntryId !== undefined) {\n keys.add(\"fulfillmentStatusEntryId\");\n keys.add(\"fulfillmentStatus\");\n }\n }\n if (\n input.shippingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined\n ) {\n keys.add(\"shippingAddressId\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (\n input.billingAddressId !== undefined ||\n input.billingAddressSnapshot !== undefined\n ) {\n keys.add(\"billingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined\n ) {\n keys.add(\"shippingMethodId\");\n keys.add(\"shippingMethodCode\");\n keys.add(\"shippingMethodSnapshot\");\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined\n ) {\n keys.add(\"paymentMethodId\");\n keys.add(\"paymentMethodCode\");\n keys.add(\"paymentMethodSnapshot\");\n }\n if (input.customFieldSetId !== undefined) keys.add(\"customFieldSetId\");\n if (input.customFields !== undefined) keys.add(\"customFields\");\n return Array.from(keys);\n}\n\n// Writes only the difference between the stored and the incoming tag set, and\n// no-ops when they are equal. The previous delete-all-then-reinsert rewrote an\n// unchanged set on every save that carried `tags`: on a large\n// sales_document_tag_assignments that delete was the dominant cost of a bulk\n// import, and it also reset each assignment's id/created_at, churned the unique\n// index and left two dead tuples per document per save.\n//\n// Semantics are unchanged \u2014 a tag removed out of band still differs from the\n// incoming set and is still restored. Removals go through the UnitOfWork rather\n// than nativeDelete because the assignments are loaded (managed) here; a native\n// delete would leave stale identities behind. The add and remove sets are\n// disjoint by construction, so MikroORM's insert-before-delete commit order can\n// never transiently violate the unique (tag_id, document_id, document_kind).\n//\n// The assignment read below is deliberately scoped by document only, with no\n// organization/tenant predicate \u2014 unlike the display reads in\n// api/documents/factory.ts, and unlike the tag-scope check above. It has to\n// match the scope of the unique constraint it reconciles against, which spans\n// (tag_id, document_id, document_kind) and no scope columns. Narrowing the read\n// would hide a mis-scoped row from the diff, put its tag in the add set, and\n// turn the insert into a unique-constraint violation. The document itself is\n// already scope-checked by the caller before this runs.\nasync function syncSalesDocumentTags(\n em: EntityManager,\n params: {\n documentId: string;\n kind: SalesDocumentKind;\n organizationId: string;\n tenantId: string;\n tagIds?: Array<string | null | undefined> | null;\n },\n) {\n if (params.tagIds === undefined) return;\n const tagIds = normalizeTagIds(params.tagIds);\n const byId = new Map<string, SalesDocumentTag>();\n if (tagIds.length > 0) {\n const tagsInScope = await em.find(SalesDocumentTag, {\n id: { $in: tagIds },\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n });\n if (tagsInScope.length !== tagIds.length) {\n throw new CrudHttpError(400, {\n error: \"One or more tags not found for this scope\",\n });\n }\n tagsInScope.forEach((tag) => byId.set(tag.id, tag));\n }\n const existing = await em.find(SalesDocumentTagAssignment, {\n documentId: params.documentId,\n documentKind: params.kind,\n });\n const existingByTagId = new Map<string, (typeof existing)[number]>();\n existing.forEach((assignment) => {\n const tagId = readAssignmentTagId(assignment);\n if (tagId) existingByTagId.set(tagId, assignment);\n });\n const wanted = new Set(tagIds);\n const toRemove = existing.filter((assignment) => {\n const tagId = readAssignmentTagId(assignment);\n return tagId === null || !wanted.has(tagId);\n });\n const toAdd = tagIds.filter((tagId) => !existingByTagId.has(tagId));\n if (toRemove.length === 0 && toAdd.length === 0) return;\n toRemove.forEach((assignment) => em.remove(assignment));\n for (const tagId of toAdd) {\n const tag = byId.get(tagId);\n if (!tag) continue;\n const assignment = em.create(SalesDocumentTagAssignment, {\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n documentId: params.documentId,\n documentKind: params.kind,\n tag,\n order:\n params.kind === \"order\"\n ? em.getReference(SalesOrder, params.documentId)\n : null,\n quote:\n params.kind === \"quote\"\n ? em.getReference(SalesQuote, params.documentId)\n : null,\n });\n em.persist(assignment);\n }\n}\n\nfunction applyQuoteSnapshot(\n quote: SalesQuote,\n snapshot: QuoteGraphSnapshot[\"quote\"],\n): void {\n quote.organizationId = snapshot.organizationId;\n quote.tenantId = snapshot.tenantId;\n quote.quoteNumber = snapshot.quoteNumber;\n quote.statusEntryId = snapshot.statusEntryId ?? null;\n quote.status = snapshot.status ?? null;\n quote.customerEntityId = snapshot.customerEntityId ?? null;\n quote.customerContactId = snapshot.customerContactId ?? null;\n quote.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n quote.billingAddressId = snapshot.billingAddressId ?? null;\n quote.shippingAddressId = snapshot.shippingAddressId ?? null;\n quote.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n quote.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n quote.currencyCode = snapshot.currencyCode;\n quote.validFrom = snapshot.validFrom ? new Date(snapshot.validFrom) : null;\n quote.validUntil = snapshot.validUntil ? new Date(snapshot.validUntil) : null;\n quote.comments = snapshot.comments ?? null;\n quote.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n quote.shippingMethodId = snapshot.shippingMethodId ?? null;\n quote.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n quote.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n quote.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n quote.paymentMethodId = snapshot.paymentMethodId ?? null;\n quote.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n quote.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n quote.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n quote.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n quote.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n quote.channelId = snapshot.channelId ?? null;\n quote.customFieldSetId = snapshot.customFieldSetId ?? null;\n quote.subtotalNetAmount = snapshot.subtotalNetAmount;\n quote.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n quote.discountTotalAmount = snapshot.discountTotalAmount;\n quote.taxTotalAmount = snapshot.taxTotalAmount;\n quote.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n quote.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n quote.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n quote.lineItemCount = snapshot.lineItemCount;\n}\n\nfunction applyOrderSnapshot(\n order: SalesOrder,\n snapshot: OrderGraphSnapshot[\"order\"],\n): void {\n order.organizationId = snapshot.organizationId;\n order.tenantId = snapshot.tenantId;\n order.orderNumber = snapshot.orderNumber;\n order.statusEntryId = snapshot.statusEntryId ?? null;\n order.status = snapshot.status ?? null;\n order.fulfillmentStatusEntryId = snapshot.fulfillmentStatusEntryId ?? null;\n order.fulfillmentStatus = snapshot.fulfillmentStatus ?? null;\n order.paymentStatusEntryId = snapshot.paymentStatusEntryId ?? null;\n order.paymentStatus = snapshot.paymentStatus ?? null;\n order.customerEntityId = snapshot.customerEntityId ?? null;\n order.customerContactId = snapshot.customerContactId ?? null;\n order.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n order.billingAddressId = snapshot.billingAddressId ?? null;\n order.shippingAddressId = snapshot.shippingAddressId ?? null;\n order.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n order.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n order.currencyCode = snapshot.currencyCode;\n order.exchangeRate = snapshot.exchangeRate ?? null;\n order.taxStrategyKey = snapshot.taxStrategyKey ?? null;\n order.discountStrategyKey = snapshot.discountStrategyKey ?? null;\n order.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n order.shippingMethodId = snapshot.shippingMethodId ?? null;\n order.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n order.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n order.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n order.paymentMethodId = snapshot.paymentMethodId ?? null;\n order.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n order.channelId = snapshot.channelId ?? null;\n order.placedAt = snapshot.placedAt ? new Date(snapshot.placedAt) : null;\n order.expectedDeliveryAt = snapshot.expectedDeliveryAt\n ? new Date(snapshot.expectedDeliveryAt)\n : null;\n order.dueAt = snapshot.dueAt ? new Date(snapshot.dueAt) : null;\n order.comments = snapshot.comments ?? null;\n order.internalNotes = snapshot.internalNotes ?? null;\n order.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n order.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n order.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n order.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n order.customFieldSetId = snapshot.customFieldSetId ?? null;\n order.subtotalNetAmount = snapshot.subtotalNetAmount;\n order.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n order.discountTotalAmount = snapshot.discountTotalAmount;\n order.taxTotalAmount = snapshot.taxTotalAmount;\n order.shippingNetAmount = snapshot.shippingNetAmount;\n order.shippingGrossAmount = snapshot.shippingGrossAmount;\n order.surchargeTotalAmount = snapshot.surchargeTotalAmount;\n order.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n order.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n order.paidTotalAmount = snapshot.paidTotalAmount;\n order.refundedTotalAmount = snapshot.refundedTotalAmount;\n order.outstandingAmount = snapshot.outstandingAmount;\n order.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n order.lineItemCount = snapshot.lineItemCount;\n // Restored with the amounts, never separately: the lines come back with their\n // own mode, so omitting this leaves a mixed document the next write recomputes.\n order.totalsMode = snapshot.totalsMode ?? \"computed\";\n}\n\nasync function assertQuoteGraphUndoCurrent(\n em: EntityManager,\n quoteId: string,\n expected: QuoteGraphSnapshot,\n): Promise<void> {\n const current = await loadQuoteSnapshot(em, quoteId);\n const unchanged =\n !!current &&\n sameIds(current.lines, expected.lines) &&\n sameIds(current.adjustments, expected.adjustments) &&\n sameRecords(current.notes, expected.notes) &&\n sameRecords(current.tags, expected.tags) &&\n sameRecords(current.addresses, expected.addresses);\n if (!unchanged) return throwDocumentUndoStale(\"quote\");\n}\n\nasync function undoQuoteGraph(\n ctx: CommandRuntimeContext,\n before: QuoteGraphSnapshot,\n after: QuoteGraphSnapshot | null | undefined,\n): Promise<void> {\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n let restored: SalesQuote | undefined;\n await em.transactional(async (tx) => {\n const quote = await findOneWithDecryption(\n tx,\n SalesQuote,\n { id: before.quote.id },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n { tenantId: before.quote.tenantId, organizationId: before.quote.organizationId },\n );\n if (after) {\n if (!quote) return throwDocumentUndoStale(\"quote\");\n await assertQuoteGraphUndoCurrent(tx, quote.id, after);\n tx.clear();\n }\n restored = await restoreQuoteGraph(tx, before, quote && after ? after : null);\n await tx.flush();\n });\n if (!restored) return;\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudUndoSideEffects({\n dataEngine,\n action: \"updated\",\n entity: restored,\n identifiers: {\n id: restored.id,\n organizationId: restored.organizationId,\n tenantId: restored.tenantId,\n },\n indexer: { entityType: E.sales.sales_quote },\n });\n}\n\nasync function restoreQuoteGraph(\n em: EntityManager,\n snapshot: QuoteGraphSnapshot,\n verified: QuoteGraphSnapshot | null = null,\n): Promise<SalesQuote> {\n let quote = await findOneWithDecryption(\n em,\n SalesQuote,\n { id: snapshot.quote.id },\n {},\n {\n tenantId: snapshot.quote.tenantId,\n organizationId: snapshot.quote.organizationId,\n },\n );\n if (!quote) {\n quote = em.create(SalesQuote, {\n id: snapshot.quote.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n quoteNumber: snapshot.quote.quoteNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n validFrom: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : null,\n validUntil: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n comments: snapshot.quote.comments ?? null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n channelId: snapshot.quote.channelId ?? null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(quote);\n }\n applyQuoteSnapshot(quote, snapshot.quote);\n await em.flush();\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n const existingAdjustments = await em.find(\n SalesQuoteAdjustment,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n const verifiedIds = (entries: ReadonlyArray<{ id: string }> | undefined) =>\n verified ? { id: { $in: (entries ?? []).map((entry) => entry.id) } } : {};\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n ...verifiedIds(verified?.addresses),\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n ...verifiedIds(verified?.notes),\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n ...verifiedIds(verified?.tags),\n });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesQuoteLine, {\n id: line.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesQuoteAdjustment, {\n id: adjustment.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.quoteLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"quote\",\n contextId: quote.id,\n order: null,\n quote,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n tag,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.quote.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: toSnapshotCustomFieldWriteValues(snapshot.quote.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: line.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: toSnapshotCustomFieldWriteValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustment.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: toSnapshotCustomFieldWriteValues(adjustment.customFields),\n });\n }\n\n return quote;\n}\n\nasync function throwDocumentUndoStale(kind: \"order\" | \"quote\"): Promise<never> {\n const { translate } = await resolveTranslations();\n throw new CrudHttpError(409, {\n error:\n kind === \"order\"\n ? translate(\n \"sales.documents.errors.undoStaleOrder\",\n \"This change can no longer be undone because the order was changed afterwards.\",\n )\n : translate(\n \"sales.documents.errors.undoStaleQuote\",\n \"This change can no longer be undone because the quote was changed afterwards.\",\n ),\n });\n}\n\nfunction canonicalizeForComparison(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value\n .map(canonicalizeForComparison)\n .map((entry) => ({ entry, key: JSON.stringify(entry) }))\n .sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0))\n .map(({ entry }) => entry);\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))\n .map((key) => [key, canonicalizeForComparison((value as Record<string, unknown>)[key])]),\n );\n }\n return value;\n}\n\nfunction toComparableRecords(\n entries: ReadonlyArray<{ id: string }> | null | undefined,\n): Map<string, unknown> {\n const records = new Map<string, unknown>();\n for (const entry of entries ?? []) {\n records.set(entry.id, canonicalizeForComparison(JSON.parse(JSON.stringify(entry))));\n }\n return records;\n}\n\nfunction withoutAllocationIds(\n payments: ReadonlyArray<PaymentSnapshot> | null | undefined,\n): Array<PaymentSnapshot> {\n return (payments ?? []).map((payment) => ({\n ...payment,\n allocations: (payment.allocations ?? []).map((allocation) =>\n Object.fromEntries(Object.entries(allocation).filter(([key]) => key !== \"id\")),\n ),\n }));\n}\n\nfunction sameRecords(\n current: ReadonlyArray<{ id: string }> | null | undefined,\n expected: ReadonlyArray<{ id: string }> | null | undefined,\n): boolean {\n const currentRecords = toComparableRecords(current);\n const expectedRecords = toComparableRecords(expected);\n if (currentRecords.size !== expectedRecords.size) return false;\n for (const [id, record] of expectedRecords) {\n if (!currentRecords.has(id)) return false;\n if (!isDeepStrictEqual(currentRecords.get(id), record)) return false;\n }\n return true;\n}\n\nfunction sameIds(\n current: ReadonlyArray<{ id: string }> | null | undefined,\n expected: ReadonlyArray<{ id: string }> | null | undefined,\n): boolean {\n const currentIds = new Set((current ?? []).map((entry) => entry.id));\n const expectedIds = (expected ?? []).map((entry) => entry.id);\n return (\n currentIds.size === expectedIds.length &&\n expectedIds.every((id) => currentIds.has(id))\n );\n}\n\nfunction sameLineProgress(\n current: ReadonlyArray<SalesLineSnapshot>,\n expected: ReadonlyArray<SalesLineSnapshot> | null | undefined,\n): boolean {\n if (!sameIds(current, expected)) return false;\n const expectedById = new Map((expected ?? []).map((line) => [line.id, line]));\n return current.every((line) => {\n const target = expectedById.get(line.id);\n return (\n !!target &&\n Number(line.fulfilledQuantity ?? 0) === Number(target.fulfilledQuantity ?? 0) &&\n Number(line.returnedQuantity ?? 0) === Number(target.returnedQuantity ?? 0)\n );\n });\n}\n\nasync function assertOrderGraphUndoCurrent(\n em: EntityManager,\n orderId: string,\n expected: OrderGraphSnapshot,\n): Promise<void> {\n const current = await loadOrderSnapshot(em, orderId);\n if (!current) return throwDocumentUndoStale(\"order\");\n const lineIds = current.lines.map((line) => line.id);\n const [returnCount, invoiceLineCount, creditMemoLineCount] = await Promise.all([\n em.count(SalesReturn, { order: orderId }),\n lineIds.length\n ? em.count(SalesInvoiceLine, { orderLine: { $in: lineIds } })\n : Promise.resolve(0),\n lineIds.length\n ? em.count(SalesCreditMemoLine, { orderLine: { $in: lineIds } })\n : Promise.resolve(0),\n ]);\n if (returnCount > 0 || invoiceLineCount > 0 || creditMemoLineCount > 0) {\n return throwDocumentUndoStale(\"order\");\n }\n const unchanged =\n sameLineProgress(current.lines, expected.lines) &&\n sameIds(current.adjustments, expected.adjustments) &&\n sameRecords(current.shipments, expected.shipments) &&\n sameRecords(withoutAllocationIds(current.payments), withoutAllocationIds(expected.payments)) &&\n sameRecords(current.notes, expected.notes) &&\n sameRecords(current.tags, expected.tags) &&\n sameRecords(current.addresses, expected.addresses);\n if (!unchanged) return throwDocumentUndoStale(\"order\");\n}\n\nasync function lockOrderForUndo(\n em: EntityManager,\n orderId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<boolean> {\n const order = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: orderId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n );\n if (!order) return false;\n await em.find(\n SalesOrderLine,\n { order: orderId },\n { lockMode: LockMode.PESSIMISTIC_WRITE, orderBy: { id: \"asc\" } },\n );\n return true;\n}\n\nasync function withVerifiedOrderGraph(\n ctx: CommandRuntimeContext,\n expected: OrderGraphSnapshot | null | undefined,\n scope: { orderId: string; tenantId: string; organizationId: string },\n work: (tx: EntityManager, exists: boolean) => Promise<void>,\n): Promise<void> {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n await em.transactional(async (tx) => {\n const exists = await lockOrderForUndo(tx, scope.orderId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n });\n if (exists && expected) {\n await assertOrderGraphUndoCurrent(tx, scope.orderId, expected);\n tx.clear();\n }\n await work(tx, exists);\n });\n}\n\nasync function undoOrderGraph(\n ctx: CommandRuntimeContext,\n before: OrderGraphSnapshot,\n after: OrderGraphSnapshot | null | undefined,\n): Promise<void> {\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n let restored: SalesOrder | undefined;\n await withVerifiedOrderGraph(\n ctx,\n after,\n {\n orderId: before.order.id,\n tenantId: before.order.tenantId,\n organizationId: before.order.organizationId,\n },\n async (tx, exists) => {\n if (!exists && after) await throwDocumentUndoStale(\"order\");\n restored = await restoreOrderGraph(tx, before, exists ? after : null);\n await tx.flush();\n },\n );\n if (!restored) return;\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudUndoSideEffects({\n dataEngine,\n action: \"updated\",\n entity: restored,\n identifiers: {\n id: restored.id,\n organizationId: restored.organizationId,\n tenantId: restored.tenantId,\n },\n indexer: { entityType: E.sales.sales_order },\n });\n}\n\nasync function restoreOrderGraph(\n em: EntityManager,\n snapshot: OrderGraphSnapshot,\n verified: OrderGraphSnapshot | null = null,\n): Promise<SalesOrder> {\n let order = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: snapshot.order.id },\n {},\n {\n tenantId: snapshot.order.tenantId,\n organizationId: snapshot.order.organizationId,\n },\n );\n let existingLines: SalesOrderLine[] = [];\n if (order) {\n existingLines = await em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n );\n await assertShippedOrderGraphRestorable(\n em,\n order,\n existingLines,\n snapshot,\n );\n }\n if (!order) {\n order = em.create(SalesOrder, {\n id: snapshot.order.id,\n organizationId: snapshot.order.organizationId,\n tenantId: snapshot.order.tenantId,\n orderNumber: snapshot.order.orderNumber,\n statusEntryId: snapshot.order.statusEntryId ?? null,\n status: snapshot.order.status ?? null,\n fulfillmentStatusEntryId: snapshot.order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: snapshot.order.fulfillmentStatus ?? null,\n paymentStatusEntryId: snapshot.order.paymentStatusEntryId ?? null,\n paymentStatus: snapshot.order.paymentStatus ?? null,\n customerEntityId: snapshot.order.customerEntityId ?? null,\n customerContactId: snapshot.order.customerContactId ?? null,\n customerSnapshot: snapshot.order.customerSnapshot\n ? cloneJson(snapshot.order.customerSnapshot)\n : null,\n billingAddressId: snapshot.order.billingAddressId ?? null,\n shippingAddressId: snapshot.order.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.order.billingAddressSnapshot\n ? cloneJson(snapshot.order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.order.shippingAddressSnapshot\n ? cloneJson(snapshot.order.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.order.currencyCode,\n exchangeRate: snapshot.order.exchangeRate ?? null,\n taxStrategyKey: snapshot.order.taxStrategyKey ?? null,\n discountStrategyKey: snapshot.order.discountStrategyKey ?? null,\n taxInfo: snapshot.order.taxInfo\n ? cloneJson(snapshot.order.taxInfo)\n : null,\n shippingMethodId: snapshot.order.shippingMethodId ?? null,\n shippingMethodCode: snapshot.order.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.order.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.order.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.order.paymentMethodId ?? null,\n paymentMethodCode: snapshot.order.paymentMethodCode ?? null,\n channelId: snapshot.order.channelId ?? null,\n placedAt: snapshot.order.placedAt\n ? new Date(snapshot.order.placedAt)\n : null,\n expectedDeliveryAt: snapshot.order.expectedDeliveryAt\n ? new Date(snapshot.order.expectedDeliveryAt)\n : null,\n dueAt: snapshot.order.dueAt ? new Date(snapshot.order.dueAt) : null,\n comments: snapshot.order.comments ?? null,\n internalNotes: snapshot.order.internalNotes ?? null,\n shippingMethodSnapshot: snapshot.order.shippingMethodSnapshot\n ? cloneJson(snapshot.order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.order.deliveryWindowSnapshot\n ? cloneJson(snapshot.order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.order.paymentMethodSnapshot\n ? cloneJson(snapshot.order.paymentMethodSnapshot)\n : null,\n metadata: snapshot.order.metadata\n ? cloneJson(snapshot.order.metadata)\n : null,\n customFieldSetId: snapshot.order.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.order.subtotalNetAmount,\n subtotalGrossAmount: snapshot.order.subtotalGrossAmount,\n discountTotalAmount: snapshot.order.discountTotalAmount,\n taxTotalAmount: snapshot.order.taxTotalAmount,\n shippingNetAmount: snapshot.order.shippingNetAmount,\n shippingGrossAmount: snapshot.order.shippingGrossAmount,\n surchargeTotalAmount: snapshot.order.surchargeTotalAmount,\n grandTotalNetAmount: snapshot.order.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.order.grandTotalGrossAmount,\n paidTotalAmount: snapshot.order.paidTotalAmount,\n refundedTotalAmount: snapshot.order.refundedTotalAmount,\n outstandingAmount: snapshot.order.outstandingAmount,\n totalsSnapshot: snapshot.order.totalsSnapshot\n ? cloneJson(snapshot.order.totalsSnapshot)\n : null,\n lineItemCount: snapshot.order.lineItemCount,\n totalsMode: snapshot.order.totalsMode ?? \"computed\",\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n }\n applyOrderSnapshot(order, snapshot.order);\n await em.flush();\n const existingAdjustments = await em.find(\n SalesOrderAdjustment,\n { order: order.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n const shipmentSnapshots = Array.isArray(snapshot.shipments)\n ? snapshot.shipments\n : [];\n const paymentSnapshots = Array.isArray(snapshot.payments)\n ? snapshot.payments\n : [];\n const existingShipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = existingShipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n existingShipments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n const verifiedIds = (entries: ReadonlyArray<{ id: string }> | undefined) =>\n verified ? { id: { $in: (entries ?? []).map((entry) => entry.id) } } : {};\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n ...verifiedIds(verified?.addresses),\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n ...verifiedIds(verified?.notes),\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n ...verifiedIds(verified?.tags),\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n // Not repaired from gross: an external line's net is the caller's figure.\n totalNetAmount: isExternalAmountsMode(line.amountsMode)\n ? line.totalNetAmount\n : toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n amountsMode: line.amountsMode ?? \"computed\",\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesOrderAdjustment, {\n id: adjustment.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.orderLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n quote: null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n tag,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.order.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: toSnapshotCustomFieldWriteValues(snapshot.order.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: line.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: toSnapshotCustomFieldWriteValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustment.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: toSnapshotCustomFieldWriteValues(adjustment.customFields),\n });\n }\n\n for (const shipment of shipmentSnapshots) {\n await restoreShipmentSnapshot(em, shipment);\n }\n\n for (const payment of paymentSnapshots) {\n await restorePaymentSnapshot(em, payment);\n }\n\n return order;\n}\n\nconst createQuoteCommand: CommandHandler<\n QuoteCreateInput,\n { quoteId: string }\n> = {\n id: \"sales.quotes.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = quoteCreateSchema.parse(rawInput ?? {});\n const quoteNumber =\n typeof initial.quoteNumber === \"string\" &&\n initial.quoteNumber.trim().length\n ? initial.quoteNumber.trim()\n : (\n await generator.generate({\n kind: \"quote\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = quoteCreateSchema.parse({ ...initial, quoteNumber });\n const ensuredQuoteNumber = parsed.quoteNumber ?? quoteNumber;\n if (!ensuredQuoteNumber) {\n throw new CrudHttpError(400, { error: \"Quote number is required.\" });\n }\n ensureQuoteScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n const quoteStatus = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n const quoteId = randomUUID();\n const quote = em.create(SalesQuote, {\n id: quoteId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteNumber: ensuredQuoteNumber,\n statusEntryId: parsed.statusEntryId ?? null,\n status: quoteStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n validFrom: parsed.validFrom ?? null,\n validUntil: parsed.validUntil ?? null,\n comments: parsed.comments ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n channelId: parsed.channelId ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n await assertAmountsModeUnsupportedOnQuote(parsed.lines ?? []);\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n quoteLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n quoteAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n }),\n )\n : null;\n\n const lineSnapshots: SalesLineSnapshot[] = normalizedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the quote header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(quote);\n await replaceQuoteLines(em, quote, calculation, normalizedLineInputs);\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: quote.id,\n kind: \"quote\",\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n tagIds: parsed.tags,\n });\n await setDocumentCustomFieldsIfSupplied(em, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customFields: parsed.customFields,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.quotes.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.quote.created\",\n );\n if (typeDef) {\n const totalAmount =\n quote.grandTotalGrossAmount && quote.currencyCode\n ? `${quote.grandTotalGrossAmount} ${quote.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.quotes.manage\",\n bodyVariables: {\n quoteNumber: quote.quoteNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:quote\",\n sourceEntityId: quote.id,\n linkHref: `/backend/sales/quotes/${quote.id}`,\n });\n\n // Bulk-import backfills opt out of the per-record notification fan-out (and its inline\n // e-mail delivery); interactive creates are unaffected.\n if (!ctx.bulkImport?.skipNotifications) {\n await notificationService.createForFeature(notificationInput, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId ?? null,\n });\n }\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n logger.error(\"sales.quotes.create failed to create notification\", { err });\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: quote,\n identifiers: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n events: quoteCrudEvents,\n indexer: { entityType: E.sales.sales_quote },\n actorUserId: ctx.auth?.sub ?? null,\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { quoteId: quote.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.create\", \"Create sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n ensureQuoteScope(ctx, after.quote.organizationId, after.quote.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n await em.transactional(async (tx) => {\n const quote = await findOneWithDecryption(\n tx,\n SalesQuote,\n { id: after.quote.id },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n {\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n },\n );\n if (!quote) return;\n await assertQuoteGraphUndoCurrent(tx, quote.id, after);\n await tx.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await tx.nativeDelete(SalesQuoteLine, { quote: quote.id });\n tx.remove(quote);\n await tx.flush();\n });\n },\n};\n\nconst deleteQuoteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string }\n> = {\n id: \"sales.quotes.delete\",\n async prepare(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await findOneWithDecryption(em, SalesQuote, { id });\n if (!quote)\n throw notFound(\"Sales quote not found\");\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const [addresses, notes, tags, adjustments, lines] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: quote.id,\n documentKind: \"quote\",\n },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: quote.id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n }),\n em.find(SalesQuoteAdjustment, { quote: quote.id }),\n em.find(SalesQuoteLine, { quote: quote.id }),\n ]);\n // Delete the quote and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n em.remove(quote);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, quote, E.sales.sales_quote),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_quote_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_quote_adjustment,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { quoteId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.delete\", \"Delete sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: before.quote.id,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\ntype TotalsCalculatedPayload = Parameters<typeof emitTotalsCalculated>[1];\ntype LockedGraphWrite<TResult> = {\n result: TResult;\n calculation: SalesDocumentCalculationResult;\n};\ntype LockedGraphSnapshots<TSnapshot> = {\n before: TSnapshot | null;\n after: TSnapshot | null;\n};\ntype LockedGraphKind<TDocument, TSnapshot> = {\n documentKind: SalesDocumentKind;\n lock: (\n em: EntityManager,\n ctx: CommandRuntimeContext,\n documentId: string,\n missingMessage: string,\n ) => Promise<TDocument>;\n loadSnapshot: (em: EntityManager, documentId: string) => Promise<TSnapshot | null>;\n snapshots: WeakMap<object, LockedGraphSnapshots<TSnapshot>>;\n};\n\nconst lockedGraphWriteInputs = new WeakSet<object>();\nconst lockedOrderGraphSnapshots = new WeakMap<object, LockedGraphSnapshots<OrderGraphSnapshot>>();\nconst lockedQuoteGraphSnapshots = new WeakMap<object, LockedGraphSnapshots<QuoteGraphSnapshot>>();\n\nfunction resolveRequestDecryptionScope(ctx: CommandRuntimeContext) {\n return {\n tenantId: ctx.auth?.tenantId ?? undefined,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? undefined,\n };\n}\n\nasync function lockOrderForTotalsWrite(\n em: EntityManager,\n ctx: CommandRuntimeContext,\n orderId: string,\n missingOrderMessage: string,\n): Promise<SalesOrder> {\n const existingOrder = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: orderId, deletedAt: null },\n {},\n resolveRequestDecryptionScope(ctx),\n );\n if (!existingOrder) throw notFound(missingOrderMessage);\n ensureOrderScope(ctx, existingOrder.organizationId, existingOrder.tenantId);\n const scope = {\n tenantId: existingOrder.tenantId,\n organizationId: existingOrder.organizationId,\n };\n if (!(await lockSalesDocumentRow(em, \"sales_orders\", orderId, scope))) {\n throw notFound(missingOrderMessage);\n }\n const order = await findOneWithDecryption(\n em,\n SalesOrder,\n { id: orderId, deletedAt: null, ...scope },\n { refresh: true },\n scope,\n );\n if (!order) throw notFound(missingOrderMessage);\n await enforceSalesDocumentOptimisticLock(ctx, order, SALES_RESOURCE_KIND_ORDER);\n return order;\n}\n\nasync function lockQuoteForTotalsWrite(\n em: EntityManager,\n ctx: CommandRuntimeContext,\n quoteId: string,\n missingQuoteMessage: string,\n): Promise<SalesQuote> {\n const existingQuote = await findOneWithDecryption(\n em,\n SalesQuote,\n { id: quoteId, deletedAt: null },\n {},\n resolveRequestDecryptionScope(ctx),\n );\n if (!existingQuote) throw notFound(missingQuoteMessage);\n ensureQuoteScope(ctx, existingQuote.organizationId, existingQuote.tenantId);\n const scope = {\n tenantId: existingQuote.tenantId,\n organizationId: existingQuote.organizationId,\n };\n if (!(await lockSalesDocumentRow(em, \"sales_quotes\", quoteId, scope))) {\n throw notFound(missingQuoteMessage);\n }\n const quote = await findOneWithDecryption(\n em,\n SalesQuote,\n { id: quoteId, deletedAt: null, ...scope },\n { refresh: true },\n scope,\n );\n if (!quote) throw notFound(missingQuoteMessage);\n await enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n return quote;\n}\n\nfunction buildTotalsCalculatedPayload(\n documentKind: SalesDocumentKind,\n document: SalesOrder | SalesQuote,\n calculation: SalesDocumentCalculationResult,\n): TotalsCalculatedPayload {\n return {\n documentKind,\n documentId: document.id,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n customerId: document.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n };\n}\n\nasync function emitCommittedTotalsCalculated(\n ctx: CommandRuntimeContext,\n payload: TotalsCalculatedPayload | null,\n): Promise<void> {\n if (!payload) return;\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n await emitTotalsCalculated(eventBus, payload);\n}\n\nconst lockedOrderGraphKind: LockedGraphKind<SalesOrder, OrderGraphSnapshot> = {\n documentKind: \"order\",\n lock: lockOrderForTotalsWrite,\n loadSnapshot: loadOrderSnapshot,\n snapshots: lockedOrderGraphSnapshots,\n};\n\nconst lockedQuoteGraphKind: LockedGraphKind<SalesQuote, QuoteGraphSnapshot> = {\n documentKind: \"quote\",\n lock: lockQuoteForTotalsWrite,\n loadSnapshot: loadQuoteSnapshot,\n snapshots: lockedQuoteGraphSnapshots,\n};\n\nfunction markLockedGraphWrite(input: object): Record<string, never> {\n lockedGraphWriteInputs.add(input);\n return {};\n}\n\nasync function writeLockedDocumentGraph<\n TDocument extends SalesOrder | SalesQuote,\n TSnapshot,\n TResult extends object,\n>(\n kind: LockedGraphKind<TDocument, TSnapshot>,\n input: object,\n ctx: CommandRuntimeContext,\n documentId: string,\n missingMessage: string,\n write: (em: EntityManager, document: TDocument) => Promise<LockedGraphWrite<TResult>>,\n): Promise<TResult> {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const captureSnapshots = lockedGraphWriteInputs.has(input);\n let written!: LockedGraphWrite<TResult>;\n let totalsEvent!: TotalsCalculatedPayload;\n let before: TSnapshot | null = null;\n let after: TSnapshot | null = null;\n await withAtomicFlush(\n em,\n [\n async () => {\n const document = await kind.lock(em, ctx, documentId, missingMessage);\n if (captureSnapshots) before = await kind.loadSnapshot(em, document.id);\n written = await write(em, document);\n totalsEvent = buildTotalsCalculatedPayload(\n kind.documentKind,\n document,\n written.calculation,\n );\n },\n ...(captureSnapshots\n ? [\n async () => {\n em.clear();\n after = await kind.loadSnapshot(em, documentId);\n },\n ]\n : []),\n ],\n { transaction: true },\n );\n if (captureSnapshots) kind.snapshots.set(written.result, { before, after });\n await emitCommittedTotalsCalculated(ctx, totalsEvent);\n return written.result;\n}\n\nfunction writeLockedOrderGraph<TResult extends object>(\n input: object,\n ctx: CommandRuntimeContext,\n orderId: string,\n missingOrderMessage: string,\n write: (em: EntityManager, order: SalesOrder) => Promise<LockedGraphWrite<TResult>>,\n): Promise<TResult> {\n return writeLockedDocumentGraph(lockedOrderGraphKind, input, ctx, orderId, missingOrderMessage, write);\n}\n\nfunction writeLockedQuoteGraph<TResult extends object>(\n input: object,\n ctx: CommandRuntimeContext,\n quoteId: string,\n missingQuoteMessage: string,\n write: (em: EntityManager, quote: SalesQuote) => Promise<LockedGraphWrite<TResult>>,\n): Promise<TResult> {\n return writeLockedDocumentGraph(lockedQuoteGraphKind, input, ctx, quoteId, missingQuoteMessage, write);\n}\n\nfunction resolveLockedOrderGraphBefore(\n result: object,\n preparedBefore: unknown,\n): OrderGraphSnapshot | undefined {\n return (\n lockedOrderGraphSnapshots.get(result)?.before ??\n (preparedBefore as OrderGraphSnapshot | undefined)\n );\n}\n\nfunction resolveLockedQuoteGraphBefore(\n result: object,\n preparedBefore: unknown,\n): QuoteGraphSnapshot | undefined {\n return (\n lockedQuoteGraphSnapshots.get(result)?.before ??\n (preparedBefore as QuoteGraphSnapshot | undefined)\n );\n}\n\nasync function captureLockedOrderGraphAfter(\n ctx: CommandRuntimeContext,\n result: object,\n orderId: string,\n): Promise<OrderGraphSnapshot | null> {\n const locked = lockedOrderGraphSnapshots.get(result);\n if (locked) return locked.after;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, orderId);\n}\n\nasync function captureLockedQuoteGraphAfter(\n ctx: CommandRuntimeContext,\n result: object,\n quoteId: string,\n): Promise<QuoteGraphSnapshot | null> {\n const locked = lockedQuoteGraphSnapshots.get(result);\n if (locked) return locked.after;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, quoteId);\n}\n\nconst updateQuoteCommand: CommandHandler<\n DocumentUpdateInput,\n { quote: SalesQuote }\n> = {\n id: \"sales.quotes.update\",\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, parsed.id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n await assertAmountsModeUnsupportedOnQuote([parsed]);\n documentEditSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n let quote!: SalesQuote;\n let totalsEvent: TotalsCalculatedPayload | null = null;\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, optional sent-token reset, and totals recalc\n // atomically. applyDocumentUpdate/replace*/setRecordCustomFields flush\n // mid-build, so without a transaction a later failure would leave a\n // half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n quote = await lockQuoteForTotalsWrite(em, ctx, parsed.id, \"Sales quote not found\");\n const shouldInvalidateSentToken = (quote.status ?? null) === \"sent\";\n await applyDocumentUpdate({\n kind: \"quote\",\n entity: quote,\n input: parsed,\n em,\n });\n // After applyDocumentUpdate, not before it: the reset must not happen\n // for an update that turns out to be invalid, or a rejected payload\n // still strips a sent quote of its acceptance link.\n if (shouldInvalidateSentToken) {\n quote.acceptanceToken = null;\n quote.sentAt = null;\n quote.status = \"draft\";\n quote.statusEntryId = await resolveStatusEntryIdByValue(em, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n value: \"draft\",\n });\n }\n },\n // Scalar mutations above are persisted by withAtomicFlush's per-phase\n // flush boundary before the recalc reads below run any query on the same\n // EntityManager. MikroORM v7 would otherwise silently discard pending\n // scalar changes on `quote` when the `em.find` line/adjustment lookups\n // reset the changeset (see SPEC-018).\n async () => {\n if (shouldRecalculateTotals) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n totalsEvent = buildTotalsCalculatedPayload(\"quote\", quote, calculation);\n }\n quote.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n await emitCommittedTotalsCalculated(ctx, totalsEvent);\n // Same as sales.orders.update (#6217): refresh the query-index projection so\n // customFields written in applyDocumentUpdate are visible on the next list GET.\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: quote,\n identifiers: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n indexer: { entityType: E.sales.sales_quote },\n actorUserId: ctx.auth?.sub ?? null,\n });\n const resourceKind =\n deriveResourceFromCommandId(updateQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { quote };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quote.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.quote as unknown as Record<string, unknown>,\n after.quote as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"quote\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.quotes.update\", \"Update sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quote.id,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\n/**\n * Output contracts for the order commands, consumed by the workflows context\n * ledger through `commandRegistry.outputSchemaOf`.\n *\n * `sales.orders.update` genuinely returns the mutated `SalesOrder` entity, not\n * an id \u2014 so the schema describes the entity's own scalar columns. It is a\n * curated subset, not the whole entity: relation properties (`channel`,\n * `shippingMethod`, `lines`) are ORM references that do not survive the JSON\n * context column, and the jsonb snapshot blobs carry no pickable shape. Zod\n * objects do not claim exhaustiveness, so naming a subset stays honest while\n * keeping the variable picker readable.\n */\nconst orderEntityOutputSchema = z.object({\n id: z.string().uuid(),\n organizationId: z.string().uuid(),\n tenantId: z.string().uuid(),\n orderNumber: z.string(),\n channelId: z.string().uuid().nullable().optional(),\n customerEntityId: z.string().uuid().nullable().optional(),\n currencyCode: z.string(),\n status: z.string().nullable().optional(),\n statusEntryId: z.string().uuid().nullable().optional(),\n fulfillmentStatus: z.string().nullable().optional(),\n paymentStatus: z.string().nullable().optional(),\n subtotalNetAmount: z.string(),\n subtotalGrossAmount: z.string(),\n discountTotalAmount: z.string(),\n taxTotalAmount: z.string(),\n grandTotalNetAmount: z.string(),\n grandTotalGrossAmount: z.string(),\n paidTotalAmount: z.string(),\n outstandingAmount: z.string(),\n lineItemCount: z.number(),\n placedAt: z.date().nullable().optional(),\n dueAt: z.date().nullable().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nconst orderUpdateOutputSchema = z.object({ order: orderEntityOutputSchema });\n\nconst orderIdOutputSchema = z.object({ orderId: z.string().uuid() });\n\nconst updateOrderCommand: CommandHandler<\n DocumentUpdateInput,\n { order: SalesOrder }\n> = {\n id: \"sales.orders.update\",\n outputSchema: orderUpdateOutputSchema,\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, parsed.id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n let order!: SalesOrder;\n let previousStatus: string | null = null;\n let nextTotalsMode: SalesAmountsMode = \"computed\";\n let totalsModeChanged = false;\n let externalHeaderSupplied = false;\n let suppliedTotals: Partial<SalesDocumentAmounts> | null = null;\n let statusChangeNote: SalesNote | null = null;\n let totalsEvent: TotalsCalculatedPayload | null = null;\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, totals recalc, and status-change note atomically.\n // applyDocumentUpdate/replace*/setRecordCustomFields flush mid-build, so\n // without a transaction a later failure would leave a half-updated order\n // committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n order = await lockOrderForTotalsWrite(em, ctx, parsed.id, \"Sales order not found\");\n const currentTotalsMode: SalesAmountsMode = order.totalsMode ?? \"computed\";\n nextTotalsMode = parsed.totalsMode ?? currentTotalsMode;\n totalsModeChanged = nextTotalsMode !== currentTotalsMode;\n externalHeaderSupplied =\n isExternalAmountsMode(nextTotalsMode) && hasAnySuppliedHeaderTotal(parsed);\n if (!totalsModeChanged && !externalHeaderSupplied) {\n documentEditSchema.parse(rawInput ?? {});\n }\n if (isExternalAmountsMode(nextTotalsMode) && (totalsModeChanged || externalHeaderSupplied)) {\n await requireOrderTotalsForExternalWrite(parsed);\n }\n suppliedTotals = isExternalAmountsMode(nextTotalsMode)\n ? externalHeaderSupplied\n ? buildExternalHeaderTotals(parsed)\n : readPersistedHeaderTotals(order)\n : null;\n previousStatus = normalizeStatusValue(order.status);\n if (parsed.statusEntryId && !isCancelledOrderStatus(previousStatus)) {\n const requestedStatus = normalizeStatusValue(\n await resolveDictionaryEntryValue(em, parsed.statusEntryId, {\n tenantId: order.tenantId,\n }),\n );\n if (isCancelledOrderStatus(requestedStatus)) {\n await assertOrderCanBeCancelled(em, order);\n }\n }\n await applyDocumentUpdate({\n kind: \"order\",\n entity: order,\n input: parsed,\n em,\n });\n },\n // Scalar mutations above are persisted by withAtomicFlush's per-phase\n // flush boundary before the recalc reads and the status-change-note\n // lookup below run any query on the same EntityManager. MikroORM v7 would\n // otherwise silently discard pending scalar changes on `order` when the\n // `em.find` lines/adjustments or appendOrderStatusChangeNote queries\n // reset the changeset (see SPEC-018).\n async () => {\n if (shouldRecalculateTotals || totalsModeChanged || externalHeaderSupplied) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n // Leaving external: the stored tax and gross are the source's figures,\n // and the computed path honours both verbatim while it re-derives net,\n // so they must be re-derived too or net + tax \u2260 gross (#7925).\n const leavingExternal =\n totalsModeChanged && !isExternalAmountsMode(nextTotalsMode);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n ...(leavingExternal ? { taxAmount: null, totalGrossAmount: null } : {}),\n amountsMode: nextTotalsMode,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode: nextTotalsMode,\n suppliedTotals,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n if (totalsModeChanged) {\n applyOrderLineAmountsFromCalculation({\n em,\n lines: existingLines,\n calculation,\n amountsMode: nextTotalsMode,\n });\n order.totalsMode = nextTotalsMode;\n }\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n totalsEvent = buildTotalsCalculatedPayload(\"order\", order, calculation);\n }\n statusChangeNote = await appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth: ctx.auth ?? null,\n });\n order.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n await emitCommittedTotalsCalculated(ctx, totalsEvent);\n emitOrderLifecycleEventsForTransition({ order, previousStatus });\n // Refresh the query-index projection (including customValues). Create already\n // did this; update used to only invalidate the HTTP CRUD cache, so a PUT that\n // wrote EAV custom fields still returned the pre-update values on the next\n // GET `/api/sales/orders?id=` (list reads cf_* from the index, #6217).\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: order,\n identifiers: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n indexer: { entityType: E.sales.sales_order },\n actorUserId: ctx.auth?.sub ?? null,\n });\n if (statusChangeNote) {\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: statusChangeNote,\n identifiers: {\n id: statusChangeNote.id,\n organizationId: statusChangeNote.organizationId,\n tenantId: statusChangeNote.tenantId,\n },\n indexer: { entityType: E.sales.sales_note },\n });\n }\n const resourceKind =\n deriveResourceFromCommandId(updateOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { order };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.order.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.order as unknown as Record<string, unknown>,\n after.order as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"order\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.orders.update\", \"Update sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.order.id,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst createOrderCommand: CommandHandler<\n OrderCreateInput,\n { orderId: string; warnings?: OrderPaymentLedgerWarning[] }\n> = {\n id: \"sales.orders.create\",\n outputSchema: orderIdOutputSchema,\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const deprecatedPaymentLedgerFields = resolveSuppliedOrderPaymentLedgerFields(rawInput)\n const initial = orderCreateSchema.parse(rawInput ?? {});\n if (deprecatedPaymentLedgerFields.length && !warnedDeprecatedOrderPaymentLedgerInput) {\n warnedDeprecatedOrderPaymentLedgerInput = true\n logger.warn(\"sales.orders.create ignored deprecated payment ledger input\", {\n code: ORDER_PAYMENT_LEDGER_WARNING_CODE,\n fields: deprecatedPaymentLedgerFields,\n })\n }\n const orderNumber =\n typeof initial.orderNumber === \"string\" &&\n initial.orderNumber.trim().length\n ? initial.orderNumber.trim()\n : (\n await generator.generate({\n kind: \"order\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = orderCreateSchema.parse({ ...initial, orderNumber });\n const ensuredOrderNumber = parsed.orderNumber ?? orderNumber;\n if (!ensuredOrderNumber) {\n throw new CrudHttpError(400, { error: \"Order number is required.\" });\n }\n ensureOrderScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n // Soft-resolve the cache so the per-order status/fulfillment/payment dictionary lookups are\n // memoized across a bulk import; degrades to a straight EM read when no cache is registered.\n const dictionaryCache = ctx.container.resolve(\"cache\", { allowUnregistered: true }) as\n | CacheStrategy\n | undefined;\n const [status, fulfillmentStatus, paymentStatus] = await Promise.all([\n resolveCachedDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: parsed.tenantId }, dictionaryCache),\n resolveCachedDictionaryEntryValue(em, parsed.fulfillmentStatusEntryId ?? null, { tenantId: parsed.tenantId }, dictionaryCache),\n resolveCachedDictionaryEntryValue(em, parsed.paymentStatusEntryId ?? null, { tenantId: parsed.tenantId }, dictionaryCache),\n ]);\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n\n const orderId = randomUUID()\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderNumber: ensuredOrderNumber,\n externalReference: parsed.externalReference ?? null,\n customerReference: parsed.customerReference ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n fulfillmentStatusEntryId: parsed.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus,\n paymentStatusEntryId: parsed.paymentStatusEntryId ?? null,\n paymentStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n exchangeRate:\n typeof parsed.exchangeRate === \"number\"\n ? toNumericString(parsed.exchangeRate)\n : null,\n taxStrategyKey: parsed.taxStrategyKey ?? null,\n discountStrategyKey: parsed.discountStrategyKey ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n channelId: parsed.channelId ?? null,\n placedAt: parsed.placedAt ?? null,\n expectedDeliveryAt: parsed.expectedDeliveryAt ?? null,\n dueAt: parsed.dueAt ?? null,\n comments: parsed.comments ?? null,\n internalNotes: parsed.internalNotes ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n shippingNetAmount: \"0\",\n shippingGrossAmount: \"0\",\n surchargeTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n orderLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n orderAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n }),\n )\n : null;\n\n const totalsMode: SalesAmountsMode = parsed.totalsMode ?? \"computed\";\n await assertUniformAmountsMode(totalsMode, normalizedLineInputs);\n const modedLineInputs = normalizedLineInputs.map((line) => ({\n ...line,\n amountsMode: totalsMode,\n }));\n if (isExternalAmountsMode(totalsMode)) {\n await assertExternalHeaderComplete(parsed);\n for (const [index, line] of modedLineInputs.entries()) {\n await assertExternalLineComplete(line, line.lineNumber ?? index + 1);\n }\n }\n order.totalsMode = totalsMode;\n const suppliedTotals: Partial<SalesDocumentAmounts> | null = isExternalAmountsMode(totalsMode)\n ? buildExternalHeaderTotals(parsed)\n : null;\n const lineSnapshots: SalesLineSnapshot[] = modedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode,\n suppliedTotals,\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the order header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(order);\n await replaceOrderLines(em, order, calculation, modedLineInputs);\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: order.id,\n kind: \"order\",\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n tagIds: parsed.tags,\n });\n await setDocumentCustomFieldsIfSupplied(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customFields: parsed.customFields,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.orders.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.order.created\",\n );\n if (typeDef) {\n const totalAmount =\n order.grandTotalGrossAmount && order.currencyCode\n ? `${order.grandTotalGrossAmount} ${order.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.orders.manage\",\n bodyVariables: {\n orderNumber: order.orderNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:order\",\n sourceEntityId: order.id,\n linkHref: `/backend/sales/orders/${order.id}`,\n });\n\n // Bulk-import backfills opt out of the per-record notification fan-out (and its inline\n // e-mail delivery); interactive creates are unaffected.\n if (!ctx.bulkImport?.skipNotifications) {\n await notificationService.createForFeature(notificationInput, {\n tenantId: order.tenantId,\n organizationId: order.organizationId ?? null,\n });\n }\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n logger.error(\"sales.orders.create failed to create notification\", { err });\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: order,\n identifiers: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n events: orderCrudEvents,\n indexer: { entityType: E.sales.sales_order },\n actorUserId: ctx.auth?.sub ?? null,\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n emitOrderLifecycleEventsForTransition({\n order,\n previousStatus: null,\n });\n\n return {\n orderId: order.id,\n ...(deprecatedPaymentLedgerFields.length\n ? {\n warnings: [\n {\n code: ORDER_PAYMENT_LEDGER_WARNING_CODE,\n fields: deprecatedPaymentLedgerFields,\n },\n ],\n }\n : {}),\n };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.create\", \"Create sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n ensureOrderScope(ctx, after.order.organizationId, after.order.tenantId);\n await withVerifiedOrderGraph(\n ctx,\n after,\n {\n orderId: after.order.id,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n },\n async (tx, exists) => {\n if (!exists) return;\n const order = await findOneWithDecryption(\n tx,\n SalesOrder,\n { id: after.order.id },\n {},\n {\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n },\n );\n if (!order) return;\n await tx.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await tx.nativeDelete(SalesOrderLine, { order: order.id });\n tx.remove(order);\n await tx.flush();\n },\n );\n },\n};\n\nconst deleteOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.orders.delete\",\n outputSchema: orderIdOutputSchema,\n async prepare(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await findOneWithDecryption(em, SalesOrder, { id });\n if (!order)\n throw notFound(\"Sales order not found\");\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n const shipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = shipments.map((entry) => entry.id);\n const [\n shipmentItems,\n payments,\n paymentAllocations,\n addresses,\n notes,\n tags,\n adjustments,\n lines,\n ] = await Promise.all([\n shipmentIds.length\n ? em.find(SalesShipmentItem, { shipment: { $in: shipmentIds } })\n : Promise.resolve([]),\n em.find(SalesPayment, { order: order.id }),\n em.find(SalesPaymentAllocation, { order: order.id }),\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: order.id,\n documentKind: \"order\",\n },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: order.id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n }),\n em.find(SalesOrderAdjustment, { order: order.id }),\n em.find(SalesOrderLine, { order: order.id }),\n ]);\n // Delete the order and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n em.remove(order);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, order, E.sales.sales_order),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_order_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_order_adjustment,\n ),\n queueDeletionSideEffects(dataEngine, shipments, E.sales.sales_shipment),\n queueDeletionSideEffects(\n dataEngine,\n shipmentItems,\n E.sales.sales_shipment_item,\n ),\n queueDeletionSideEffects(dataEngine, payments, E.sales.sales_payment),\n queueDeletionSideEffects(\n dataEngine,\n paymentAllocations,\n E.sales.sales_payment_allocation,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { orderId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.delete\", \"Delete sales order\"),\n resourceKind: \"sales.order\",\n resourceId: before.order.id,\n tenantId: before.order.tenantId,\n organizationId: before.order.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteConvertToOrderSchema = z.object({\n quoteId: z.string().uuid(),\n orderId: z.string().uuid().optional(),\n orderNumber: z.string().trim().max(191).optional(),\n});\n\nconst convertQuoteToOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.quotes.convert_to_order\",\n async prepare(input, ctx) {\n const parsed = quoteConvertToOrderSchema.safeParse(input ?? {});\n const quoteId = parsed.success\n ? parsed.data.quoteId\n : typeof (input as any)?.quoteId === \"string\"\n ? (input as any).quoteId\n : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const payload = quoteConvertToOrderSchema.parse(rawInput ?? {});\n // When the caller supplies an existing transactional EntityManager, reuse it\n // (and its row locks) so the quote status flip and the order materialization\n // commit or roll back as one atomic unit \u2014 no out-of-band compensating write.\n const callerEm = ctx.transactionalEm;\n const rootEm =\n callerEm ?? (ctx.container.resolve(\"em\") as EntityManager).fork();\n const transactionalEm = rootEm as EntityManager & {\n transactional?: <TResult>(\n callback: (trx: EntityManager) => Promise<TResult>,\n ) => Promise<TResult>;\n };\n const runConversion = async (em: EntityManager) => {\n const quote = await findOneWithDecryption(\n em,\n SalesQuote,\n {\n id: payload.quoteId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n );\n const { translate } = await resolveTranslations();\n if (!quote)\n throw notFound(translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ));\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n await enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n const snapshot = await loadQuoteSnapshot(em, payload.quoteId);\n if (!snapshot)\n throw notFound(translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ));\n const orderId = payload.orderId ?? quote.id;\n const existingOrder = await findOneWithDecryption(em, SalesOrder, {\n id: orderId,\n deletedAt: null,\n }, undefined, { tenantId: quote.tenantId, organizationId: quote.organizationId });\n if (existingOrder) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.detail.convertExists\",\n \"Order already exists for this quote.\",\n ),\n });\n }\n\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const generatedNumber = (\n await generator.generate({\n kind: \"order\",\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n })\n ).number;\n const orderNumber =\n typeof payload.orderNumber === \"string\" &&\n payload.orderNumber.trim().length\n ? payload.orderNumber.trim()\n : generatedNumber;\n\n const [quoteCustomFields, quoteLineCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [snapshot.quote.id],\n tenantIdByRecord: { [snapshot.quote.id]: snapshot.quote.tenantId },\n organizationIdByRecord: {\n [snapshot.quote.id]: snapshot.quote.organizationId,\n },\n }),\n snapshot.lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: snapshot.lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [line.id, snapshot.quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [\n line.id,\n snapshot.quote.organizationId,\n ]),\n ),\n })\n : Promise.resolve({}),\n ]);\n\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n orderNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n fulfillmentStatusEntryId: null,\n fulfillmentStatus: null,\n paymentStatusEntryId: null,\n paymentStatus: null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n exchangeRate: null,\n taxStrategyKey: null,\n discountStrategyKey: null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n channelId: snapshot.quote.channelId ?? null,\n placedAt: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : quote.createdAt,\n expectedDeliveryAt: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n dueAt: null,\n comments: snapshot.quote.comments ?? null,\n internalNotes: null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n ...resolveConvertedOrderFeeTotals({\n totalsSnapshot: snapshot.quote.totalsSnapshot,\n currencyCode: snapshot.quote.currencyCode,\n adjustments: snapshot.adjustments,\n }),\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n\n const orderLineMap = new Map<string, SalesOrderLine>();\n snapshot.lines.forEach((line, index) => {\n const orderLine = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind as SalesLineKind,\n statusEntryId: (line as any).statusEntryId ?? null,\n status: (line as any).status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration\n ? cloneJson(line.configuration)\n : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(orderLine);\n orderLineMap.set(orderLine.id, orderLine);\n });\n\n snapshot.adjustments.forEach((adj, index) => {\n const orderLineId = adj.quoteLineId ?? null;\n const orderLine = orderLineId\n ? (orderLineMap.get(orderLineId) ?? null)\n : null;\n const entity = em.create(SalesOrderAdjustment, {\n id: adj.id,\n order,\n orderLine: orderLine ?? null,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n scope: adj.scope,\n kind: adj.kind as SalesAdjustmentKind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n const [addresses, notes, tags] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n },\n {},\n {\n tenantId: snapshot.quote.tenantId,\n organizationId: snapshot.quote.organizationId,\n },\n ),\n findWithDecryption(\n em,\n SalesNote,\n {\n contextType: \"quote\",\n contextId: snapshot.quote.id,\n },\n {},\n {\n tenantId: snapshot.quote.tenantId,\n organizationId: snapshot.quote.organizationId,\n },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n }),\n ]);\n addresses.forEach((entry) => {\n entry.documentKind = \"order\";\n entry.documentId = order.id;\n entry.order = order;\n entry.quote = null;\n entry.updatedAt = new Date();\n });\n notes.forEach((note) => {\n note.contextType = \"order\";\n note.contextId = order.id;\n note.order = order;\n note.quote = null;\n note.updatedAt = new Date();\n });\n tags.forEach((assignment) => {\n assignment.documentKind = \"order\";\n assignment.documentId = order.id;\n assignment.order = order;\n assignment.quote = null;\n assignment.updatedAt = new Date();\n });\n\n const documentCustomValues = quoteCustomFields[snapshot.quote.id];\n if (documentCustomValues && Object.keys(documentCustomValues).length) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values: documentCustomValues,\n });\n }\n const lineCustomEntries = quoteLineCustomFields as Record<\n string,\n Record<string, unknown>\n >;\n if (lineCustomEntries && Object.keys(lineCustomEntries).length) {\n for (const [lineId, values] of Object.entries(lineCustomEntries)) {\n if (!values || !Object.keys(values).length) continue;\n if (!orderLineMap.has(lineId)) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values,\n });\n }\n }\n\n await em.nativeDelete(SalesQuoteAdjustment, { quote: snapshot.quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: snapshot.quote.id });\n em.remove(quote);\n await em.flush();\n\n return { orderId: order.id };\n };\n if (callerEm) {\n // Already inside the caller's transaction \u2014 run directly so the whole flow\n // stays a single transaction (no nested savepoint).\n return runConversion(callerEm);\n }\n return typeof transactionalEm.transactional === \"function\"\n ? transactionalEm.transactional((trx) => runConversion(trx))\n : runConversion(rootEm);\n },\n captureAfter: async (_input, result, ctx) => {\n // Prefer the caller's transactional EM so the just-created (still\n // uncommitted) order is visible when building the audit \"after\" snapshot.\n const em =\n ctx.transactionalEm ??\n (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.convert\",\n \"Convert quote to order\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n quote: before,\n order: after ?? null,\n } satisfies QuoteConvertUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteConvertUndoPayload>(logEntry);\n const quoteSnapshot = payload?.quote;\n const orderSnapshot = payload?.order;\n if (!quoteSnapshot) return;\n ensureQuoteScope(\n ctx,\n quoteSnapshot.quote.organizationId,\n quoteSnapshot.quote.tenantId,\n );\n const revertConversion = async (em: EntityManager, orderExists: boolean) => {\n if (orderSnapshot) {\n const orderId = orderSnapshot.order.id;\n const orderLineIds = orderSnapshot.lines.map((line) => line.id);\n const existingOrder = orderExists\n ? await findOneWithDecryption(em, SalesOrder, { id: orderId }, undefined, { tenantId: quoteSnapshot.quote.tenantId, organizationId: quoteSnapshot.quote.organizationId })\n : null;\n if (existingOrder) {\n const shipments = await em.find(SalesShipment, { order: orderId });\n const shipmentIds = shipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: orderId });\n await em.nativeDelete(SalesPayment, { order: orderId });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: orderId });\n await em.nativeDelete(SalesOrderLine, { order: orderId });\n em.remove(existingOrder);\n }\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: orderId,\n });\n if (orderLineIds.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: orderLineIds } as any,\n });\n }\n }\n const noteIds = quoteSnapshot.notes.map((note) => note.id);\n if (noteIds.length) {\n await em.nativeDelete(SalesNote, { id: { $in: noteIds } });\n }\n await restoreQuoteGraph(em, quoteSnapshot);\n await em.flush();\n };\n if (orderSnapshot) {\n await withVerifiedOrderGraph(\n ctx,\n orderSnapshot,\n {\n orderId: orderSnapshot.order.id,\n tenantId: orderSnapshot.order.tenantId,\n organizationId: orderSnapshot.order.organizationId,\n },\n revertConversion,\n );\n return;\n }\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n await em.transactional((tx) => revertConversion(tx, false));\n },\n};\n\n// Nested rather than spread flat: a line payload already has a `totalNetAmount`\n// that means the line's, not the document's.\nconst orderLineUpsertSchema = orderLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n orderTotals: orderHeaderTotalsSchema.optional(),\n});\n\nconst orderLineDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n orderTotals: orderHeaderTotalsSchema.optional(),\n});\n\nconst quoteLineUpsertSchema = quoteLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n});\n\nconst quoteLineDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst orderAdjustmentUpsertSchema = orderAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst orderAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n});\n\nconst quoteAdjustmentUpsertSchema = quoteAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst quoteAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst SHIPPED_QUANTITY_TOLERANCE = 1e-6;\n\n// Locked outright on a shipped line: none of these may move at all.\nconst SHIPPED_LINE_NUMERIC_PRICING_FIELDS = [\n \"unitPriceNet\",\n \"unitPriceGross\",\n \"discountAmount\",\n \"discountPercent\",\n \"taxRate\",\n] as const;\n\n// Line totals are derived, not authored: clients recompute and echo them on every\n// submit, so raising the quantity of a shipped line legitimately changes them. They\n// are still writable straight through, so they cannot simply be ignored either.\n// The invariant that separates a quantity edit from moving money is the per-unit\n// economics \u2014 total per unit must stay put, whatever the quantity does. That also\n// keeps discounted lines working, since a proportional total scales with quantity.\nconst SHIPPED_LINE_DERIVED_TOTAL_FIELDS = [\n \"totalNetAmount\",\n \"totalGrossAmount\",\n] as const;\n\ntype ShippedLineComparable = Pick<\n SalesLineSnapshot,\n | \"quantity\"\n | \"quantityUnit\"\n | (typeof SHIPPED_LINE_NUMERIC_PRICING_FIELDS)[number]\n | (typeof SHIPPED_LINE_DERIVED_TOTAL_FIELDS)[number]\n>;\n\nconst hasNumericChange = (\n next: number | null | undefined,\n previous: number | null | undefined,\n): boolean => {\n if (next === undefined || next === null) return false;\n if (previous === undefined || previous === null) return true;\n return Math.abs(next - previous) > SHIPPED_QUANTITY_TOLERANCE;\n};\n\nconst hasExactNumericChange = (\n next: number | null | undefined,\n previous: number | null | undefined,\n): boolean => {\n if (next === undefined || next === null) {\n return previous !== undefined && previous !== null;\n }\n if (previous === undefined || previous === null) return true;\n return Math.abs(next - previous) > SHIPPED_QUANTITY_TOLERANCE;\n};\n\nconst hasUnitChange = (\n next: string | null | undefined,\n previous: string | null | undefined,\n): boolean => {\n if (next === undefined || next === null) return false;\n const normalizedPrevious = (previous ?? \"\").trim().toLowerCase();\n if (!normalizedPrevious) return false;\n return next.trim().toLowerCase() !== normalizedPrevious;\n};\n\nconst hasExactUnitChange = (\n next: string | null | undefined,\n previous: string | null | undefined,\n): boolean =>\n (next ?? \"\").trim().toLowerCase() !==\n (previous ?? \"\").trim().toLowerCase();\n\nfunction hasShippedLineTotalChange(\n next: Partial<ShippedLineComparable>,\n previous: ShippedLineComparable,\n nextQuantity: number | null | undefined,\n exact: boolean,\n): boolean {\n const numericChange = exact ? hasExactNumericChange : hasNumericChange;\n const previousQuantity = previous.quantity;\n const canScale =\n typeof previousQuantity === \"number\" &&\n Math.abs(previousQuantity) > SHIPPED_QUANTITY_TOLERANCE &&\n typeof nextQuantity === \"number\";\n\n return SHIPPED_LINE_DERIVED_TOTAL_FIELDS.some((field) => {\n const nextTotal = next[field];\n const previousTotal = previous[field];\n // Without a scalable quantity pair there is nothing to derive the expected\n // total from, so fall back to locking the value outright.\n if (!canScale || typeof previousTotal !== \"number\") {\n return numericChange(nextTotal, previousTotal);\n }\n if (nextTotal === undefined || nextTotal === null) {\n return exact ? numericChange(nextTotal, previousTotal) : false;\n }\n const expectedTotal =\n (previousTotal / (previousQuantity as number)) * (nextQuantity as number);\n // Scale the tolerance with magnitude: a fixed 1e-6 is below the float noise\n // floor once totals reach six figures.\n const tolerance = Math.max(\n SHIPPED_QUANTITY_TOLERANCE,\n Math.abs(expectedTotal) * 1e-9,\n );\n return Math.abs(nextTotal - expectedTotal) > tolerance;\n });\n}\n\nfunction hasShippedLinePricingChange(\n next: Partial<ShippedLineComparable>,\n previous: ShippedLineComparable,\n nextQuantity: number | null | undefined,\n exact: boolean,\n): boolean {\n const numericChange = exact ? hasExactNumericChange : hasNumericChange;\n return (\n SHIPPED_LINE_NUMERIC_PRICING_FIELDS.some((field) =>\n numericChange(next[field], previous[field]),\n ) ||\n hasShippedLineTotalChange(next, previous, nextQuantity, exact) ||\n (exact\n ? hasExactUnitChange(next.quantityUnit, previous.quantityUnit)\n : hasUnitChange(next.quantityUnit, previous.quantityUnit))\n );\n}\n\nasync function assertShippedOrderLineChangeAllowed(\n existingSnapshot: SalesLineSnapshot,\n nextSnapshot: Partial<ShippedLineComparable> | null,\n shippedQuantity: number,\n exact: boolean,\n): Promise<void> {\n if (shippedQuantity <= 0) return;\n\n const nextQuantity = nextSnapshot\n ? exact\n ? nextSnapshot.quantity\n : (nextSnapshot.quantity ?? existingSnapshot.quantity)\n : 0;\n const quantityInvalid =\n nextQuantity === undefined ||\n nextQuantity < shippedQuantity - SHIPPED_QUANTITY_TOLERANCE;\n const pricingChanged =\n nextSnapshot !== null &&\n hasShippedLinePricingChange(\n nextSnapshot,\n existingSnapshot,\n nextQuantity,\n exact,\n );\n if (!quantityInvalid && !pricingChanged) return;\n\n const { translate } = await resolveTranslations();\n if (quantityInvalid) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorQuantityBelowShipped\",\n \"You cannot lower the quantity below the {{shipped}} already shipped.\",\n { shipped: shippedQuantity },\n ),\n });\n }\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorPriceShipped\",\n \"You cannot change the price or unit of a line that has shipped items.\",\n ),\n });\n}\n\n/**\n * Shipment guard for one line, against an already-loaded shipped-quantity map.\n * A bulk write loads that map once for the whole order instead of once per\n * line; the per-line command keeps loading it itself via\n * {@link assertShippedOrderLineEditable}.\n */\nasync function assertShippedOrderLineEditableAgainst(\n shippedQuantityByLine: Map<string, number>,\n existingSnapshot: SalesLineSnapshot | null,\n parsed: OrderLineUpsertInput,\n): Promise<void> {\n const lineId = existingSnapshot?.id;\n if (!existingSnapshot || !lineId) return;\n await assertShippedOrderLineChangeAllowed(\n existingSnapshot,\n parsed,\n shippedQuantityByLine.get(lineId) ?? 0,\n false,\n );\n}\n\nasync function assertShippedOrderLineEditable(\n em: EntityManager,\n order: SalesOrder,\n existingSnapshot: SalesLineSnapshot | null,\n parsed: z.infer<typeof orderLineUpsertSchema>,\n): Promise<void> {\n if (!existingSnapshot?.id) return;\n const shippedQuantityByLine = await loadShippedQuantityByLine(em, order.id, {\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n });\n await assertShippedOrderLineEditableAgainst(\n shippedQuantityByLine,\n existingSnapshot,\n parsed,\n );\n}\n\nasync function assertShippedOrderGraphRestorable(\n em: EntityManager,\n order: SalesOrder,\n existingLines: SalesOrderLine[],\n snapshot: OrderGraphSnapshot,\n): Promise<void> {\n const shippedByLine = await loadShippedQuantityByLine(em, order.id, {\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n });\n if (shippedByLine.size === 0) return;\n\n const snapshotLinesById = new Map(\n snapshot.lines.flatMap((line) => (line.id ? [[line.id, line] as const] : [])),\n );\n for (const line of existingLines) {\n const shippedQuantity = shippedByLine.get(line.id) ?? 0;\n if (shippedQuantity <= 0) continue;\n await assertShippedOrderLineChangeAllowed(\n mapOrderLineEntityToSnapshot(line),\n snapshotLinesById.get(line.id) ?? null,\n shippedQuantity,\n true,\n );\n }\n}\n\nconst FULFILLED_ORDER_STATUS = \"fulfilled\";\n\nconst isFulfilledOrder = (order: SalesOrder): boolean => {\n const normalize = (value: string | null | undefined): string =>\n (value ?? \"\").trim().toLowerCase();\n return (\n normalize(order.status) === FULFILLED_ORDER_STATUS ||\n normalize(order.fulfillmentStatus) === FULFILLED_ORDER_STATUS\n );\n};\n\nasync function assertOrderAcceptsNewLine(\n order: SalesOrder,\n existingSnapshot: SalesLineSnapshot | null,\n): Promise<void> {\n if (existingSnapshot) return;\n if (!isFulfilledOrder(order)) return;\n const { translate } = await resolveTranslations();\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorAddToFulfilled\",\n \"You cannot add a new item to a fulfilled order. Change the order status first.\",\n ),\n });\n}\n\ntype OrderLineUpsertInput = Omit<\n z.infer<typeof orderLineUpsertSchema>,\n \"orderId\"\n> & { orderId?: string };\n\ntype OrderLineUpsertDependencies = {\n em: EntityManager;\n order: SalesOrder;\n uomResolver: UomResolver;\n resolveTaxCalculationService: () => TaxCalculationService | null;\n};\n\n/**\n * Resolve `taxCalculationService` lazily and at most once. A line that already\n * carries both net and gross never needs it, and a bulk write must not resolve\n * it once per line.\n */\nfunction createTaxCalculationServiceResolver(container: {\n resolve: (name: string) => unknown;\n}): () => TaxCalculationService | null {\n let resolved = false;\n let service: TaxCalculationService | null = null;\n return () => {\n if (resolved) return service;\n resolved = true;\n try {\n service = container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n service = null;\n }\n return service;\n };\n}\n\n/**\n * Resolve one order-line upsert entry into the line snapshot it should become:\n * price-mode net/gross fallback, metadata merge, UoM normalization and the\n * unit-price conversion that follows a unit change, then the merged snapshot.\n *\n * Shared by `sales.orders.lines.upsert` and `sales.orders.lines.upsert_many` so\n * the per-line semantics cannot drift between them. Guards, line numbering,\n * totals and persistence stay with the callers \u2014 this builds a value and\n * touches nothing.\n */\nasync function buildUpsertedOrderLineSnapshot(\n dependencies: OrderLineUpsertDependencies,\n parsed: OrderLineUpsertInput,\n existingSnapshot: SalesPersistedLineSnapshot | null,\n fallbackLineNumber: number,\n): Promise<SalesPersistedLineSnapshot> {\n const { em, order, uomResolver, resolveTaxCalculationService } =\n dependencies;\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n const unitPriceSupplied = unitPriceNet !== null || unitPriceGross !== null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n const taxService = resolveTaxCalculationService();\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? existingSnapshot?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesPersistedLineSnapshot = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n fallbackLineNumber,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n order.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n ...resolveUpsertDiscountFields(\n parsed.discountAmount,\n parsed.discountAmountBasis,\n existingSnapshot,\n ),\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n ...resolveUpsertTotalsOrigin(parsed.totalNetAmount, existingSnapshot),\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : (existingSnapshot?.customFields ?? null),\n amountsMode: order.totalsMode ?? \"computed\",\n statusEntryId,\n catalogSnapshot:\n parsed.catalogSnapshot ?? existingSnapshot?.catalogSnapshot ?? null,\n promotionSnapshot:\n parsed.promotionSnapshot ?? existingSnapshot?.promotionSnapshot ?? null,\n };\n // `taxAmount` and `totalGrossAmount` are the engine's own output read back off\n // the row, so carrying them verbatim pinned a line's gross to its pre-edit\n // value whenever the caller changed quantity or pricing without supplying\n // totals (#6459). Dropping them when the pricing moved makes the calculation\n // recompute instead. Both commands go through here, so neither can drift.\n Object.assign(\n updatedSnapshot,\n resolveUpsertCalculatedAmounts(parsed, updatedSnapshot, existingSnapshot),\n );\n\n if (isExternalAmountsMode(order.totalsMode ?? \"computed\")) {\n await assertExternalLineComplete(\n { ...updatedSnapshot, unitPriceNet: unitPriceSupplied ? unitPriceNet : null },\n updatedSnapshot.lineNumber ?? 1,\n );\n }\n\n return updatedSnapshot;\n}\n\nconst orderLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = orderLineUpsertSchema.parse(rawBody);\n return writeLockedOrderGraph(input, ctx, parsed.orderId, \"Sales order not found\", async (em, order) => {\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const totalsMode: SalesAmountsMode = order.totalsMode ?? \"computed\";\n await assertUniformAmountsMode(totalsMode, [parsed]);\n if (isExternalAmountsMode(totalsMode)) {\n await requireOrderTotalsForExternalWrite(parsed.orderTotals);\n }\n const suppliedTotals: Partial<SalesDocumentAmounts> | null = isExternalAmountsMode(totalsMode)\n ? buildExternalHeaderTotals(parsed.orderTotals)\n : null;\n await assertOrderAcceptsNewLine(order, existingSnapshot);\n await assertShippedOrderLineEditable(em, order, existingSnapshot, parsed);\n const uomResolver = createUomResolver();\n const updatedSnapshot = await buildUpsertedOrderLineSnapshot(\n {\n em,\n order,\n uomResolver,\n resolveTaxCalculationService: createTaxCalculationServiceResolver(\n ctx.container,\n ),\n },\n parsed,\n existingSnapshot,\n lineSnapshots.length + 1,\n );\n const lineId = updatedSnapshot.id;\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode,\n suppliedTotals,\n });\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n return { result: { orderId: order.id, lineId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.upsert\",\n \"Upsert order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst orderLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const { translate } = await resolveTranslations();\n const parsed = orderLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedOrderGraph(input, ctx, parsed.orderId, translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ), async (em, order) => {\n const shipmentCount = await em.count(SalesShipmentItem, {\n orderLine: parsed.id,\n shipment: { deletedAt: null },\n });\n if (shipmentCount > 0) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteShipped\",\n \"Cannot delete a line that has shipped items.\",\n ),\n });\n }\n const existingLines = await em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw notFound(translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ));\n }\n if (filtered.length === 0) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteLast\",\n \"An order must contain at least one line item.\",\n ),\n });\n }\n const totalsMode: SalesAmountsMode = order.totalsMode ?? \"computed\";\n if (isExternalAmountsMode(totalsMode)) {\n await requireOrderTotalsForExternalWrite(parsed.orderTotals);\n }\n const suppliedTotals: Partial<SalesDocumentAmounts> | null = isExternalAmountsMode(totalsMode)\n ? buildExternalHeaderTotals(parsed.orderTotals)\n : null;\n const sourceInputs = filtered.map((line, index) => ({\n ...mapOrderLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode,\n suppliedTotals,\n });\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n return { result: { orderId: order.id, lineId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.delete\",\n \"Delete order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\n/**\n * Place `line` in `lines` at the position the caller asked for.\n *\n * A supplied `targetPosition` is a 1-based destination, not a sort key: the\n * line is pulled out of its current slot and spliced back in there, so moving\n * a line one step in either direction is expressible (sorting a list that\n * contains ties is not \u2014 see the per-line command). Without a target position\n * an existing line keeps its slot and a new line is appended.\n */\nfunction placeOrderLine(\n lines: SalesPersistedLineSnapshot[],\n line: SalesPersistedLineSnapshot,\n targetPosition: number | null,\n): SalesPersistedLineSnapshot[] {\n const currentIndex = lines.findIndex((entry) => entry.id === line.id);\n const remaining =\n currentIndex === -1\n ? [...lines]\n : [...lines.slice(0, currentIndex), ...lines.slice(currentIndex + 1)];\n if (targetPosition == null) {\n if (currentIndex === -1) {\n remaining.push(line);\n return remaining;\n }\n remaining.splice(currentIndex, 0, line);\n return remaining;\n }\n const index = Math.min(Math.max(targetPosition - 1, 0), remaining.length);\n remaining.splice(index, 0, line);\n return remaining;\n}\n\n/**\n * Write a whole set of order-line changes in one aggregate load.\n *\n * `sales.orders.lines.upsert` is per line: each call reloads the order, all of\n * its lines and adjustments, recalculates the document and flushes, so writing\n * N lines costs O(N\u00B2) in rows read. This command takes the same per-line\n * bodies as a list, loads the aggregate once, resolves every line in memory\n * against one UoM resolver, calculates totals once and flushes once \u2014 O(N) \u2014\n * and produces the end state N sequential single upserts would produce.\n *\n * All-or-nothing: a refusal on any line or delete aborts the whole batch.\n */\nconst orderLineBulkUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineIds: string[] }\n> = {\n id: \"sales.orders.lines.upsert_many\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const { translate } = await resolveTranslations();\n const parsed = orderLineBulkUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedOrderGraph(input, ctx, parsed.orderId, \"Sales order not found\", async (em, order) => {\n const totalsMode: SalesAmountsMode = order.totalsMode ?? \"computed\";\n await assertUniformAmountsMode(totalsMode, parsed.lines);\n if (isExternalAmountsMode(totalsMode)) {\n await requireOrderTotalsForExternalWrite(parsed.orderTotals);\n }\n const suppliedTotals: Partial<SalesDocumentAmounts> | null = isExternalAmountsMode(totalsMode)\n ? buildExternalHeaderTotals(parsed.orderTotals)\n : null;\n\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const existingSnapshotsById = new Map(\n existingLines.map((line) => [line.id, mapOrderLineEntityToSnapshot(line)]),\n );\n\n // An entry id names a line to update. One this order does not have is\n // refused rather than created: it is a line deleted since the caller read\n // the order, or one belonging to another order.\n const deleteIds = new Set(parsed.deleteIds);\n const referencedIds = [\n ...deleteIds,\n ...parsed.lines.flatMap((line) => (line.id ? [line.id] : [])),\n ];\n for (const id of referencedIds) {\n if (existingSnapshotsById.has(id)) continue;\n throw notFound(\n translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n );\n }\n if (deleteIds.size) {\n const shippedItems = await em.find(SalesShipmentItem, {\n orderLine: { $in: [...deleteIds] },\n shipment: { deletedAt: null },\n });\n if (shippedItems.length) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteShipped\",\n \"Cannot delete a line that has shipped items.\",\n ),\n });\n }\n }\n\n const editsExistingLine = parsed.lines.some(\n (line) => line.id != null && existingSnapshotsById.has(line.id),\n );\n const shippedQuantityByLine = editsExistingLine\n ? await loadShippedQuantityByLine(em, order.id, {\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n })\n : new Map<string, number>();\n\n const dependencies: OrderLineUpsertDependencies = {\n em,\n order,\n uomResolver: createUomResolver(),\n resolveTaxCalculationService: createTaxCalculationServiceResolver(\n ctx.container,\n ),\n };\n let nextLines = [...existingSnapshotsById.values()].filter(\n (line) => !deleteIds.has(line.id),\n );\n const lineIds: string[] = [];\n for (const entry of parsed.lines) {\n const existingSnapshot = entry.id\n ? (existingSnapshotsById.get(entry.id) ?? null)\n : null;\n await assertOrderAcceptsNewLine(order, existingSnapshot);\n await assertShippedOrderLineEditableAgainst(\n shippedQuantityByLine,\n existingSnapshot,\n entry,\n );\n const upserted = await buildUpsertedOrderLineSnapshot(\n dependencies,\n {\n ...entry,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n },\n existingSnapshot,\n nextLines.length + 1,\n );\n nextLines = placeOrderLine(nextLines, upserted, entry.lineNumber ?? null);\n lineIds.push(upserted.id);\n }\n\n if (!nextLines.length) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteLast\",\n \"An order must contain at least one line item.\",\n ),\n });\n }\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot ?? null,\n promotionSnapshot: line.promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n totalsMode,\n suppliedTotals,\n });\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n return { result: { orderId: order.id, lineIds }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.upsert_many\",\n \"Update order lines\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n // Same path as every other order-graph undo: it locks the order, refuses\n // with 409 when the graph moved since the batch ran \u2014 a payment, shipment\n // or note recorded afterwards would otherwise be hard-deleted by the\n // restore (#6462, #6833) \u2014 restores inside one transaction, and refreshes\n // the query index.\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = quoteLineUpsertSchema.parse(rawBody);\n await assertAmountsModeUnsupportedOnQuote([parsed]);\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n let taxService: TaxCalculationService | null = null;\n try {\n taxService = ctx.container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n taxService = null;\n }\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? (existingSnapshot as any)?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n const uomResolver = createUomResolver();\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesLineSnapshot & {\n statusEntryId?: string | null;\n catalogSnapshot?: Record<string, unknown> | null;\n promotionSnapshot?: Record<string, unknown> | null;\n } = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n lineSnapshots.length + 1,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n quote.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n ...resolveUpsertDiscountFields(\n parsed.discountAmount,\n parsed.discountAmountBasis,\n existingSnapshot,\n ),\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n ...resolveUpsertTotalsOrigin(parsed.totalNetAmount, existingSnapshot),\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : ((existingSnapshot as any)?.customFields ?? null),\n };\n Object.assign(\n updatedSnapshot,\n resolveUpsertCalculatedAmounts(parsed, updatedSnapshot, existingSnapshot),\n );\n (updatedSnapshot as any).statusEntryId = statusEntryId;\n (updatedSnapshot as any).catalogSnapshot =\n parsed.catalogSnapshot ??\n (existingSnapshot as any)?.catalogSnapshot ??\n null;\n (updatedSnapshot as any).promotionSnapshot =\n parsed.promotionSnapshot ??\n (existingSnapshot as any)?.promotionSnapshot ??\n null;\n\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n return { result: { quoteId: quote.id, lineId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.upsert\",\n \"Upsert quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = quoteLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw notFound(\"Quote line not found\");\n }\n const sourceInputs = filtered.map((line, index) => ({\n ...mapQuoteLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n return { result: { quoteId: quote.id, lineId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ result, snapshots }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.delete\",\n \"Delete quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\nconst orderAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedOrderGraph(input, ctx, parsed.orderId, \"Sales order not found\", async (em, order) => {\n if (isExternalAmountsMode(order.totalsMode ?? \"computed\")) await refuseOnExternalOrder();\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapOrderAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? order.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? order.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n return { result: { orderId: order.id, adjustmentId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.upsert\",\n \"Upsert order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst orderAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedOrderGraph(input, ctx, parsed.orderId, \"Sales order not found\", async (em, order) => {\n if (isExternalAmountsMode(order.totalsMode ?? \"computed\")) await refuseOnExternalOrder();\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw notFound(\"Adjustment not found\");\n }\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n return { result: { orderId: order.id, adjustmentId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedOrderGraphAfter(ctx, result, result.orderId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedOrderGraphBefore(result, snapshots.before);\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.delete\",\n \"Delete order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoOrderGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.upsert\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapQuoteAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? quote.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? quote.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n return { result: { quoteId: quote.id, adjustmentId }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.upsert\",\n \"Upsert quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\nconst quoteAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.delete\",\n async prepare(input) {\n return markLockedGraphWrite(input);\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n return writeLockedQuoteGraph(input, ctx, parsed.quoteId, \"Sales quote not found\", async (em, quote) => {\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw notFound(\"Adjustment not found\");\n }\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n return { result: { quoteId: quote.id, adjustmentId: parsed.id }, calculation };\n });\n },\n captureAfter: async (_input, result, ctx) =>\n captureLockedQuoteGraphAfter(ctx, result, result.quoteId),\n buildLog: async ({ snapshots, result }) => {\n const before = resolveLockedQuoteGraphBefore(result, snapshots.before);\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.delete\",\n \"Delete quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n await undoQuoteGraph(ctx, before, payload?.after);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Invoice CRUD commands\n// ---------------------------------------------------------------------------\n\nconst invoiceCrudEvents: CrudEventsConfig<SalesInvoice> = {\n module: \"sales\",\n entity: \"invoice\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createInvoiceCommand: CommandHandler<\n InvoiceCreateInput,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = invoiceCreateSchema.parse(rawInput ?? {});\n const invoiceNumber =\n typeof initial.invoiceNumber === \"string\" &&\n initial.invoiceNumber.trim().length\n ? initial.invoiceNumber.trim()\n : (\n await generator.generate({\n kind: \"invoice\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = invoiceCreateSchema.parse({ ...initial, invoiceNumber });\n const ensuredInvoiceNumber = parsed.invoiceNumber ?? invoiceNumber;\n if (!ensuredInvoiceNumber) {\n throw new CrudHttpError(400, { error: \"Invoice number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await findOneWithDecryption(\n em,\n SalesOrder,\n {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n );\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n const invoiceId = randomUUID();\n const invoice = em.create(SalesInvoice, {\n id: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n invoiceNumber: ensuredInvoiceNumber,\n orderId: parsed.orderId ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n issueDate: parsed.issueDate ?? new Date(),\n dueDate: parsed.dueDate ?? null,\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n discountTotalAmount: toNumericString(parsed.discountTotalAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n paidTotalAmount: toNumericString(parsed.paidTotalAmount ?? 0),\n outstandingAmount: toNumericString(parsed.outstandingAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(invoice);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesInvoiceLine, {\n id: randomUUID(),\n invoice,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n discountAmount: toNumericString(line.discountAmount ?? 0),\n discountPercent: toNumericString(line.discountPercent ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount ?? 0, line.totalGrossAmount ?? 0, line.taxRate ?? 0),\n ),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_invoice,\n recordId: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.create\", \"Create invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: after.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n await em.nativeDelete(SalesInvoiceLine, { invoice: invoice.id });\n em.remove(invoice);\n await em.flush();\n },\n};\n\nconst invoiceUpdateChangeKeys = [\n \"invoiceNumber\",\n \"statusEntryId\",\n \"status\",\n \"issueDate\",\n \"dueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"discountTotalAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"paidTotalAmount\",\n \"outstandingAmount\",\n \"metadata\",\n] as const;\n\nfunction toAuditISOString(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString();\n }\n if (typeof value === \"string\") {\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();\n }\n return null;\n}\n\nfunction auditValuesEqual(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true;\n if (left instanceof Date || right instanceof Date) {\n const leftIso = toAuditISOString(left);\n const rightIso = toAuditISOString(right);\n return leftIso !== null && rightIso !== null && leftIso === rightIso;\n }\n return isDeepStrictEqual(left, right);\n}\n\nfunction buildAuditChanges(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n keys: readonly string[],\n): Record<string, { from: unknown; to: unknown }> {\n const changedKeys = keys.filter((key) => !auditValuesEqual(before[key], after[key]));\n return buildChanges(before, after, changedKeys);\n}\n\nfunction selectInvoiceUpdateChangeKeys(\n input: z.infer<typeof invoiceUpdateSchema>,\n): Array<(typeof invoiceUpdateChangeKeys)[number]> {\n return invoiceUpdateChangeKeys.filter((key) =>\n key === \"status\"\n ? input.statusEntryId !== undefined\n : input[key as keyof z.infer<typeof invoiceUpdateSchema>] !== undefined,\n );\n}\n\nfunction applyInvoiceHeaderUpdate(\n invoice: SalesInvoice,\n input: z.infer<typeof invoiceUpdateSchema>,\n resolvedStatus: string | null | undefined,\n): void {\n if (input.invoiceNumber !== undefined) invoice.invoiceNumber = input.invoiceNumber;\n if (input.statusEntryId !== undefined) {\n invoice.statusEntryId = input.statusEntryId;\n invoice.status = resolvedStatus ?? null;\n }\n if (input.issueDate !== undefined) invoice.issueDate = input.issueDate;\n if (input.dueDate !== undefined) invoice.dueDate = input.dueDate;\n if (input.currencyCode !== undefined) invoice.currencyCode = input.currencyCode;\n if (input.subtotalNetAmount !== undefined) invoice.subtotalNetAmount = toNumericString(input.subtotalNetAmount);\n if (input.subtotalGrossAmount !== undefined) invoice.subtotalGrossAmount = toNumericString(input.subtotalGrossAmount);\n if (input.discountTotalAmount !== undefined) invoice.discountTotalAmount = toNumericString(input.discountTotalAmount);\n if (input.taxTotalAmount !== undefined) invoice.taxTotalAmount = toNumericString(input.taxTotalAmount);\n if (input.grandTotalNetAmount !== undefined) invoice.grandTotalNetAmount = toNumericString(input.grandTotalNetAmount);\n if (input.grandTotalGrossAmount !== undefined) invoice.grandTotalGrossAmount = toNumericString(input.grandTotalGrossAmount);\n if (input.paidTotalAmount !== undefined) invoice.paidTotalAmount = toNumericString(input.paidTotalAmount);\n if (input.outstandingAmount !== undefined) invoice.outstandingAmount = toNumericString(input.outstandingAmount);\n if (input.metadata !== undefined) invoice.metadata = input.metadata;\n}\n\nconst updateInvoiceCommand: CommandHandler<\n z.infer<typeof invoiceUpdateSchema>,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = invoiceUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n let resolvedStatus: string | null | undefined;\n if (parsed.statusEntryId !== undefined) {\n resolvedStatus = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: invoice.tenantId });\n }\n\n applyInvoiceHeaderUpdate(invoice, parsed, resolvedStatus);\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ input, result, snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildAuditChanges(\n before.invoice as unknown as Record<string, unknown>,\n after.invoice as unknown as Record<string, unknown>,\n selectInvoiceUpdateChangeKeys(input),\n )\n : {};\n return {\n actionLabel: translate(\"sales.audit.invoices.update\", \"Update invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: { before, after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: before.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n invoice.invoiceNumber = before.invoice.invoiceNumber;\n invoice.orderId = before.invoice.orderId;\n invoice.statusEntryId = before.invoice.statusEntryId;\n invoice.status = before.invoice.status;\n invoice.issueDate = before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : null;\n invoice.dueDate = before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null;\n invoice.currencyCode = before.invoice.currencyCode;\n invoice.subtotalNetAmount = before.invoice.subtotalNetAmount;\n invoice.subtotalGrossAmount = before.invoice.subtotalGrossAmount;\n invoice.discountTotalAmount = before.invoice.discountTotalAmount;\n invoice.taxTotalAmount = before.invoice.taxTotalAmount;\n invoice.grandTotalNetAmount = before.invoice.grandTotalNetAmount;\n invoice.grandTotalGrossAmount = before.invoice.grandTotalGrossAmount;\n invoice.paidTotalAmount = before.invoice.paidTotalAmount;\n invoice.outstandingAmount = before.invoice.outstandingAmount;\n invoice.metadata = before.invoice.metadata;\n invoice.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteInvoiceCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { invoiceId: string }\n> = {\n id: \"sales.invoices.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n invoice.deletedAt = new Date();\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { invoiceId: invoice.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.delete\", \"Delete invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: before.invoice.id,\n tenantId: before.invoice.tenantId,\n organizationId: before.invoice.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.invoice.organizationId);\n ensureTenantScope(ctx, before.invoice.tenantId);\n const restored = em.create(SalesInvoice, {\n id: before.invoice.id,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n invoiceNumber: before.invoice.invoiceNumber,\n orderId: before.invoice.orderId,\n statusEntryId: before.invoice.statusEntryId,\n status: before.invoice.status,\n issueDate: before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : new Date(),\n dueDate: before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null,\n currencyCode: before.invoice.currencyCode,\n subtotalNetAmount: before.invoice.subtotalNetAmount,\n subtotalGrossAmount: before.invoice.subtotalGrossAmount,\n discountTotalAmount: before.invoice.discountTotalAmount,\n taxTotalAmount: before.invoice.taxTotalAmount,\n grandTotalNetAmount: before.invoice.grandTotalNetAmount,\n grandTotalGrossAmount: before.invoice.grandTotalGrossAmount,\n paidTotalAmount: before.invoice.paidTotalAmount,\n outstandingAmount: before.invoice.outstandingAmount,\n metadata: before.invoice.metadata,\n customFieldSetId: before.invoice.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesInvoiceLine, {\n id: line.id,\n invoice: restored,\n orderLineId: line.orderLineId,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\n// ---------------------------------------------------------------------------\n// Credit Memo CRUD commands\n// ---------------------------------------------------------------------------\n\nconst creditMemoCrudEvents: CrudEventsConfig<SalesCreditMemo> = {\n module: \"sales\",\n entity: \"credit_memo\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createCreditMemoCommand: CommandHandler<\n CreditMemoCreateInput,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = creditMemoCreateSchema.parse(rawInput ?? {});\n const creditMemoNumber =\n typeof initial.creditMemoNumber === \"string\" &&\n initial.creditMemoNumber.trim().length\n ? initial.creditMemoNumber.trim()\n : (\n await generator.generate({\n kind: \"credit_memo\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = creditMemoCreateSchema.parse({ ...initial, creditMemoNumber });\n const ensuredCreditMemoNumber = parsed.creditMemoNumber ?? creditMemoNumber;\n if (!ensuredCreditMemoNumber) {\n throw new CrudHttpError(400, { error: \"Credit memo number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await findOneWithDecryption(\n em,\n SalesOrder,\n {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n );\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n // Validate invoiceId belongs to same org/tenant\n if (parsed.invoiceId) {\n const invoiceExists = await em.findOne(SalesInvoice, {\n id: parsed.invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!invoiceExists) {\n throw new CrudHttpError(400, { error: \"Referenced invoice not found in current scope.\" });\n }\n }\n\n const creditMemoId = randomUUID();\n const creditMemo = em.create(SalesCreditMemo, {\n id: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n creditMemoNumber: ensuredCreditMemoNumber,\n order: parsed.orderId ? em.getReference(SalesOrder, parsed.orderId) : null,\n invoice: parsed.invoiceId ? em.getReference(SalesInvoice, parsed.invoiceId) : null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n reason: parsed.reason ?? null,\n issueDate: parsed.issueDate ?? new Date(),\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(creditMemo);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesCreditMemoLine, {\n id: randomUUID(),\n creditMemo,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount ?? 0, line.totalGrossAmount ?? 0, line.taxRate ?? 0),\n ),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_credit_memo,\n recordId: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.create\", \"Create credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: after.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n await em.nativeDelete(SalesCreditMemoLine, { creditMemo: creditMemo.id });\n em.remove(creditMemo);\n await em.flush();\n },\n};\n\nconst creditMemoUpdateChangeKeys = [\n \"creditMemoNumber\",\n \"statusEntryId\",\n \"status\",\n \"reason\",\n \"issueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"metadata\",\n] as const;\n\nfunction selectCreditMemoUpdateChangeKeys(\n input: z.infer<typeof creditMemoUpdateSchema>,\n): Array<(typeof creditMemoUpdateChangeKeys)[number]> {\n return creditMemoUpdateChangeKeys.filter((key) =>\n key === \"status\"\n ? input.statusEntryId !== undefined\n : input[key as keyof z.infer<typeof creditMemoUpdateSchema>] !== undefined,\n );\n}\n\nfunction applyCreditMemoHeaderUpdate(\n creditMemo: SalesCreditMemo,\n input: z.infer<typeof creditMemoUpdateSchema>,\n resolvedStatus: string | null | undefined,\n): void {\n if (input.creditMemoNumber !== undefined) creditMemo.creditMemoNumber = input.creditMemoNumber;\n if (input.statusEntryId !== undefined) {\n creditMemo.statusEntryId = input.statusEntryId;\n creditMemo.status = resolvedStatus ?? null;\n }\n if (input.reason !== undefined) creditMemo.reason = input.reason;\n if (input.issueDate !== undefined) creditMemo.issueDate = input.issueDate;\n if (input.currencyCode !== undefined) creditMemo.currencyCode = input.currencyCode;\n if (input.subtotalNetAmount !== undefined) creditMemo.subtotalNetAmount = toNumericString(input.subtotalNetAmount);\n if (input.subtotalGrossAmount !== undefined) creditMemo.subtotalGrossAmount = toNumericString(input.subtotalGrossAmount);\n if (input.taxTotalAmount !== undefined) creditMemo.taxTotalAmount = toNumericString(input.taxTotalAmount);\n if (input.grandTotalNetAmount !== undefined) creditMemo.grandTotalNetAmount = toNumericString(input.grandTotalNetAmount);\n if (input.grandTotalGrossAmount !== undefined) creditMemo.grandTotalGrossAmount = toNumericString(input.grandTotalGrossAmount);\n if (input.metadata !== undefined) creditMemo.metadata = input.metadata;\n}\n\nconst updateCreditMemoCommand: CommandHandler<\n z.infer<typeof creditMemoUpdateSchema>,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = creditMemoUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n let resolvedStatus: string | null | undefined;\n if (parsed.statusEntryId !== undefined) {\n resolvedStatus = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: creditMemo.tenantId });\n }\n\n applyCreditMemoHeaderUpdate(creditMemo, parsed, resolvedStatus);\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ input, result, snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildAuditChanges(\n before.creditMemo as unknown as Record<string, unknown>,\n after.creditMemo as unknown as Record<string, unknown>,\n selectCreditMemoUpdateChangeKeys(input),\n )\n : {};\n return {\n actionLabel: translate(\"sales.audit.credit_memos.update\", \"Update credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: { before, after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: before.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n creditMemo.creditMemoNumber = before.creditMemo.creditMemoNumber;\n creditMemo.order = before.creditMemo.orderId\n ? em.getReference(SalesOrder, before.creditMemo.orderId)\n : null;\n creditMemo.invoice = before.creditMemo.invoiceId\n ? em.getReference(SalesInvoice, before.creditMemo.invoiceId)\n : null;\n creditMemo.statusEntryId = before.creditMemo.statusEntryId;\n creditMemo.status = before.creditMemo.status;\n creditMemo.reason = before.creditMemo.reason;\n creditMemo.issueDate = before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : null;\n creditMemo.currencyCode = before.creditMemo.currencyCode;\n creditMemo.subtotalNetAmount = before.creditMemo.subtotalNetAmount;\n creditMemo.subtotalGrossAmount = before.creditMemo.subtotalGrossAmount;\n creditMemo.taxTotalAmount = before.creditMemo.taxTotalAmount;\n creditMemo.grandTotalNetAmount = before.creditMemo.grandTotalNetAmount;\n creditMemo.grandTotalGrossAmount = before.creditMemo.grandTotalGrossAmount;\n creditMemo.metadata = before.creditMemo.metadata;\n creditMemo.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteCreditMemoCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n creditMemo.deletedAt = new Date();\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.delete\", \"Delete credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: before.creditMemo.id,\n tenantId: before.creditMemo.tenantId,\n organizationId: before.creditMemo.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.creditMemo.organizationId);\n ensureTenantScope(ctx, before.creditMemo.tenantId);\n const restored = em.create(SalesCreditMemo, {\n id: before.creditMemo.id,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n creditMemoNumber: before.creditMemo.creditMemoNumber,\n order: before.creditMemo.orderId\n ? em.getReference(SalesOrder, before.creditMemo.orderId)\n : null,\n invoice: before.creditMemo.invoiceId\n ? em.getReference(SalesInvoice, before.creditMemo.invoiceId)\n : null,\n statusEntryId: before.creditMemo.statusEntryId,\n status: before.creditMemo.status,\n reason: before.creditMemo.reason,\n issueDate: before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : new Date(),\n currencyCode: before.creditMemo.currencyCode,\n subtotalNetAmount: before.creditMemo.subtotalNetAmount,\n subtotalGrossAmount: before.creditMemo.subtotalGrossAmount,\n taxTotalAmount: before.creditMemo.taxTotalAmount,\n grandTotalNetAmount: before.creditMemo.grandTotalNetAmount,\n grandTotalGrossAmount: before.creditMemo.grandTotalGrossAmount,\n metadata: before.creditMemo.metadata,\n customFieldSetId: before.creditMemo.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesCreditMemoLine, {\n id: line.id,\n creditMemo: restored,\n orderLineId: line.orderLineId,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n lineNumber: line.lineNumber,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: toNumericString(\n deriveLineNetFromGross(line.totalNetAmount, line.totalGrossAmount, line.taxRate),\n ),\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\nregisterCommand(updateQuoteCommand);\nregisterCommand(createQuoteCommand);\nregisterCommand(deleteQuoteCommand);\nregisterCommand(convertQuoteToOrderCommand);\nregisterCommand(updateOrderCommand);\nregisterCommand(createOrderCommand);\nregisterCommand(deleteOrderCommand);\nregisterCommand(orderLineUpsertCommand);\nregisterCommand(orderLineBulkUpsertCommand);\nregisterCommand(orderLineDeleteCommand);\nregisterCommand(quoteLineUpsertCommand);\nregisterCommand(quoteLineDeleteCommand);\nregisterCommand(orderAdjustmentUpsertCommand);\nregisterCommand(orderAdjustmentDeleteCommand);\nregisterCommand(quoteAdjustmentUpsertCommand);\nregisterCommand(quoteAdjustmentDeleteCommand);\nregisterCommand(createInvoiceCommand);\nregisterCommand(updateInvoiceCommand);\nregisterCommand(deleteInvoiceCommand);\nregisterCommand(createCreditMemoCommand);\nregisterCommand(updateCreditMemoCommand);\nregisterCommand(deleteCreditMemoCommand);\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;AAClC,SAAS,SAAS;AAClB,SAAS,uBAAuB;AAEhC,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,gBAAgB;AAIzB,SAAS,eAAe,gBAAgB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAC3C,SAAS,wCAAwC;AACjD,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAClB,SAAS,oBAAoB,6BAA6B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,uBAAuB;AAC5C,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAUK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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