@open-mercato/core 0.9.1-develop.7513.1.ae2715553f → 0.9.1-develop.7515.1.e2712c8b00
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/shipping_carriers/api/webhook/[provider]/route.js +4 -7
- package/dist/modules/shipping_carriers/api/webhook/[provider]/route.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipping-service.js +29 -11
- package/dist/modules/shipping_carriers/lib/shipping-service.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/status-sync.js +2 -2
- package/dist/modules/shipping_carriers/lib/status-sync.js.map +2 -2
- package/dist/modules/shipping_carriers/workers/webhook-processor.js +60 -33
- package/dist/modules/shipping_carriers/workers/webhook-processor.js.map +3 -3
- package/dist/modules/warranty_claims/commands/claim-lines.js +89 -68
- package/dist/modules/warranty_claims/commands/claim-lines.js.map +2 -2
- package/dist/modules/warranty_claims/commands/claims.js +14 -13
- package/dist/modules/warranty_claims/commands/claims.js.map +2 -2
- package/dist/modules/warranty_claims/commands/shared.js +8 -2
- package/dist/modules/warranty_claims/commands/shared.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/shipping_carriers/api/webhook/[provider]/route.ts +4 -7
- package/src/modules/shipping_carriers/lib/shipping-service.ts +29 -11
- package/src/modules/shipping_carriers/lib/status-sync.ts +2 -2
- package/src/modules/shipping_carriers/workers/webhook-processor.ts +71 -39
- package/src/modules/warranty_claims/commands/claim-lines.ts +107 -66
- package/src/modules/warranty_claims/commands/claims.ts +14 -13
- package/src/modules/warranty_claims/commands/shared.ts +7 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/warranty_claims/commands/claims.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from 'crypto'\nimport { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { registerCommand, type CommandBus, type CommandHandler, type CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { invalidateCrudCache } from '@open-mercato/shared/lib/crud/cache'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readSafeDecryptedString } from '../lib/decryptionSafety'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport {\n WarrantyClaim,\n WarrantyClaimLine,\n} from '../data/entities'\nimport {\n CLAIM_FULFILLMENT_UPDATE_FIELDS,\n CLAIM_INTAKE_UPDATE_FIELDS,\n claimCreateSchema,\n claimUpdateSchema,\n assignClaimInputSchema,\n claimCreateCreditMemoSchema,\n claimCreateReplacementOrderSchema,\n claimCreateSalesReturnSchema,\n claimSetReturnLabelSchema,\n commentClaimInputSchema,\n transitionClaimInputSchema,\n vendorRecoveryInputSchema,\n type ClaimCreateInput,\n type ClaimInitialLineCreateInput,\n type ClaimUpdateInput,\n type AssignClaimInput,\n type ClaimCreateCreditMemoInput,\n type ClaimCreateReplacementOrderInput,\n type ClaimCreateSalesReturnInput,\n type ClaimSetReturnLabelInput,\n type CommentClaimInput,\n type TransitionClaimInput,\n type VendorRecoveryInput,\n type WarrantyClaimChannel,\n type WarrantyClaimLineStatus,\n type WarrantyClaimPriority,\n type WarrantyClaimDisposition,\n type WarrantyClaimStatus,\n type WarrantyClaimType,\n type WarrantyClaimWarrantyStatus,\n} from '../data/validators'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { isAssignableStaffUser } from '../lib/assigneeNames'\nimport { WarrantyClaimNumberGenerator } from '../services/claimNumberGenerator'\nimport { emitWarrantyClaimsEvent } from '../events'\nimport { assertTransition, canResolveWithLineStatuses, computeHeaderRollups } from '../lib/stateMachine'\nimport { assertOrderBelongsToCustomer } from '../lib/orderOwnership'\nimport { addBusinessMillis, businessMillisBetween } from '../lib/businessHours'\nimport { resolveEffectiveWarrantyClaimSettings, type WarrantyClaimEffectiveSettings } from '../lib/settings'\nimport { evaluateClaimRisk } from '../lib/risk'\nimport type { WarrantyAdjudicationEvaluator } from '../services/adjudicationEvaluator'\nimport type { WarrantyEntitlementInput, WarrantyEntitlementResolver } from '../services/entitlementResolver'\nimport {\n WARRANTY_CLAIM_RESOURCE_KIND,\n appendClaimEvent,\n enforceWarrantyClaimOptimisticLock,\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n requireScopedClaim,\n type WarrantyClaimScope,\n} from './shared'\n\nconst claimCrudEvents: CrudEventsConfig = {\n module: 'warranty_claims',\n entity: 'claim',\n persistent: true,\n buildPayload: (ctx) => {\n const claim = ctx.entity as WarrantyClaim | null\n return {\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n claimType: claim?.claimType ?? null,\n status: claim?.status ?? null,\n }\n },\n}\n\nconst claimDeleteSchema = z\n .object({\n id: z.string().uuid(),\n organizationId: z.string().uuid().optional(),\n tenantId: z.string().uuid().optional(),\n })\n .strict()\n\nconst submitClaimSchema = claimDeleteSchema.extend({\n actorCustomerId: z.string().uuid().optional(),\n})\nconst escalateClaimInputSchema = z\n .object({\n id: z.string().uuid(),\n organizationId: z.string().uuid(),\n tenantId: z.string().uuid(),\n toLevel: z.coerce.number().int().min(1).max(1000),\n reassignToUserId: z.string().uuid().optional(),\n })\n .strict()\n\ntype ClaimDeleteInput = z.infer<typeof claimDeleteSchema>\ntype SubmitClaimInput = z.infer<typeof submitClaimSchema>\ntype EscalateClaimInput = z.infer<typeof escalateClaimInputSchema>\ntype EscalateClaimResult = { claimId: string; escalationLevel: number; escalated: boolean }\ntype ClaimSetReturnLabelResult = {\n claimId: string\n labelUrl: string | null\n trackingNumber: string | null\n carrier: string | null\n}\n\ntype ScopeInput = {\n organizationId?: string | null\n tenantId?: string | null\n}\n\ntype ClaimUpdateField =\n | (typeof CLAIM_INTAKE_UPDATE_FIELDS)[number]\n | (typeof CLAIM_FULFILLMENT_UPDATE_FIELDS)[number]\n\ntype ClaimLineSnapshot = {\n id: string\n lineNo: number\n productId: string | null\n variantId: string | null\n sku: string | null\n productName: string | null\n orderLineId: string | null\n serialNumber: string | null\n lotNumber: string | null\n purchaseDate: string | null\n warrantyMonths: number | null\n warrantyExpiresAt: string | null\n warrantyStatus: WarrantyClaimWarrantyStatus\n faultCode: string | null\n faultDescription: string | null\n qtyClaimed: string\n qtyApproved: string | null\n qtyReceived: string | null\n conditionOnReceipt: string | null\n conditionGrade: string | null\n quarantineStatus: string\n inspectionNotes: string | null\n assessmentPayload: Record<string, unknown> | null\n disposition: WarrantyClaimDisposition | null\n lineStatus: WarrantyClaimLineStatus\n creditAmount: string | null\n restockingFee: string | null\n coreChargeAmount: string | null\n coreCreditAmount: string | null\n vendorClaimLineId: string | null\n vendorName: string | null\n deletedAt: string | null\n updatedAt: string | null\n}\n\ntype ClaimSnapshot = {\n id: string\n organizationId: string\n tenantId: string\n claimNumber: string\n claimType: WarrantyClaimType\n status: WarrantyClaimStatus\n channel: WarrantyClaimChannel\n priority: WarrantyClaimPriority\n customerId: string | null\n customerName: string | null\n externalRef: string | null\n intakeMessageRef: string | null\n entitlementSource: string | null\n contactEmail: string | null\n returnLabelUrl: string | null\n returnTrackingNumber: string | null\n returnCarrier: string | null\n vendorName: string | null\n vendorRef: string | null\n orderId: string | null\n orderNumber: string | null\n awaitingStaffReply: boolean\n salesReturnId: string | null\n replacementOrderId: string | null\n creditMemoId: string | null\n sourceClaimId: string | null\n advanceReplacement: boolean\n advanceShippedAt: string | null\n reasonCode: string | null\n rejectionReasonCode: string | null\n resolutionSummary: string | null\n notes: string | null\n currencyCode: string | null\n totalClaimedAmount: string | null\n totalApprovedAmount: string | null\n totalRecoveredAmount: string | null\n escalationLevel: number\n escalatedAt: string | null\n slaDueAt: string | null\n slaPausedAt: string | null\n slaAtRiskNotifiedAt: string | null\n slaBreachedNotifiedAt: string | null\n submittedAt: string | null\n resolvedAt: string | null\n closedAt: string | null\n assigneeUserId: string | null\n deletedAt: string | null\n updatedAt: string | null\n lines: ClaimLineSnapshot[]\n}\n\ntype ClaimUndoPayload = {\n before?: ClaimSnapshot | null\n after?: ClaimSnapshot | null\n}\n\ntype ClaimEventPayload = {\n id: string\n claimId: string\n claimNumber: string\n externalRef: string | null\n claimType: WarrantyClaimType\n status: WarrantyClaimStatus\n customerId: string | null\n organizationId: string\n tenantId: string\n}\n\ntype ReferenceLookupResult = 'missing' | 'unknown'\n\ntype ReferenceValidationInput = {\n orderId?: string | null\n salesReturnId?: string | null\n replacementOrderId?: string | null\n creditMemoId?: string | null\n lineOrderRefs?: Array<{ orderLineId: string; orderId: string | null }>\n}\n\nconst intakeStatuses = new Set<WarrantyClaimStatus>(['draft', 'submitted', 'in_review', 'info_requested'])\nconst fulfillmentStatuses = new Set<WarrantyClaimStatus>(['approved', 'awaiting_return', 'received', 'inspecting'])\nconst deletableStatuses = new Set<WarrantyClaimStatus>(['draft', 'cancelled'])\nconst preReceivedStatuses = new Set<WarrantyClaimStatus>([\n 'draft',\n 'submitted',\n 'in_review',\n 'info_requested',\n 'approved',\n 'awaiting_return',\n])\n\nfunction parseCommandInput<T>(schema: z.ZodType<T>, rawInput: unknown): T {\n const result = schema.safeParse(rawInput ?? {})\n if (!result.success) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidInput' })\n }\n return result.data\n}\n\nfunction hasOwn(input: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(input, key)\n}\n\nfunction resolveScope(ctx: CommandRuntimeContext, input: ScopeInput): WarrantyClaimScope {\n const tenantId = input.tenantId ?? ctx.auth?.tenantId ?? null\n const organizationId = input.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n if (!tenantId) throw new CrudHttpError(400, { error: '[internal] tenant scope required for warranty claim command' })\n if (!organizationId) throw new CrudHttpError(400, { error: '[internal] organization scope required for warranty claim command' })\n ensureTenantScope(ctx, tenantId)\n ensureOrganizationScope(ctx, organizationId)\n return { tenantId, organizationId }\n}\n\nfunction toIso(value: Date | string | null | undefined): string | null {\n if (!value) return null\n const date = value instanceof Date ? value : new Date(value)\n return Number.isNaN(date.getTime()) ? null : date.toISOString()\n}\n\nfunction toDate(value: string | null): Date | null {\n if (!value) return null\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\nfunction toDateOnlyIso(value: Date | string | null | undefined): string | null {\n const iso = toIso(value)\n return iso ? iso.slice(0, 10) : null\n}\n\nfunction toDateOnly(value: string | null): Date | null {\n if (!value) return null\n const date = new Date(`${value}T00:00:00.000Z`)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\nfunction amountString(value: number | string | null | undefined, fallback = '0'): string | null {\n if (value === null) return null\n if (value === undefined) return fallback\n const parsed = typeof value === 'number' ? value : Number(value)\n if (!Number.isFinite(parsed)) return fallback\n return String(parsed)\n}\n\nfunction nullableAmountString(value: number | string | null | undefined): string | null {\n if (value === undefined || value === null) return null\n return amountString(value, '0')\n}\n\nfunction addMonths(date: Date, months: number): Date {\n const target = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + months, 1))\n const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate()\n const copy = new Date(date.getTime())\n copy.setUTCDate(1)\n copy.setUTCFullYear(target.getUTCFullYear(), target.getUTCMonth(), Math.min(date.getUTCDate(), lastDay))\n return copy\n}\n\nfunction computeWarrantyDates(\n purchaseDate: Date | null | undefined,\n warrantyMonths: number | null | undefined,\n): { warrantyExpiresAt: Date | null; warrantyStatus: WarrantyClaimWarrantyStatus } {\n if (!purchaseDate || warrantyMonths === null || warrantyMonths === undefined) {\n return { warrantyExpiresAt: null, warrantyStatus: 'unknown' }\n }\n const warrantyExpiresAt = addMonths(purchaseDate, warrantyMonths)\n const warrantyStatus = warrantyExpiresAt.getTime() >= Date.now() ? 'in_warranty' : 'out_of_warranty'\n return { warrantyExpiresAt, warrantyStatus }\n}\n\nfunction buildCreateEntitlementInput(input: ClaimCreateInput): WarrantyEntitlementInput | null {\n const lines = input.lines ?? []\n const sourceLine = lines.find((line) => typeof line.serialNumber === 'string' && line.serialNumber.trim().length > 0)\n ?? lines.find((line) => Boolean(line.productId))\n ?? lines.find((line) => typeof line.sku === 'string' && line.sku.trim().length > 0)\n ?? (input.orderId ? lines.find((line) => Boolean(line.purchaseDate)) : null)\n ?? null\n\n const serialNumber = sourceLine?.serialNumber?.trim() || null\n const orderId = input.orderId ?? null\n const productId = sourceLine?.productId ?? null\n const sku = sourceLine?.sku?.trim() || null\n\n if (!serialNumber && !orderId && !productId && !sku) return null\n\n return {\n serialNumber,\n orderId,\n productId,\n sku,\n purchaseDate: toDateOnlyIso(sourceLine?.purchaseDate),\n }\n}\n\nasync function stampEntitlementSourceIfResolvable(\n ctx: CommandRuntimeContext,\n em: EntityManager,\n claim: WarrantyClaim,\n input: ClaimCreateInput,\n scope: WarrantyClaimScope,\n): Promise<void> {\n const entitlementInput = buildCreateEntitlementInput(input)\n if (!entitlementInput) return\n\n try {\n const resolver = ctx.container.resolve<WarrantyEntitlementResolver>('warrantyEntitlementResolver')\n const result = await resolver.resolveEntitlement(entitlementInput, scope, em)\n claim.entitlementSource = result.source ?? null\n } catch {\n claim.entitlementSource = null\n }\n}\n\nfunction buildInitialLineData(\n claim: WarrantyClaim,\n input: ClaimInitialLineCreateInput,\n index: number,\n): Partial<WarrantyClaimLine> & {\n id: string\n claim: WarrantyClaim\n organizationId: string\n tenantId: string\n lineNo: number\n qtyClaimed: string\n lineStatus: WarrantyClaimLineStatus\n warrantyStatus: WarrantyClaimWarrantyStatus\n createdAt: Date\n updatedAt: Date\n} {\n const purchaseDate = input.purchaseDate ?? null\n const warrantyMonths = input.warrantyMonths ?? null\n const computedWarranty = computeWarrantyDates(purchaseDate, warrantyMonths)\n return {\n id: randomUUID(),\n claim,\n organizationId: claim.organizationId,\n tenantId: claim.tenantId,\n lineNo: input.lineNo ?? index + 1,\n productId: input.productId ?? null,\n variantId: input.variantId ?? null,\n sku: input.sku ?? null,\n productName: input.productName ?? null,\n orderLineId: input.orderLineId ?? null,\n serialNumber: input.serialNumber ?? null,\n lotNumber: input.lotNumber ?? null,\n purchaseDate,\n warrantyMonths,\n warrantyExpiresAt: input.warrantyExpiresAt ?? computedWarranty.warrantyExpiresAt,\n warrantyStatus: input.warrantyStatus ?? computedWarranty.warrantyStatus,\n faultCode: input.faultCode ?? null,\n faultDescription: input.faultDescription ?? null,\n qtyClaimed: amountString(input.qtyClaimed, '1') ?? '1',\n qtyApproved: nullableAmountString(input.qtyApproved),\n qtyReceived: nullableAmountString(input.qtyReceived),\n conditionOnReceipt: input.conditionOnReceipt ?? null,\n inspectionNotes: input.inspectionNotes ?? null,\n disposition: input.disposition ?? null,\n vendorName: input.vendorName ?? null,\n lineStatus: 'pending',\n creditAmount: nullableAmountString(input.creditAmount),\n restockingFee: nullableAmountString(input.restockingFee),\n coreChargeAmount: nullableAmountString(input.coreChargeAmount),\n coreCreditAmount: nullableAmountString(input.coreCreditAmount),\n createdAt: new Date(),\n updatedAt: new Date(),\n }\n}\n\nfunction snapshotLine(line: WarrantyClaimLine): ClaimLineSnapshot {\n return {\n id: line.id,\n lineNo: line.lineNo,\n productId: line.productId ?? null,\n variantId: line.variantId ?? null,\n sku: line.sku ?? null,\n productName: line.productName ?? null,\n orderLineId: line.orderLineId ?? null,\n serialNumber: line.serialNumber ?? null,\n lotNumber: line.lotNumber ?? null,\n purchaseDate: toDateOnlyIso(line.purchaseDate),\n warrantyMonths: line.warrantyMonths ?? null,\n warrantyExpiresAt: toDateOnlyIso(line.warrantyExpiresAt),\n warrantyStatus: line.warrantyStatus,\n faultCode: line.faultCode ?? null,\n faultDescription: line.faultDescription ?? null,\n qtyClaimed: line.qtyClaimed,\n qtyApproved: line.qtyApproved ?? null,\n qtyReceived: line.qtyReceived ?? null,\n conditionOnReceipt: line.conditionOnReceipt ?? null,\n conditionGrade: line.conditionGrade ?? null,\n quarantineStatus: line.quarantineStatus,\n inspectionNotes: line.inspectionNotes ?? null,\n assessmentPayload: line.assessmentPayload ?? null,\n disposition: line.disposition ?? null,\n lineStatus: line.lineStatus,\n creditAmount: line.creditAmount ?? null,\n restockingFee: line.restockingFee ?? null,\n coreChargeAmount: line.coreChargeAmount ?? null,\n coreCreditAmount: line.coreCreditAmount ?? null,\n vendorClaimLineId: line.vendorClaimLineId ?? null,\n vendorName: line.vendorName ?? null,\n deletedAt: toIso(line.deletedAt),\n updatedAt: toIso(line.updatedAt),\n }\n}\n\nfunction snapshotClaim(claim: WarrantyClaim, lines: readonly WarrantyClaimLine[]): ClaimSnapshot {\n return {\n id: claim.id,\n organizationId: claim.organizationId,\n tenantId: claim.tenantId,\n claimNumber: claim.claimNumber,\n claimType: claim.claimType,\n status: claim.status,\n channel: claim.channel,\n priority: claim.priority,\n customerId: claim.customerId ?? null,\n customerName: claim.customerName ?? null,\n externalRef: claim.externalRef ?? null,\n intakeMessageRef: claim.intakeMessageRef ?? null,\n entitlementSource: claim.entitlementSource ?? null,\n contactEmail: claim.contactEmail ?? null,\n returnLabelUrl: claim.returnLabelUrl ?? null,\n returnTrackingNumber: claim.returnTrackingNumber ?? null,\n returnCarrier: claim.returnCarrier ?? null,\n vendorName: claim.vendorName ?? null,\n vendorRef: claim.vendorRef ?? null,\n orderId: claim.orderId ?? null,\n orderNumber: claim.orderNumber ?? null,\n awaitingStaffReply: claim.awaitingStaffReply === true,\n salesReturnId: claim.salesReturnId ?? null,\n replacementOrderId: claim.replacementOrderId ?? null,\n creditMemoId: claim.creditMemoId ?? null,\n sourceClaimId: claim.sourceClaimId ?? null,\n advanceReplacement: claim.advanceReplacement,\n advanceShippedAt: toIso(claim.advanceShippedAt),\n reasonCode: claim.reasonCode ?? null,\n rejectionReasonCode: claim.rejectionReasonCode ?? null,\n resolutionSummary: claim.resolutionSummary ?? null,\n notes: claim.notes ?? null,\n currencyCode: claim.currencyCode ?? null,\n totalClaimedAmount: claim.totalClaimedAmount ?? null,\n totalApprovedAmount: claim.totalApprovedAmount ?? null,\n totalRecoveredAmount: claim.totalRecoveredAmount ?? null,\n escalationLevel: claim.escalationLevel ?? 0,\n escalatedAt: toIso(claim.escalatedAt),\n slaDueAt: toIso(claim.slaDueAt),\n slaPausedAt: toIso(claim.slaPausedAt),\n slaAtRiskNotifiedAt: toIso(claim.slaAtRiskNotifiedAt),\n slaBreachedNotifiedAt: toIso(claim.slaBreachedNotifiedAt),\n submittedAt: toIso(claim.submittedAt),\n resolvedAt: toIso(claim.resolvedAt),\n closedAt: toIso(claim.closedAt),\n assigneeUserId: claim.assigneeUserId ?? null,\n deletedAt: toIso(claim.deletedAt),\n updatedAt: toIso(claim.updatedAt),\n lines: lines.map(snapshotLine),\n }\n}\n\nasync function loadClaimSnapshot(\n em: EntityManager,\n claimId: string,\n scope: WarrantyClaimScope,\n): Promise<ClaimSnapshot | null> {\n const claim = await findOneWithDecryption(em, WarrantyClaim, { id: claimId, tenantId: scope.tenantId, organizationId: scope.organizationId }, {}, scope)\n if (!claim) return null\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId },\n {},\n scope,\n )\n return snapshotClaim(claim, lines)\n}\n\nfunction snapshotValueChanged(before: unknown, after: unknown): boolean {\n return JSON.stringify(before) !== JSON.stringify(after)\n}\n\nfunction restoreClaimDelta(claim: WarrantyClaim, before: ClaimSnapshot, after: ClaimSnapshot): void {\n if (before.claimNumber !== after.claimNumber) claim.claimNumber = before.claimNumber\n if (before.claimType !== after.claimType) claim.claimType = before.claimType\n if (before.status !== after.status) claim.status = before.status\n if (before.channel !== after.channel) claim.channel = before.channel\n if (before.priority !== after.priority) claim.priority = before.priority\n if (before.customerId !== after.customerId) claim.customerId = before.customerId\n if (before.customerName !== after.customerName) claim.customerName = before.customerName\n if (before.externalRef !== after.externalRef) claim.externalRef = before.externalRef\n if (before.intakeMessageRef !== after.intakeMessageRef) claim.intakeMessageRef = before.intakeMessageRef\n if (before.entitlementSource !== after.entitlementSource) claim.entitlementSource = before.entitlementSource\n if (before.contactEmail !== after.contactEmail) claim.contactEmail = before.contactEmail\n if (before.returnLabelUrl !== after.returnLabelUrl) claim.returnLabelUrl = before.returnLabelUrl\n if (before.returnTrackingNumber !== after.returnTrackingNumber) claim.returnTrackingNumber = before.returnTrackingNumber\n if (before.returnCarrier !== after.returnCarrier) claim.returnCarrier = before.returnCarrier\n if (before.vendorName !== after.vendorName) claim.vendorName = before.vendorName\n if (before.vendorRef !== after.vendorRef) claim.vendorRef = before.vendorRef\n if (before.orderId !== after.orderId) claim.orderId = before.orderId\n if (before.orderNumber !== after.orderNumber) claim.orderNumber = before.orderNumber\n if (before.awaitingStaffReply !== after.awaitingStaffReply) claim.awaitingStaffReply = before.awaitingStaffReply === true\n if (before.salesReturnId !== after.salesReturnId) claim.salesReturnId = before.salesReturnId\n if (before.replacementOrderId !== after.replacementOrderId) claim.replacementOrderId = before.replacementOrderId\n if (before.creditMemoId !== after.creditMemoId) claim.creditMemoId = before.creditMemoId\n if (before.sourceClaimId !== after.sourceClaimId) claim.sourceClaimId = before.sourceClaimId\n if (before.advanceReplacement !== after.advanceReplacement) claim.advanceReplacement = before.advanceReplacement\n if (before.advanceShippedAt !== after.advanceShippedAt) claim.advanceShippedAt = toDate(before.advanceShippedAt)\n if (before.reasonCode !== after.reasonCode) claim.reasonCode = before.reasonCode\n if (before.rejectionReasonCode !== after.rejectionReasonCode) claim.rejectionReasonCode = before.rejectionReasonCode\n if (before.resolutionSummary !== after.resolutionSummary) claim.resolutionSummary = before.resolutionSummary\n if (before.notes !== after.notes) claim.notes = before.notes\n if (before.currencyCode !== after.currencyCode) claim.currencyCode = before.currencyCode\n if (before.totalClaimedAmount !== after.totalClaimedAmount) claim.totalClaimedAmount = before.totalClaimedAmount\n if (before.totalApprovedAmount !== after.totalApprovedAmount) claim.totalApprovedAmount = before.totalApprovedAmount\n if (before.totalRecoveredAmount !== after.totalRecoveredAmount) claim.totalRecoveredAmount = before.totalRecoveredAmount\n if (before.escalationLevel !== after.escalationLevel) claim.escalationLevel = before.escalationLevel\n if (before.escalatedAt !== after.escalatedAt) claim.escalatedAt = toDate(before.escalatedAt)\n if (before.slaDueAt !== after.slaDueAt) claim.slaDueAt = toDate(before.slaDueAt)\n if (before.slaPausedAt !== after.slaPausedAt) claim.slaPausedAt = toDate(before.slaPausedAt)\n if (before.slaAtRiskNotifiedAt !== after.slaAtRiskNotifiedAt) claim.slaAtRiskNotifiedAt = toDate(before.slaAtRiskNotifiedAt)\n if (before.slaBreachedNotifiedAt !== after.slaBreachedNotifiedAt) claim.slaBreachedNotifiedAt = toDate(before.slaBreachedNotifiedAt)\n if (before.submittedAt !== after.submittedAt) claim.submittedAt = toDate(before.submittedAt)\n if (before.resolvedAt !== after.resolvedAt) claim.resolvedAt = toDate(before.resolvedAt)\n if (before.closedAt !== after.closedAt) claim.closedAt = toDate(before.closedAt)\n if (before.assigneeUserId !== after.assigneeUserId) claim.assigneeUserId = before.assigneeUserId\n if (before.deletedAt !== after.deletedAt) claim.deletedAt = toDate(before.deletedAt)\n claim.updatedAt = new Date()\n}\n\nfunction restoreLineDelta(line: WarrantyClaimLine, before: ClaimLineSnapshot, after: ClaimLineSnapshot): void {\n if (before.lineNo !== after.lineNo) line.lineNo = before.lineNo\n if (before.productId !== after.productId) line.productId = before.productId\n if (before.variantId !== after.variantId) line.variantId = before.variantId\n if (before.sku !== after.sku) line.sku = before.sku\n if (before.productName !== after.productName) line.productName = before.productName\n if (before.orderLineId !== after.orderLineId) line.orderLineId = before.orderLineId\n if (before.serialNumber !== after.serialNumber) line.serialNumber = before.serialNumber\n if (before.lotNumber !== after.lotNumber) line.lotNumber = before.lotNumber\n if (before.purchaseDate !== after.purchaseDate) line.purchaseDate = toDateOnly(before.purchaseDate)\n if (before.warrantyMonths !== after.warrantyMonths) line.warrantyMonths = before.warrantyMonths\n if (before.warrantyExpiresAt !== after.warrantyExpiresAt) line.warrantyExpiresAt = toDateOnly(before.warrantyExpiresAt)\n if (before.warrantyStatus !== after.warrantyStatus) line.warrantyStatus = before.warrantyStatus\n if (before.faultCode !== after.faultCode) line.faultCode = before.faultCode\n if (before.faultDescription !== after.faultDescription) line.faultDescription = before.faultDescription\n if (before.qtyClaimed !== after.qtyClaimed) line.qtyClaimed = before.qtyClaimed\n if (before.qtyApproved !== after.qtyApproved) line.qtyApproved = before.qtyApproved\n if (before.qtyReceived !== after.qtyReceived) line.qtyReceived = before.qtyReceived\n if (before.conditionOnReceipt !== after.conditionOnReceipt) line.conditionOnReceipt = before.conditionOnReceipt\n if (before.conditionGrade !== after.conditionGrade) line.conditionGrade = before.conditionGrade\n if (before.quarantineStatus !== after.quarantineStatus) line.quarantineStatus = before.quarantineStatus\n if (before.inspectionNotes !== after.inspectionNotes) line.inspectionNotes = before.inspectionNotes\n if (snapshotValueChanged(before.assessmentPayload, after.assessmentPayload)) line.assessmentPayload = before.assessmentPayload\n if (before.disposition !== after.disposition) line.disposition = before.disposition\n if (before.lineStatus !== after.lineStatus) line.lineStatus = before.lineStatus\n if (before.creditAmount !== after.creditAmount) line.creditAmount = before.creditAmount\n if (before.restockingFee !== after.restockingFee) line.restockingFee = before.restockingFee\n if (before.coreChargeAmount !== after.coreChargeAmount) line.coreChargeAmount = before.coreChargeAmount\n if (before.coreCreditAmount !== after.coreCreditAmount) line.coreCreditAmount = before.coreCreditAmount\n if (before.vendorClaimLineId !== after.vendorClaimLineId) line.vendorClaimLineId = before.vendorClaimLineId\n if (before.vendorName !== after.vendorName) line.vendorName = before.vendorName\n if (before.deletedAt !== after.deletedAt) line.deletedAt = toDate(before.deletedAt)\n line.updatedAt = new Date()\n}\n\nfunction throwClaimUndoConflict(): never {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.conflict' })\n}\n\nasync function requireCurrentUndoSnapshot(\n em: EntityManager,\n after: ClaimSnapshot,\n): Promise<{ claim: WarrantyClaim; lines: WarrantyClaimLine[] }> {\n const scope = { tenantId: after.tenantId, organizationId: after.organizationId }\n const claim = await findOneWithDecryption(\n em,\n WarrantyClaim,\n { id: after.id, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n )\n const expectedClaimUpdatedAt = toIso(after.updatedAt)\n if (!claim || !expectedClaimUpdatedAt || toIso(claim.updatedAt) !== expectedClaimUpdatedAt) throwClaimUndoConflict()\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: after.id, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n )\n const afterLines = Array.isArray(after.lines) ? after.lines : []\n if (lines.length !== afterLines.length) throwClaimUndoConflict()\n const afterLinesById = new Map(afterLines.map((line) => [line.id, line]))\n for (const line of lines) {\n const expected = afterLinesById.get(line.id)\n const expectedLineUpdatedAt = toIso(expected?.updatedAt)\n if (!expectedLineUpdatedAt || toIso(line.updatedAt) !== expectedLineUpdatedAt) throwClaimUndoConflict()\n }\n return { claim, lines }\n}\n\nasync function assertUndoSnapshotCurrent(ctx: CommandRuntimeContext, after: ClaimSnapshot): Promise<void> {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n await em.transactional(async (tx) => {\n await requireCurrentUndoSnapshot(tx, after)\n })\n}\n\nasync function restoreSnapshot(em: EntityManager, before: ClaimSnapshot, after: ClaimSnapshot): Promise<WarrantyClaim> {\n const { claim, lines } = await requireCurrentUndoSnapshot(em, after)\n restoreClaimDelta(claim, before, after)\n const beforeLinesById = new Map((Array.isArray(before.lines) ? before.lines : []).map((line) => [line.id, line]))\n const afterLinesById = new Map((Array.isArray(after.lines) ? after.lines : []).map((line) => [line.id, line]))\n for (const line of lines) {\n const beforeLine = beforeLinesById.get(line.id)\n const afterLine = afterLinesById.get(line.id)\n if (!beforeLine || !afterLine) throwClaimUndoConflict()\n if (snapshotValueChanged(beforeLine, afterLine)) restoreLineDelta(line, beforeLine, afterLine)\n }\n return claim\n}\n\nfunction claimEventPayload(claim: WarrantyClaim): ClaimEventPayload {\n return {\n id: claim.id,\n claimId: claim.id,\n claimNumber: claim.claimNumber,\n externalRef: claim.externalRef ?? null,\n claimType: claim.claimType,\n status: claim.status,\n customerId: claim.customerId ?? null,\n organizationId: claim.organizationId,\n tenantId: claim.tenantId,\n }\n}\n\nfunction claimPersistentEmitOptions(claim: WarrantyClaim) {\n return {\n persistent: true,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n } as const\n}\n\nasync function emitClaimCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n claim: WarrantyClaim,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action,\n entity: claim,\n identifiers: { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim },\n events: claimCrudEvents,\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim',\n { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim.${action}`,\n )\n}\n\nasync function emitClaimUndoCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n claim: WarrantyClaim,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action,\n entity: claim,\n identifiers: { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim },\n events: claimCrudEvents,\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim',\n { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim.undo.${action}`,\n )\n}\n\nasync function emitLineCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n line: WarrantyClaimLine,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action,\n entity: line,\n identifiers: { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim_line },\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim_line',\n { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim_line.${action}`,\n )\n}\n\nasync function emitLineUndoCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n line: WarrantyClaimLine,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action,\n entity: line,\n identifiers: { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim_line },\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim_line',\n { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim_line.undo.${action}`,\n )\n}\n\nfunction resolveClaimNumberGenerator(ctx: CommandRuntimeContext, em: EntityManager): WarrantyClaimNumberGenerator {\n try {\n return ctx.container.resolve('warrantyClaimNumberGenerator') as WarrantyClaimNumberGenerator\n } catch {\n return new WarrantyClaimNumberGenerator(em)\n }\n}\n\nfunction readCustomerName(row: Record<string, unknown>): string | null {\n const candidates = [row.display_name, row.displayName, row.name, row.label]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) return candidate.trim()\n }\n return null\n}\n\nfunction readString(row: Record<string, unknown>, key: string): string | null {\n const value = row[key]\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null\n}\n\ntype SalesReferenceTable = 'sales_orders' | 'sales_returns' | 'sales_credit_memos' | 'sales_order_lines'\n\ntype SalesReferenceDb = {\n sales_orders: {\n id: string\n currency_code: string\n customer_entity_id: string | null\n customer_contact_id: string | null\n billing_address_id: string | null\n shipping_address_id: string | null\n channel_id: string | null\n updated_at: Date | string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n sales_returns: {\n id: string\n updated_at: Date | string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n sales_credit_memos: {\n id: string\n updated_at: Date | string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n sales_order_lines: {\n id: string\n order_id: string\n product_id: string | null\n product_variant_id: string | null\n name: string | null\n kind: 'product' | 'service' | 'shipping' | 'discount' | 'adjustment'\n currency_code: string\n quantity: string | null\n unit_price_net: string\n unit_price_gross: string\n tax_rate: string\n total_net_amount: string\n total_gross_amount: string\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n}\n\ntype ClaimedQuantityDb = SalesReferenceDb & {\n warranty_claims: {\n id: string\n status: string\n tenant_id: string\n organization_id: string\n deleted_at: Date | null\n }\n warranty_claim_lines: {\n id: string\n claim_id: string\n order_line_id: string | null\n qty_claimed: string | null\n line_status: string\n tenant_id: string\n organization_id: string\n deleted_at: Date | null\n }\n}\n\nexport type ClaimedQuantityLine = {\n id?: string | null\n orderLineId?: string | null\n qtyClaimed: string | number\n deletedAt?: Date | string | null\n}\n\nfunction isMissingReferenceTableError(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false\n const candidate = err as { code?: unknown; message?: unknown }\n return candidate.code === '42P01'\n || (typeof candidate.message === 'string' && candidate.message.includes('does not exist'))\n}\n\nasync function querySalesReferenceRow(\n ctx: CommandRuntimeContext,\n table: SalesReferenceTable,\n scope: WarrantyClaimScope,\n id: string,\n select: string[],\n): Promise<Record<string, unknown> | null | undefined> {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<SalesReferenceDb>()\n try {\n const row = await db\n .selectFrom(table)\n .select(select as never[])\n .where('id' as never, '=', id as never)\n .where('tenant_id' as never, '=', scope.tenantId as never)\n .where('organization_id' as never, '=', scope.organizationId as never)\n .where('deleted_at' as never, 'is', null)\n .executeTakeFirst()\n return (row as Record<string, unknown> | undefined) ?? null\n } catch (err) {\n if (isMissingReferenceTableError(err)) return undefined\n throw err\n }\n}\n\nasync function querySalesOrderLineReferences(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n ids: string[],\n select: string[] = ['id', 'order_id'],\n): Promise<Record<string, unknown>[] | undefined> {\n if (ids.length === 0) return []\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<SalesReferenceDb>()\n try {\n const rows = await db\n .selectFrom('sales_order_lines')\n .select(select as never[])\n .where('id', 'in', ids)\n .where('tenant_id', '=', scope.tenantId)\n .where('organization_id', '=', scope.organizationId)\n .where('deleted_at', 'is', null)\n .execute()\n return rows as Record<string, unknown>[]\n } catch (err) {\n if (isMissingReferenceTableError(err)) return undefined\n throw err\n }\n}\n\nconst CLAIMED_QUANTITY_SCALE = 10_000n\nconst TAX_RATE_FORMULA_SCALE = 1_000_000n\n\nfunction claimedQuantityUnits(value: string | number | null | undefined): bigint | null {\n if (value === null || value === undefined) return null\n let normalized = String(value).trim()\n if (/e/i.test(normalized)) {\n const numeric = Number(normalized)\n if (!Number.isFinite(numeric)) return null\n normalized = numeric.toFixed(4)\n }\n const match = /^([+-]?)(\\d+)(?:\\.(\\d+))?$/.exec(normalized)\n if (!match) return null\n const [, sign, whole, fraction = ''] = match\n const scaledFraction = fraction.slice(0, 4).padEnd(4, '0')\n let units = BigInt(whole) * CLAIMED_QUANTITY_SCALE + BigInt(scaledFraction)\n if (fraction.length > 4 && fraction[4] >= '5') units += 1n\n return sign === '-' ? -units : units\n}\n\nfunction roundHalfUpDivision(numerator: bigint, denominator: bigint): bigint {\n if (denominator <= 0n) throw new Error('[internal] Positive denominator required')\n if (numerator < 0n) return -roundHalfUpDivision(-numerator, denominator)\n return (numerator + denominator / 2n) / denominator\n}\n\nfunction formatScaledUnits(units: bigint): string {\n const sign = units < 0n ? '-' : ''\n const absolute = units < 0n ? -units : units\n const whole = absolute / CLAIMED_QUANTITY_SCALE\n const fraction = String(absolute % CLAIMED_QUANTITY_SCALE).padStart(4, '0')\n return `${sign}${whole}.${fraction}`\n}\n\nfunction netUnitsFromGross(grossUnits: bigint, taxRateUnits: bigint): bigint {\n const denominator = TAX_RATE_FORMULA_SCALE + taxRateUnits\n return roundHalfUpDivision(grossUnits * TAX_RATE_FORMULA_SCALE, denominator)\n}\n\nexport async function assertClaimedQtyWithinSold(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n claimIdOrPendingLines: string | readonly ClaimedQuantityLine[],\n candidateLine: ClaimedQuantityLine,\n): Promise<void> {\n const orderLineId = candidateLine.orderLineId ?? null\n if (!orderLineId || !resolveOptionalEntityId('sales', 'sales_order_line')) return\n\n const salesLine = await querySalesReferenceRow(ctx, 'sales_order_lines', scope, orderLineId, ['id', 'quantity'])\n const soldQuantity = claimedQuantityUnits(salesLine?.quantity as string | number | null | undefined)\n if (salesLine === undefined || salesLine === null || soldQuantity === null) return\n\n let lines: readonly ClaimedQuantityLine[]\n if (typeof claimIdOrPendingLines === 'string') {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claimIdOrPendingLines,\n orderLineId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n {},\n scope,\n )\n } else {\n lines = claimIdOrPendingLines\n }\n\n let claimedQuantity = claimedQuantityUnits(candidateLine.qtyClaimed) ?? 0n\n for (const line of lines) {\n if (line.deletedAt || (line.orderLineId ?? null) !== orderLineId) continue\n if (candidateLine.id != null && line.id === candidateLine.id) continue\n claimedQuantity += claimedQuantityUnits(line.qtyClaimed) ?? 0n\n }\n if (claimedQuantity > soldQuantity) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.qtyExceedsOrdered' })\n }\n}\n\nexport async function assertPendingClaimQuantitiesWithinSold(\n em: EntityManager,\n scope: WarrantyClaimScope,\n pendingLinesByOrderLine: ReadonlyMap<string, readonly ClaimedQuantityLine[]>,\n options: { currentClaimId: string; excludedLineIds?: ReadonlySet<string> },\n): Promise<void> {\n const db = em.getKysely<ClaimedQuantityDb>()\n const orderLineIds = Array.from(pendingLinesByOrderLine.keys()).sort((left, right) => left.localeCompare(right))\n for (const orderLineId of orderLineIds) {\n let soldRow: { id: string; quantity: string | null } | undefined\n try {\n soldRow = await db\n .selectFrom('sales_order_lines')\n .select(['id', 'quantity'])\n .where('id', '=', orderLineId)\n .where('tenant_id', '=', scope.tenantId)\n .where('organization_id', '=', scope.organizationId)\n .where('deleted_at', 'is', null)\n .forUpdate()\n .executeTakeFirst()\n } catch (err) {\n if (isMissingReferenceTableError(err)) return\n throw err\n }\n const soldQuantity = claimedQuantityUnits(soldRow?.quantity)\n if (!soldRow || soldQuantity === null) continue\n\n const persistedRows = await db\n .selectFrom('warranty_claim_lines')\n .innerJoin('warranty_claims', 'warranty_claims.id', 'warranty_claim_lines.claim_id')\n .select(['warranty_claim_lines.id', 'warranty_claim_lines.qty_claimed'])\n .where('warranty_claim_lines.order_line_id', '=', orderLineId)\n .where('warranty_claim_lines.tenant_id', '=', scope.tenantId)\n .where('warranty_claim_lines.organization_id', '=', scope.organizationId)\n .where('warranty_claim_lines.deleted_at', 'is', null)\n .where('warranty_claim_lines.line_status', '!=', 'rejected')\n .where('warranty_claims.tenant_id', '=', scope.tenantId)\n .where('warranty_claims.organization_id', '=', scope.organizationId)\n .where('warranty_claims.id', '=', options.currentClaimId)\n .where('warranty_claims.deleted_at', 'is', null)\n .where('warranty_claims.status', '!=', 'cancelled')\n .execute()\n\n let claimedQuantity = 0n\n for (const row of persistedRows) {\n if (options.excludedLineIds?.has(row.id)) continue\n claimedQuantity += claimedQuantityUnits(row.qty_claimed) ?? 0n\n }\n for (const line of pendingLinesByOrderLine.get(orderLineId) ?? []) {\n claimedQuantity += claimedQuantityUnits(line.qtyClaimed) ?? 0n\n }\n if (claimedQuantity > soldQuantity) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.qtyExceedsOrdered' })\n }\n }\n}\n\ntype CustomerEntitiesDb = {\n customer_entities: {\n id: string\n display_name: string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n}\n\nfunction isMissingCustomerTableError(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false\n const candidate = err as { code?: unknown; message?: unknown }\n return candidate.code === '42P01'\n || (typeof candidate.message === 'string'\n && candidate.message.includes('customer_entities')\n && candidate.message.includes('does not exist'))\n}\n\nasync function assertCustomerExists(\n ctx: CommandRuntimeContext,\n customerId: string,\n scope: WarrantyClaimScope,\n): Promise<void> {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<CustomerEntitiesDb>()\n let row: { id: string } | undefined\n try {\n row = await db\n .selectFrom('customer_entities')\n .select('id')\n .where('id', '=', customerId)\n .where('tenant_id', '=', scope.tenantId)\n .where('organization_id', '=', scope.organizationId)\n .where('deleted_at', 'is', null)\n .executeTakeFirst()\n } catch (err) {\n if (isMissingCustomerTableError(err)) return\n throw err\n }\n if (!row) throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidInput' })\n}\n\nasync function resolveCustomerName(\n ctx: CommandRuntimeContext,\n customerId: string | null | undefined,\n scope: WarrantyClaimScope,\n fallback: string | null | undefined,\n options: { strict: boolean } = { strict: false },\n): Promise<string | null> {\n if (!customerId) return fallback ?? null\n if (options.strict) await assertCustomerExists(ctx, customerId, scope)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<CustomerEntitiesDb>()\n let customer: Record<string, unknown> | undefined\n try {\n customer = await db\n .selectFrom('customer_entities')\n .select(['id', 'display_name'] as never[])\n .where('id' as never, '=', customerId as never)\n .where('tenant_id' as never, '=', scope.tenantId as never)\n .where('organization_id' as never, '=', scope.organizationId as never)\n .where('deleted_at' as never, 'is', null)\n .executeTakeFirst() as Record<string, unknown> | undefined\n } catch (err) {\n if (!isMissingCustomerTableError(err)) throw err\n return fallback ?? null\n }\n if (!customer) return fallback ?? null\n let encryption: {\n decryptEntityPayload: (entityId: string, payload: Record<string, unknown>, tenantId: string | null, organizationId?: string | null) => Promise<Record<string, unknown>>\n } | null = null\n try {\n encryption = ctx.container.resolve('tenantEncryptionService')\n } catch {\n encryption = null\n }\n if (encryption) {\n try {\n customer = await encryption.decryptEntityPayload('customers:customer_entity', customer, scope.tenantId, scope.organizationId)\n } catch {\n return fallback ?? null\n }\n }\n return readSafeDecryptedString(readCustomerName(customer)) ?? fallback ?? null\n}\n\nasync function resolveOrderNumber(\n ctx: CommandRuntimeContext,\n orderId: string | null | undefined,\n scope: WarrantyClaimScope,\n fallback: string | null | undefined,\n): Promise<string | null> {\n if (!orderId) return null\n const row = await querySalesReferenceRow(ctx, 'sales_orders', scope, orderId, ['id', 'order_number'])\n if (!row) return fallback ?? null\n return readString(row, 'order_number') ?? fallback ?? null\n}\n\ntype CustomerUsersDb = {\n customer_users: {\n id: string\n tenant_id: string | null\n organization_id: string | null\n customer_entity_id: string | null\n is_active: boolean\n deleted_at: Date | null\n }\n}\n\nasync function resolvePortalRecipientUserIds(\n ctx: CommandRuntimeContext,\n claim: WarrantyClaim,\n): Promise<string[]> {\n if (!claim.customerId) return []\n try {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<CustomerUsersDb>()\n const rows = await db\n .selectFrom('customer_users')\n .select('id')\n .where('tenant_id', '=', claim.tenantId)\n .where('organization_id', '=', claim.organizationId)\n .where('customer_entity_id', '=', claim.customerId)\n .where('is_active', '=', true)\n .where('deleted_at', 'is', null)\n .limit(100)\n .execute()\n return rows.map((row) => row.id)\n } catch {\n return []\n }\n}\n\nasync function emitClaimStatusChanged(\n ctx: CommandRuntimeContext,\n claim: WarrantyClaim,\n fromStatus: WarrantyClaimStatus,\n toStatus: WarrantyClaimStatus,\n): Promise<void> {\n const payload = {\n ...claimEventPayload(claim),\n fromStatus,\n toStatus,\n }\n await emitWarrantyClaimsEvent('warranty_claims.claim.status_changed', payload, claimPersistentEmitOptions(claim))\n const recipientUserIds = await resolvePortalRecipientUserIds(ctx, claim)\n if (recipientUserIds.length === 0) return\n await emitWarrantyClaimsEvent('warranty_claims.claim.portal_status_changed', {\n ...payload,\n recipientUserIds,\n }, claimPersistentEmitOptions(claim))\n}\n\nasync function emitCustomerVisibleCommentAdded(\n ctx: CommandRuntimeContext,\n claim: WarrantyClaim,\n input: CommentClaimInput,\n): Promise<void> {\n const recipientUserIds = await resolvePortalRecipientUserIds(ctx, claim)\n if (recipientUserIds.length === 0) return\n await emitWarrantyClaimsEvent('warranty_claims.claim.comment_added', {\n ...claimEventPayload(claim),\n visibility: input.visibility,\n actorCustomerId: input.actorCustomerId ?? null,\n recipientUserIds,\n }, claimPersistentEmitOptions(claim))\n}\n\nfunction applySlaPause(\n em: EntityManager,\n claim: WarrantyClaim,\n fromStatus: WarrantyClaimStatus,\n toStatus: WarrantyClaimStatus,\n now: Date,\n effectiveSettings: WarrantyClaimEffectiveSettings,\n): void {\n if (fromStatus === toStatus || toStatus !== 'info_requested' || !effectiveSettings.slaPauseOnInfoRequested) return\n claim.slaPausedAt = now\n appendClaimEvent(em, claim, 'system', {\n visibility: 'customer',\n payload: { action: 'sla_paused' },\n actorUserId: null,\n })\n}\n\nfunction applySlaResume(\n em: EntityManager,\n claim: WarrantyClaim,\n fromStatus: WarrantyClaimStatus,\n toStatus: WarrantyClaimStatus,\n now: Date,\n effectiveSettings: WarrantyClaimEffectiveSettings,\n): void {\n if (fromStatus !== 'info_requested' || toStatus === 'info_requested' || !claim.slaPausedAt) return\n // Preserve the business time that was still remaining when the clock stopped;\n // a claim already past due when paused stays past due.\n if (claim.slaDueAt && claim.slaDueAt.getTime() > claim.slaPausedAt.getTime()) {\n const remainingBusinessMillis = businessMillisBetween(claim.slaPausedAt, claim.slaDueAt, effectiveSettings.businessHours)\n claim.slaDueAt = addBusinessMillis(now, remainingBusinessMillis, effectiveSettings.businessHours)\n }\n claim.slaPausedAt = null\n claim.slaAtRiskNotifiedAt = null\n claim.slaBreachedNotifiedAt = null\n appendClaimEvent(em, claim, 'system', {\n visibility: 'customer',\n payload: { action: 'sla_resumed' },\n actorUserId: null,\n })\n}\n\nfunction resolveOptionalEntityId(moduleId: string, entity: string): EntityId | null {\n const registry = E as unknown as Record<string, Record<string, string> | undefined>\n const value = registry[moduleId]?.[entity]\n return typeof value === 'string' ? (value as EntityId) : null\n}\n\nasync function lookupSalesReference(\n ctx: CommandRuntimeContext,\n entityId: EntityId | null,\n table: SalesReferenceTable,\n scope: WarrantyClaimScope,\n id: string,\n select: string[],\n): Promise<Record<string, unknown> | ReferenceLookupResult> {\n if (!entityId) return 'unknown'\n const row = await querySalesReferenceRow(ctx, table, scope, id, select)\n if (row === undefined) return 'unknown'\n return row ?? 'missing'\n}\n\nfunction assertValidSalesReference(result: Record<string, unknown> | ReferenceLookupResult): asserts result is Record<string, unknown> | 'unknown' {\n if (result === 'missing') {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidReference' })\n }\n}\n\nexport async function validateClaimReferences(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n input: ReferenceValidationInput,\n): Promise<void> {\n if (input.orderId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_order'), 'sales_orders', scope, input.orderId, ['id'])\n assertValidSalesReference(result)\n }\n if (input.replacementOrderId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_order'), 'sales_orders', scope, input.replacementOrderId, ['id'])\n assertValidSalesReference(result)\n }\n if (input.salesReturnId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_return'), 'sales_returns', scope, input.salesReturnId, ['id'])\n assertValidSalesReference(result)\n }\n if (input.creditMemoId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_credit_memo'), 'sales_credit_memos', scope, input.creditMemoId, ['id'])\n assertValidSalesReference(result)\n }\n const lineRefs = input.lineOrderRefs ?? []\n if (lineRefs.length === 0 || !resolveOptionalEntityId('sales', 'sales_order_line')) return\n const lineRows = await querySalesOrderLineReferences(\n ctx,\n scope,\n Array.from(new Set(lineRefs.map((lineRef) => lineRef.orderLineId))),\n )\n if (lineRows === undefined) return\n const lineRowsById = new Map(lineRows.map((row) => [readString(row, 'id'), row]))\n for (const lineRef of lineRefs) {\n const result = lineRowsById.get(lineRef.orderLineId)\n if (!result) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidReference' })\n }\n if (lineRef.orderId && readString(result, 'order_id') !== lineRef.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidReference' })\n }\n }\n}\n\nasync function validateAssigneeUser(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n assigneeUserId: string | null | undefined,\n): Promise<void> {\n if (!assigneeUserId) return\n const assignable = await isAssignableStaffUser({\n container: ctx.container,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n }, assigneeUserId)\n if (!assignable) throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidAssignee' })\n}\n\nfunction applyClaimAssignment(\n em: EntityManager,\n claim: WarrantyClaim,\n assigneeUserId: string | null,\n actorUserId: string | null,\n now: Date,\n): void {\n claim.assigneeUserId = assigneeUserId\n claim.updatedAt = now\n appendClaimEvent(em, claim, 'assignment', {\n visibility: 'internal',\n payload: { assigneeUserId: claim.assigneeUserId },\n actorUserId,\n })\n}\n\nfunction allowedUpdateFields(status: WarrantyClaimStatus): Set<ClaimUpdateField> {\n if (intakeStatuses.has(status)) return new Set(CLAIM_INTAKE_UPDATE_FIELDS)\n if (fulfillmentStatuses.has(status)) return new Set(CLAIM_FULFILLMENT_UPDATE_FIELDS)\n return new Set()\n}\n\nfunction assertClaimUpdateFields(claim: WarrantyClaim, input: ClaimUpdateInput): void {\n const keys = [...CLAIM_INTAKE_UPDATE_FIELDS, ...CLAIM_FULFILLMENT_UPDATE_FIELDS]\n const requested = keys.filter((key) => hasOwn(input, key))\n if (!requested.length) return\n const allowed = allowedUpdateFields(claim.status)\n const disallowed = requested.filter((key) => !allowed.has(key))\n if (disallowed.length > 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.fieldLocked' })\n }\n}\n\nfunction applyClaimUpdate(claim: WarrantyClaim, input: ClaimUpdateInput, customerName: string | null, orderNumber: string | null): void {\n if (hasOwn(input, 'customerId')) claim.customerId = input.customerId ?? null\n if (hasOwn(input, 'customerName')) claim.customerName = customerName\n if (hasOwn(input, 'orderId')) {\n claim.orderId = input.orderId ?? null\n claim.orderNumber = orderNumber\n }\n if (hasOwn(input, 'reasonCode')) claim.reasonCode = input.reasonCode ?? null\n if (hasOwn(input, 'priority') && input.priority) claim.priority = input.priority\n if (hasOwn(input, 'notes')) claim.notes = input.notes ?? null\n if (hasOwn(input, 'advanceReplacement')) claim.advanceReplacement = input.advanceReplacement ?? false\n if (hasOwn(input, 'replacementOrderId')) claim.replacementOrderId = input.replacementOrderId ?? null\n if (hasOwn(input, 'advanceShippedAt')) claim.advanceShippedAt = input.advanceShippedAt ?? null\n if (hasOwn(input, 'salesReturnId')) claim.salesReturnId = input.salesReturnId ?? null\n if (hasOwn(input, 'creditMemoId')) claim.creditMemoId = input.creditMemoId ?? null\n if (hasOwn(input, 'vendorName')) claim.vendorName = input.vendorName ?? null\n if (hasOwn(input, 'vendorRef')) claim.vendorRef = input.vendorRef ?? null\n if (hasOwn(input, 'resolutionSummary')) claim.resolutionSummary = input.resolutionSummary ?? null\n claim.updatedAt = new Date()\n}\n\nasync function recomputeClaimRollups(em: EntityManager, claim: WarrantyClaim): Promise<void> {\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claim.id,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n deletedAt: null,\n },\n {},\n { tenantId: claim.tenantId, organizationId: claim.organizationId },\n )\n const totals = computeHeaderRollups(lines, { claimType: claim.claimType })\n claim.totalClaimedAmount = String(totals.totalClaimedAmount)\n claim.totalApprovedAmount = String(totals.totalApprovedAmount)\n}\n\nfunction assertCanResolve(lines: readonly WarrantyClaimLine[]): void {\n if (!canResolveWithLineStatuses(lines)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n}\n\nfunction assertVendorRecoveryLines(lines: readonly WarrantyClaimLine[], requestedLineIds: readonly string[]): void {\n if (lines.length !== requestedLineIds.length) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.vendorRecoveryNeedsResolvedLines' })\n }\n for (const line of lines) {\n if (line.lineStatus !== 'resolved' || line.vendorClaimLineId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.vendorRecoveryNeedsResolvedLines' })\n }\n }\n}\n\nfunction buildClaimLog(\n actionLabel: string,\n resourceId: string,\n snapshots: { before?: unknown; after?: unknown },\n): {\n actionLabel: string\n resourceKind: string\n resourceId: string\n tenantId: string | null\n organizationId: string | null\n snapshotBefore: unknown\n snapshotAfter: unknown\n payload: { undo: ClaimUndoPayload }\n} {\n const after = snapshots.after as ClaimSnapshot | null | undefined\n const before = snapshots.before as ClaimSnapshot | null | undefined\n return {\n actionLabel,\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId,\n tenantId: after?.tenantId ?? before?.tenantId ?? null,\n organizationId: after?.organizationId ?? before?.organizationId ?? null,\n snapshotBefore: before ?? null,\n snapshotAfter: after ?? null,\n payload: { undo: { before: before ?? null, after: after ?? null } },\n }\n}\n\nconst createClaimCommand: CommandHandler<ClaimCreateInput, { claimId: string }> = {\n id: 'warranty_claims.claim.create',\n isUndoable: true,\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n await validateClaimReferences(ctx, scope, {\n orderId: input.orderId ?? null,\n salesReturnId: input.salesReturnId ?? null,\n replacementOrderId: input.replacementOrderId ?? null,\n creditMemoId: null,\n lineOrderRefs: (input.lines ?? [])\n .filter((line): line is ClaimInitialLineCreateInput & { orderLineId: string } => typeof line.orderLineId === 'string')\n .map((line) => ({ orderLineId: line.orderLineId, orderId: input.orderId ?? null })),\n })\n await assertOrderBelongsToCustomer(em, scope, input.orderId ?? null, input.customerId ?? null)\n const pendingLines = (input.lines ?? []).map((line) => ({\n orderLineId: line.orderLineId ?? null,\n qtyClaimed: amountString(line.qtyClaimed, '1') ?? '1',\n }))\n const pendingLinesByOrderLine = new Map<string, ClaimedQuantityLine[]>()\n for (const line of pendingLines) {\n if (!line.orderLineId) continue\n const grouped = pendingLinesByOrderLine.get(line.orderLineId) ?? []\n grouped.push(line)\n pendingLinesByOrderLine.set(line.orderLineId, grouped)\n }\n const numberGenerator = resolveClaimNumberGenerator(ctx, em)\n const generated = await numberGenerator.generate({\n claimType: input.claimType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const customerName = await resolveCustomerName(ctx, input.customerId, scope, input.customerName, { strict: true })\n // A linked order derives its number from the order itself (falling back to any supplied\n // reference); without a linked order, persist the free-text reference as the display number\n // so the portal \"my order isn't listed\" path is captured (WQA-002).\n const orderNumber = input.orderId\n ? await resolveOrderNumber(ctx, input.orderId, scope, input.orderNumber ?? null)\n : (input.orderNumber ?? null)\n const claimId = randomUUID()\n let claim!: WarrantyClaim\n let createdLines: WarrantyClaimLine[] = []\n\n await withAtomicFlush(em, [\n async () => {\n await assertPendingClaimQuantitiesWithinSold(em, scope, pendingLinesByOrderLine, { currentClaimId: claimId })\n claim = em.create(WarrantyClaim, {\n id: claimId,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n claimNumber: generated.number,\n claimType: input.claimType,\n status: 'draft',\n channel: input.channel ?? 'staff',\n priority: input.priority ?? 'normal',\n customerId: input.customerId ?? null,\n customerName,\n externalRef: input.externalRef ?? null,\n intakeMessageRef: input.intakeMessageRef ?? null,\n contactEmail: input.contactEmail ?? null,\n vendorName: input.vendorName ?? null,\n vendorRef: input.vendorRef ?? null,\n orderId: input.orderId ?? null,\n orderNumber,\n salesReturnId: input.salesReturnId ?? null,\n replacementOrderId: input.replacementOrderId ?? null,\n creditMemoId: null,\n sourceClaimId: null,\n advanceReplacement: input.advanceReplacement ?? false,\n advanceShippedAt: input.advanceShippedAt ?? null,\n reasonCode: input.reasonCode ?? null,\n rejectionReasonCode: input.rejectionReasonCode ?? null,\n resolutionSummary: input.resolutionSummary ?? null,\n notes: input.notes ?? null,\n currencyCode: input.currencyCode ?? null,\n totalClaimedAmount: '0',\n totalApprovedAmount: '0',\n totalRecoveredAmount: '0',\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(claim)\n createdLines = (input.lines ?? []).map((lineInput, index) => {\n const line = em.create(WarrantyClaimLine, buildInitialLineData(claim, lineInput, index))\n em.persist(line)\n return line\n })\n const totals = computeHeaderRollups(createdLines, { claimType: claim.claimType })\n claim.totalClaimedAmount = String(totals.totalClaimedAmount)\n claim.totalApprovedAmount = String(totals.totalApprovedAmount)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n () => stampEntitlementSourceIfResolvable(ctx, em, claim, input, scope),\n ], { transaction: true, label: 'warranty_claims.claim.create' })\n\n await emitClaimCrud(ctx, 'created', claim)\n await Promise.all(createdLines.map((line) => emitLineCrud(ctx, 'created', line)))\n return { claimId: claim.id }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.create', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n let lines: WarrantyClaimLine[] = []\n await withAtomicFlush(em, [\n async () => {\n const current = await requireCurrentUndoSnapshot(em, after)\n claim = current.claim\n lines = current.lines.filter((line) => !line.deletedAt)\n const now = new Date()\n claim.deletedAt = now\n claim.updatedAt = now\n for (const line of lines) {\n line.deletedAt = now\n line.updatedAt = now\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.create.undo' })\n await emitClaimUndoCrud(ctx, 'deleted', claim)\n await Promise.all(lines.map((line) => emitLineUndoCrud(ctx, 'deleted', line)))\n },\n}\n\nconst updateClaimCommand: CommandHandler<ClaimUpdateInput, { claimId: string }> = {\n id: 'warranty_claims.claim.update',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimUpdateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimUpdateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n assertClaimUpdateFields(claim, input)\n await validateClaimReferences(ctx, scope, {\n orderId: hasOwn(input, 'orderId') && (input.orderId ?? null) !== (claim.orderId ?? null) ? input.orderId ?? null : null,\n salesReturnId: hasOwn(input, 'salesReturnId') && (input.salesReturnId ?? null) !== (claim.salesReturnId ?? null) ? input.salesReturnId ?? null : null,\n replacementOrderId: hasOwn(input, 'replacementOrderId') && (input.replacementOrderId ?? null) !== (claim.replacementOrderId ?? null) ? input.replacementOrderId ?? null : null,\n creditMemoId: hasOwn(input, 'creditMemoId') && (input.creditMemoId ?? null) !== (claim.creditMemoId ?? null) ? input.creditMemoId ?? null : null,\n })\n const effectiveOrderId = hasOwn(input, 'orderId') ? (input.orderId ?? null) : (claim.orderId ?? null)\n const effectiveCustomerId = hasOwn(input, 'customerId') ? (input.customerId ?? null) : (claim.customerId ?? null)\n await assertOrderBelongsToCustomer(em, scope, effectiveOrderId, effectiveCustomerId)\n const customerChanged = hasOwn(input, 'customerId') && (input.customerId ?? null) !== (claim.customerId ?? null)\n const shouldRefreshCustomerName = hasOwn(input, 'customerId') || hasOwn(input, 'customerName')\n const customerName = shouldRefreshCustomerName\n ? await resolveCustomerName(ctx, input.customerId ?? claim.customerId, scope, input.customerName ?? claim.customerName, { strict: customerChanged })\n : claim.customerName ?? null\n const orderNumber = hasOwn(input, 'orderId')\n ? await resolveOrderNumber(ctx, input.orderId, scope, (input.orderId ?? null) === (claim.orderId ?? null) ? claim.orderNumber : null)\n : claim.orderNumber ?? null\n await withAtomicFlush(em, [\n () => applyClaimUpdate(claim, input, customerName, orderNumber),\n ], { transaction: true, label: 'warranty_claims.claim.update' })\n await emitClaimCrud(ctx, 'updated', claim)\n return { claimId: claim.id }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimUpdateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.update', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n },\n ], { transaction: true, label: 'warranty_claims.claim.update.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst deleteClaimCommand: CommandHandler<ClaimDeleteInput, { claimId: string }> = {\n id: 'warranty_claims.claim.delete',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimDeleteSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimDeleteSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n if (!deletableStatuses.has(claim.status)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.deleteNotAllowed' })\n }\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n await withAtomicFlush(em, [\n () => {\n const now = new Date()\n claim.deletedAt = now\n claim.updatedAt = now\n for (const line of lines) {\n line.deletedAt = now\n line.updatedAt = now\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.delete' })\n await emitClaimCrud(ctx, 'deleted', claim)\n await Promise.all(lines.map((line) => emitLineCrud(ctx, 'deleted', line)))\n return { claimId: claim.id }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimDeleteSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.delete', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n },\n ], { transaction: true, label: 'warranty_claims.claim.delete.undo' })\n await emitClaimUndoCrud(ctx, 'created', claim)\n const restoredLines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n await Promise.all(restoredLines.map((line) => emitLineCrud(ctx, 'created', line)))\n },\n}\n\nconst submitClaimCommand: CommandHandler<SubmitClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.submit',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(submitClaimSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n if (claim.status !== 'draft') {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n const fromStatus = claim.status\n let autoApproved = false\n let effectiveSettings: WarrantyClaimEffectiveSettings | null = null\n await withAtomicFlush(em, [\n async () => {\n effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n const submittedAt = new Date()\n claim.status = 'submitted'\n claim.submittedAt = submittedAt\n claim.slaDueAt = addBusinessMillis(submittedAt, effectiveSettings.slaHours * 60 * 60 * 1000, effectiveSettings.businessHours)\n claim.slaAtRiskNotifiedAt = null\n claim.slaBreachedNotifiedAt = null\n claim.updatedAt = submittedAt\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: { from: fromStatus, to: 'submitted' },\n actorUserId: input.actorCustomerId ? null : (ctx.auth?.sub ?? null),\n actorCustomerId: input.actorCustomerId ?? null,\n })\n },\n async () => {\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claim.id,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n deletedAt: null,\n },\n {},\n scope,\n )\n const risk = await evaluateClaimRisk(em, claim, lines)\n const settings = effectiveSettings ?? await resolveEffectiveWarrantyClaimSettings(em, scope)\n const evaluator = ctx.container.resolve<WarrantyAdjudicationEvaluator>('warrantyAdjudicationEvaluator')\n const { decision } = await evaluator.evaluate({\n claim,\n lines,\n settings,\n risk,\n container: ctx.container,\n em,\n scope,\n })\n if (decision === 'auto_approve') {\n claim.status = 'approved'\n claim.updatedAt = new Date()\n autoApproved = true\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: { from: 'submitted', to: 'approved' },\n actorUserId: null,\n })\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: {\n action: 'auto_approved',\n maxAmount: settings.autoApproveMaxAmount,\n currencyCode: settings.autoApproveCurrencyCode,\n },\n actorUserId: null,\n })\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.submit' })\n await emitClaimCrud(ctx, 'updated', claim)\n const payload = claimEventPayload(claim)\n await emitWarrantyClaimsEvent('warranty_claims.claim.submitted', payload, claimPersistentEmitOptions(claim))\n await emitClaimStatusChanged(ctx, claim, autoApproved ? 'submitted' : fromStatus, autoApproved ? 'approved' : 'submitted')\n return { claimId: claim.id }\n },\n}\n\nconst transitionClaimCommand: CommandHandler<TransitionClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.transition',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(transitionClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(transitionClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n const fromStatus = claim.status\n assertTransition(fromStatus, input.toStatus)\n if (input.toStatus === 'cancelled' && !preReceivedStatuses.has(fromStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n if (input.toStatus === 'rejected' && !input.rejectionReasonCode) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n const lines = input.toStatus === 'resolved'\n ? await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claim.id,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n deletedAt: null,\n },\n {},\n { tenantId: claim.tenantId, organizationId: claim.organizationId },\n )\n : []\n if (input.toStatus === 'resolved') assertCanResolve(lines)\n await withAtomicFlush(em, [\n async () => {\n const effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n const now = new Date()\n claim.status = input.toStatus\n if (input.toStatus === 'rejected') claim.rejectionReasonCode = input.rejectionReasonCode ?? null\n if (input.toStatus === 'resolved') {\n claim.resolvedAt = now\n if (hasOwn(input, 'resolutionSummary')) claim.resolutionSummary = input.resolutionSummary ?? null\n }\n if (input.toStatus === 'closed') claim.closedAt = now\n applySlaResume(em, claim, fromStatus, input.toStatus, now, effectiveSettings)\n applySlaPause(em, claim, fromStatus, input.toStatus, now, effectiveSettings)\n claim.awaitingStaffReply = false\n claim.updatedAt = now\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: {\n from: fromStatus,\n to: input.toStatus,\n ...(input.systemNote ? { systemNote: input.systemNote } : {}),\n },\n actorUserId: input.actorCustomerId ? null : (ctx.auth?.sub ?? null),\n actorCustomerId: input.actorCustomerId ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.transition' })\n await emitClaimCrud(ctx, 'updated', claim)\n await emitClaimStatusChanged(ctx, claim, fromStatus, input.toStatus)\n return { claimId: claim.id }\n },\n captureAfter: async (_rawInput, result, ctx) => {\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.transition', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_status_transition' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.transition.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst assignClaimCommand: CommandHandler<AssignClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.assign',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(assignClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n await validateAssigneeUser(ctx, scope, input.assigneeUserId ?? null)\n await withAtomicFlush(em, [\n () => {\n applyClaimAssignment(em, claim, input.assigneeUserId ?? null, ctx.auth?.sub ?? null, new Date())\n },\n ], { transaction: true, label: 'warranty_claims.claim.assign' })\n await emitClaimCrud(ctx, 'updated', claim)\n await emitWarrantyClaimsEvent('warranty_claims.claim.assigned', {\n ...claimEventPayload(claim),\n assigneeUserId: claim.assigneeUserId,\n }, claimPersistentEmitOptions(claim))\n return { claimId: claim.id }\n },\n}\n\nconst setReturnLabelCommand: CommandHandler<ClaimSetReturnLabelInput, ClaimSetReturnLabelResult> = {\n id: 'warranty_claims.claim.set_return_label',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimSetReturnLabelSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimSetReturnLabelSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n\n await withAtomicFlush(em, [\n () => {\n if (input.labelUrl !== undefined) claim.returnLabelUrl = input.labelUrl\n if (input.trackingNumber !== undefined) claim.returnTrackingNumber = input.trackingNumber\n if (input.carrier !== undefined) claim.returnCarrier = input.carrier\n claim.updatedAt = new Date()\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: {\n action: 'return_label_created',\n carrier: claim.returnCarrier ?? null,\n trackingNumber: claim.returnTrackingNumber ?? null,\n },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.set_return_label' })\n\n await emitClaimCrud(ctx, 'updated', claim)\n await emitWarrantyClaimsEvent('warranty_claims.claim.return_label_created', {\n id: claim.id,\n claimId: claim.id,\n carrier: claim.returnCarrier ?? null,\n trackingNumber: claim.returnTrackingNumber ?? null,\n scope,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n }, claimPersistentEmitOptions(claim))\n\n return {\n claimId: claim.id,\n labelUrl: claim.returnLabelUrl ?? null,\n trackingNumber: claim.returnTrackingNumber ?? null,\n carrier: claim.returnCarrier ?? null,\n }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimSetReturnLabelSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.set_return_label', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_return_label' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.set_return_label.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst escalateClaimCommand: CommandHandler<EscalateClaimInput, EscalateClaimResult> = {\n id: 'warranty_claims.claim.escalate',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(escalateClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n if (input.reassignToUserId) {\n await validateAssigneeUser(ctx, scope, input.reassignToUserId)\n }\n\n let claim: WarrantyClaim | null = null\n let escalated = false\n await withAtomicFlush(em, [\n async () => {\n claim = await requireScopedClaim(em, input.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if ((claim.escalationLevel ?? 0) >= input.toLevel) return\n\n const now = new Date()\n claim.escalationLevel = input.toLevel\n claim.escalatedAt = now\n claim.updatedAt = now\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: {\n action: 'sla_escalated',\n level: input.toLevel,\n reassignToUserId: input.reassignToUserId ?? null,\n },\n actorUserId: ctx.auth?.sub ?? null,\n })\n if (input.reassignToUserId) {\n applyClaimAssignment(em, claim, input.reassignToUserId, ctx.auth?.sub ?? null, now)\n }\n escalated = true\n },\n ], { transaction: true, label: 'warranty_claims.claim.escalate' })\n\n const escalatedClaim = claim as WarrantyClaim | null\n if (!escalatedClaim) {\n throw new CrudHttpError(404, { error: 'warranty_claims.errors.notFound' })\n }\n if (!escalated) {\n return { claimId: escalatedClaim.id, escalationLevel: escalatedClaim.escalationLevel ?? 0, escalated: false }\n }\n\n await emitClaimCrud(ctx, 'updated', escalatedClaim)\n if (input.reassignToUserId) {\n await emitWarrantyClaimsEvent('warranty_claims.claim.assigned', {\n ...claimEventPayload(escalatedClaim),\n assigneeUserId: escalatedClaim.assigneeUserId ?? null,\n }, claimPersistentEmitOptions(escalatedClaim))\n }\n await emitWarrantyClaimsEvent('warranty_claims.claim.escalated', {\n ...claimEventPayload(escalatedClaim),\n level: escalatedClaim.escalationLevel,\n escalationLevel: escalatedClaim.escalationLevel,\n reassignToUserId: input.reassignToUserId ?? null,\n }, claimPersistentEmitOptions(escalatedClaim))\n\n return { claimId: escalatedClaim.id, escalationLevel: escalatedClaim.escalationLevel, escalated: true }\n },\n}\n\nconst commentClaimCommand: CommandHandler<CommentClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.comment',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(commentClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.claimId, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n let autoResumed = false\n await withAtomicFlush(em, [\n async () => {\n const fromStatus = claim.status\n appendClaimEvent(em, claim, 'comment', {\n visibility: input.visibility,\n body: input.body,\n actorUserId: input.actorCustomerId ? null : (ctx.auth?.sub ?? null),\n actorCustomerId: input.actorCustomerId ?? null,\n })\n claim.awaitingStaffReply = Boolean(input.actorCustomerId)\n claim.updatedAt = new Date()\n if (input.actorCustomerId && fromStatus === 'info_requested') {\n const now = new Date()\n const effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n claim.status = 'in_review'\n applySlaResume(em, claim, fromStatus, 'in_review', now, effectiveSettings)\n claim.updatedAt = now\n autoResumed = true\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: { from: fromStatus, to: 'in_review' },\n actorUserId: null,\n })\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.comment' })\n if (input.visibility === 'customer') {\n await emitCustomerVisibleCommentAdded(ctx, claim, input)\n }\n await emitClaimCrud(ctx, 'updated', claim)\n if (autoResumed) {\n await emitClaimStatusChanged(ctx, claim, 'info_requested', 'in_review')\n }\n return { claimId: claim.id }\n },\n}\n\nconst createVendorRecoveryCommand: CommandHandler<VendorRecoveryInput, { claimId: string }> = {\n id: 'warranty_claims.claim.create_vendor_recovery',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(vendorRecoveryInputSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const sourceClaim = await requireScopedClaim(em, input.claimId, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, sourceClaim)\n const preflightLines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n id: { $in: input.lineIds },\n claim: sourceClaim.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n {},\n scope,\n )\n assertVendorRecoveryLines(preflightLines, input.lineIds)\n const numberGenerator = resolveClaimNumberGenerator(ctx, em)\n const generated = await numberGenerator.generate({\n claimType: 'vendor_recovery',\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n let recoveryClaim!: WarrantyClaim\n let copiedLines: WarrantyClaimLine[] = []\n let updatedSourceLines: WarrantyClaimLine[] = []\n\n await em.transactional(async (tx) => {\n const lockedSource = await requireScopedClaim(tx, sourceClaim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n const lockedLines = await findWithDecryption(\n tx,\n WarrantyClaimLine,\n {\n id: { $in: input.lineIds },\n claim: lockedSource.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n )\n assertVendorRecoveryLines(lockedLines, input.lineIds)\n updatedSourceLines = lockedLines\n recoveryClaim = tx.create(WarrantyClaim, {\n id: randomUUID(),\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n claimNumber: generated.number,\n claimType: 'vendor_recovery',\n status: 'draft',\n channel: 'staff',\n priority: lockedSource.priority,\n customerId: lockedSource.customerId ?? null,\n customerName: lockedSource.customerName ?? null,\n vendorName: input.vendorName,\n vendorRef: input.vendorRef ?? null,\n sourceClaimId: lockedSource.id,\n advanceReplacement: false,\n currencyCode: lockedSource.currencyCode ?? null,\n totalClaimedAmount: '0',\n totalApprovedAmount: '0',\n totalRecoveredAmount: '0',\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tx.persist(recoveryClaim)\n const lineOrder = new Map(input.lineIds.map((id, index) => [id, index]))\n copiedLines = [...lockedLines]\n .sort((left, right) => (lineOrder.get(left.id) ?? 0) - (lineOrder.get(right.id) ?? 0))\n .map((sourceLine, index) => {\n const copiedLine = tx.create(WarrantyClaimLine, {\n id: randomUUID(),\n claim: recoveryClaim,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n lineNo: index + 1,\n productId: sourceLine.productId ?? null,\n variantId: sourceLine.variantId ?? null,\n sku: sourceLine.sku ?? null,\n productName: sourceLine.productName ?? null,\n orderLineId: sourceLine.orderLineId ?? null,\n serialNumber: sourceLine.serialNumber ?? null,\n lotNumber: sourceLine.lotNumber ?? null,\n purchaseDate: sourceLine.purchaseDate ?? null,\n warrantyMonths: sourceLine.warrantyMonths ?? null,\n warrantyExpiresAt: sourceLine.warrantyExpiresAt ?? null,\n warrantyStatus: sourceLine.warrantyStatus,\n faultCode: sourceLine.faultCode ?? null,\n faultDescription: sourceLine.faultDescription ?? null,\n qtyClaimed: sourceLine.qtyApproved ?? sourceLine.qtyClaimed,\n qtyApproved: sourceLine.qtyApproved ?? null,\n conditionOnReceipt: sourceLine.conditionOnReceipt ?? null,\n inspectionNotes: sourceLine.inspectionNotes ?? null,\n disposition: sourceLine.disposition ?? null,\n lineStatus: 'pending',\n creditAmount: sourceLine.creditAmount ?? null,\n restockingFee: sourceLine.restockingFee ?? null,\n coreChargeAmount: sourceLine.coreChargeAmount ?? null,\n coreCreditAmount: sourceLine.coreCreditAmount ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n sourceLine.vendorClaimLineId = copiedLine.id\n sourceLine.updatedAt = new Date()\n tx.persist(copiedLine)\n return copiedLine\n })\n const totals = computeHeaderRollups(copiedLines)\n recoveryClaim.totalClaimedAmount = String(totals.totalClaimedAmount)\n recoveryClaim.totalApprovedAmount = String(totals.totalApprovedAmount)\n appendClaimEvent(tx, lockedSource, 'system', {\n visibility: 'internal',\n payload: { action: 'vendor_recovery_created', recoveryClaimId: recoveryClaim.id },\n actorUserId: ctx.auth?.sub ?? null,\n })\n appendClaimEvent(tx, recoveryClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'created_from_source_claim', sourceClaimId: lockedSource.id },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await tx.flush()\n })\n\n await emitClaimCrud(ctx, 'created', recoveryClaim)\n await Promise.all(copiedLines.map((line) => emitLineCrud(ctx, 'created', line)))\n await Promise.all(updatedSourceLines.map((line) => emitLineCrud(ctx, 'updated', line)))\n await Promise.all(input.lineIds.map((sourceLineId) => invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim_line',\n { id: sourceLineId, organizationId: sourceClaim.organizationId, tenantId: sourceClaim.tenantId },\n ctx.auth?.tenantId ?? null,\n 'warranty_claims.vendor_recovery.source_lines',\n )))\n return { claimId: recoveryClaim.id }\n },\n}\n\nconst salesReturnBridgeLogger = createLogger('warranty_claims')\n\nconst SALES_RETURN_ELIGIBLE_CLAIM_STATUSES = new Set<WarrantyClaimStatus>(['approved', 'awaiting_return', 'received', 'inspecting'])\nconst SALES_RETURN_ELIGIBLE_LINE_STATUSES = new Set<WarrantyClaimLineStatus>(['approved', 'received', 'inspected', 'resolved'])\n\ntype ClaimSalesReturnUndoPayload = ClaimUndoPayload & {\n salesReturn?: { id: string; orderId: string; updatedAt: string | null } | null\n}\n\ntype ClaimCreateSalesReturnResult = {\n claimId: string\n salesReturnId: string\n salesReturnUpdatedAt: string | null\n skippedLineIds: string[]\n}\n\nfunction scrubbedDispatchContext(ctx: CommandRuntimeContext): CommandRuntimeContext {\n return { ...ctx, request: undefined }\n}\n\nfunction isSalesQuantityRejection(err: unknown): boolean {\n if (!(err instanceof CrudHttpError) || err.status !== 400) return false\n const body = err.body as { error?: unknown } | null\n const message = typeof body?.error === 'string' ? body.error : ''\n return message.includes('quantityExceedsShipped') || message.includes('Cannot return more than the shipped quantity')\n}\n\nasync function dispatchSalesReturnDelete(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n salesReturnId: string,\n orderId: string,\n): Promise<void> {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute(\n 'sales.returns.delete',\n {\n input: { id: salesReturnId, orderId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n}\n\nconst createSalesReturnCommand: CommandHandler<ClaimCreateSalesReturnInput, ClaimCreateSalesReturnResult> = {\n id: 'warranty_claims.claim.create_sales_return',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimCreateSalesReturnSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateSalesReturnSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n if (!claim.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnRequiresOrder' })\n }\n if (!SALES_RETURN_ELIGIBLE_CLAIM_STATUSES.has(claim.status as WarrantyClaimStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnStatusNotEligible' })\n }\n if (claim.salesReturnId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnAlreadyLinked' })\n }\n if (!resolveOptionalEntityId('sales', 'sales_return')) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesUnavailable' })\n }\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n const eligibleLines: Array<{ orderLineId: string; quantity: string }> = []\n const skippedLineIds: string[] = []\n for (const line of lines) {\n const effectiveQty = line.qtyApproved ?? line.qtyClaimed\n const quantityUnits = claimedQuantityUnits(effectiveQty) ?? 0n\n const eligible = Boolean(line.orderLineId)\n && SALES_RETURN_ELIGIBLE_LINE_STATUSES.has(line.lineStatus as WarrantyClaimLineStatus)\n && quantityUnits > 0n\n && quantityUnits % CLAIMED_QUANTITY_SCALE === 0n\n if (eligible && line.orderLineId) {\n eligibleLines.push({ orderLineId: line.orderLineId, quantity: String(effectiveQty) })\n } else {\n skippedLineIds.push(line.id)\n }\n }\n if (eligibleLines.length === 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnNoEligibleLines' })\n }\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n let salesReturnId: string\n try {\n const { result: dispatchedResult } = await commandBus.execute<\n { orderId: string; reason?: string; tenantId: string; organizationId: string; lines: Array<{ orderLineId: string; quantity: string }> },\n { returnId: string }\n >(\n 'sales.returns.create',\n {\n input: {\n orderId: claim.orderId,\n reason: claim.claimNumber,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n lines: eligibleLines,\n },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n if (!dispatchedResult?.returnId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n }\n salesReturnId = dispatchedResult.returnId\n } catch (err) {\n if (isSalesQuantityRejection(err)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnQuantityRejected' })\n }\n throw err\n }\n let salesReturnUpdatedAt: string | null = null\n try {\n const createdReturnRow = await querySalesReferenceRow(ctx, 'sales_returns', scope, salesReturnId, ['id', 'updated_at'])\n salesReturnUpdatedAt = createdReturnRow?.updated_at\n ? new Date(createdReturnRow.updated_at as string | Date).toISOString()\n : null\n await em.transactional(async (tx) => {\n const lockedClaim = await requireScopedClaim(tx, claim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if (lockedClaim.salesReturnId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnAlreadyLinked' })\n }\n lockedClaim.salesReturnId = salesReturnId\n lockedClaim.updatedAt = new Date()\n appendClaimEvent(tx, lockedClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'sales_return_created', salesReturnId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n claim.salesReturnId = salesReturnId\n claim.updatedAt = lockedClaim.updatedAt\n await tx.flush()\n })\n } catch (err) {\n try {\n await dispatchSalesReturnDelete(ctx, scope, salesReturnId, claim.orderId)\n } catch (compensationErr) {\n salesReturnBridgeLogger.error('warranty_claims.claim.create_sales_return compensation failed \u2014 orphaned sales return', {\n err: compensationErr,\n claimId: claim.id,\n salesReturnId,\n })\n const orphanEm = (ctx.container.resolve('em') as EntityManager).fork()\n const orphanClaim = await findOneWithDecryption(\n orphanEm,\n WarrantyClaim,\n { id: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n if (orphanClaim) {\n try {\n appendClaimEvent(orphanEm, orphanClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'sales_return_orphaned', salesReturnId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await orphanEm.flush()\n } catch (orphanEventErr) {\n salesReturnBridgeLogger.error('warranty_claims.claim.create_sales_return orphan timeline write failed', {\n err: orphanEventErr,\n claimId: claim.id,\n salesReturnId,\n })\n }\n }\n throw new CrudHttpError(500, { error: 'warranty_claims.errors.save_failed' })\n }\n throw err\n }\n await emitClaimCrud(ctx, 'updated', claim)\n return { claimId: claim.id, salesReturnId, salesReturnUpdatedAt, skippedLineIds }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateSalesReturnSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => {\n const base = buildClaimLog('warranty_claims.audit.claim.create_sales_return', result.claimId, snapshots)\n const after = snapshots.after as { orderId?: string | null } | null | undefined\n const undoPayload: ClaimSalesReturnUndoPayload = {\n ...(base.payload.undo as ClaimUndoPayload),\n salesReturn: {\n id: result.salesReturnId,\n orderId: after?.orderId ?? '',\n updatedAt: result.salesReturnUpdatedAt,\n },\n }\n return { ...base, payload: { undo: undoPayload } }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimSalesReturnUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) throwClaimUndoConflict()\n await assertUndoSnapshotCurrent(ctx, after)\n const scope: WarrantyClaimScope = { tenantId: before.tenantId, organizationId: before.organizationId }\n const salesReturn = payload?.salesReturn ?? null\n if (salesReturn?.id && salesReturn.orderId) {\n const currentRow = await querySalesReferenceRow(ctx, 'sales_returns', scope, salesReturn.id, ['id', 'updated_at'])\n if (currentRow) {\n const currentUpdatedAt = currentRow.updated_at\n ? new Date(currentRow.updated_at as string | Date).toISOString()\n : null\n if (!salesReturn.updatedAt || (currentUpdatedAt && currentUpdatedAt !== salesReturn.updatedAt)) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.salesReturnChangedUndoAborted' })\n }\n await dispatchSalesReturnDelete(ctx, scope, salesReturn.id, salesReturn.orderId)\n }\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_sales_return_created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.create_sales_return.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst creditMemoBridgeLogger = createLogger('warranty_claims')\n\nconst CREDIT_MEMO_ELIGIBLE_CLAIM_STATUSES = new Set<WarrantyClaimStatus>(['received', 'inspecting', 'resolved'])\nconst CREDIT_MEMO_ELIGIBLE_LINE_STATUSES = new Set<WarrantyClaimLineStatus>(['received', 'inspected', 'resolved'])\nconst CREDIT_MEMO_ELIGIBLE_DISPOSITIONS = new Set<WarrantyClaimDisposition>(['credit', 'refund'])\n\ntype CreditMemoLineInput = {\n orderLineId: string\n quantity: string\n currencyCode: string\n unitPriceNet: string\n unitPriceGross: string\n taxRate: string\n taxAmount: string\n totalNetAmount: string\n totalGrossAmount: string\n metadata: { warrantyClaimLineId: string }\n name?: string\n}\n\ntype CreditMemoCreateInput = {\n organizationId: string\n tenantId: string\n orderId: string\n currencyCode: string\n reason: string\n metadata: { warrantyClaimId: string; warrantyClaimNumber: string }\n lines: CreditMemoLineInput[]\n subtotalNetAmount: string\n subtotalGrossAmount: string\n taxTotalAmount: string\n grandTotalNetAmount: string\n grandTotalGrossAmount: string\n}\n\ntype PreparedCreditMemoLine = {\n input: CreditMemoLineInput\n netUnits: bigint\n grossUnits: bigint\n taxUnits: bigint\n}\n\ntype ClaimCreditMemoUndoPayload = ClaimUndoPayload & {\n creditMemo?: { id: string; updatedAt: string | null } | null\n}\n\ntype ClaimCreateCreditMemoResult = {\n claimId: string\n creditMemoId: string\n creditMemoUpdatedAt: string | null\n skippedLineIds: string[]\n grandTotalGrossAmount: string\n currencyCode: string\n}\n\nfunction minimumUnits(left: bigint, right: bigint): bigint {\n return left < right ? left : right\n}\n\nfunction prepareCreditMemoLine(\n claimLine: WarrantyClaimLine,\n sourceLine: Record<string, unknown>,\n creditedQuantityUnits: bigint,\n currencyCode: string,\n): PreparedCreditMemoLine | null {\n const orderQuantityUnits = claimedQuantityUnits(sourceLine.quantity as string | number | null | undefined)\n const sourceGrossUnits = claimedQuantityUnits(sourceLine.total_gross_amount as string | number | null | undefined)\n const sourceNetUnits = claimedQuantityUnits(sourceLine.total_net_amount as string | number | null | undefined)\n const taxRateUnits = claimedQuantityUnits(sourceLine.tax_rate as string | number | null | undefined)\n if (\n orderQuantityUnits === null\n || orderQuantityUnits <= 0n\n || creditedQuantityUnits > orderQuantityUnits\n || sourceGrossUnits === null\n || sourceNetUnits === null\n || taxRateUnits === null\n ) {\n return null\n }\n\n let netBasisUnits = sourceNetUnits\n if (sourceGrossUnits > 0n && netBasisUnits <= 0n) {\n netBasisUnits = netUnitsFromGross(sourceGrossUnits, taxRateUnits)\n }\n const proratedGrossUnits = roundHalfUpDivision(sourceGrossUnits * creditedQuantityUnits, orderQuantityUnits)\n const proratedNetUnits = roundHalfUpDivision(netBasisUnits * creditedQuantityUnits, orderQuantityUnits)\n const creditAmountUnits = claimedQuantityUnits(claimLine.creditAmount)\n const restockingFeeUnits = claimedQuantityUnits(claimLine.restockingFee) ?? 0n\n const coreCreditUnits = claimedQuantityUnits(claimLine.coreCreditAmount) ?? 0n\n const baseGrossUnits = creditAmountUnits ?? proratedGrossUnits\n const adjustedGrossUnits = baseGrossUnits - restockingFeeUnits + coreCreditUnits\n const grossUnits = adjustedGrossUnits > 0n ? adjustedGrossUnits : 0n\n let netUnits = grossUnits === proratedGrossUnits\n ? proratedNetUnits\n : netUnitsFromGross(grossUnits, taxRateUnits)\n if (grossUnits > 0n && netUnits <= 0n) {\n netUnits = netUnitsFromGross(grossUnits, taxRateUnits)\n }\n const taxUnits = grossUnits - netUnits\n const input: CreditMemoLineInput = {\n orderLineId: claimLine.orderLineId as string,\n quantity: formatScaledUnits(creditedQuantityUnits),\n currencyCode,\n unitPriceNet: formatScaledUnits(roundHalfUpDivision(netUnits * CLAIMED_QUANTITY_SCALE, creditedQuantityUnits)),\n unitPriceGross: formatScaledUnits(roundHalfUpDivision(grossUnits * CLAIMED_QUANTITY_SCALE, creditedQuantityUnits)),\n taxRate: formatScaledUnits(taxRateUnits),\n taxAmount: formatScaledUnits(taxUnits),\n totalNetAmount: formatScaledUnits(netUnits),\n totalGrossAmount: formatScaledUnits(grossUnits),\n metadata: { warrantyClaimLineId: claimLine.id },\n }\n const name = readString(sourceLine, 'name')\n if (name) input.name = name\n return { input, netUnits, grossUnits, taxUnits }\n}\n\nasync function dispatchCreditMemoDelete(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n creditMemoId: string,\n): Promise<void> {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute(\n 'sales.credit_memos.delete',\n {\n input: { id: creditMemoId, organizationId: scope.organizationId, tenantId: scope.tenantId },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n}\n\nconst createCreditMemoCommand: CommandHandler<ClaimCreateCreditMemoInput, ClaimCreateCreditMemoResult> = {\n id: 'warranty_claims.claim.create_credit_memo',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimCreateCreditMemoSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateCreditMemoSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n if (!claim.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoRequiresOrder' })\n }\n if (!CREDIT_MEMO_ELIGIBLE_CLAIM_STATUSES.has(claim.status as WarrantyClaimStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoInvalidStatus' })\n }\n if (claim.creditMemoId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoAlreadyLinked' })\n }\n if (!resolveOptionalEntityId('sales', 'sales_credit_memo')) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoSalesUnavailable' })\n }\n\n const sourceOrder = await querySalesReferenceRow(\n ctx,\n 'sales_orders',\n scope,\n claim.orderId,\n ['id', 'currency_code'],\n )\n const orderCurrencyCode = sourceOrder ? readString(sourceOrder, 'currency_code') : null\n if (!sourceOrder || !orderCurrencyCode) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoRequiresOrder' })\n }\n\n const claimLines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n const sourceLineRows = await querySalesOrderLineReferences(\n ctx,\n scope,\n Array.from(new Set(claimLines.flatMap((line) => line.orderLineId ? [line.orderLineId] : []))),\n ['id', 'order_id', 'name', 'currency_code', 'quantity', 'total_net_amount', 'total_gross_amount', 'tax_rate'],\n )\n const sourceLinesById = new Map((sourceLineRows ?? []).map((row) => [readString(row, 'id'), row]))\n const preparedLines: PreparedCreditMemoLine[] = []\n const skippedLineIds: string[] = []\n for (const claimLine of claimLines) {\n const approvedQuantityUnits = claimedQuantityUnits(claimLine.qtyApproved ?? claimLine.qtyClaimed) ?? 0n\n const receivedQuantityUnits = claimedQuantityUnits(claimLine.qtyReceived) ?? 0n\n const creditedQuantityUnits = minimumUnits(approvedQuantityUnits, receivedQuantityUnits)\n const initiallyEligible = Boolean(claimLine.orderLineId)\n && CREDIT_MEMO_ELIGIBLE_DISPOSITIONS.has(claimLine.disposition as WarrantyClaimDisposition)\n && CREDIT_MEMO_ELIGIBLE_LINE_STATUSES.has(claimLine.lineStatus as WarrantyClaimLineStatus)\n && creditedQuantityUnits > 0n\n if (!initiallyEligible || !claimLine.orderLineId) {\n skippedLineIds.push(claimLine.id)\n continue\n }\n\n const sourceLine = sourceLinesById.get(claimLine.orderLineId) ?? null\n const sourceCurrencyCode = sourceLine ? readString(sourceLine, 'currency_code') : null\n if (\n !sourceLine\n || sourceLine.order_id !== claim.orderId\n || sourceCurrencyCode !== orderCurrencyCode\n ) {\n skippedLineIds.push(claimLine.id)\n continue\n }\n const preparedLine = prepareCreditMemoLine(\n claimLine,\n sourceLine,\n creditedQuantityUnits,\n orderCurrencyCode,\n )\n if (!preparedLine) {\n skippedLineIds.push(claimLine.id)\n continue\n }\n preparedLines.push(preparedLine)\n }\n if (preparedLines.length === 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoNoEligibleLines' })\n }\n\n const totals = preparedLines.reduce(\n (result, line) => ({\n netUnits: result.netUnits + line.netUnits,\n grossUnits: result.grossUnits + line.grossUnits,\n taxUnits: result.taxUnits + line.taxUnits,\n }),\n { netUnits: 0n, grossUnits: 0n, taxUnits: 0n },\n )\n const grandTotalNetAmount = formatScaledUnits(totals.netUnits)\n const grandTotalGrossAmount = formatScaledUnits(totals.grossUnits)\n const creditMemoInput: CreditMemoCreateInput = {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n orderId: claim.orderId,\n currencyCode: orderCurrencyCode,\n reason: claim.claimNumber,\n metadata: { warrantyClaimId: claim.id, warrantyClaimNumber: claim.claimNumber },\n lines: preparedLines.map((line) => line.input),\n subtotalNetAmount: grandTotalNetAmount,\n subtotalGrossAmount: grandTotalGrossAmount,\n taxTotalAmount: formatScaledUnits(totals.taxUnits),\n grandTotalNetAmount,\n grandTotalGrossAmount,\n }\n\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n let creditMemoId: string | null = null\n let creditMemoUpdatedAt: string | null = null\n try {\n const { result: dispatchedResult } = await commandBus.execute<CreditMemoCreateInput, { creditMemoId: string }>(\n 'sales.credit_memos.create',\n { input: creditMemoInput, ctx: scrubbedDispatchContext(ctx) },\n )\n if (!dispatchedResult?.creditMemoId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n }\n creditMemoId = dispatchedResult.creditMemoId\n const createdCreditMemoRow = await querySalesReferenceRow(\n ctx,\n 'sales_credit_memos',\n scope,\n creditMemoId,\n ['id', 'updated_at'],\n )\n creditMemoUpdatedAt = createdCreditMemoRow?.updated_at\n ? new Date(createdCreditMemoRow.updated_at as string | Date).toISOString()\n : null\n await em.transactional(async (tx) => {\n const lockedClaim = await requireScopedClaim(tx, claim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if (lockedClaim.creditMemoId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoAlreadyLinked' })\n }\n lockedClaim.creditMemoId = creditMemoId\n lockedClaim.updatedAt = new Date()\n appendClaimEvent(tx, lockedClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'credit_memo_created', creditMemoId, grandTotalGrossAmount, currencyCode: orderCurrencyCode },\n actorUserId: ctx.auth?.sub ?? null,\n })\n claim.creditMemoId = creditMemoId\n claim.updatedAt = lockedClaim.updatedAt\n await tx.flush()\n })\n } catch (err) {\n if (!creditMemoId) throw err\n try {\n await dispatchCreditMemoDelete(ctx, scope, creditMemoId)\n } catch (compensationErr) {\n creditMemoBridgeLogger.error('warranty_claims.claim.create_credit_memo compensation failed \u2014 orphaned credit memo', {\n err: compensationErr,\n claimId: claim.id,\n creditMemoId,\n })\n try {\n const orphanEm = (ctx.container.resolve('em') as EntityManager).fork()\n const orphanClaim = await findOneWithDecryption(\n orphanEm,\n WarrantyClaim,\n { id: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n if (orphanClaim) {\n appendClaimEvent(orphanEm, orphanClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'credit_memo_orphaned', creditMemoId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await orphanEm.flush()\n }\n } catch (orphanEventErr) {\n creditMemoBridgeLogger.error('warranty_claims.claim.create_credit_memo orphan timeline write failed', {\n err: orphanEventErr,\n claimId: claim.id,\n creditMemoId,\n })\n }\n throw new CrudHttpError(500, { error: 'warranty_claims.errors.save_failed' })\n }\n throw err\n }\n\n await emitClaimCrud(ctx, 'updated', claim)\n return {\n claimId: claim.id,\n creditMemoId,\n creditMemoUpdatedAt,\n skippedLineIds,\n grandTotalGrossAmount,\n currencyCode: orderCurrencyCode,\n }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateCreditMemoSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => {\n const base = buildClaimLog('warranty_claims.audit.claim.create_credit_memo', result.claimId, snapshots)\n const undoPayload: ClaimCreditMemoUndoPayload = {\n ...(base.payload.undo as ClaimUndoPayload),\n creditMemo: { id: result.creditMemoId, updatedAt: result.creditMemoUpdatedAt },\n }\n return { ...base, payload: { undo: undoPayload } }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimCreditMemoUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) throwClaimUndoConflict()\n await assertUndoSnapshotCurrent(ctx, after)\n const scope: WarrantyClaimScope = { tenantId: before.tenantId, organizationId: before.organizationId }\n const creditMemo = payload?.creditMemo ?? null\n if (creditMemo?.id) {\n const currentRow = await querySalesReferenceRow(ctx, 'sales_credit_memos', scope, creditMemo.id, ['id', 'updated_at'])\n if (currentRow === undefined) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.creditMemoChangedUndoAborted' })\n }\n if (currentRow) {\n const currentUpdatedAt = currentRow.updated_at\n ? new Date(currentRow.updated_at as string | Date).toISOString()\n : null\n if (!creditMemo.updatedAt || !currentUpdatedAt || currentUpdatedAt !== creditMemo.updatedAt) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.creditMemoChangedUndoAborted' })\n }\n await dispatchCreditMemoDelete(ctx, scope, creditMemo.id)\n } else {\n creditMemoBridgeLogger.info('warranty_claims.claim.create_credit_memo undo found credit memo already absent', {\n claimId: before.id,\n creditMemoId: creditMemo.id,\n })\n }\n }\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_credit_memo_created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.create_credit_memo.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst replacementOrderBridgeLogger = createLogger('warranty_claims')\n\nconst REPLACEMENT_ELIGIBLE_CLAIM_STATUSES = new Set<WarrantyClaimStatus>([\n 'approved',\n 'awaiting_return',\n 'received',\n 'inspecting',\n 'resolved',\n])\nconst REPLACEMENT_ELIGIBLE_LINE_STATUSES = new Set<WarrantyClaimLineStatus>(['approved', 'received', 'inspected', 'resolved'])\nconst ADVANCE_REPLACEMENT_CLAIM_STATUSES = new Set<WarrantyClaimStatus>(['approved', 'awaiting_return'])\nconst SALES_ORDER_LINE_KINDS = new Set(['product', 'service', 'shipping', 'discount', 'adjustment'] as const)\n\ntype SalesOrderLineKind = 'product' | 'service' | 'shipping' | 'discount' | 'adjustment'\n\ntype ReplacementOrderLineInput = {\n kind: SalesOrderLineKind\n currencyCode: string\n quantity: string\n unitPriceNet: string\n unitPriceGross: string\n productId?: string\n productVariantId?: string\n name?: string\n taxRate?: string\n}\n\ntype ReplacementOrderCreateInput = {\n organizationId: string\n tenantId: string\n currencyCode: string\n metadata: { warrantyClaimId: string; warrantyClaimNumber: string }\n lines: ReplacementOrderLineInput[]\n customerEntityId?: string\n customerContactId?: string\n billingAddressId?: string\n shippingAddressId?: string\n channelId?: string\n}\n\ntype ClaimReplacementOrderUndoPayload = ClaimUndoPayload & {\n replacementOrder?: { id: string; updatedAt: string | null } | null\n}\n\ntype ClaimCreateReplacementOrderResult = {\n claimId: string\n replacementOrderId: string\n replacementOrderUpdatedAt: string | null\n skippedLineIds: string[]\n pricing: 'zero' | 'original'\n}\n\nfunction readSalesOrderLineKind(value: unknown): SalesOrderLineKind | null {\n return typeof value === 'string' && SALES_ORDER_LINE_KINDS.has(value as SalesOrderLineKind)\n ? value as SalesOrderLineKind\n : null\n}\n\nasync function dispatchSalesOrderDelete(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n replacementOrderId: string,\n): Promise<void> {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute(\n 'sales.orders.delete',\n {\n input: { id: replacementOrderId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n}\n\nconst createReplacementOrderCommand: CommandHandler<ClaimCreateReplacementOrderInput, ClaimCreateReplacementOrderResult> = {\n id: 'warranty_claims.claim.create_replacement_order',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimCreateReplacementOrderSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateReplacementOrderSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n if (!claim.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementOrderRequiresOrder' })\n }\n if (!REPLACEMENT_ELIGIBLE_CLAIM_STATUSES.has(claim.status as WarrantyClaimStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementInvalidStatus' })\n }\n if (claim.replacementOrderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementAlreadyLinked' })\n }\n if (!resolveOptionalEntityId('sales', 'sales_order')) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementSalesUnavailable' })\n }\n\n const sourceOrder = await querySalesReferenceRow(\n ctx,\n 'sales_orders',\n scope,\n claim.orderId,\n [\n 'id',\n 'currency_code',\n 'customer_entity_id',\n 'customer_contact_id',\n 'billing_address_id',\n 'shipping_address_id',\n 'channel_id',\n ],\n )\n const orderCurrencyCode = sourceOrder ? readString(sourceOrder, 'currency_code') : null\n if (!sourceOrder || !orderCurrencyCode) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementOrderRequiresOrder' })\n }\n\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n const sourceLineRows = await querySalesOrderLineReferences(\n ctx,\n scope,\n Array.from(new Set(lines.flatMap((line) => line.orderLineId ? [line.orderLineId] : []))),\n [\n 'id',\n 'order_id',\n 'product_id',\n 'product_variant_id',\n 'name',\n 'kind',\n 'currency_code',\n 'unit_price_net',\n 'unit_price_gross',\n 'tax_rate',\n ],\n )\n const sourceLinesById = new Map((sourceLineRows ?? []).map((row) => [readString(row, 'id'), row]))\n const replacementLines: ReplacementOrderLineInput[] = []\n const skippedLineIds: string[] = []\n for (const line of lines) {\n const effectiveQty = line.qtyApproved ?? line.qtyClaimed\n const quantityUnits = claimedQuantityUnits(effectiveQty) ?? 0n\n const initiallyEligible = line.disposition === 'replace'\n && Boolean(line.orderLineId)\n && REPLACEMENT_ELIGIBLE_LINE_STATUSES.has(line.lineStatus as WarrantyClaimLineStatus)\n && quantityUnits > 0n\n && quantityUnits % CLAIMED_QUANTITY_SCALE === 0n\n if (!initiallyEligible || !line.orderLineId) {\n skippedLineIds.push(line.id)\n continue\n }\n\n const sourceLine = sourceLinesById.get(line.orderLineId) ?? null\n const productId = sourceLine ? readString(sourceLine, 'product_id') : null\n const productVariantId = sourceLine ? readString(sourceLine, 'product_variant_id') : null\n const name = sourceLine ? readString(sourceLine, 'name') : null\n const kind = sourceLine ? readSalesOrderLineKind(sourceLine.kind) : null\n const currencyCode = sourceLine ? readString(sourceLine, 'currency_code') : null\n const unitPriceNet = sourceLine ? readString(sourceLine, 'unit_price_net') : null\n const unitPriceGross = sourceLine ? readString(sourceLine, 'unit_price_gross') : null\n const taxRate = sourceLine ? readString(sourceLine, 'tax_rate') : null\n const originalPricingIncomplete = input.pricing === 'original'\n && (unitPriceNet === null || unitPriceGross === null || taxRate === null)\n if (\n !sourceLine\n || sourceLine.order_id !== claim.orderId\n || (!productId && !productVariantId && !name)\n || !kind\n || !currencyCode\n || originalPricingIncomplete\n ) {\n skippedLineIds.push(line.id)\n continue\n }\n\n const replacementLine: ReplacementOrderLineInput = {\n kind,\n currencyCode,\n quantity: String(effectiveQty),\n unitPriceNet: input.pricing === 'zero' ? '0' : unitPriceNet as string,\n unitPriceGross: input.pricing === 'zero' ? '0' : unitPriceGross as string,\n }\n if (productId) replacementLine.productId = productId\n if (productVariantId) replacementLine.productVariantId = productVariantId\n if (name) replacementLine.name = name\n if (input.pricing === 'original') replacementLine.taxRate = taxRate as string\n replacementLines.push(replacementLine)\n }\n if (replacementLines.length === 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementNoEligibleLines' })\n }\n\n const orderInput: ReplacementOrderCreateInput = {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n currencyCode: orderCurrencyCode,\n metadata: { warrantyClaimId: claim.id, warrantyClaimNumber: claim.claimNumber },\n lines: replacementLines,\n }\n const customerEntityId = readString(sourceOrder, 'customer_entity_id')\n const customerContactId = readString(sourceOrder, 'customer_contact_id')\n const billingAddressId = readString(sourceOrder, 'billing_address_id')\n const shippingAddressId = readString(sourceOrder, 'shipping_address_id')\n const channelId = readString(sourceOrder, 'channel_id')\n if (customerEntityId) orderInput.customerEntityId = customerEntityId\n if (customerContactId) orderInput.customerContactId = customerContactId\n if (billingAddressId) orderInput.billingAddressId = billingAddressId\n if (shippingAddressId) orderInput.shippingAddressId = shippingAddressId\n if (channelId) orderInput.channelId = channelId\n\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const { result: dispatchedResult } = await commandBus.execute<ReplacementOrderCreateInput, { orderId: string }>(\n 'sales.orders.create',\n { input: orderInput, ctx: scrubbedDispatchContext(ctx) },\n )\n if (!dispatchedResult?.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n }\n const replacementOrderId = dispatchedResult.orderId\n let replacementOrderUpdatedAt: string | null = null\n try {\n const createdOrderRow = await querySalesReferenceRow(ctx, 'sales_orders', scope, replacementOrderId, ['id', 'updated_at'])\n replacementOrderUpdatedAt = createdOrderRow?.updated_at\n ? new Date(createdOrderRow.updated_at as string | Date).toISOString()\n : null\n await em.transactional(async (tx) => {\n const lockedClaim = await requireScopedClaim(tx, claim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if (lockedClaim.replacementOrderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementAlreadyLinked' })\n }\n lockedClaim.replacementOrderId = replacementOrderId\n if (ADVANCE_REPLACEMENT_CLAIM_STATUSES.has(lockedClaim.status as WarrantyClaimStatus)) {\n lockedClaim.advanceReplacement = true\n }\n lockedClaim.updatedAt = new Date()\n appendClaimEvent(tx, lockedClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'replacement_order_created', replacementOrderId, pricing: input.pricing },\n actorUserId: ctx.auth?.sub ?? null,\n })\n claim.replacementOrderId = replacementOrderId\n claim.advanceReplacement = lockedClaim.advanceReplacement\n claim.updatedAt = lockedClaim.updatedAt\n await tx.flush()\n })\n } catch (err) {\n try {\n await dispatchSalesOrderDelete(ctx, scope, replacementOrderId)\n } catch (compensationErr) {\n replacementOrderBridgeLogger.error('warranty_claims.claim.create_replacement_order compensation failed \u2014 orphaned sales order', {\n err: compensationErr,\n claimId: claim.id,\n replacementOrderId,\n })\n try {\n const orphanEm = (ctx.container.resolve('em') as EntityManager).fork()\n const orphanClaim = await findOneWithDecryption(\n orphanEm,\n WarrantyClaim,\n { id: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n if (orphanClaim) {\n appendClaimEvent(orphanEm, orphanClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'replacement_order_orphaned', replacementOrderId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await orphanEm.flush()\n }\n } catch (orphanEventErr) {\n replacementOrderBridgeLogger.error('warranty_claims.claim.create_replacement_order orphan timeline write failed', {\n err: orphanEventErr,\n claimId: claim.id,\n replacementOrderId,\n })\n }\n throw new CrudHttpError(500, { error: 'warranty_claims.errors.save_failed' })\n }\n throw err\n }\n\n await emitClaimCrud(ctx, 'updated', claim)\n return {\n claimId: claim.id,\n replacementOrderId,\n replacementOrderUpdatedAt,\n skippedLineIds,\n pricing: input.pricing,\n }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateReplacementOrderSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => {\n const base = buildClaimLog('warranty_claims.audit.claim.create_replacement_order', result.claimId, snapshots)\n const undoPayload: ClaimReplacementOrderUndoPayload = {\n ...(base.payload.undo as ClaimUndoPayload),\n replacementOrder: {\n id: result.replacementOrderId,\n updatedAt: result.replacementOrderUpdatedAt,\n },\n }\n return { ...base, payload: { undo: undoPayload } }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimReplacementOrderUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) throwClaimUndoConflict()\n await assertUndoSnapshotCurrent(ctx, after)\n const scope: WarrantyClaimScope = { tenantId: before.tenantId, organizationId: before.organizationId }\n const replacementOrder = payload?.replacementOrder ?? null\n if (replacementOrder?.id) {\n const currentRow = await querySalesReferenceRow(ctx, 'sales_orders', scope, replacementOrder.id, ['id', 'updated_at'])\n if (currentRow === undefined) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.replacementOrderChangedUndoAborted' })\n }\n if (currentRow) {\n const currentUpdatedAt = currentRow.updated_at\n ? new Date(currentRow.updated_at as string | Date).toISOString()\n : null\n if (!replacementOrder.updatedAt || !currentUpdatedAt || currentUpdatedAt !== replacementOrder.updatedAt) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.replacementOrderChangedUndoAborted' })\n }\n await dispatchSalesOrderDelete(ctx, scope, replacementOrder.id)\n } else {\n replacementOrderBridgeLogger.info('warranty_claims.claim.create_replacement_order undo found replacement order already absent', {\n claimId: before.id,\n replacementOrderId: replacementOrder.id,\n })\n }\n }\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_replacement_order_created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.create_replacement_order.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nregisterCommand(createClaimCommand)\nregisterCommand(updateClaimCommand)\nregisterCommand(deleteClaimCommand)\nregisterCommand(submitClaimCommand)\nregisterCommand(transitionClaimCommand)\nregisterCommand(assignClaimCommand)\nregisterCommand(setReturnLabelCommand)\nregisterCommand(escalateClaimCommand)\nregisterCommand(commentClaimCommand)\nregisterCommand(createVendorRecoveryCommand)\nregisterCommand(createSalesReturnCommand)\nregisterCommand(createCreditMemoCommand)\nregisterCommand(createReplacementOrderCommand)\n\nexport const claimCommands = [\n createClaimCommand,\n updateClaimCommand,\n deleteClaimCommand,\n submitClaimCommand,\n transitionClaimCommand,\n assignClaimCommand,\n setReturnLabelCommand,\n escalateClaimCommand,\n commentClaimCommand,\n createVendorRecoveryCommand,\n createSalesReturnCommand,\n createCreditMemoCommand,\n createReplacementOrderCommand,\n]\n\nexport {\n claimCrudEvents,\n createClaimCommand,\n updateClaimCommand,\n deleteClaimCommand,\n submitClaimCommand,\n transitionClaimCommand,\n assignClaimCommand,\n setReturnLabelCommand,\n escalateClaimCommand,\n commentClaimCommand,\n createVendorRecoveryCommand,\n createSalesReturnCommand,\n createCreditMemoCommand,\n createReplacementOrderCommand,\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AAEzB,SAAS,SAAS;AAClB,SAAS,uBAAyF;AAClG,SAAS,uBAAuB;AAChC,SAAS,qBAAqB,+BAA+B;AAE7D,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,+BAA+B;AAGxC,SAAS,SAAS;AAClB;AAAA,EACE;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,OAmBK;AACP,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,oCAAoC;AAC7C,SAAS,+BAA+B;AACxC,SAAS,kBAAkB,4BAA4B,4BAA4B;AACnF,SAAS,oCAAoC;AAC7C,SAAS,mBAAmB,6BAA6B;AACzD,SAAS,6CAAkF;AAC3F,SAAS,yBAAyB;AAGlC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,kBAAoC;AAAA,EACxC,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,cAAc,CAAC,QAAQ;AACrB,UAAM,QAAQ,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AAA,MACH;AAAA,IACF;AAEA,UAAM,KAAM,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAC/D,QAAI;AACJ,UAAM,gBAAgB,IAAI;AAAA,MACxB,YAAY;AACV,gBAAQ,MAAM,gBAAgB,IAAI,QAAQ,KAAK;AAC/C,yBAAiB,IAAI,OAAO,UAAU;AAAA,UACpC,YAAY;AAAA,UACZ,SAAS,EAAE,QAAQ,iCAAiC;AAAA,UACpD,aAAa,IAAI,MAAM,OAAO;AAAA,QAChC,CAAC;AAAA,MACH;AAAA,IACF,GAAG,EAAE,aAAa,MAAM,OAAO,sDAAsD,CAAC;AACtF,UAAM,kBAAkB,KAAK,WAAW,KAAK;AAAA,EAC/C;AACF;AAEA,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,sBAAsB;AACtC,gBAAgB,kBAAkB;AAClC,gBAAgB,qBAAqB;AACrC,gBAAgB,oBAAoB;AACpC,gBAAgB,mBAAmB;AACnC,gBAAgB,2BAA2B;AAC3C,gBAAgB,wBAAwB;AACxC,gBAAgB,uBAAuB;AACvC,gBAAgB,6BAA6B;AAEtC,MAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from 'crypto'\nimport { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { registerCommand, type CommandBus, type CommandHandler, type CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { invalidateCrudCache } from '@open-mercato/shared/lib/crud/cache'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readSafeDecryptedString } from '../lib/decryptionSafety'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport {\n WarrantyClaim,\n WarrantyClaimLine,\n} from '../data/entities'\nimport {\n CLAIM_FULFILLMENT_UPDATE_FIELDS,\n CLAIM_INTAKE_UPDATE_FIELDS,\n claimCreateSchema,\n claimUpdateSchema,\n assignClaimInputSchema,\n claimCreateCreditMemoSchema,\n claimCreateReplacementOrderSchema,\n claimCreateSalesReturnSchema,\n claimSetReturnLabelSchema,\n commentClaimInputSchema,\n transitionClaimInputSchema,\n vendorRecoveryInputSchema,\n type ClaimCreateInput,\n type ClaimInitialLineCreateInput,\n type ClaimUpdateInput,\n type AssignClaimInput,\n type ClaimCreateCreditMemoInput,\n type ClaimCreateReplacementOrderInput,\n type ClaimCreateSalesReturnInput,\n type ClaimSetReturnLabelInput,\n type CommentClaimInput,\n type TransitionClaimInput,\n type VendorRecoveryInput,\n type WarrantyClaimChannel,\n type WarrantyClaimLineStatus,\n type WarrantyClaimPriority,\n type WarrantyClaimDisposition,\n type WarrantyClaimStatus,\n type WarrantyClaimType,\n type WarrantyClaimWarrantyStatus,\n} from '../data/validators'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { isAssignableStaffUser } from '../lib/assigneeNames'\nimport { WarrantyClaimNumberGenerator } from '../services/claimNumberGenerator'\nimport { emitWarrantyClaimsEvent } from '../events'\nimport { assertTransition, canResolveWithLineStatuses, computeHeaderRollups } from '../lib/stateMachine'\nimport { assertOrderBelongsToCustomer } from '../lib/orderOwnership'\nimport { addBusinessMillis, businessMillisBetween } from '../lib/businessHours'\nimport { resolveEffectiveWarrantyClaimSettings, type WarrantyClaimEffectiveSettings } from '../lib/settings'\nimport { evaluateClaimRisk } from '../lib/risk'\nimport type { WarrantyAdjudicationEvaluator } from '../services/adjudicationEvaluator'\nimport type { WarrantyEntitlementInput, WarrantyEntitlementResolver } from '../services/entitlementResolver'\nimport {\n WARRANTY_CLAIM_RESOURCE_KIND,\n appendClaimEvent,\n enforceWarrantyClaimOptimisticLock,\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n requireScopedClaim,\n throwUndoRefusal,\n type WarrantyClaimScope,\n} from './shared'\n\nconst claimCrudEvents: CrudEventsConfig = {\n module: 'warranty_claims',\n entity: 'claim',\n persistent: true,\n buildPayload: (ctx) => {\n const claim = ctx.entity as WarrantyClaim | null\n return {\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n claimType: claim?.claimType ?? null,\n status: claim?.status ?? null,\n }\n },\n}\n\nconst claimDeleteSchema = z\n .object({\n id: z.string().uuid(),\n organizationId: z.string().uuid().optional(),\n tenantId: z.string().uuid().optional(),\n })\n .strict()\n\nconst submitClaimSchema = claimDeleteSchema.extend({\n actorCustomerId: z.string().uuid().optional(),\n})\nconst escalateClaimInputSchema = z\n .object({\n id: z.string().uuid(),\n organizationId: z.string().uuid(),\n tenantId: z.string().uuid(),\n toLevel: z.coerce.number().int().min(1).max(1000),\n reassignToUserId: z.string().uuid().optional(),\n })\n .strict()\n\ntype ClaimDeleteInput = z.infer<typeof claimDeleteSchema>\ntype SubmitClaimInput = z.infer<typeof submitClaimSchema>\ntype EscalateClaimInput = z.infer<typeof escalateClaimInputSchema>\ntype EscalateClaimResult = { claimId: string; escalationLevel: number; escalated: boolean }\ntype ClaimSetReturnLabelResult = {\n claimId: string\n labelUrl: string | null\n trackingNumber: string | null\n carrier: string | null\n}\n\ntype ScopeInput = {\n organizationId?: string | null\n tenantId?: string | null\n}\n\ntype ClaimUpdateField =\n | (typeof CLAIM_INTAKE_UPDATE_FIELDS)[number]\n | (typeof CLAIM_FULFILLMENT_UPDATE_FIELDS)[number]\n\ntype ClaimLineSnapshot = {\n id: string\n lineNo: number\n productId: string | null\n variantId: string | null\n sku: string | null\n productName: string | null\n orderLineId: string | null\n serialNumber: string | null\n lotNumber: string | null\n purchaseDate: string | null\n warrantyMonths: number | null\n warrantyExpiresAt: string | null\n warrantyStatus: WarrantyClaimWarrantyStatus\n faultCode: string | null\n faultDescription: string | null\n qtyClaimed: string\n qtyApproved: string | null\n qtyReceived: string | null\n conditionOnReceipt: string | null\n conditionGrade: string | null\n quarantineStatus: string\n inspectionNotes: string | null\n assessmentPayload: Record<string, unknown> | null\n disposition: WarrantyClaimDisposition | null\n lineStatus: WarrantyClaimLineStatus\n creditAmount: string | null\n restockingFee: string | null\n coreChargeAmount: string | null\n coreCreditAmount: string | null\n vendorClaimLineId: string | null\n vendorName: string | null\n deletedAt: string | null\n updatedAt: string | null\n}\n\ntype ClaimSnapshot = {\n id: string\n organizationId: string\n tenantId: string\n claimNumber: string\n claimType: WarrantyClaimType\n status: WarrantyClaimStatus\n channel: WarrantyClaimChannel\n priority: WarrantyClaimPriority\n customerId: string | null\n customerName: string | null\n externalRef: string | null\n intakeMessageRef: string | null\n entitlementSource: string | null\n contactEmail: string | null\n returnLabelUrl: string | null\n returnTrackingNumber: string | null\n returnCarrier: string | null\n vendorName: string | null\n vendorRef: string | null\n orderId: string | null\n orderNumber: string | null\n awaitingStaffReply: boolean\n salesReturnId: string | null\n replacementOrderId: string | null\n creditMemoId: string | null\n sourceClaimId: string | null\n advanceReplacement: boolean\n advanceShippedAt: string | null\n reasonCode: string | null\n rejectionReasonCode: string | null\n resolutionSummary: string | null\n notes: string | null\n currencyCode: string | null\n totalClaimedAmount: string | null\n totalApprovedAmount: string | null\n totalRecoveredAmount: string | null\n escalationLevel: number\n escalatedAt: string | null\n slaDueAt: string | null\n slaPausedAt: string | null\n slaAtRiskNotifiedAt: string | null\n slaBreachedNotifiedAt: string | null\n submittedAt: string | null\n resolvedAt: string | null\n closedAt: string | null\n assigneeUserId: string | null\n deletedAt: string | null\n updatedAt: string | null\n lines: ClaimLineSnapshot[]\n}\n\ntype ClaimUndoPayload = {\n before?: ClaimSnapshot | null\n after?: ClaimSnapshot | null\n}\n\ntype ClaimEventPayload = {\n id: string\n claimId: string\n claimNumber: string\n externalRef: string | null\n claimType: WarrantyClaimType\n status: WarrantyClaimStatus\n customerId: string | null\n organizationId: string\n tenantId: string\n}\n\ntype ReferenceLookupResult = 'missing' | 'unknown'\n\ntype ReferenceValidationInput = {\n orderId?: string | null\n salesReturnId?: string | null\n replacementOrderId?: string | null\n creditMemoId?: string | null\n lineOrderRefs?: Array<{ orderLineId: string; orderId: string | null }>\n}\n\nconst intakeStatuses = new Set<WarrantyClaimStatus>(['draft', 'submitted', 'in_review', 'info_requested'])\nconst fulfillmentStatuses = new Set<WarrantyClaimStatus>(['approved', 'awaiting_return', 'received', 'inspecting'])\nconst deletableStatuses = new Set<WarrantyClaimStatus>(['draft', 'cancelled'])\nconst preReceivedStatuses = new Set<WarrantyClaimStatus>([\n 'draft',\n 'submitted',\n 'in_review',\n 'info_requested',\n 'approved',\n 'awaiting_return',\n])\n\nfunction parseCommandInput<T>(schema: z.ZodType<T>, rawInput: unknown): T {\n const result = schema.safeParse(rawInput ?? {})\n if (!result.success) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidInput' })\n }\n return result.data\n}\n\nfunction hasOwn(input: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(input, key)\n}\n\nfunction resolveScope(ctx: CommandRuntimeContext, input: ScopeInput): WarrantyClaimScope {\n const tenantId = input.tenantId ?? ctx.auth?.tenantId ?? null\n const organizationId = input.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n if (!tenantId) throw new CrudHttpError(400, { error: '[internal] tenant scope required for warranty claim command' })\n if (!organizationId) throw new CrudHttpError(400, { error: '[internal] organization scope required for warranty claim command' })\n ensureTenantScope(ctx, tenantId)\n ensureOrganizationScope(ctx, organizationId)\n return { tenantId, organizationId }\n}\n\nfunction toIso(value: Date | string | null | undefined): string | null {\n if (!value) return null\n const date = value instanceof Date ? value : new Date(value)\n return Number.isNaN(date.getTime()) ? null : date.toISOString()\n}\n\nfunction toDate(value: string | null): Date | null {\n if (!value) return null\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\nfunction toDateOnlyIso(value: Date | string | null | undefined): string | null {\n const iso = toIso(value)\n return iso ? iso.slice(0, 10) : null\n}\n\nfunction toDateOnly(value: string | null): Date | null {\n if (!value) return null\n const date = new Date(`${value}T00:00:00.000Z`)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\nfunction amountString(value: number | string | null | undefined, fallback = '0'): string | null {\n if (value === null) return null\n if (value === undefined) return fallback\n const parsed = typeof value === 'number' ? value : Number(value)\n if (!Number.isFinite(parsed)) return fallback\n return String(parsed)\n}\n\nfunction nullableAmountString(value: number | string | null | undefined): string | null {\n if (value === undefined || value === null) return null\n return amountString(value, '0')\n}\n\nfunction addMonths(date: Date, months: number): Date {\n const target = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + months, 1))\n const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate()\n const copy = new Date(date.getTime())\n copy.setUTCDate(1)\n copy.setUTCFullYear(target.getUTCFullYear(), target.getUTCMonth(), Math.min(date.getUTCDate(), lastDay))\n return copy\n}\n\nfunction computeWarrantyDates(\n purchaseDate: Date | null | undefined,\n warrantyMonths: number | null | undefined,\n): { warrantyExpiresAt: Date | null; warrantyStatus: WarrantyClaimWarrantyStatus } {\n if (!purchaseDate || warrantyMonths === null || warrantyMonths === undefined) {\n return { warrantyExpiresAt: null, warrantyStatus: 'unknown' }\n }\n const warrantyExpiresAt = addMonths(purchaseDate, warrantyMonths)\n const warrantyStatus = warrantyExpiresAt.getTime() >= Date.now() ? 'in_warranty' : 'out_of_warranty'\n return { warrantyExpiresAt, warrantyStatus }\n}\n\nfunction buildCreateEntitlementInput(input: ClaimCreateInput): WarrantyEntitlementInput | null {\n const lines = input.lines ?? []\n const sourceLine = lines.find((line) => typeof line.serialNumber === 'string' && line.serialNumber.trim().length > 0)\n ?? lines.find((line) => Boolean(line.productId))\n ?? lines.find((line) => typeof line.sku === 'string' && line.sku.trim().length > 0)\n ?? (input.orderId ? lines.find((line) => Boolean(line.purchaseDate)) : null)\n ?? null\n\n const serialNumber = sourceLine?.serialNumber?.trim() || null\n const orderId = input.orderId ?? null\n const productId = sourceLine?.productId ?? null\n const sku = sourceLine?.sku?.trim() || null\n\n if (!serialNumber && !orderId && !productId && !sku) return null\n\n return {\n serialNumber,\n orderId,\n productId,\n sku,\n purchaseDate: toDateOnlyIso(sourceLine?.purchaseDate),\n }\n}\n\nasync function stampEntitlementSourceIfResolvable(\n ctx: CommandRuntimeContext,\n em: EntityManager,\n claim: WarrantyClaim,\n input: ClaimCreateInput,\n scope: WarrantyClaimScope,\n): Promise<void> {\n const entitlementInput = buildCreateEntitlementInput(input)\n if (!entitlementInput) return\n\n try {\n const resolver = ctx.container.resolve<WarrantyEntitlementResolver>('warrantyEntitlementResolver')\n const result = await resolver.resolveEntitlement(entitlementInput, scope, em)\n claim.entitlementSource = result.source ?? null\n } catch {\n claim.entitlementSource = null\n }\n}\n\nfunction buildInitialLineData(\n claim: WarrantyClaim,\n input: ClaimInitialLineCreateInput,\n index: number,\n): Partial<WarrantyClaimLine> & {\n id: string\n claim: WarrantyClaim\n organizationId: string\n tenantId: string\n lineNo: number\n qtyClaimed: string\n lineStatus: WarrantyClaimLineStatus\n warrantyStatus: WarrantyClaimWarrantyStatus\n createdAt: Date\n updatedAt: Date\n} {\n const purchaseDate = input.purchaseDate ?? null\n const warrantyMonths = input.warrantyMonths ?? null\n const computedWarranty = computeWarrantyDates(purchaseDate, warrantyMonths)\n return {\n id: randomUUID(),\n claim,\n organizationId: claim.organizationId,\n tenantId: claim.tenantId,\n lineNo: input.lineNo ?? index + 1,\n productId: input.productId ?? null,\n variantId: input.variantId ?? null,\n sku: input.sku ?? null,\n productName: input.productName ?? null,\n orderLineId: input.orderLineId ?? null,\n serialNumber: input.serialNumber ?? null,\n lotNumber: input.lotNumber ?? null,\n purchaseDate,\n warrantyMonths,\n warrantyExpiresAt: input.warrantyExpiresAt ?? computedWarranty.warrantyExpiresAt,\n warrantyStatus: input.warrantyStatus ?? computedWarranty.warrantyStatus,\n faultCode: input.faultCode ?? null,\n faultDescription: input.faultDescription ?? null,\n qtyClaimed: amountString(input.qtyClaimed, '1') ?? '1',\n qtyApproved: nullableAmountString(input.qtyApproved),\n qtyReceived: nullableAmountString(input.qtyReceived),\n conditionOnReceipt: input.conditionOnReceipt ?? null,\n inspectionNotes: input.inspectionNotes ?? null,\n disposition: input.disposition ?? null,\n vendorName: input.vendorName ?? null,\n lineStatus: 'pending',\n creditAmount: nullableAmountString(input.creditAmount),\n restockingFee: nullableAmountString(input.restockingFee),\n coreChargeAmount: nullableAmountString(input.coreChargeAmount),\n coreCreditAmount: nullableAmountString(input.coreCreditAmount),\n createdAt: new Date(),\n updatedAt: new Date(),\n }\n}\n\nfunction snapshotLine(line: WarrantyClaimLine): ClaimLineSnapshot {\n return {\n id: line.id,\n lineNo: line.lineNo,\n productId: line.productId ?? null,\n variantId: line.variantId ?? null,\n sku: line.sku ?? null,\n productName: line.productName ?? null,\n orderLineId: line.orderLineId ?? null,\n serialNumber: line.serialNumber ?? null,\n lotNumber: line.lotNumber ?? null,\n purchaseDate: toDateOnlyIso(line.purchaseDate),\n warrantyMonths: line.warrantyMonths ?? null,\n warrantyExpiresAt: toDateOnlyIso(line.warrantyExpiresAt),\n warrantyStatus: line.warrantyStatus,\n faultCode: line.faultCode ?? null,\n faultDescription: line.faultDescription ?? null,\n qtyClaimed: line.qtyClaimed,\n qtyApproved: line.qtyApproved ?? null,\n qtyReceived: line.qtyReceived ?? null,\n conditionOnReceipt: line.conditionOnReceipt ?? null,\n conditionGrade: line.conditionGrade ?? null,\n quarantineStatus: line.quarantineStatus,\n inspectionNotes: line.inspectionNotes ?? null,\n assessmentPayload: line.assessmentPayload ?? null,\n disposition: line.disposition ?? null,\n lineStatus: line.lineStatus,\n creditAmount: line.creditAmount ?? null,\n restockingFee: line.restockingFee ?? null,\n coreChargeAmount: line.coreChargeAmount ?? null,\n coreCreditAmount: line.coreCreditAmount ?? null,\n vendorClaimLineId: line.vendorClaimLineId ?? null,\n vendorName: line.vendorName ?? null,\n deletedAt: toIso(line.deletedAt),\n updatedAt: toIso(line.updatedAt),\n }\n}\n\nfunction snapshotClaim(claim: WarrantyClaim, lines: readonly WarrantyClaimLine[]): ClaimSnapshot {\n return {\n id: claim.id,\n organizationId: claim.organizationId,\n tenantId: claim.tenantId,\n claimNumber: claim.claimNumber,\n claimType: claim.claimType,\n status: claim.status,\n channel: claim.channel,\n priority: claim.priority,\n customerId: claim.customerId ?? null,\n customerName: claim.customerName ?? null,\n externalRef: claim.externalRef ?? null,\n intakeMessageRef: claim.intakeMessageRef ?? null,\n entitlementSource: claim.entitlementSource ?? null,\n contactEmail: claim.contactEmail ?? null,\n returnLabelUrl: claim.returnLabelUrl ?? null,\n returnTrackingNumber: claim.returnTrackingNumber ?? null,\n returnCarrier: claim.returnCarrier ?? null,\n vendorName: claim.vendorName ?? null,\n vendorRef: claim.vendorRef ?? null,\n orderId: claim.orderId ?? null,\n orderNumber: claim.orderNumber ?? null,\n awaitingStaffReply: claim.awaitingStaffReply === true,\n salesReturnId: claim.salesReturnId ?? null,\n replacementOrderId: claim.replacementOrderId ?? null,\n creditMemoId: claim.creditMemoId ?? null,\n sourceClaimId: claim.sourceClaimId ?? null,\n advanceReplacement: claim.advanceReplacement,\n advanceShippedAt: toIso(claim.advanceShippedAt),\n reasonCode: claim.reasonCode ?? null,\n rejectionReasonCode: claim.rejectionReasonCode ?? null,\n resolutionSummary: claim.resolutionSummary ?? null,\n notes: claim.notes ?? null,\n currencyCode: claim.currencyCode ?? null,\n totalClaimedAmount: claim.totalClaimedAmount ?? null,\n totalApprovedAmount: claim.totalApprovedAmount ?? null,\n totalRecoveredAmount: claim.totalRecoveredAmount ?? null,\n escalationLevel: claim.escalationLevel ?? 0,\n escalatedAt: toIso(claim.escalatedAt),\n slaDueAt: toIso(claim.slaDueAt),\n slaPausedAt: toIso(claim.slaPausedAt),\n slaAtRiskNotifiedAt: toIso(claim.slaAtRiskNotifiedAt),\n slaBreachedNotifiedAt: toIso(claim.slaBreachedNotifiedAt),\n submittedAt: toIso(claim.submittedAt),\n resolvedAt: toIso(claim.resolvedAt),\n closedAt: toIso(claim.closedAt),\n assigneeUserId: claim.assigneeUserId ?? null,\n deletedAt: toIso(claim.deletedAt),\n updatedAt: toIso(claim.updatedAt),\n lines: lines.map(snapshotLine),\n }\n}\n\nasync function loadClaimSnapshot(\n em: EntityManager,\n claimId: string,\n scope: WarrantyClaimScope,\n): Promise<ClaimSnapshot | null> {\n const claim = await findOneWithDecryption(em, WarrantyClaim, { id: claimId, tenantId: scope.tenantId, organizationId: scope.organizationId }, {}, scope)\n if (!claim) return null\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId },\n {},\n scope,\n )\n return snapshotClaim(claim, lines)\n}\n\nfunction snapshotValueChanged(before: unknown, after: unknown): boolean {\n return JSON.stringify(before) !== JSON.stringify(after)\n}\n\nfunction restoreClaimDelta(claim: WarrantyClaim, before: ClaimSnapshot, after: ClaimSnapshot): void {\n if (before.claimNumber !== after.claimNumber) claim.claimNumber = before.claimNumber\n if (before.claimType !== after.claimType) claim.claimType = before.claimType\n if (before.status !== after.status) claim.status = before.status\n if (before.channel !== after.channel) claim.channel = before.channel\n if (before.priority !== after.priority) claim.priority = before.priority\n if (before.customerId !== after.customerId) claim.customerId = before.customerId\n if (before.customerName !== after.customerName) claim.customerName = before.customerName\n if (before.externalRef !== after.externalRef) claim.externalRef = before.externalRef\n if (before.intakeMessageRef !== after.intakeMessageRef) claim.intakeMessageRef = before.intakeMessageRef\n if (before.entitlementSource !== after.entitlementSource) claim.entitlementSource = before.entitlementSource\n if (before.contactEmail !== after.contactEmail) claim.contactEmail = before.contactEmail\n if (before.returnLabelUrl !== after.returnLabelUrl) claim.returnLabelUrl = before.returnLabelUrl\n if (before.returnTrackingNumber !== after.returnTrackingNumber) claim.returnTrackingNumber = before.returnTrackingNumber\n if (before.returnCarrier !== after.returnCarrier) claim.returnCarrier = before.returnCarrier\n if (before.vendorName !== after.vendorName) claim.vendorName = before.vendorName\n if (before.vendorRef !== after.vendorRef) claim.vendorRef = before.vendorRef\n if (before.orderId !== after.orderId) claim.orderId = before.orderId\n if (before.orderNumber !== after.orderNumber) claim.orderNumber = before.orderNumber\n if (before.awaitingStaffReply !== after.awaitingStaffReply) claim.awaitingStaffReply = before.awaitingStaffReply === true\n if (before.salesReturnId !== after.salesReturnId) claim.salesReturnId = before.salesReturnId\n if (before.replacementOrderId !== after.replacementOrderId) claim.replacementOrderId = before.replacementOrderId\n if (before.creditMemoId !== after.creditMemoId) claim.creditMemoId = before.creditMemoId\n if (before.sourceClaimId !== after.sourceClaimId) claim.sourceClaimId = before.sourceClaimId\n if (before.advanceReplacement !== after.advanceReplacement) claim.advanceReplacement = before.advanceReplacement\n if (before.advanceShippedAt !== after.advanceShippedAt) claim.advanceShippedAt = toDate(before.advanceShippedAt)\n if (before.reasonCode !== after.reasonCode) claim.reasonCode = before.reasonCode\n if (before.rejectionReasonCode !== after.rejectionReasonCode) claim.rejectionReasonCode = before.rejectionReasonCode\n if (before.resolutionSummary !== after.resolutionSummary) claim.resolutionSummary = before.resolutionSummary\n if (before.notes !== after.notes) claim.notes = before.notes\n if (before.currencyCode !== after.currencyCode) claim.currencyCode = before.currencyCode\n if (before.totalClaimedAmount !== after.totalClaimedAmount) claim.totalClaimedAmount = before.totalClaimedAmount\n if (before.totalApprovedAmount !== after.totalApprovedAmount) claim.totalApprovedAmount = before.totalApprovedAmount\n if (before.totalRecoveredAmount !== after.totalRecoveredAmount) claim.totalRecoveredAmount = before.totalRecoveredAmount\n if (before.escalationLevel !== after.escalationLevel) claim.escalationLevel = before.escalationLevel\n if (before.escalatedAt !== after.escalatedAt) claim.escalatedAt = toDate(before.escalatedAt)\n if (before.slaDueAt !== after.slaDueAt) claim.slaDueAt = toDate(before.slaDueAt)\n if (before.slaPausedAt !== after.slaPausedAt) claim.slaPausedAt = toDate(before.slaPausedAt)\n if (before.slaAtRiskNotifiedAt !== after.slaAtRiskNotifiedAt) claim.slaAtRiskNotifiedAt = toDate(before.slaAtRiskNotifiedAt)\n if (before.slaBreachedNotifiedAt !== after.slaBreachedNotifiedAt) claim.slaBreachedNotifiedAt = toDate(before.slaBreachedNotifiedAt)\n if (before.submittedAt !== after.submittedAt) claim.submittedAt = toDate(before.submittedAt)\n if (before.resolvedAt !== after.resolvedAt) claim.resolvedAt = toDate(before.resolvedAt)\n if (before.closedAt !== after.closedAt) claim.closedAt = toDate(before.closedAt)\n if (before.assigneeUserId !== after.assigneeUserId) claim.assigneeUserId = before.assigneeUserId\n if (before.deletedAt !== after.deletedAt) claim.deletedAt = toDate(before.deletedAt)\n claim.updatedAt = new Date()\n}\n\nfunction restoreLineDelta(line: WarrantyClaimLine, before: ClaimLineSnapshot, after: ClaimLineSnapshot): void {\n if (before.lineNo !== after.lineNo) line.lineNo = before.lineNo\n if (before.productId !== after.productId) line.productId = before.productId\n if (before.variantId !== after.variantId) line.variantId = before.variantId\n if (before.sku !== after.sku) line.sku = before.sku\n if (before.productName !== after.productName) line.productName = before.productName\n if (before.orderLineId !== after.orderLineId) line.orderLineId = before.orderLineId\n if (before.serialNumber !== after.serialNumber) line.serialNumber = before.serialNumber\n if (before.lotNumber !== after.lotNumber) line.lotNumber = before.lotNumber\n if (before.purchaseDate !== after.purchaseDate) line.purchaseDate = toDateOnly(before.purchaseDate)\n if (before.warrantyMonths !== after.warrantyMonths) line.warrantyMonths = before.warrantyMonths\n if (before.warrantyExpiresAt !== after.warrantyExpiresAt) line.warrantyExpiresAt = toDateOnly(before.warrantyExpiresAt)\n if (before.warrantyStatus !== after.warrantyStatus) line.warrantyStatus = before.warrantyStatus\n if (before.faultCode !== after.faultCode) line.faultCode = before.faultCode\n if (before.faultDescription !== after.faultDescription) line.faultDescription = before.faultDescription\n if (before.qtyClaimed !== after.qtyClaimed) line.qtyClaimed = before.qtyClaimed\n if (before.qtyApproved !== after.qtyApproved) line.qtyApproved = before.qtyApproved\n if (before.qtyReceived !== after.qtyReceived) line.qtyReceived = before.qtyReceived\n if (before.conditionOnReceipt !== after.conditionOnReceipt) line.conditionOnReceipt = before.conditionOnReceipt\n if (before.conditionGrade !== after.conditionGrade) line.conditionGrade = before.conditionGrade\n if (before.quarantineStatus !== after.quarantineStatus) line.quarantineStatus = before.quarantineStatus\n if (before.inspectionNotes !== after.inspectionNotes) line.inspectionNotes = before.inspectionNotes\n if (snapshotValueChanged(before.assessmentPayload, after.assessmentPayload)) line.assessmentPayload = before.assessmentPayload\n if (before.disposition !== after.disposition) line.disposition = before.disposition\n if (before.lineStatus !== after.lineStatus) line.lineStatus = before.lineStatus\n if (before.creditAmount !== after.creditAmount) line.creditAmount = before.creditAmount\n if (before.restockingFee !== after.restockingFee) line.restockingFee = before.restockingFee\n if (before.coreChargeAmount !== after.coreChargeAmount) line.coreChargeAmount = before.coreChargeAmount\n if (before.coreCreditAmount !== after.coreCreditAmount) line.coreCreditAmount = before.coreCreditAmount\n if (before.vendorClaimLineId !== after.vendorClaimLineId) line.vendorClaimLineId = before.vendorClaimLineId\n if (before.vendorName !== after.vendorName) line.vendorName = before.vendorName\n if (before.deletedAt !== after.deletedAt) line.deletedAt = toDate(before.deletedAt)\n line.updatedAt = new Date()\n}\n\nfunction throwClaimUndoConflict(): Promise<never> {\n return throwUndoRefusal('warranty_claims.errors.conflict', 'This claim changed while you were editing it.')\n}\n\nasync function requireCurrentUndoSnapshot(\n em: EntityManager,\n after: ClaimSnapshot,\n): Promise<{ claim: WarrantyClaim; lines: WarrantyClaimLine[] }> {\n const scope = { tenantId: after.tenantId, organizationId: after.organizationId }\n const claim = await findOneWithDecryption(\n em,\n WarrantyClaim,\n { id: after.id, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n )\n const expectedClaimUpdatedAt = toIso(after.updatedAt)\n if (!claim || !expectedClaimUpdatedAt || toIso(claim.updatedAt) !== expectedClaimUpdatedAt) return throwClaimUndoConflict()\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: after.id, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n )\n const afterLines = Array.isArray(after.lines) ? after.lines : []\n if (lines.length !== afterLines.length) return throwClaimUndoConflict()\n const afterLinesById = new Map(afterLines.map((line) => [line.id, line]))\n for (const line of lines) {\n const expected = afterLinesById.get(line.id)\n const expectedLineUpdatedAt = toIso(expected?.updatedAt)\n if (!expectedLineUpdatedAt || toIso(line.updatedAt) !== expectedLineUpdatedAt) return throwClaimUndoConflict()\n }\n return { claim, lines }\n}\n\nasync function assertUndoSnapshotCurrent(ctx: CommandRuntimeContext, after: ClaimSnapshot): Promise<void> {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n await em.transactional(async (tx) => {\n await requireCurrentUndoSnapshot(tx, after)\n })\n}\n\nasync function restoreSnapshot(em: EntityManager, before: ClaimSnapshot, after: ClaimSnapshot): Promise<WarrantyClaim> {\n const { claim, lines } = await requireCurrentUndoSnapshot(em, after)\n restoreClaimDelta(claim, before, after)\n const beforeLinesById = new Map((Array.isArray(before.lines) ? before.lines : []).map((line) => [line.id, line]))\n const afterLinesById = new Map((Array.isArray(after.lines) ? after.lines : []).map((line) => [line.id, line]))\n for (const line of lines) {\n const beforeLine = beforeLinesById.get(line.id)\n const afterLine = afterLinesById.get(line.id)\n if (!beforeLine || !afterLine) return throwClaimUndoConflict()\n if (snapshotValueChanged(beforeLine, afterLine)) restoreLineDelta(line, beforeLine, afterLine)\n }\n return claim\n}\n\nfunction claimEventPayload(claim: WarrantyClaim): ClaimEventPayload {\n return {\n id: claim.id,\n claimId: claim.id,\n claimNumber: claim.claimNumber,\n externalRef: claim.externalRef ?? null,\n claimType: claim.claimType,\n status: claim.status,\n customerId: claim.customerId ?? null,\n organizationId: claim.organizationId,\n tenantId: claim.tenantId,\n }\n}\n\nfunction claimPersistentEmitOptions(claim: WarrantyClaim) {\n return {\n persistent: true,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n } as const\n}\n\nasync function emitClaimCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n claim: WarrantyClaim,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action,\n entity: claim,\n identifiers: { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim },\n events: claimCrudEvents,\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim',\n { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim.${action}`,\n )\n}\n\nasync function emitClaimUndoCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n claim: WarrantyClaim,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action,\n entity: claim,\n identifiers: { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim },\n events: claimCrudEvents,\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim',\n { id: claim.id, organizationId: claim.organizationId, tenantId: claim.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim.undo.${action}`,\n )\n}\n\nasync function emitLineCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n line: WarrantyClaimLine,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action,\n entity: line,\n identifiers: { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim_line },\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim_line',\n { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim_line.${action}`,\n )\n}\n\nasync function emitLineUndoCrud(\n ctx: CommandRuntimeContext,\n action: 'created' | 'updated' | 'deleted',\n line: WarrantyClaimLine,\n): Promise<void> {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action,\n entity: line,\n identifiers: { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n indexer: { entityType: E.warranty_claims.warranty_claim_line },\n })\n await invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim_line',\n { id: line.id, organizationId: line.organizationId, tenantId: line.tenantId },\n ctx.auth?.tenantId ?? null,\n `warranty_claims.claim_line.undo.${action}`,\n )\n}\n\nfunction resolveClaimNumberGenerator(ctx: CommandRuntimeContext, em: EntityManager): WarrantyClaimNumberGenerator {\n try {\n return ctx.container.resolve('warrantyClaimNumberGenerator') as WarrantyClaimNumberGenerator\n } catch {\n return new WarrantyClaimNumberGenerator(em)\n }\n}\n\nfunction readCustomerName(row: Record<string, unknown>): string | null {\n const candidates = [row.display_name, row.displayName, row.name, row.label]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) return candidate.trim()\n }\n return null\n}\n\nfunction readString(row: Record<string, unknown>, key: string): string | null {\n const value = row[key]\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null\n}\n\ntype SalesReferenceTable = 'sales_orders' | 'sales_returns' | 'sales_credit_memos' | 'sales_order_lines'\n\ntype SalesReferenceDb = {\n sales_orders: {\n id: string\n currency_code: string\n customer_entity_id: string | null\n customer_contact_id: string | null\n billing_address_id: string | null\n shipping_address_id: string | null\n channel_id: string | null\n updated_at: Date | string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n sales_returns: {\n id: string\n updated_at: Date | string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n sales_credit_memos: {\n id: string\n updated_at: Date | string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n sales_order_lines: {\n id: string\n order_id: string\n product_id: string | null\n product_variant_id: string | null\n name: string | null\n kind: 'product' | 'service' | 'shipping' | 'discount' | 'adjustment'\n currency_code: string\n quantity: string | null\n unit_price_net: string\n unit_price_gross: string\n tax_rate: string\n total_net_amount: string\n total_gross_amount: string\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n}\n\ntype ClaimedQuantityDb = SalesReferenceDb & {\n warranty_claims: {\n id: string\n status: string\n tenant_id: string\n organization_id: string\n deleted_at: Date | null\n }\n warranty_claim_lines: {\n id: string\n claim_id: string\n order_line_id: string | null\n qty_claimed: string | null\n line_status: string\n tenant_id: string\n organization_id: string\n deleted_at: Date | null\n }\n}\n\nexport type ClaimedQuantityLine = {\n id?: string | null\n orderLineId?: string | null\n qtyClaimed: string | number\n deletedAt?: Date | string | null\n}\n\nfunction isMissingReferenceTableError(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false\n const candidate = err as { code?: unknown; message?: unknown }\n return candidate.code === '42P01'\n || (typeof candidate.message === 'string' && candidate.message.includes('does not exist'))\n}\n\nasync function querySalesReferenceRow(\n ctx: CommandRuntimeContext,\n table: SalesReferenceTable,\n scope: WarrantyClaimScope,\n id: string,\n select: string[],\n): Promise<Record<string, unknown> | null | undefined> {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<SalesReferenceDb>()\n try {\n const row = await db\n .selectFrom(table)\n .select(select as never[])\n .where('id' as never, '=', id as never)\n .where('tenant_id' as never, '=', scope.tenantId as never)\n .where('organization_id' as never, '=', scope.organizationId as never)\n .where('deleted_at' as never, 'is', null)\n .executeTakeFirst()\n return (row as Record<string, unknown> | undefined) ?? null\n } catch (err) {\n if (isMissingReferenceTableError(err)) return undefined\n throw err\n }\n}\n\nasync function querySalesOrderLineReferences(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n ids: string[],\n select: string[] = ['id', 'order_id'],\n): Promise<Record<string, unknown>[] | undefined> {\n if (ids.length === 0) return []\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<SalesReferenceDb>()\n try {\n const rows = await db\n .selectFrom('sales_order_lines')\n .select(select as never[])\n .where('id', 'in', ids)\n .where('tenant_id', '=', scope.tenantId)\n .where('organization_id', '=', scope.organizationId)\n .where('deleted_at', 'is', null)\n .execute()\n return rows as Record<string, unknown>[]\n } catch (err) {\n if (isMissingReferenceTableError(err)) return undefined\n throw err\n }\n}\n\nconst CLAIMED_QUANTITY_SCALE = 10_000n\nconst TAX_RATE_FORMULA_SCALE = 1_000_000n\n\nfunction claimedQuantityUnits(value: string | number | null | undefined): bigint | null {\n if (value === null || value === undefined) return null\n let normalized = String(value).trim()\n if (/e/i.test(normalized)) {\n const numeric = Number(normalized)\n if (!Number.isFinite(numeric)) return null\n normalized = numeric.toFixed(4)\n }\n const match = /^([+-]?)(\\d+)(?:\\.(\\d+))?$/.exec(normalized)\n if (!match) return null\n const [, sign, whole, fraction = ''] = match\n const scaledFraction = fraction.slice(0, 4).padEnd(4, '0')\n let units = BigInt(whole) * CLAIMED_QUANTITY_SCALE + BigInt(scaledFraction)\n if (fraction.length > 4 && fraction[4] >= '5') units += 1n\n return sign === '-' ? -units : units\n}\n\nfunction roundHalfUpDivision(numerator: bigint, denominator: bigint): bigint {\n if (denominator <= 0n) throw new Error('[internal] Positive denominator required')\n if (numerator < 0n) return -roundHalfUpDivision(-numerator, denominator)\n return (numerator + denominator / 2n) / denominator\n}\n\nfunction formatScaledUnits(units: bigint): string {\n const sign = units < 0n ? '-' : ''\n const absolute = units < 0n ? -units : units\n const whole = absolute / CLAIMED_QUANTITY_SCALE\n const fraction = String(absolute % CLAIMED_QUANTITY_SCALE).padStart(4, '0')\n return `${sign}${whole}.${fraction}`\n}\n\nfunction netUnitsFromGross(grossUnits: bigint, taxRateUnits: bigint): bigint {\n const denominator = TAX_RATE_FORMULA_SCALE + taxRateUnits\n return roundHalfUpDivision(grossUnits * TAX_RATE_FORMULA_SCALE, denominator)\n}\n\nexport async function assertClaimedQtyWithinSold(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n claimIdOrPendingLines: string | readonly ClaimedQuantityLine[],\n candidateLine: ClaimedQuantityLine,\n): Promise<void> {\n const orderLineId = candidateLine.orderLineId ?? null\n if (!orderLineId || !resolveOptionalEntityId('sales', 'sales_order_line')) return\n\n const salesLine = await querySalesReferenceRow(ctx, 'sales_order_lines', scope, orderLineId, ['id', 'quantity'])\n const soldQuantity = claimedQuantityUnits(salesLine?.quantity as string | number | null | undefined)\n if (salesLine === undefined || salesLine === null || soldQuantity === null) return\n\n let lines: readonly ClaimedQuantityLine[]\n if (typeof claimIdOrPendingLines === 'string') {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claimIdOrPendingLines,\n orderLineId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n {},\n scope,\n )\n } else {\n lines = claimIdOrPendingLines\n }\n\n let claimedQuantity = claimedQuantityUnits(candidateLine.qtyClaimed) ?? 0n\n for (const line of lines) {\n if (line.deletedAt || (line.orderLineId ?? null) !== orderLineId) continue\n if (candidateLine.id != null && line.id === candidateLine.id) continue\n claimedQuantity += claimedQuantityUnits(line.qtyClaimed) ?? 0n\n }\n if (claimedQuantity > soldQuantity) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.qtyExceedsOrdered' })\n }\n}\n\nexport async function assertPendingClaimQuantitiesWithinSold(\n em: EntityManager,\n scope: WarrantyClaimScope,\n pendingLinesByOrderLine: ReadonlyMap<string, readonly ClaimedQuantityLine[]>,\n options: { currentClaimId: string; excludedLineIds?: ReadonlySet<string> },\n): Promise<void> {\n const db = em.getKysely<ClaimedQuantityDb>()\n const orderLineIds = Array.from(pendingLinesByOrderLine.keys()).sort((left, right) => left.localeCompare(right))\n for (const orderLineId of orderLineIds) {\n let soldRow: { id: string; quantity: string | null } | undefined\n try {\n soldRow = await db\n .selectFrom('sales_order_lines')\n .select(['id', 'quantity'])\n .where('id', '=', orderLineId)\n .where('tenant_id', '=', scope.tenantId)\n .where('organization_id', '=', scope.organizationId)\n .where('deleted_at', 'is', null)\n .forUpdate()\n .executeTakeFirst()\n } catch (err) {\n if (isMissingReferenceTableError(err)) return\n throw err\n }\n const soldQuantity = claimedQuantityUnits(soldRow?.quantity)\n if (!soldRow || soldQuantity === null) continue\n\n const persistedRows = await db\n .selectFrom('warranty_claim_lines')\n .innerJoin('warranty_claims', 'warranty_claims.id', 'warranty_claim_lines.claim_id')\n .select(['warranty_claim_lines.id', 'warranty_claim_lines.qty_claimed'])\n .where('warranty_claim_lines.order_line_id', '=', orderLineId)\n .where('warranty_claim_lines.tenant_id', '=', scope.tenantId)\n .where('warranty_claim_lines.organization_id', '=', scope.organizationId)\n .where('warranty_claim_lines.deleted_at', 'is', null)\n .where('warranty_claim_lines.line_status', '!=', 'rejected')\n .where('warranty_claims.tenant_id', '=', scope.tenantId)\n .where('warranty_claims.organization_id', '=', scope.organizationId)\n .where('warranty_claims.id', '=', options.currentClaimId)\n .where('warranty_claims.deleted_at', 'is', null)\n .where('warranty_claims.status', '!=', 'cancelled')\n .execute()\n\n let claimedQuantity = 0n\n for (const row of persistedRows) {\n if (options.excludedLineIds?.has(row.id)) continue\n claimedQuantity += claimedQuantityUnits(row.qty_claimed) ?? 0n\n }\n for (const line of pendingLinesByOrderLine.get(orderLineId) ?? []) {\n claimedQuantity += claimedQuantityUnits(line.qtyClaimed) ?? 0n\n }\n if (claimedQuantity > soldQuantity) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.qtyExceedsOrdered' })\n }\n }\n}\n\ntype CustomerEntitiesDb = {\n customer_entities: {\n id: string\n display_name: string | null\n tenant_id: string | null\n organization_id: string | null\n deleted_at: Date | null\n }\n}\n\nfunction isMissingCustomerTableError(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false\n const candidate = err as { code?: unknown; message?: unknown }\n return candidate.code === '42P01'\n || (typeof candidate.message === 'string'\n && candidate.message.includes('customer_entities')\n && candidate.message.includes('does not exist'))\n}\n\nasync function assertCustomerExists(\n ctx: CommandRuntimeContext,\n customerId: string,\n scope: WarrantyClaimScope,\n): Promise<void> {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<CustomerEntitiesDb>()\n let row: { id: string } | undefined\n try {\n row = await db\n .selectFrom('customer_entities')\n .select('id')\n .where('id', '=', customerId)\n .where('tenant_id', '=', scope.tenantId)\n .where('organization_id', '=', scope.organizationId)\n .where('deleted_at', 'is', null)\n .executeTakeFirst()\n } catch (err) {\n if (isMissingCustomerTableError(err)) return\n throw err\n }\n if (!row) throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidInput' })\n}\n\nasync function resolveCustomerName(\n ctx: CommandRuntimeContext,\n customerId: string | null | undefined,\n scope: WarrantyClaimScope,\n fallback: string | null | undefined,\n options: { strict: boolean } = { strict: false },\n): Promise<string | null> {\n if (!customerId) return fallback ?? null\n if (options.strict) await assertCustomerExists(ctx, customerId, scope)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<CustomerEntitiesDb>()\n let customer: Record<string, unknown> | undefined\n try {\n customer = await db\n .selectFrom('customer_entities')\n .select(['id', 'display_name'] as never[])\n .where('id' as never, '=', customerId as never)\n .where('tenant_id' as never, '=', scope.tenantId as never)\n .where('organization_id' as never, '=', scope.organizationId as never)\n .where('deleted_at' as never, 'is', null)\n .executeTakeFirst() as Record<string, unknown> | undefined\n } catch (err) {\n if (!isMissingCustomerTableError(err)) throw err\n return fallback ?? null\n }\n if (!customer) return fallback ?? null\n let encryption: {\n decryptEntityPayload: (entityId: string, payload: Record<string, unknown>, tenantId: string | null, organizationId?: string | null) => Promise<Record<string, unknown>>\n } | null = null\n try {\n encryption = ctx.container.resolve('tenantEncryptionService')\n } catch {\n encryption = null\n }\n if (encryption) {\n try {\n customer = await encryption.decryptEntityPayload('customers:customer_entity', customer, scope.tenantId, scope.organizationId)\n } catch {\n return fallback ?? null\n }\n }\n return readSafeDecryptedString(readCustomerName(customer)) ?? fallback ?? null\n}\n\nasync function resolveOrderNumber(\n ctx: CommandRuntimeContext,\n orderId: string | null | undefined,\n scope: WarrantyClaimScope,\n fallback: string | null | undefined,\n): Promise<string | null> {\n if (!orderId) return null\n const row = await querySalesReferenceRow(ctx, 'sales_orders', scope, orderId, ['id', 'order_number'])\n if (!row) return fallback ?? null\n return readString(row, 'order_number') ?? fallback ?? null\n}\n\ntype CustomerUsersDb = {\n customer_users: {\n id: string\n tenant_id: string | null\n organization_id: string | null\n customer_entity_id: string | null\n is_active: boolean\n deleted_at: Date | null\n }\n}\n\nasync function resolvePortalRecipientUserIds(\n ctx: CommandRuntimeContext,\n claim: WarrantyClaim,\n): Promise<string[]> {\n if (!claim.customerId) return []\n try {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const db = em.getKysely<CustomerUsersDb>()\n const rows = await db\n .selectFrom('customer_users')\n .select('id')\n .where('tenant_id', '=', claim.tenantId)\n .where('organization_id', '=', claim.organizationId)\n .where('customer_entity_id', '=', claim.customerId)\n .where('is_active', '=', true)\n .where('deleted_at', 'is', null)\n .limit(100)\n .execute()\n return rows.map((row) => row.id)\n } catch {\n return []\n }\n}\n\nasync function emitClaimStatusChanged(\n ctx: CommandRuntimeContext,\n claim: WarrantyClaim,\n fromStatus: WarrantyClaimStatus,\n toStatus: WarrantyClaimStatus,\n): Promise<void> {\n const payload = {\n ...claimEventPayload(claim),\n fromStatus,\n toStatus,\n }\n await emitWarrantyClaimsEvent('warranty_claims.claim.status_changed', payload, claimPersistentEmitOptions(claim))\n const recipientUserIds = await resolvePortalRecipientUserIds(ctx, claim)\n if (recipientUserIds.length === 0) return\n await emitWarrantyClaimsEvent('warranty_claims.claim.portal_status_changed', {\n ...payload,\n recipientUserIds,\n }, claimPersistentEmitOptions(claim))\n}\n\nasync function emitCustomerVisibleCommentAdded(\n ctx: CommandRuntimeContext,\n claim: WarrantyClaim,\n input: CommentClaimInput,\n): Promise<void> {\n const recipientUserIds = await resolvePortalRecipientUserIds(ctx, claim)\n if (recipientUserIds.length === 0) return\n await emitWarrantyClaimsEvent('warranty_claims.claim.comment_added', {\n ...claimEventPayload(claim),\n visibility: input.visibility,\n actorCustomerId: input.actorCustomerId ?? null,\n recipientUserIds,\n }, claimPersistentEmitOptions(claim))\n}\n\nfunction applySlaPause(\n em: EntityManager,\n claim: WarrantyClaim,\n fromStatus: WarrantyClaimStatus,\n toStatus: WarrantyClaimStatus,\n now: Date,\n effectiveSettings: WarrantyClaimEffectiveSettings,\n): void {\n if (fromStatus === toStatus || toStatus !== 'info_requested' || !effectiveSettings.slaPauseOnInfoRequested) return\n claim.slaPausedAt = now\n appendClaimEvent(em, claim, 'system', {\n visibility: 'customer',\n payload: { action: 'sla_paused' },\n actorUserId: null,\n })\n}\n\nfunction applySlaResume(\n em: EntityManager,\n claim: WarrantyClaim,\n fromStatus: WarrantyClaimStatus,\n toStatus: WarrantyClaimStatus,\n now: Date,\n effectiveSettings: WarrantyClaimEffectiveSettings,\n): void {\n if (fromStatus !== 'info_requested' || toStatus === 'info_requested' || !claim.slaPausedAt) return\n // Preserve the business time that was still remaining when the clock stopped;\n // a claim already past due when paused stays past due.\n if (claim.slaDueAt && claim.slaDueAt.getTime() > claim.slaPausedAt.getTime()) {\n const remainingBusinessMillis = businessMillisBetween(claim.slaPausedAt, claim.slaDueAt, effectiveSettings.businessHours)\n claim.slaDueAt = addBusinessMillis(now, remainingBusinessMillis, effectiveSettings.businessHours)\n }\n claim.slaPausedAt = null\n claim.slaAtRiskNotifiedAt = null\n claim.slaBreachedNotifiedAt = null\n appendClaimEvent(em, claim, 'system', {\n visibility: 'customer',\n payload: { action: 'sla_resumed' },\n actorUserId: null,\n })\n}\n\nfunction resolveOptionalEntityId(moduleId: string, entity: string): EntityId | null {\n const registry = E as unknown as Record<string, Record<string, string> | undefined>\n const value = registry[moduleId]?.[entity]\n return typeof value === 'string' ? (value as EntityId) : null\n}\n\nasync function lookupSalesReference(\n ctx: CommandRuntimeContext,\n entityId: EntityId | null,\n table: SalesReferenceTable,\n scope: WarrantyClaimScope,\n id: string,\n select: string[],\n): Promise<Record<string, unknown> | ReferenceLookupResult> {\n if (!entityId) return 'unknown'\n const row = await querySalesReferenceRow(ctx, table, scope, id, select)\n if (row === undefined) return 'unknown'\n return row ?? 'missing'\n}\n\nfunction assertValidSalesReference(result: Record<string, unknown> | ReferenceLookupResult): asserts result is Record<string, unknown> | 'unknown' {\n if (result === 'missing') {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidReference' })\n }\n}\n\nexport async function validateClaimReferences(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n input: ReferenceValidationInput,\n): Promise<void> {\n if (input.orderId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_order'), 'sales_orders', scope, input.orderId, ['id'])\n assertValidSalesReference(result)\n }\n if (input.replacementOrderId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_order'), 'sales_orders', scope, input.replacementOrderId, ['id'])\n assertValidSalesReference(result)\n }\n if (input.salesReturnId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_return'), 'sales_returns', scope, input.salesReturnId, ['id'])\n assertValidSalesReference(result)\n }\n if (input.creditMemoId) {\n const result = await lookupSalesReference(ctx, resolveOptionalEntityId('sales', 'sales_credit_memo'), 'sales_credit_memos', scope, input.creditMemoId, ['id'])\n assertValidSalesReference(result)\n }\n const lineRefs = input.lineOrderRefs ?? []\n if (lineRefs.length === 0 || !resolveOptionalEntityId('sales', 'sales_order_line')) return\n const lineRows = await querySalesOrderLineReferences(\n ctx,\n scope,\n Array.from(new Set(lineRefs.map((lineRef) => lineRef.orderLineId))),\n )\n if (lineRows === undefined) return\n const lineRowsById = new Map(lineRows.map((row) => [readString(row, 'id'), row]))\n for (const lineRef of lineRefs) {\n const result = lineRowsById.get(lineRef.orderLineId)\n if (!result) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidReference' })\n }\n if (lineRef.orderId && readString(result, 'order_id') !== lineRef.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidReference' })\n }\n }\n}\n\nasync function validateAssigneeUser(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n assigneeUserId: string | null | undefined,\n): Promise<void> {\n if (!assigneeUserId) return\n const assignable = await isAssignableStaffUser({\n container: ctx.container,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n }, assigneeUserId)\n if (!assignable) throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidAssignee' })\n}\n\nfunction applyClaimAssignment(\n em: EntityManager,\n claim: WarrantyClaim,\n assigneeUserId: string | null,\n actorUserId: string | null,\n now: Date,\n): void {\n claim.assigneeUserId = assigneeUserId\n claim.updatedAt = now\n appendClaimEvent(em, claim, 'assignment', {\n visibility: 'internal',\n payload: { assigneeUserId: claim.assigneeUserId },\n actorUserId,\n })\n}\n\nfunction allowedUpdateFields(status: WarrantyClaimStatus): Set<ClaimUpdateField> {\n if (intakeStatuses.has(status)) return new Set(CLAIM_INTAKE_UPDATE_FIELDS)\n if (fulfillmentStatuses.has(status)) return new Set(CLAIM_FULFILLMENT_UPDATE_FIELDS)\n return new Set()\n}\n\nfunction assertClaimUpdateFields(claim: WarrantyClaim, input: ClaimUpdateInput): void {\n const keys = [...CLAIM_INTAKE_UPDATE_FIELDS, ...CLAIM_FULFILLMENT_UPDATE_FIELDS]\n const requested = keys.filter((key) => hasOwn(input, key))\n if (!requested.length) return\n const allowed = allowedUpdateFields(claim.status)\n const disallowed = requested.filter((key) => !allowed.has(key))\n if (disallowed.length > 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.fieldLocked' })\n }\n}\n\nfunction applyClaimUpdate(claim: WarrantyClaim, input: ClaimUpdateInput, customerName: string | null, orderNumber: string | null): void {\n if (hasOwn(input, 'customerId')) claim.customerId = input.customerId ?? null\n if (hasOwn(input, 'customerName')) claim.customerName = customerName\n if (hasOwn(input, 'orderId')) {\n claim.orderId = input.orderId ?? null\n claim.orderNumber = orderNumber\n }\n if (hasOwn(input, 'reasonCode')) claim.reasonCode = input.reasonCode ?? null\n if (hasOwn(input, 'priority') && input.priority) claim.priority = input.priority\n if (hasOwn(input, 'notes')) claim.notes = input.notes ?? null\n if (hasOwn(input, 'advanceReplacement')) claim.advanceReplacement = input.advanceReplacement ?? false\n if (hasOwn(input, 'replacementOrderId')) claim.replacementOrderId = input.replacementOrderId ?? null\n if (hasOwn(input, 'advanceShippedAt')) claim.advanceShippedAt = input.advanceShippedAt ?? null\n if (hasOwn(input, 'salesReturnId')) claim.salesReturnId = input.salesReturnId ?? null\n if (hasOwn(input, 'creditMemoId')) claim.creditMemoId = input.creditMemoId ?? null\n if (hasOwn(input, 'vendorName')) claim.vendorName = input.vendorName ?? null\n if (hasOwn(input, 'vendorRef')) claim.vendorRef = input.vendorRef ?? null\n if (hasOwn(input, 'resolutionSummary')) claim.resolutionSummary = input.resolutionSummary ?? null\n claim.updatedAt = new Date()\n}\n\nasync function recomputeClaimRollups(em: EntityManager, claim: WarrantyClaim): Promise<void> {\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claim.id,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n deletedAt: null,\n },\n {},\n { tenantId: claim.tenantId, organizationId: claim.organizationId },\n )\n const totals = computeHeaderRollups(lines, { claimType: claim.claimType })\n claim.totalClaimedAmount = String(totals.totalClaimedAmount)\n claim.totalApprovedAmount = String(totals.totalApprovedAmount)\n}\n\nfunction assertCanResolve(lines: readonly WarrantyClaimLine[]): void {\n if (!canResolveWithLineStatuses(lines)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n}\n\nfunction assertVendorRecoveryLines(lines: readonly WarrantyClaimLine[], requestedLineIds: readonly string[]): void {\n if (lines.length !== requestedLineIds.length) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.vendorRecoveryNeedsResolvedLines' })\n }\n for (const line of lines) {\n if (line.lineStatus !== 'resolved' || line.vendorClaimLineId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.vendorRecoveryNeedsResolvedLines' })\n }\n }\n}\n\nfunction buildClaimLog(\n actionLabel: string,\n resourceId: string,\n snapshots: { before?: unknown; after?: unknown },\n): {\n actionLabel: string\n resourceKind: string\n resourceId: string\n tenantId: string | null\n organizationId: string | null\n snapshotBefore: unknown\n snapshotAfter: unknown\n payload: { undo: ClaimUndoPayload }\n} {\n const after = snapshots.after as ClaimSnapshot | null | undefined\n const before = snapshots.before as ClaimSnapshot | null | undefined\n return {\n actionLabel,\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId,\n tenantId: after?.tenantId ?? before?.tenantId ?? null,\n organizationId: after?.organizationId ?? before?.organizationId ?? null,\n snapshotBefore: before ?? null,\n snapshotAfter: after ?? null,\n payload: { undo: { before: before ?? null, after: after ?? null } },\n }\n}\n\nconst createClaimCommand: CommandHandler<ClaimCreateInput, { claimId: string }> = {\n id: 'warranty_claims.claim.create',\n isUndoable: true,\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n await validateClaimReferences(ctx, scope, {\n orderId: input.orderId ?? null,\n salesReturnId: input.salesReturnId ?? null,\n replacementOrderId: input.replacementOrderId ?? null,\n creditMemoId: null,\n lineOrderRefs: (input.lines ?? [])\n .filter((line): line is ClaimInitialLineCreateInput & { orderLineId: string } => typeof line.orderLineId === 'string')\n .map((line) => ({ orderLineId: line.orderLineId, orderId: input.orderId ?? null })),\n })\n await assertOrderBelongsToCustomer(em, scope, input.orderId ?? null, input.customerId ?? null)\n const pendingLines = (input.lines ?? []).map((line) => ({\n orderLineId: line.orderLineId ?? null,\n qtyClaimed: amountString(line.qtyClaimed, '1') ?? '1',\n }))\n const pendingLinesByOrderLine = new Map<string, ClaimedQuantityLine[]>()\n for (const line of pendingLines) {\n if (!line.orderLineId) continue\n const grouped = pendingLinesByOrderLine.get(line.orderLineId) ?? []\n grouped.push(line)\n pendingLinesByOrderLine.set(line.orderLineId, grouped)\n }\n const numberGenerator = resolveClaimNumberGenerator(ctx, em)\n const generated = await numberGenerator.generate({\n claimType: input.claimType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const customerName = await resolveCustomerName(ctx, input.customerId, scope, input.customerName, { strict: true })\n // A linked order derives its number from the order itself (falling back to any supplied\n // reference); without a linked order, persist the free-text reference as the display number\n // so the portal \"my order isn't listed\" path is captured (WQA-002).\n const orderNumber = input.orderId\n ? await resolveOrderNumber(ctx, input.orderId, scope, input.orderNumber ?? null)\n : (input.orderNumber ?? null)\n const claimId = randomUUID()\n let claim!: WarrantyClaim\n let createdLines: WarrantyClaimLine[] = []\n\n await withAtomicFlush(em, [\n async () => {\n await assertPendingClaimQuantitiesWithinSold(em, scope, pendingLinesByOrderLine, { currentClaimId: claimId })\n claim = em.create(WarrantyClaim, {\n id: claimId,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n claimNumber: generated.number,\n claimType: input.claimType,\n status: 'draft',\n channel: input.channel ?? 'staff',\n priority: input.priority ?? 'normal',\n customerId: input.customerId ?? null,\n customerName,\n externalRef: input.externalRef ?? null,\n intakeMessageRef: input.intakeMessageRef ?? null,\n contactEmail: input.contactEmail ?? null,\n vendorName: input.vendorName ?? null,\n vendorRef: input.vendorRef ?? null,\n orderId: input.orderId ?? null,\n orderNumber,\n salesReturnId: input.salesReturnId ?? null,\n replacementOrderId: input.replacementOrderId ?? null,\n creditMemoId: null,\n sourceClaimId: null,\n advanceReplacement: input.advanceReplacement ?? false,\n advanceShippedAt: input.advanceShippedAt ?? null,\n reasonCode: input.reasonCode ?? null,\n rejectionReasonCode: input.rejectionReasonCode ?? null,\n resolutionSummary: input.resolutionSummary ?? null,\n notes: input.notes ?? null,\n currencyCode: input.currencyCode ?? null,\n totalClaimedAmount: '0',\n totalApprovedAmount: '0',\n totalRecoveredAmount: '0',\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(claim)\n createdLines = (input.lines ?? []).map((lineInput, index) => {\n const line = em.create(WarrantyClaimLine, buildInitialLineData(claim, lineInput, index))\n em.persist(line)\n return line\n })\n const totals = computeHeaderRollups(createdLines, { claimType: claim.claimType })\n claim.totalClaimedAmount = String(totals.totalClaimedAmount)\n claim.totalApprovedAmount = String(totals.totalApprovedAmount)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n () => stampEntitlementSourceIfResolvable(ctx, em, claim, input, scope),\n ], { transaction: true, label: 'warranty_claims.claim.create' })\n\n await emitClaimCrud(ctx, 'created', claim)\n await Promise.all(createdLines.map((line) => emitLineCrud(ctx, 'created', line)))\n return { claimId: claim.id }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.create', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n let lines: WarrantyClaimLine[] = []\n await withAtomicFlush(em, [\n async () => {\n const current = await requireCurrentUndoSnapshot(em, after)\n claim = current.claim\n lines = current.lines.filter((line) => !line.deletedAt)\n const now = new Date()\n claim.deletedAt = now\n claim.updatedAt = now\n for (const line of lines) {\n line.deletedAt = now\n line.updatedAt = now\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.create.undo' })\n await emitClaimUndoCrud(ctx, 'deleted', claim)\n await Promise.all(lines.map((line) => emitLineUndoCrud(ctx, 'deleted', line)))\n },\n}\n\nconst updateClaimCommand: CommandHandler<ClaimUpdateInput, { claimId: string }> = {\n id: 'warranty_claims.claim.update',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimUpdateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimUpdateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n assertClaimUpdateFields(claim, input)\n await validateClaimReferences(ctx, scope, {\n orderId: hasOwn(input, 'orderId') && (input.orderId ?? null) !== (claim.orderId ?? null) ? input.orderId ?? null : null,\n salesReturnId: hasOwn(input, 'salesReturnId') && (input.salesReturnId ?? null) !== (claim.salesReturnId ?? null) ? input.salesReturnId ?? null : null,\n replacementOrderId: hasOwn(input, 'replacementOrderId') && (input.replacementOrderId ?? null) !== (claim.replacementOrderId ?? null) ? input.replacementOrderId ?? null : null,\n creditMemoId: hasOwn(input, 'creditMemoId') && (input.creditMemoId ?? null) !== (claim.creditMemoId ?? null) ? input.creditMemoId ?? null : null,\n })\n const effectiveOrderId = hasOwn(input, 'orderId') ? (input.orderId ?? null) : (claim.orderId ?? null)\n const effectiveCustomerId = hasOwn(input, 'customerId') ? (input.customerId ?? null) : (claim.customerId ?? null)\n await assertOrderBelongsToCustomer(em, scope, effectiveOrderId, effectiveCustomerId)\n const customerChanged = hasOwn(input, 'customerId') && (input.customerId ?? null) !== (claim.customerId ?? null)\n const shouldRefreshCustomerName = hasOwn(input, 'customerId') || hasOwn(input, 'customerName')\n const customerName = shouldRefreshCustomerName\n ? await resolveCustomerName(ctx, input.customerId ?? claim.customerId, scope, input.customerName ?? claim.customerName, { strict: customerChanged })\n : claim.customerName ?? null\n const orderNumber = hasOwn(input, 'orderId')\n ? await resolveOrderNumber(ctx, input.orderId, scope, (input.orderId ?? null) === (claim.orderId ?? null) ? claim.orderNumber : null)\n : claim.orderNumber ?? null\n await withAtomicFlush(em, [\n () => applyClaimUpdate(claim, input, customerName, orderNumber),\n ], { transaction: true, label: 'warranty_claims.claim.update' })\n await emitClaimCrud(ctx, 'updated', claim)\n return { claimId: claim.id }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimUpdateSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.update', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) return throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n },\n ], { transaction: true, label: 'warranty_claims.claim.update.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst deleteClaimCommand: CommandHandler<ClaimDeleteInput, { claimId: string }> = {\n id: 'warranty_claims.claim.delete',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimDeleteSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimDeleteSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n if (!deletableStatuses.has(claim.status)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.deleteNotAllowed' })\n }\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n await withAtomicFlush(em, [\n () => {\n const now = new Date()\n claim.deletedAt = now\n claim.updatedAt = now\n for (const line of lines) {\n line.deletedAt = now\n line.updatedAt = now\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.delete' })\n await emitClaimCrud(ctx, 'deleted', claim)\n await Promise.all(lines.map((line) => emitLineCrud(ctx, 'deleted', line)))\n return { claimId: claim.id }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimDeleteSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.delete', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) return throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n },\n ], { transaction: true, label: 'warranty_claims.claim.delete.undo' })\n await emitClaimUndoCrud(ctx, 'created', claim)\n const restoredLines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n await Promise.all(restoredLines.map((line) => emitLineCrud(ctx, 'created', line)))\n },\n}\n\nconst submitClaimCommand: CommandHandler<SubmitClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.submit',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(submitClaimSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n if (claim.status !== 'draft') {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n const fromStatus = claim.status\n let autoApproved = false\n let effectiveSettings: WarrantyClaimEffectiveSettings | null = null\n await withAtomicFlush(em, [\n async () => {\n effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n const submittedAt = new Date()\n claim.status = 'submitted'\n claim.submittedAt = submittedAt\n claim.slaDueAt = addBusinessMillis(submittedAt, effectiveSettings.slaHours * 60 * 60 * 1000, effectiveSettings.businessHours)\n claim.slaAtRiskNotifiedAt = null\n claim.slaBreachedNotifiedAt = null\n claim.updatedAt = submittedAt\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: { from: fromStatus, to: 'submitted' },\n actorUserId: input.actorCustomerId ? null : (ctx.auth?.sub ?? null),\n actorCustomerId: input.actorCustomerId ?? null,\n })\n },\n async () => {\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claim.id,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n deletedAt: null,\n },\n {},\n scope,\n )\n const risk = await evaluateClaimRisk(em, claim, lines)\n const settings = effectiveSettings ?? await resolveEffectiveWarrantyClaimSettings(em, scope)\n const evaluator = ctx.container.resolve<WarrantyAdjudicationEvaluator>('warrantyAdjudicationEvaluator')\n const { decision } = await evaluator.evaluate({\n claim,\n lines,\n settings,\n risk,\n container: ctx.container,\n em,\n scope,\n })\n if (decision === 'auto_approve') {\n claim.status = 'approved'\n claim.updatedAt = new Date()\n autoApproved = true\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: { from: 'submitted', to: 'approved' },\n actorUserId: null,\n })\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: {\n action: 'auto_approved',\n maxAmount: settings.autoApproveMaxAmount,\n currencyCode: settings.autoApproveCurrencyCode,\n },\n actorUserId: null,\n })\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.submit' })\n await emitClaimCrud(ctx, 'updated', claim)\n const payload = claimEventPayload(claim)\n await emitWarrantyClaimsEvent('warranty_claims.claim.submitted', payload, claimPersistentEmitOptions(claim))\n await emitClaimStatusChanged(ctx, claim, autoApproved ? 'submitted' : fromStatus, autoApproved ? 'approved' : 'submitted')\n return { claimId: claim.id }\n },\n}\n\nconst transitionClaimCommand: CommandHandler<TransitionClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.transition',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(transitionClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(transitionClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n const fromStatus = claim.status\n assertTransition(fromStatus, input.toStatus)\n if (input.toStatus === 'cancelled' && !preReceivedStatuses.has(fromStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n if (input.toStatus === 'rejected' && !input.rejectionReasonCode) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.invalidTransition' })\n }\n const lines = input.toStatus === 'resolved'\n ? await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n claim: claim.id,\n tenantId: claim.tenantId,\n organizationId: claim.organizationId,\n deletedAt: null,\n },\n {},\n { tenantId: claim.tenantId, organizationId: claim.organizationId },\n )\n : []\n if (input.toStatus === 'resolved') assertCanResolve(lines)\n await withAtomicFlush(em, [\n async () => {\n const effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n const now = new Date()\n claim.status = input.toStatus\n if (input.toStatus === 'rejected') claim.rejectionReasonCode = input.rejectionReasonCode ?? null\n if (input.toStatus === 'resolved') {\n claim.resolvedAt = now\n if (hasOwn(input, 'resolutionSummary')) claim.resolutionSummary = input.resolutionSummary ?? null\n }\n if (input.toStatus === 'closed') claim.closedAt = now\n applySlaResume(em, claim, fromStatus, input.toStatus, now, effectiveSettings)\n applySlaPause(em, claim, fromStatus, input.toStatus, now, effectiveSettings)\n claim.awaitingStaffReply = false\n claim.updatedAt = now\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: {\n from: fromStatus,\n to: input.toStatus,\n ...(input.systemNote ? { systemNote: input.systemNote } : {}),\n },\n actorUserId: input.actorCustomerId ? null : (ctx.auth?.sub ?? null),\n actorCustomerId: input.actorCustomerId ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.transition' })\n await emitClaimCrud(ctx, 'updated', claim)\n await emitClaimStatusChanged(ctx, claim, fromStatus, input.toStatus)\n return { claimId: claim.id }\n },\n captureAfter: async (_rawInput, result, ctx) => {\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.transition', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) return throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_status_transition' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.transition.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst assignClaimCommand: CommandHandler<AssignClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.assign',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(assignClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n await validateAssigneeUser(ctx, scope, input.assigneeUserId ?? null)\n await withAtomicFlush(em, [\n () => {\n applyClaimAssignment(em, claim, input.assigneeUserId ?? null, ctx.auth?.sub ?? null, new Date())\n },\n ], { transaction: true, label: 'warranty_claims.claim.assign' })\n await emitClaimCrud(ctx, 'updated', claim)\n await emitWarrantyClaimsEvent('warranty_claims.claim.assigned', {\n ...claimEventPayload(claim),\n assigneeUserId: claim.assigneeUserId,\n }, claimPersistentEmitOptions(claim))\n return { claimId: claim.id }\n },\n}\n\nconst setReturnLabelCommand: CommandHandler<ClaimSetReturnLabelInput, ClaimSetReturnLabelResult> = {\n id: 'warranty_claims.claim.set_return_label',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimSetReturnLabelSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimSetReturnLabelSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n\n await withAtomicFlush(em, [\n () => {\n if (input.labelUrl !== undefined) claim.returnLabelUrl = input.labelUrl\n if (input.trackingNumber !== undefined) claim.returnTrackingNumber = input.trackingNumber\n if (input.carrier !== undefined) claim.returnCarrier = input.carrier\n claim.updatedAt = new Date()\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: {\n action: 'return_label_created',\n carrier: claim.returnCarrier ?? null,\n trackingNumber: claim.returnTrackingNumber ?? null,\n },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.set_return_label' })\n\n await emitClaimCrud(ctx, 'updated', claim)\n await emitWarrantyClaimsEvent('warranty_claims.claim.return_label_created', {\n id: claim.id,\n claimId: claim.id,\n carrier: claim.returnCarrier ?? null,\n trackingNumber: claim.returnTrackingNumber ?? null,\n scope,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n }, claimPersistentEmitOptions(claim))\n\n return {\n claimId: claim.id,\n labelUrl: claim.returnLabelUrl ?? null,\n trackingNumber: claim.returnTrackingNumber ?? null,\n carrier: claim.returnCarrier ?? null,\n }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimSetReturnLabelSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => buildClaimLog('warranty_claims.audit.claim.set_return_label', result.claimId, snapshots),\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) return throwClaimUndoConflict()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_return_label' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.set_return_label.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst escalateClaimCommand: CommandHandler<EscalateClaimInput, EscalateClaimResult> = {\n id: 'warranty_claims.claim.escalate',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(escalateClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n if (input.reassignToUserId) {\n await validateAssigneeUser(ctx, scope, input.reassignToUserId)\n }\n\n let claim: WarrantyClaim | null = null\n let escalated = false\n await withAtomicFlush(em, [\n async () => {\n claim = await requireScopedClaim(em, input.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if ((claim.escalationLevel ?? 0) >= input.toLevel) return\n\n const now = new Date()\n claim.escalationLevel = input.toLevel\n claim.escalatedAt = now\n claim.updatedAt = now\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: {\n action: 'sla_escalated',\n level: input.toLevel,\n reassignToUserId: input.reassignToUserId ?? null,\n },\n actorUserId: ctx.auth?.sub ?? null,\n })\n if (input.reassignToUserId) {\n applyClaimAssignment(em, claim, input.reassignToUserId, ctx.auth?.sub ?? null, now)\n }\n escalated = true\n },\n ], { transaction: true, label: 'warranty_claims.claim.escalate' })\n\n const escalatedClaim = claim as WarrantyClaim | null\n if (!escalatedClaim) {\n throw new CrudHttpError(404, { error: 'warranty_claims.errors.notFound' })\n }\n if (!escalated) {\n return { claimId: escalatedClaim.id, escalationLevel: escalatedClaim.escalationLevel ?? 0, escalated: false }\n }\n\n await emitClaimCrud(ctx, 'updated', escalatedClaim)\n if (input.reassignToUserId) {\n await emitWarrantyClaimsEvent('warranty_claims.claim.assigned', {\n ...claimEventPayload(escalatedClaim),\n assigneeUserId: escalatedClaim.assigneeUserId ?? null,\n }, claimPersistentEmitOptions(escalatedClaim))\n }\n await emitWarrantyClaimsEvent('warranty_claims.claim.escalated', {\n ...claimEventPayload(escalatedClaim),\n level: escalatedClaim.escalationLevel,\n escalationLevel: escalatedClaim.escalationLevel,\n reassignToUserId: input.reassignToUserId ?? null,\n }, claimPersistentEmitOptions(escalatedClaim))\n\n return { claimId: escalatedClaim.id, escalationLevel: escalatedClaim.escalationLevel, escalated: true }\n },\n}\n\nconst commentClaimCommand: CommandHandler<CommentClaimInput, { claimId: string }> = {\n id: 'warranty_claims.claim.comment',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(commentClaimInputSchema, rawInput)\n const scope = resolveScope(ctx, {})\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.claimId, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim)\n let autoResumed = false\n await withAtomicFlush(em, [\n async () => {\n const fromStatus = claim.status\n appendClaimEvent(em, claim, 'comment', {\n visibility: input.visibility,\n body: input.body,\n actorUserId: input.actorCustomerId ? null : (ctx.auth?.sub ?? null),\n actorCustomerId: input.actorCustomerId ?? null,\n })\n claim.awaitingStaffReply = Boolean(input.actorCustomerId)\n claim.updatedAt = new Date()\n if (input.actorCustomerId && fromStatus === 'info_requested') {\n const now = new Date()\n const effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n claim.status = 'in_review'\n applySlaResume(em, claim, fromStatus, 'in_review', now, effectiveSettings)\n claim.updatedAt = now\n autoResumed = true\n appendClaimEvent(em, claim, 'status_changed', {\n visibility: 'customer',\n payload: { from: fromStatus, to: 'in_review' },\n actorUserId: null,\n })\n }\n },\n ], { transaction: true, label: 'warranty_claims.claim.comment' })\n if (input.visibility === 'customer') {\n await emitCustomerVisibleCommentAdded(ctx, claim, input)\n }\n await emitClaimCrud(ctx, 'updated', claim)\n if (autoResumed) {\n await emitClaimStatusChanged(ctx, claim, 'info_requested', 'in_review')\n }\n return { claimId: claim.id }\n },\n}\n\nconst createVendorRecoveryCommand: CommandHandler<VendorRecoveryInput, { claimId: string }> = {\n id: 'warranty_claims.claim.create_vendor_recovery',\n async execute(rawInput, ctx) {\n const input = parseCommandInput(vendorRecoveryInputSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const sourceClaim = await requireScopedClaim(em, input.claimId, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, sourceClaim)\n const preflightLines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n {\n id: { $in: input.lineIds },\n claim: sourceClaim.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n {},\n scope,\n )\n assertVendorRecoveryLines(preflightLines, input.lineIds)\n const numberGenerator = resolveClaimNumberGenerator(ctx, em)\n const generated = await numberGenerator.generate({\n claimType: 'vendor_recovery',\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n let recoveryClaim!: WarrantyClaim\n let copiedLines: WarrantyClaimLine[] = []\n let updatedSourceLines: WarrantyClaimLine[] = []\n\n await em.transactional(async (tx) => {\n const lockedSource = await requireScopedClaim(tx, sourceClaim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n const lockedLines = await findWithDecryption(\n tx,\n WarrantyClaimLine,\n {\n id: { $in: input.lineIds },\n claim: lockedSource.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n scope,\n )\n assertVendorRecoveryLines(lockedLines, input.lineIds)\n updatedSourceLines = lockedLines\n recoveryClaim = tx.create(WarrantyClaim, {\n id: randomUUID(),\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n claimNumber: generated.number,\n claimType: 'vendor_recovery',\n status: 'draft',\n channel: 'staff',\n priority: lockedSource.priority,\n customerId: lockedSource.customerId ?? null,\n customerName: lockedSource.customerName ?? null,\n vendorName: input.vendorName,\n vendorRef: input.vendorRef ?? null,\n sourceClaimId: lockedSource.id,\n advanceReplacement: false,\n currencyCode: lockedSource.currencyCode ?? null,\n totalClaimedAmount: '0',\n totalApprovedAmount: '0',\n totalRecoveredAmount: '0',\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tx.persist(recoveryClaim)\n const lineOrder = new Map(input.lineIds.map((id, index) => [id, index]))\n copiedLines = [...lockedLines]\n .sort((left, right) => (lineOrder.get(left.id) ?? 0) - (lineOrder.get(right.id) ?? 0))\n .map((sourceLine, index) => {\n const copiedLine = tx.create(WarrantyClaimLine, {\n id: randomUUID(),\n claim: recoveryClaim,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n lineNo: index + 1,\n productId: sourceLine.productId ?? null,\n variantId: sourceLine.variantId ?? null,\n sku: sourceLine.sku ?? null,\n productName: sourceLine.productName ?? null,\n orderLineId: sourceLine.orderLineId ?? null,\n serialNumber: sourceLine.serialNumber ?? null,\n lotNumber: sourceLine.lotNumber ?? null,\n purchaseDate: sourceLine.purchaseDate ?? null,\n warrantyMonths: sourceLine.warrantyMonths ?? null,\n warrantyExpiresAt: sourceLine.warrantyExpiresAt ?? null,\n warrantyStatus: sourceLine.warrantyStatus,\n faultCode: sourceLine.faultCode ?? null,\n faultDescription: sourceLine.faultDescription ?? null,\n qtyClaimed: sourceLine.qtyApproved ?? sourceLine.qtyClaimed,\n qtyApproved: sourceLine.qtyApproved ?? null,\n conditionOnReceipt: sourceLine.conditionOnReceipt ?? null,\n inspectionNotes: sourceLine.inspectionNotes ?? null,\n disposition: sourceLine.disposition ?? null,\n lineStatus: 'pending',\n creditAmount: sourceLine.creditAmount ?? null,\n restockingFee: sourceLine.restockingFee ?? null,\n coreChargeAmount: sourceLine.coreChargeAmount ?? null,\n coreCreditAmount: sourceLine.coreCreditAmount ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n sourceLine.vendorClaimLineId = copiedLine.id\n sourceLine.updatedAt = new Date()\n tx.persist(copiedLine)\n return copiedLine\n })\n const totals = computeHeaderRollups(copiedLines)\n recoveryClaim.totalClaimedAmount = String(totals.totalClaimedAmount)\n recoveryClaim.totalApprovedAmount = String(totals.totalApprovedAmount)\n appendClaimEvent(tx, lockedSource, 'system', {\n visibility: 'internal',\n payload: { action: 'vendor_recovery_created', recoveryClaimId: recoveryClaim.id },\n actorUserId: ctx.auth?.sub ?? null,\n })\n appendClaimEvent(tx, recoveryClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'created_from_source_claim', sourceClaimId: lockedSource.id },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await tx.flush()\n })\n\n await emitClaimCrud(ctx, 'created', recoveryClaim)\n await Promise.all(copiedLines.map((line) => emitLineCrud(ctx, 'created', line)))\n await Promise.all(updatedSourceLines.map((line) => emitLineCrud(ctx, 'updated', line)))\n await Promise.all(input.lineIds.map((sourceLineId) => invalidateCrudCache(\n ctx.container,\n 'warranty_claims.claim_line',\n { id: sourceLineId, organizationId: sourceClaim.organizationId, tenantId: sourceClaim.tenantId },\n ctx.auth?.tenantId ?? null,\n 'warranty_claims.vendor_recovery.source_lines',\n )))\n return { claimId: recoveryClaim.id }\n },\n}\n\nconst salesReturnBridgeLogger = createLogger('warranty_claims')\n\nconst SALES_RETURN_ELIGIBLE_CLAIM_STATUSES = new Set<WarrantyClaimStatus>(['approved', 'awaiting_return', 'received', 'inspecting'])\nconst SALES_RETURN_ELIGIBLE_LINE_STATUSES = new Set<WarrantyClaimLineStatus>(['approved', 'received', 'inspected', 'resolved'])\n\ntype ClaimSalesReturnUndoPayload = ClaimUndoPayload & {\n salesReturn?: { id: string; orderId: string; updatedAt: string | null } | null\n}\n\ntype ClaimCreateSalesReturnResult = {\n claimId: string\n salesReturnId: string\n salesReturnUpdatedAt: string | null\n skippedLineIds: string[]\n}\n\nfunction scrubbedDispatchContext(ctx: CommandRuntimeContext): CommandRuntimeContext {\n return { ...ctx, request: undefined }\n}\n\nfunction isSalesQuantityRejection(err: unknown): boolean {\n if (!(err instanceof CrudHttpError) || err.status !== 400) return false\n const body = err.body as { error?: unknown } | null\n const message = typeof body?.error === 'string' ? body.error : ''\n return message.includes('quantityExceedsShipped') || message.includes('Cannot return more than the shipped quantity')\n}\n\nasync function dispatchSalesReturnDelete(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n salesReturnId: string,\n orderId: string,\n): Promise<void> {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute(\n 'sales.returns.delete',\n {\n input: { id: salesReturnId, orderId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n}\n\nconst createSalesReturnCommand: CommandHandler<ClaimCreateSalesReturnInput, ClaimCreateSalesReturnResult> = {\n id: 'warranty_claims.claim.create_sales_return',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimCreateSalesReturnSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateSalesReturnSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n if (!claim.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnRequiresOrder' })\n }\n if (!SALES_RETURN_ELIGIBLE_CLAIM_STATUSES.has(claim.status as WarrantyClaimStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnStatusNotEligible' })\n }\n if (claim.salesReturnId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnAlreadyLinked' })\n }\n if (!resolveOptionalEntityId('sales', 'sales_return')) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesUnavailable' })\n }\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n const eligibleLines: Array<{ orderLineId: string; quantity: string }> = []\n const skippedLineIds: string[] = []\n for (const line of lines) {\n const effectiveQty = line.qtyApproved ?? line.qtyClaimed\n const quantityUnits = claimedQuantityUnits(effectiveQty) ?? 0n\n const eligible = Boolean(line.orderLineId)\n && SALES_RETURN_ELIGIBLE_LINE_STATUSES.has(line.lineStatus as WarrantyClaimLineStatus)\n && quantityUnits > 0n\n && quantityUnits % CLAIMED_QUANTITY_SCALE === 0n\n if (eligible && line.orderLineId) {\n eligibleLines.push({ orderLineId: line.orderLineId, quantity: String(effectiveQty) })\n } else {\n skippedLineIds.push(line.id)\n }\n }\n if (eligibleLines.length === 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnNoEligibleLines' })\n }\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n let salesReturnId: string\n try {\n const { result: dispatchedResult } = await commandBus.execute<\n { orderId: string; reason?: string; tenantId: string; organizationId: string; lines: Array<{ orderLineId: string; quantity: string }> },\n { returnId: string }\n >(\n 'sales.returns.create',\n {\n input: {\n orderId: claim.orderId,\n reason: claim.claimNumber,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n lines: eligibleLines,\n },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n if (!dispatchedResult?.returnId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n }\n salesReturnId = dispatchedResult.returnId\n } catch (err) {\n if (isSalesQuantityRejection(err)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnQuantityRejected' })\n }\n throw err\n }\n let salesReturnUpdatedAt: string | null = null\n try {\n const createdReturnRow = await querySalesReferenceRow(ctx, 'sales_returns', scope, salesReturnId, ['id', 'updated_at'])\n salesReturnUpdatedAt = createdReturnRow?.updated_at\n ? new Date(createdReturnRow.updated_at as string | Date).toISOString()\n : null\n await em.transactional(async (tx) => {\n const lockedClaim = await requireScopedClaim(tx, claim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if (lockedClaim.salesReturnId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.salesReturnAlreadyLinked' })\n }\n lockedClaim.salesReturnId = salesReturnId\n lockedClaim.updatedAt = new Date()\n appendClaimEvent(tx, lockedClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'sales_return_created', salesReturnId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n claim.salesReturnId = salesReturnId\n claim.updatedAt = lockedClaim.updatedAt\n await tx.flush()\n })\n } catch (err) {\n try {\n await dispatchSalesReturnDelete(ctx, scope, salesReturnId, claim.orderId)\n } catch (compensationErr) {\n salesReturnBridgeLogger.error('warranty_claims.claim.create_sales_return compensation failed \u2014 orphaned sales return', {\n err: compensationErr,\n claimId: claim.id,\n salesReturnId,\n })\n const orphanEm = (ctx.container.resolve('em') as EntityManager).fork()\n const orphanClaim = await findOneWithDecryption(\n orphanEm,\n WarrantyClaim,\n { id: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n if (orphanClaim) {\n try {\n appendClaimEvent(orphanEm, orphanClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'sales_return_orphaned', salesReturnId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await orphanEm.flush()\n } catch (orphanEventErr) {\n salesReturnBridgeLogger.error('warranty_claims.claim.create_sales_return orphan timeline write failed', {\n err: orphanEventErr,\n claimId: claim.id,\n salesReturnId,\n })\n }\n }\n throw new CrudHttpError(500, { error: 'warranty_claims.errors.save_failed' })\n }\n throw err\n }\n await emitClaimCrud(ctx, 'updated', claim)\n return { claimId: claim.id, salesReturnId, salesReturnUpdatedAt, skippedLineIds }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateSalesReturnSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => {\n const base = buildClaimLog('warranty_claims.audit.claim.create_sales_return', result.claimId, snapshots)\n const after = snapshots.after as { orderId?: string | null } | null | undefined\n const undoPayload: ClaimSalesReturnUndoPayload = {\n ...(base.payload.undo as ClaimUndoPayload),\n salesReturn: {\n id: result.salesReturnId,\n orderId: after?.orderId ?? '',\n updatedAt: result.salesReturnUpdatedAt,\n },\n }\n return { ...base, payload: { undo: undoPayload } }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimSalesReturnUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) return throwClaimUndoConflict()\n await assertUndoSnapshotCurrent(ctx, after)\n const scope: WarrantyClaimScope = { tenantId: before.tenantId, organizationId: before.organizationId }\n const salesReturn = payload?.salesReturn ?? null\n if (salesReturn?.id && salesReturn.orderId) {\n const currentRow = await querySalesReferenceRow(ctx, 'sales_returns', scope, salesReturn.id, ['id', 'updated_at'])\n if (currentRow) {\n const currentUpdatedAt = currentRow.updated_at\n ? new Date(currentRow.updated_at as string | Date).toISOString()\n : null\n if (!salesReturn.updatedAt || (currentUpdatedAt && currentUpdatedAt !== salesReturn.updatedAt)) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.salesReturnChangedUndoAborted' })\n }\n await dispatchSalesReturnDelete(ctx, scope, salesReturn.id, salesReturn.orderId)\n }\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_sales_return_created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.create_sales_return.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst creditMemoBridgeLogger = createLogger('warranty_claims')\n\nconst CREDIT_MEMO_ELIGIBLE_CLAIM_STATUSES = new Set<WarrantyClaimStatus>(['received', 'inspecting', 'resolved'])\nconst CREDIT_MEMO_ELIGIBLE_LINE_STATUSES = new Set<WarrantyClaimLineStatus>(['received', 'inspected', 'resolved'])\nconst CREDIT_MEMO_ELIGIBLE_DISPOSITIONS = new Set<WarrantyClaimDisposition>(['credit', 'refund'])\n\ntype CreditMemoLineInput = {\n orderLineId: string\n quantity: string\n currencyCode: string\n unitPriceNet: string\n unitPriceGross: string\n taxRate: string\n taxAmount: string\n totalNetAmount: string\n totalGrossAmount: string\n metadata: { warrantyClaimLineId: string }\n name?: string\n}\n\ntype CreditMemoCreateInput = {\n organizationId: string\n tenantId: string\n orderId: string\n currencyCode: string\n reason: string\n metadata: { warrantyClaimId: string; warrantyClaimNumber: string }\n lines: CreditMemoLineInput[]\n subtotalNetAmount: string\n subtotalGrossAmount: string\n taxTotalAmount: string\n grandTotalNetAmount: string\n grandTotalGrossAmount: string\n}\n\ntype PreparedCreditMemoLine = {\n input: CreditMemoLineInput\n netUnits: bigint\n grossUnits: bigint\n taxUnits: bigint\n}\n\ntype ClaimCreditMemoUndoPayload = ClaimUndoPayload & {\n creditMemo?: { id: string; updatedAt: string | null } | null\n}\n\ntype ClaimCreateCreditMemoResult = {\n claimId: string\n creditMemoId: string\n creditMemoUpdatedAt: string | null\n skippedLineIds: string[]\n grandTotalGrossAmount: string\n currencyCode: string\n}\n\nfunction minimumUnits(left: bigint, right: bigint): bigint {\n return left < right ? left : right\n}\n\nfunction prepareCreditMemoLine(\n claimLine: WarrantyClaimLine,\n sourceLine: Record<string, unknown>,\n creditedQuantityUnits: bigint,\n currencyCode: string,\n): PreparedCreditMemoLine | null {\n const orderQuantityUnits = claimedQuantityUnits(sourceLine.quantity as string | number | null | undefined)\n const sourceGrossUnits = claimedQuantityUnits(sourceLine.total_gross_amount as string | number | null | undefined)\n const sourceNetUnits = claimedQuantityUnits(sourceLine.total_net_amount as string | number | null | undefined)\n const taxRateUnits = claimedQuantityUnits(sourceLine.tax_rate as string | number | null | undefined)\n if (\n orderQuantityUnits === null\n || orderQuantityUnits <= 0n\n || creditedQuantityUnits > orderQuantityUnits\n || sourceGrossUnits === null\n || sourceNetUnits === null\n || taxRateUnits === null\n ) {\n return null\n }\n\n let netBasisUnits = sourceNetUnits\n if (sourceGrossUnits > 0n && netBasisUnits <= 0n) {\n netBasisUnits = netUnitsFromGross(sourceGrossUnits, taxRateUnits)\n }\n const proratedGrossUnits = roundHalfUpDivision(sourceGrossUnits * creditedQuantityUnits, orderQuantityUnits)\n const proratedNetUnits = roundHalfUpDivision(netBasisUnits * creditedQuantityUnits, orderQuantityUnits)\n const creditAmountUnits = claimedQuantityUnits(claimLine.creditAmount)\n const restockingFeeUnits = claimedQuantityUnits(claimLine.restockingFee) ?? 0n\n const coreCreditUnits = claimedQuantityUnits(claimLine.coreCreditAmount) ?? 0n\n const baseGrossUnits = creditAmountUnits ?? proratedGrossUnits\n const adjustedGrossUnits = baseGrossUnits - restockingFeeUnits + coreCreditUnits\n const grossUnits = adjustedGrossUnits > 0n ? adjustedGrossUnits : 0n\n let netUnits = grossUnits === proratedGrossUnits\n ? proratedNetUnits\n : netUnitsFromGross(grossUnits, taxRateUnits)\n if (grossUnits > 0n && netUnits <= 0n) {\n netUnits = netUnitsFromGross(grossUnits, taxRateUnits)\n }\n const taxUnits = grossUnits - netUnits\n const input: CreditMemoLineInput = {\n orderLineId: claimLine.orderLineId as string,\n quantity: formatScaledUnits(creditedQuantityUnits),\n currencyCode,\n unitPriceNet: formatScaledUnits(roundHalfUpDivision(netUnits * CLAIMED_QUANTITY_SCALE, creditedQuantityUnits)),\n unitPriceGross: formatScaledUnits(roundHalfUpDivision(grossUnits * CLAIMED_QUANTITY_SCALE, creditedQuantityUnits)),\n taxRate: formatScaledUnits(taxRateUnits),\n taxAmount: formatScaledUnits(taxUnits),\n totalNetAmount: formatScaledUnits(netUnits),\n totalGrossAmount: formatScaledUnits(grossUnits),\n metadata: { warrantyClaimLineId: claimLine.id },\n }\n const name = readString(sourceLine, 'name')\n if (name) input.name = name\n return { input, netUnits, grossUnits, taxUnits }\n}\n\nasync function dispatchCreditMemoDelete(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n creditMemoId: string,\n): Promise<void> {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute(\n 'sales.credit_memos.delete',\n {\n input: { id: creditMemoId, organizationId: scope.organizationId, tenantId: scope.tenantId },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n}\n\nconst createCreditMemoCommand: CommandHandler<ClaimCreateCreditMemoInput, ClaimCreateCreditMemoResult> = {\n id: 'warranty_claims.claim.create_credit_memo',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimCreateCreditMemoSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateCreditMemoSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n if (!claim.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoRequiresOrder' })\n }\n if (!CREDIT_MEMO_ELIGIBLE_CLAIM_STATUSES.has(claim.status as WarrantyClaimStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoInvalidStatus' })\n }\n if (claim.creditMemoId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoAlreadyLinked' })\n }\n if (!resolveOptionalEntityId('sales', 'sales_credit_memo')) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoSalesUnavailable' })\n }\n\n const sourceOrder = await querySalesReferenceRow(\n ctx,\n 'sales_orders',\n scope,\n claim.orderId,\n ['id', 'currency_code'],\n )\n const orderCurrencyCode = sourceOrder ? readString(sourceOrder, 'currency_code') : null\n if (!sourceOrder || !orderCurrencyCode) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoRequiresOrder' })\n }\n\n const claimLines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n const sourceLineRows = await querySalesOrderLineReferences(\n ctx,\n scope,\n Array.from(new Set(claimLines.flatMap((line) => line.orderLineId ? [line.orderLineId] : []))),\n ['id', 'order_id', 'name', 'currency_code', 'quantity', 'total_net_amount', 'total_gross_amount', 'tax_rate'],\n )\n const sourceLinesById = new Map((sourceLineRows ?? []).map((row) => [readString(row, 'id'), row]))\n const preparedLines: PreparedCreditMemoLine[] = []\n const skippedLineIds: string[] = []\n for (const claimLine of claimLines) {\n const approvedQuantityUnits = claimedQuantityUnits(claimLine.qtyApproved ?? claimLine.qtyClaimed) ?? 0n\n const receivedQuantityUnits = claimedQuantityUnits(claimLine.qtyReceived) ?? 0n\n const creditedQuantityUnits = minimumUnits(approvedQuantityUnits, receivedQuantityUnits)\n const initiallyEligible = Boolean(claimLine.orderLineId)\n && CREDIT_MEMO_ELIGIBLE_DISPOSITIONS.has(claimLine.disposition as WarrantyClaimDisposition)\n && CREDIT_MEMO_ELIGIBLE_LINE_STATUSES.has(claimLine.lineStatus as WarrantyClaimLineStatus)\n && creditedQuantityUnits > 0n\n if (!initiallyEligible || !claimLine.orderLineId) {\n skippedLineIds.push(claimLine.id)\n continue\n }\n\n const sourceLine = sourceLinesById.get(claimLine.orderLineId) ?? null\n const sourceCurrencyCode = sourceLine ? readString(sourceLine, 'currency_code') : null\n if (\n !sourceLine\n || sourceLine.order_id !== claim.orderId\n || sourceCurrencyCode !== orderCurrencyCode\n ) {\n skippedLineIds.push(claimLine.id)\n continue\n }\n const preparedLine = prepareCreditMemoLine(\n claimLine,\n sourceLine,\n creditedQuantityUnits,\n orderCurrencyCode,\n )\n if (!preparedLine) {\n skippedLineIds.push(claimLine.id)\n continue\n }\n preparedLines.push(preparedLine)\n }\n if (preparedLines.length === 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoNoEligibleLines' })\n }\n\n const totals = preparedLines.reduce(\n (result, line) => ({\n netUnits: result.netUnits + line.netUnits,\n grossUnits: result.grossUnits + line.grossUnits,\n taxUnits: result.taxUnits + line.taxUnits,\n }),\n { netUnits: 0n, grossUnits: 0n, taxUnits: 0n },\n )\n const grandTotalNetAmount = formatScaledUnits(totals.netUnits)\n const grandTotalGrossAmount = formatScaledUnits(totals.grossUnits)\n const creditMemoInput: CreditMemoCreateInput = {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n orderId: claim.orderId,\n currencyCode: orderCurrencyCode,\n reason: claim.claimNumber,\n metadata: { warrantyClaimId: claim.id, warrantyClaimNumber: claim.claimNumber },\n lines: preparedLines.map((line) => line.input),\n subtotalNetAmount: grandTotalNetAmount,\n subtotalGrossAmount: grandTotalGrossAmount,\n taxTotalAmount: formatScaledUnits(totals.taxUnits),\n grandTotalNetAmount,\n grandTotalGrossAmount,\n }\n\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n let creditMemoId: string | null = null\n let creditMemoUpdatedAt: string | null = null\n try {\n const { result: dispatchedResult } = await commandBus.execute<CreditMemoCreateInput, { creditMemoId: string }>(\n 'sales.credit_memos.create',\n { input: creditMemoInput, ctx: scrubbedDispatchContext(ctx) },\n )\n if (!dispatchedResult?.creditMemoId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n }\n creditMemoId = dispatchedResult.creditMemoId\n const createdCreditMemoRow = await querySalesReferenceRow(\n ctx,\n 'sales_credit_memos',\n scope,\n creditMemoId,\n ['id', 'updated_at'],\n )\n creditMemoUpdatedAt = createdCreditMemoRow?.updated_at\n ? new Date(createdCreditMemoRow.updated_at as string | Date).toISOString()\n : null\n await em.transactional(async (tx) => {\n const lockedClaim = await requireScopedClaim(tx, claim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if (lockedClaim.creditMemoId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.creditMemoAlreadyLinked' })\n }\n lockedClaim.creditMemoId = creditMemoId\n lockedClaim.updatedAt = new Date()\n appendClaimEvent(tx, lockedClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'credit_memo_created', creditMemoId, grandTotalGrossAmount, currencyCode: orderCurrencyCode },\n actorUserId: ctx.auth?.sub ?? null,\n })\n claim.creditMemoId = creditMemoId\n claim.updatedAt = lockedClaim.updatedAt\n await tx.flush()\n })\n } catch (err) {\n if (!creditMemoId) throw err\n try {\n await dispatchCreditMemoDelete(ctx, scope, creditMemoId)\n } catch (compensationErr) {\n creditMemoBridgeLogger.error('warranty_claims.claim.create_credit_memo compensation failed \u2014 orphaned credit memo', {\n err: compensationErr,\n claimId: claim.id,\n creditMemoId,\n })\n try {\n const orphanEm = (ctx.container.resolve('em') as EntityManager).fork()\n const orphanClaim = await findOneWithDecryption(\n orphanEm,\n WarrantyClaim,\n { id: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n if (orphanClaim) {\n appendClaimEvent(orphanEm, orphanClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'credit_memo_orphaned', creditMemoId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await orphanEm.flush()\n }\n } catch (orphanEventErr) {\n creditMemoBridgeLogger.error('warranty_claims.claim.create_credit_memo orphan timeline write failed', {\n err: orphanEventErr,\n claimId: claim.id,\n creditMemoId,\n })\n }\n throw new CrudHttpError(500, { error: 'warranty_claims.errors.save_failed' })\n }\n throw err\n }\n\n await emitClaimCrud(ctx, 'updated', claim)\n return {\n claimId: claim.id,\n creditMemoId,\n creditMemoUpdatedAt,\n skippedLineIds,\n grandTotalGrossAmount,\n currencyCode: orderCurrencyCode,\n }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateCreditMemoSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => {\n const base = buildClaimLog('warranty_claims.audit.claim.create_credit_memo', result.claimId, snapshots)\n const undoPayload: ClaimCreditMemoUndoPayload = {\n ...(base.payload.undo as ClaimUndoPayload),\n creditMemo: { id: result.creditMemoId, updatedAt: result.creditMemoUpdatedAt },\n }\n return { ...base, payload: { undo: undoPayload } }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimCreditMemoUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) return throwClaimUndoConflict()\n await assertUndoSnapshotCurrent(ctx, after)\n const scope: WarrantyClaimScope = { tenantId: before.tenantId, organizationId: before.organizationId }\n const creditMemo = payload?.creditMemo ?? null\n if (creditMemo?.id) {\n const currentRow = await querySalesReferenceRow(ctx, 'sales_credit_memos', scope, creditMemo.id, ['id', 'updated_at'])\n if (currentRow === undefined) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.creditMemoChangedUndoAborted' })\n }\n if (currentRow) {\n const currentUpdatedAt = currentRow.updated_at\n ? new Date(currentRow.updated_at as string | Date).toISOString()\n : null\n if (!creditMemo.updatedAt || !currentUpdatedAt || currentUpdatedAt !== creditMemo.updatedAt) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.creditMemoChangedUndoAborted' })\n }\n await dispatchCreditMemoDelete(ctx, scope, creditMemo.id)\n } else {\n creditMemoBridgeLogger.info('warranty_claims.claim.create_credit_memo undo found credit memo already absent', {\n claimId: before.id,\n creditMemoId: creditMemo.id,\n })\n }\n }\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_credit_memo_created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.create_credit_memo.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nconst replacementOrderBridgeLogger = createLogger('warranty_claims')\n\nconst REPLACEMENT_ELIGIBLE_CLAIM_STATUSES = new Set<WarrantyClaimStatus>([\n 'approved',\n 'awaiting_return',\n 'received',\n 'inspecting',\n 'resolved',\n])\nconst REPLACEMENT_ELIGIBLE_LINE_STATUSES = new Set<WarrantyClaimLineStatus>(['approved', 'received', 'inspected', 'resolved'])\nconst ADVANCE_REPLACEMENT_CLAIM_STATUSES = new Set<WarrantyClaimStatus>(['approved', 'awaiting_return'])\nconst SALES_ORDER_LINE_KINDS = new Set(['product', 'service', 'shipping', 'discount', 'adjustment'] as const)\n\ntype SalesOrderLineKind = 'product' | 'service' | 'shipping' | 'discount' | 'adjustment'\n\ntype ReplacementOrderLineInput = {\n kind: SalesOrderLineKind\n currencyCode: string\n quantity: string\n unitPriceNet: string\n unitPriceGross: string\n productId?: string\n productVariantId?: string\n name?: string\n taxRate?: string\n}\n\ntype ReplacementOrderCreateInput = {\n organizationId: string\n tenantId: string\n currencyCode: string\n metadata: { warrantyClaimId: string; warrantyClaimNumber: string }\n lines: ReplacementOrderLineInput[]\n customerEntityId?: string\n customerContactId?: string\n billingAddressId?: string\n shippingAddressId?: string\n channelId?: string\n}\n\ntype ClaimReplacementOrderUndoPayload = ClaimUndoPayload & {\n replacementOrder?: { id: string; updatedAt: string | null } | null\n}\n\ntype ClaimCreateReplacementOrderResult = {\n claimId: string\n replacementOrderId: string\n replacementOrderUpdatedAt: string | null\n skippedLineIds: string[]\n pricing: 'zero' | 'original'\n}\n\nfunction readSalesOrderLineKind(value: unknown): SalesOrderLineKind | null {\n return typeof value === 'string' && SALES_ORDER_LINE_KINDS.has(value as SalesOrderLineKind)\n ? value as SalesOrderLineKind\n : null\n}\n\nasync function dispatchSalesOrderDelete(\n ctx: CommandRuntimeContext,\n scope: WarrantyClaimScope,\n replacementOrderId: string,\n): Promise<void> {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute(\n 'sales.orders.delete',\n {\n input: { id: replacementOrderId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n ctx: scrubbedDispatchContext(ctx),\n },\n )\n}\n\nconst createReplacementOrderCommand: CommandHandler<ClaimCreateReplacementOrderInput, ClaimCreateReplacementOrderResult> = {\n id: 'warranty_claims.claim.create_replacement_order',\n isUndoable: true,\n prepare: async (rawInput, ctx) => {\n const input = parseCommandInput(claimCreateReplacementOrderSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return { before: await loadClaimSnapshot(em, input.id, scope) }\n },\n async execute(rawInput, ctx) {\n const input = parseCommandInput(claimCreateReplacementOrderSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, input.id, scope)\n await enforceWarrantyClaimOptimisticLock(ctx, claim, WARRANTY_CLAIM_RESOURCE_KIND, input.updatedAt ?? undefined)\n if (!claim.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementOrderRequiresOrder' })\n }\n if (!REPLACEMENT_ELIGIBLE_CLAIM_STATUSES.has(claim.status as WarrantyClaimStatus)) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementInvalidStatus' })\n }\n if (claim.replacementOrderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementAlreadyLinked' })\n }\n if (!resolveOptionalEntityId('sales', 'sales_order')) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementSalesUnavailable' })\n }\n\n const sourceOrder = await querySalesReferenceRow(\n ctx,\n 'sales_orders',\n scope,\n claim.orderId,\n [\n 'id',\n 'currency_code',\n 'customer_entity_id',\n 'customer_contact_id',\n 'billing_address_id',\n 'shipping_address_id',\n 'channel_id',\n ],\n )\n const orderCurrencyCode = sourceOrder ? readString(sourceOrder, 'currency_code') : null\n if (!sourceOrder || !orderCurrencyCode) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementOrderRequiresOrder' })\n }\n\n const lines = await findWithDecryption(\n em,\n WarrantyClaimLine,\n { claim: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n const sourceLineRows = await querySalesOrderLineReferences(\n ctx,\n scope,\n Array.from(new Set(lines.flatMap((line) => line.orderLineId ? [line.orderLineId] : []))),\n [\n 'id',\n 'order_id',\n 'product_id',\n 'product_variant_id',\n 'name',\n 'kind',\n 'currency_code',\n 'unit_price_net',\n 'unit_price_gross',\n 'tax_rate',\n ],\n )\n const sourceLinesById = new Map((sourceLineRows ?? []).map((row) => [readString(row, 'id'), row]))\n const replacementLines: ReplacementOrderLineInput[] = []\n const skippedLineIds: string[] = []\n for (const line of lines) {\n const effectiveQty = line.qtyApproved ?? line.qtyClaimed\n const quantityUnits = claimedQuantityUnits(effectiveQty) ?? 0n\n const initiallyEligible = line.disposition === 'replace'\n && Boolean(line.orderLineId)\n && REPLACEMENT_ELIGIBLE_LINE_STATUSES.has(line.lineStatus as WarrantyClaimLineStatus)\n && quantityUnits > 0n\n && quantityUnits % CLAIMED_QUANTITY_SCALE === 0n\n if (!initiallyEligible || !line.orderLineId) {\n skippedLineIds.push(line.id)\n continue\n }\n\n const sourceLine = sourceLinesById.get(line.orderLineId) ?? null\n const productId = sourceLine ? readString(sourceLine, 'product_id') : null\n const productVariantId = sourceLine ? readString(sourceLine, 'product_variant_id') : null\n const name = sourceLine ? readString(sourceLine, 'name') : null\n const kind = sourceLine ? readSalesOrderLineKind(sourceLine.kind) : null\n const currencyCode = sourceLine ? readString(sourceLine, 'currency_code') : null\n const unitPriceNet = sourceLine ? readString(sourceLine, 'unit_price_net') : null\n const unitPriceGross = sourceLine ? readString(sourceLine, 'unit_price_gross') : null\n const taxRate = sourceLine ? readString(sourceLine, 'tax_rate') : null\n const originalPricingIncomplete = input.pricing === 'original'\n && (unitPriceNet === null || unitPriceGross === null || taxRate === null)\n if (\n !sourceLine\n || sourceLine.order_id !== claim.orderId\n || (!productId && !productVariantId && !name)\n || !kind\n || !currencyCode\n || originalPricingIncomplete\n ) {\n skippedLineIds.push(line.id)\n continue\n }\n\n const replacementLine: ReplacementOrderLineInput = {\n kind,\n currencyCode,\n quantity: String(effectiveQty),\n unitPriceNet: input.pricing === 'zero' ? '0' : unitPriceNet as string,\n unitPriceGross: input.pricing === 'zero' ? '0' : unitPriceGross as string,\n }\n if (productId) replacementLine.productId = productId\n if (productVariantId) replacementLine.productVariantId = productVariantId\n if (name) replacementLine.name = name\n if (input.pricing === 'original') replacementLine.taxRate = taxRate as string\n replacementLines.push(replacementLine)\n }\n if (replacementLines.length === 0) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementNoEligibleLines' })\n }\n\n const orderInput: ReplacementOrderCreateInput = {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n currencyCode: orderCurrencyCode,\n metadata: { warrantyClaimId: claim.id, warrantyClaimNumber: claim.claimNumber },\n lines: replacementLines,\n }\n const customerEntityId = readString(sourceOrder, 'customer_entity_id')\n const customerContactId = readString(sourceOrder, 'customer_contact_id')\n const billingAddressId = readString(sourceOrder, 'billing_address_id')\n const shippingAddressId = readString(sourceOrder, 'shipping_address_id')\n const channelId = readString(sourceOrder, 'channel_id')\n if (customerEntityId) orderInput.customerEntityId = customerEntityId\n if (customerContactId) orderInput.customerContactId = customerContactId\n if (billingAddressId) orderInput.billingAddressId = billingAddressId\n if (shippingAddressId) orderInput.shippingAddressId = shippingAddressId\n if (channelId) orderInput.channelId = channelId\n\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const { result: dispatchedResult } = await commandBus.execute<ReplacementOrderCreateInput, { orderId: string }>(\n 'sales.orders.create',\n { input: orderInput, ctx: scrubbedDispatchContext(ctx) },\n )\n if (!dispatchedResult?.orderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n }\n const replacementOrderId = dispatchedResult.orderId\n let replacementOrderUpdatedAt: string | null = null\n try {\n const createdOrderRow = await querySalesReferenceRow(ctx, 'sales_orders', scope, replacementOrderId, ['id', 'updated_at'])\n replacementOrderUpdatedAt = createdOrderRow?.updated_at\n ? new Date(createdOrderRow.updated_at as string | Date).toISOString()\n : null\n await em.transactional(async (tx) => {\n const lockedClaim = await requireScopedClaim(tx, claim.id, scope, { lockMode: LockMode.PESSIMISTIC_WRITE })\n if (lockedClaim.replacementOrderId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.replacementAlreadyLinked' })\n }\n lockedClaim.replacementOrderId = replacementOrderId\n if (ADVANCE_REPLACEMENT_CLAIM_STATUSES.has(lockedClaim.status as WarrantyClaimStatus)) {\n lockedClaim.advanceReplacement = true\n }\n lockedClaim.updatedAt = new Date()\n appendClaimEvent(tx, lockedClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'replacement_order_created', replacementOrderId, pricing: input.pricing },\n actorUserId: ctx.auth?.sub ?? null,\n })\n claim.replacementOrderId = replacementOrderId\n claim.advanceReplacement = lockedClaim.advanceReplacement\n claim.updatedAt = lockedClaim.updatedAt\n await tx.flush()\n })\n } catch (err) {\n try {\n await dispatchSalesOrderDelete(ctx, scope, replacementOrderId)\n } catch (compensationErr) {\n replacementOrderBridgeLogger.error('warranty_claims.claim.create_replacement_order compensation failed \u2014 orphaned sales order', {\n err: compensationErr,\n claimId: claim.id,\n replacementOrderId,\n })\n try {\n const orphanEm = (ctx.container.resolve('em') as EntityManager).fork()\n const orphanClaim = await findOneWithDecryption(\n orphanEm,\n WarrantyClaim,\n { id: claim.id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n {},\n scope,\n )\n if (orphanClaim) {\n appendClaimEvent(orphanEm, orphanClaim, 'system', {\n visibility: 'internal',\n payload: { action: 'replacement_order_orphaned', replacementOrderId },\n actorUserId: ctx.auth?.sub ?? null,\n })\n await orphanEm.flush()\n }\n } catch (orphanEventErr) {\n replacementOrderBridgeLogger.error('warranty_claims.claim.create_replacement_order orphan timeline write failed', {\n err: orphanEventErr,\n claimId: claim.id,\n replacementOrderId,\n })\n }\n throw new CrudHttpError(500, { error: 'warranty_claims.errors.save_failed' })\n }\n throw err\n }\n\n await emitClaimCrud(ctx, 'updated', claim)\n return {\n claimId: claim.id,\n replacementOrderId,\n replacementOrderUpdatedAt,\n skippedLineIds,\n pricing: input.pricing,\n }\n },\n captureAfter: async (rawInput, result, ctx) => {\n const input = parseCommandInput(claimCreateReplacementOrderSchema, rawInput)\n const scope = resolveScope(ctx, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadClaimSnapshot(em, result.claimId, scope)\n },\n buildLog: async ({ result, snapshots }) => {\n const base = buildClaimLog('warranty_claims.audit.claim.create_replacement_order', result.claimId, snapshots)\n const undoPayload: ClaimReplacementOrderUndoPayload = {\n ...(base.payload.undo as ClaimUndoPayload),\n replacementOrder: {\n id: result.replacementOrderId,\n updatedAt: result.replacementOrderUpdatedAt,\n },\n }\n return { ...base, payload: { undo: undoPayload } }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<ClaimReplacementOrderUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n if (!after) return throwClaimUndoConflict()\n await assertUndoSnapshotCurrent(ctx, after)\n const scope: WarrantyClaimScope = { tenantId: before.tenantId, organizationId: before.organizationId }\n const replacementOrder = payload?.replacementOrder ?? null\n if (replacementOrder?.id) {\n const currentRow = await querySalesReferenceRow(ctx, 'sales_orders', scope, replacementOrder.id, ['id', 'updated_at'])\n if (currentRow === undefined) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.replacementOrderChangedUndoAborted' })\n }\n if (currentRow) {\n const currentUpdatedAt = currentRow.updated_at\n ? new Date(currentRow.updated_at as string | Date).toISOString()\n : null\n if (!replacementOrder.updatedAt || !currentUpdatedAt || currentUpdatedAt !== replacementOrder.updatedAt) {\n throw new CrudHttpError(409, { error: 'warranty_claims.errors.replacementOrderChangedUndoAborted' })\n }\n await dispatchSalesOrderDelete(ctx, scope, replacementOrder.id)\n } else {\n replacementOrderBridgeLogger.info('warranty_claims.claim.create_replacement_order undo found replacement order already absent', {\n claimId: before.id,\n replacementOrderId: replacementOrder.id,\n })\n }\n }\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let claim!: WarrantyClaim\n await withAtomicFlush(em, [\n async () => {\n claim = await restoreSnapshot(em, before, after)\n appendClaimEvent(em, claim, 'system', {\n visibility: 'internal',\n payload: { action: 'undo_replacement_order_created' },\n actorUserId: ctx.auth?.sub ?? null,\n })\n },\n ], { transaction: true, label: 'warranty_claims.claim.create_replacement_order.undo' })\n await emitClaimUndoCrud(ctx, 'updated', claim)\n },\n}\n\nregisterCommand(createClaimCommand)\nregisterCommand(updateClaimCommand)\nregisterCommand(deleteClaimCommand)\nregisterCommand(submitClaimCommand)\nregisterCommand(transitionClaimCommand)\nregisterCommand(assignClaimCommand)\nregisterCommand(setReturnLabelCommand)\nregisterCommand(escalateClaimCommand)\nregisterCommand(commentClaimCommand)\nregisterCommand(createVendorRecoveryCommand)\nregisterCommand(createSalesReturnCommand)\nregisterCommand(createCreditMemoCommand)\nregisterCommand(createReplacementOrderCommand)\n\nexport const claimCommands = [\n createClaimCommand,\n updateClaimCommand,\n deleteClaimCommand,\n submitClaimCommand,\n transitionClaimCommand,\n assignClaimCommand,\n setReturnLabelCommand,\n escalateClaimCommand,\n commentClaimCommand,\n createVendorRecoveryCommand,\n createSalesReturnCommand,\n createCreditMemoCommand,\n createReplacementOrderCommand,\n]\n\nexport {\n claimCrudEvents,\n createClaimCommand,\n updateClaimCommand,\n deleteClaimCommand,\n submitClaimCommand,\n transitionClaimCommand,\n assignClaimCommand,\n setReturnLabelCommand,\n escalateClaimCommand,\n commentClaimCommand,\n createVendorRecoveryCommand,\n createSalesReturnCommand,\n createCreditMemoCommand,\n createReplacementOrderCommand,\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AAEzB,SAAS,SAAS;AAClB,SAAS,uBAAyF;AAClG,SAAS,uBAAuB;AAChC,SAAS,qBAAqB,+BAA+B;AAE7D,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,+BAA+B;AAGxC,SAAS,SAAS;AAClB;AAAA,EACE;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,OAmBK;AACP,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,oCAAoC;AAC7C,SAAS,+BAA+B;AACxC,SAAS,kBAAkB,4BAA4B,4BAA4B;AACnF,SAAS,oCAAoC;AAC7C,SAAS,mBAAmB,6BAA6B;AACzD,SAAS,6CAAkF;AAC3F,SAAS,yBAAyB;AAGlC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,kBAAoC;AAAA,EACxC,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,cAAc,CAAC,QAAQ;AACrB,UAAM,QAAQ,IAAI;AAClB,WAAO;AAAA,MACL,IAAI,IAAI,YAAY;AAAA,MACpB,gBAAgB,IAAI,YAAY;AAAA,MAChC,UAAU,IAAI,YAAY;AAAA,MAC1B,WAAW,OAAO,aAAa;AAAA,MAC/B,QA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