@open-mercato/core 0.7.1-develop.7130.1.fef2396fd8 → 0.7.1-develop.7131.1.20abf9e885

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.
Files changed (203) hide show
  1. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js +5 -0
  2. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js.map +2 -2
  3. package/dist/modules/auth/api/profile/route.js +5 -0
  4. package/dist/modules/auth/api/profile/route.js.map +2 -2
  5. package/dist/modules/customers/api/activities/route.js +13 -0
  6. package/dist/modules/customers/api/activities/route.js.map +2 -2
  7. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +9 -0
  8. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  9. package/dist/modules/customers/api/dictionaries/[kind]/route.js +5 -0
  10. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  11. package/dist/modules/customers/api/dictionaries/kind-settings/route.js +5 -0
  12. package/dist/modules/customers/api/dictionaries/kind-settings/route.js.map +2 -2
  13. package/dist/modules/customers/api/interactions/cancel/route.js +5 -0
  14. package/dist/modules/customers/api/interactions/cancel/route.js.map +2 -2
  15. package/dist/modules/customers/api/interactions/complete/route.js +5 -0
  16. package/dist/modules/customers/api/interactions/complete/route.js.map +2 -2
  17. package/dist/modules/customers/api/labels/assign/route.js +5 -0
  18. package/dist/modules/customers/api/labels/assign/route.js.map +2 -2
  19. package/dist/modules/customers/api/labels/route.js +5 -0
  20. package/dist/modules/customers/api/labels/route.js.map +2 -2
  21. package/dist/modules/customers/api/labels/unassign/route.js +5 -0
  22. package/dist/modules/customers/api/labels/unassign/route.js.map +2 -2
  23. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +9 -0
  24. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
  25. package/dist/modules/customers/api/people/[id]/companies/route.js +5 -0
  26. package/dist/modules/customers/api/people/[id]/companies/route.js.map +2 -2
  27. package/dist/modules/customers/api/pipeline-stages/reorder/route.js +5 -0
  28. package/dist/modules/customers/api/pipeline-stages/reorder/route.js.map +2 -2
  29. package/dist/modules/customers/api/pipeline-stages/route.js +13 -0
  30. package/dist/modules/customers/api/pipeline-stages/route.js.map +2 -2
  31. package/dist/modules/customers/api/pipelines/route.js +13 -0
  32. package/dist/modules/customers/api/pipelines/route.js.map +2 -2
  33. package/dist/modules/customers/api/settings/address-format/route.js +5 -0
  34. package/dist/modules/customers/api/settings/address-format/route.js.map +2 -2
  35. package/dist/modules/customers/api/settings/dictionary-sort-modes/route.js +5 -0
  36. package/dist/modules/customers/api/settings/dictionary-sort-modes/route.js.map +2 -2
  37. package/dist/modules/customers/api/settings/stuck-threshold/route.js +5 -0
  38. package/dist/modules/customers/api/settings/stuck-threshold/route.js.map +2 -2
  39. package/dist/modules/customers/api/tags/assign/route.js +5 -0
  40. package/dist/modules/customers/api/tags/assign/route.js.map +2 -2
  41. package/dist/modules/customers/api/tags/unassign/route.js +5 -0
  42. package/dist/modules/customers/api/tags/unassign/route.js.map +2 -2
  43. package/dist/modules/customers/api/todos/route.js +13 -0
  44. package/dist/modules/customers/api/todos/route.js.map +2 -2
  45. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +9 -0
  46. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
  47. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js +5 -0
  48. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js.map +2 -2
  49. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +5 -0
  50. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  51. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js +5 -0
  52. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js.map +2 -2
  53. package/dist/modules/directory/api/organization-branding/route.js +5 -0
  54. package/dist/modules/directory/api/organization-branding/route.js.map +2 -2
  55. package/dist/modules/eudr/api/plots/import/route.js.map +2 -2
  56. package/dist/modules/eudr/api/product-mappings/suggestions/apply/route.js.map +2 -2
  57. package/dist/modules/feature_toggles/api/overrides/route.js +5 -0
  58. package/dist/modules/feature_toggles/api/overrides/route.js.map +2 -2
  59. package/dist/modules/messages/api/[id]/actions/[actionId]/route.js +5 -0
  60. package/dist/modules/messages/api/[id]/actions/[actionId]/route.js.map +2 -2
  61. package/dist/modules/messages/api/[id]/conversation/archive/route.js +5 -0
  62. package/dist/modules/messages/api/[id]/conversation/archive/route.js.map +2 -2
  63. package/dist/modules/messages/api/[id]/conversation/read/route.js +5 -0
  64. package/dist/modules/messages/api/[id]/conversation/read/route.js.map +2 -2
  65. package/dist/modules/messages/api/[id]/conversation/route.js +5 -0
  66. package/dist/modules/messages/api/[id]/conversation/route.js.map +2 -2
  67. package/dist/modules/messages/api/[id]/forward/route.js +5 -0
  68. package/dist/modules/messages/api/[id]/forward/route.js.map +2 -2
  69. package/dist/modules/messages/api/[id]/reply/route.js +5 -0
  70. package/dist/modules/messages/api/[id]/reply/route.js.map +2 -2
  71. package/dist/modules/messages/api/[id]/route.js +9 -0
  72. package/dist/modules/messages/api/[id]/route.js.map +2 -2
  73. package/dist/modules/messages/api/token/[token]/route.js +5 -0
  74. package/dist/modules/messages/api/token/[token]/route.js.map +2 -2
  75. package/dist/modules/resources/api/resources/tags/assign/route.js +5 -0
  76. package/dist/modules/resources/api/resources/tags/assign/route.js.map +2 -2
  77. package/dist/modules/resources/api/resources/tags/unassign/route.js +5 -0
  78. package/dist/modules/resources/api/resources/tags/unassign/route.js.map +2 -2
  79. package/dist/modules/sales/api/quotes/accept/route.js +5 -0
  80. package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
  81. package/dist/modules/sales/api/quotes/convert/route.js +5 -0
  82. package/dist/modules/sales/api/quotes/convert/route.js.map +2 -2
  83. package/dist/modules/sales/api/settings/document-numbers/route.js +5 -0
  84. package/dist/modules/sales/api/settings/document-numbers/route.js.map +2 -2
  85. package/dist/modules/sales/api/settings/order-editing/route.js +5 -0
  86. package/dist/modules/sales/api/settings/order-editing/route.js.map +2 -2
  87. package/dist/modules/staff/api/leave-requests/accept/route.js +5 -0
  88. package/dist/modules/staff/api/leave-requests/accept/route.js.map +2 -2
  89. package/dist/modules/staff/api/leave-requests/reject/route.js +5 -0
  90. package/dist/modules/staff/api/leave-requests/reject/route.js.map +2 -2
  91. package/dist/modules/staff/api/team-members/self/route.js +5 -0
  92. package/dist/modules/staff/api/team-members/self/route.js.map +2 -2
  93. package/dist/modules/staff/api/team-members/tags/assign/route.js +5 -0
  94. package/dist/modules/staff/api/team-members/tags/assign/route.js.map +2 -2
  95. package/dist/modules/staff/api/team-members/tags/unassign/route.js +5 -0
  96. package/dist/modules/staff/api/team-members/tags/unassign/route.js.map +2 -2
  97. package/dist/modules/staff/api/timesheets/time-entries/start-timer/route.js +5 -0
  98. package/dist/modules/staff/api/timesheets/time-entries/start-timer/route.js.map +2 -2
  99. package/dist/modules/translations/api/[entityType]/[entityId]/route.js +9 -0
  100. package/dist/modules/translations/api/[entityType]/[entityId]/route.js.map +2 -2
  101. package/dist/modules/warranty_claims/api/ai/assess/route.js +5 -0
  102. package/dist/modules/warranty_claims/api/ai/assess/route.js.map +2 -2
  103. package/dist/modules/warranty_claims/api/assign/route.js +5 -0
  104. package/dist/modules/warranty_claims/api/assign/route.js.map +2 -2
  105. package/dist/modules/warranty_claims/api/credit-memo/route.js +5 -0
  106. package/dist/modules/warranty_claims/api/credit-memo/route.js.map +2 -2
  107. package/dist/modules/warranty_claims/api/events/route.js +5 -0
  108. package/dist/modules/warranty_claims/api/events/route.js.map +2 -2
  109. package/dist/modules/warranty_claims/api/portal/claims/[id]/submit/route.js +5 -0
  110. package/dist/modules/warranty_claims/api/portal/claims/[id]/submit/route.js.map +2 -2
  111. package/dist/modules/warranty_claims/api/portal/claims/[id]/withdraw/route.js +5 -0
  112. package/dist/modules/warranty_claims/api/portal/claims/[id]/withdraw/route.js.map +2 -2
  113. package/dist/modules/warranty_claims/api/portal/claims/route.js +5 -0
  114. package/dist/modules/warranty_claims/api/portal/claims/route.js.map +2 -2
  115. package/dist/modules/warranty_claims/api/portal/events/route.js +5 -0
  116. package/dist/modules/warranty_claims/api/portal/events/route.js.map +2 -2
  117. package/dist/modules/warranty_claims/api/receiving/route.js +5 -0
  118. package/dist/modules/warranty_claims/api/receiving/route.js.map +2 -2
  119. package/dist/modules/warranty_claims/api/replacement-order/route.js +5 -0
  120. package/dist/modules/warranty_claims/api/replacement-order/route.js.map +2 -2
  121. package/dist/modules/warranty_claims/api/return-label/route.js +5 -0
  122. package/dist/modules/warranty_claims/api/return-label/route.js.map +2 -2
  123. package/dist/modules/warranty_claims/api/sales-return/route.js +5 -0
  124. package/dist/modules/warranty_claims/api/sales-return/route.js.map +2 -2
  125. package/dist/modules/warranty_claims/api/settings-general/route.js +5 -0
  126. package/dist/modules/warranty_claims/api/settings-general/route.js.map +2 -2
  127. package/dist/modules/warranty_claims/api/submit/route.js +5 -0
  128. package/dist/modules/warranty_claims/api/submit/route.js.map +2 -2
  129. package/dist/modules/warranty_claims/api/transition/route.js +5 -0
  130. package/dist/modules/warranty_claims/api/transition/route.js.map +2 -2
  131. package/dist/modules/warranty_claims/api/vendor-recovery/route.js +5 -0
  132. package/dist/modules/warranty_claims/api/vendor-recovery/route.js.map +2 -2
  133. package/dist/modules/wms/api/sales-orders/[salesOrderId]/warehouse-assignment/route.js +5 -0
  134. package/dist/modules/wms/api/sales-orders/[salesOrderId]/warehouse-assignment/route.js.map +2 -2
  135. package/package.json +7 -7
  136. package/src/modules/audit_logs/api/audit-logs/actions/redo/route.ts +5 -0
  137. package/src/modules/auth/api/profile/route.ts +5 -0
  138. package/src/modules/customers/api/activities/route.ts +13 -0
  139. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +9 -0
  140. package/src/modules/customers/api/dictionaries/[kind]/route.ts +5 -0
  141. package/src/modules/customers/api/dictionaries/kind-settings/route.ts +5 -0
  142. package/src/modules/customers/api/interactions/cancel/route.ts +5 -0
  143. package/src/modules/customers/api/interactions/complete/route.ts +5 -0
  144. package/src/modules/customers/api/labels/assign/route.ts +5 -0
  145. package/src/modules/customers/api/labels/route.ts +5 -0
  146. package/src/modules/customers/api/labels/unassign/route.ts +5 -0
  147. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +9 -0
  148. package/src/modules/customers/api/people/[id]/companies/route.ts +5 -0
  149. package/src/modules/customers/api/pipeline-stages/reorder/route.ts +5 -0
  150. package/src/modules/customers/api/pipeline-stages/route.ts +13 -0
  151. package/src/modules/customers/api/pipelines/route.ts +13 -0
  152. package/src/modules/customers/api/settings/address-format/route.ts +5 -0
  153. package/src/modules/customers/api/settings/dictionary-sort-modes/route.ts +5 -0
  154. package/src/modules/customers/api/settings/stuck-threshold/route.ts +5 -0
  155. package/src/modules/customers/api/tags/assign/route.ts +5 -0
  156. package/src/modules/customers/api/tags/unassign/route.ts +5 -0
  157. package/src/modules/customers/api/todos/route.ts +13 -0
  158. package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +9 -0
  159. package/src/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.ts +5 -0
  160. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +5 -0
  161. package/src/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.ts +5 -0
  162. package/src/modules/directory/api/organization-branding/route.ts +5 -0
  163. package/src/modules/eudr/api/plots/import/route.ts +7 -0
  164. package/src/modules/eudr/api/product-mappings/suggestions/apply/route.ts +7 -0
  165. package/src/modules/feature_toggles/api/overrides/route.ts +5 -0
  166. package/src/modules/messages/api/[id]/actions/[actionId]/route.ts +5 -0
  167. package/src/modules/messages/api/[id]/conversation/archive/route.ts +5 -0
  168. package/src/modules/messages/api/[id]/conversation/read/route.ts +5 -0
  169. package/src/modules/messages/api/[id]/conversation/route.ts +5 -0
  170. package/src/modules/messages/api/[id]/forward/route.ts +5 -0
  171. package/src/modules/messages/api/[id]/reply/route.ts +5 -0
  172. package/src/modules/messages/api/[id]/route.ts +9 -0
  173. package/src/modules/messages/api/token/[token]/route.ts +5 -0
  174. package/src/modules/resources/api/resources/tags/assign/route.ts +5 -0
  175. package/src/modules/resources/api/resources/tags/unassign/route.ts +5 -0
  176. package/src/modules/sales/api/quotes/accept/route.ts +5 -0
  177. package/src/modules/sales/api/quotes/convert/route.ts +5 -0
  178. package/src/modules/sales/api/settings/document-numbers/route.ts +5 -0
  179. package/src/modules/sales/api/settings/order-editing/route.ts +5 -0
  180. package/src/modules/staff/api/leave-requests/accept/route.ts +5 -0
  181. package/src/modules/staff/api/leave-requests/reject/route.ts +5 -0
  182. package/src/modules/staff/api/team-members/self/route.ts +5 -0
  183. package/src/modules/staff/api/team-members/tags/assign/route.ts +5 -0
  184. package/src/modules/staff/api/team-members/tags/unassign/route.ts +5 -0
  185. package/src/modules/staff/api/timesheets/time-entries/start-timer/route.ts +5 -0
  186. package/src/modules/translations/api/[entityType]/[entityId]/route.ts +9 -0
  187. package/src/modules/warranty_claims/api/ai/assess/route.ts +5 -0
  188. package/src/modules/warranty_claims/api/assign/route.ts +5 -0
  189. package/src/modules/warranty_claims/api/credit-memo/route.ts +5 -0
  190. package/src/modules/warranty_claims/api/events/route.ts +5 -0
  191. package/src/modules/warranty_claims/api/portal/claims/[id]/submit/route.ts +5 -0
  192. package/src/modules/warranty_claims/api/portal/claims/[id]/withdraw/route.ts +5 -0
  193. package/src/modules/warranty_claims/api/portal/claims/route.ts +5 -0
  194. package/src/modules/warranty_claims/api/portal/events/route.ts +5 -0
  195. package/src/modules/warranty_claims/api/receiving/route.ts +5 -0
  196. package/src/modules/warranty_claims/api/replacement-order/route.ts +5 -0
  197. package/src/modules/warranty_claims/api/return-label/route.ts +5 -0
  198. package/src/modules/warranty_claims/api/sales-return/route.ts +5 -0
  199. package/src/modules/warranty_claims/api/settings-general/route.ts +5 -0
  200. package/src/modules/warranty_claims/api/submit/route.ts +5 -0
  201. package/src/modules/warranty_claims/api/transition/route.ts +5 -0
  202. package/src/modules/warranty_claims/api/vendor-recovery/route.ts +5 -0
  203. package/src/modules/wms/api/sales-orders/[salesOrderId]/warehouse-assignment/route.ts +5 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/warranty_claims/api/replacement-order/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n claimCreateReplacementOrderSchema,\n type ClaimCreateReplacementOrderInput,\n} from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype ReplacementOrderCommandResult = {\n claimId: string\n replacementOrderId: string\n replacementOrderUpdatedAt: string | null\n skippedLineIds: string[]\n pricing: 'zero' | 'original'\n}\n\nconst replacementOrderRequestSchema = z\n .object({\n claimId: z.string().uuid(),\n pricing: z.enum(['zero', 'original']).optional(),\n updatedAt: z.string().datetime().nullable().optional(),\n })\n .strict()\n\ntype ReplacementOrderRequest = z.infer<typeof replacementOrderRequestSchema>\n\nconst replacementOrderResponseSchema = z.object({\n replacementOrderId: z.string().uuid(),\n skippedLineIds: z.array(z.string().uuid()),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n})\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage', 'sales.orders.manage'] },\n}\n\nfunction translateKey(key: string): string {\n return key\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.organization_required' })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate: translateKey,\n }\n}\n\nfunction toReplacementOrderRequest(payload: Record<string, unknown>): ReplacementOrderRequest {\n return replacementOrderRequestSchema.parse(payload)\n}\n\nfunction toCommandInput(\n input: ReplacementOrderRequest,\n context: ActionRouteContext,\n): ClaimCreateReplacementOrderInput {\n const scopedPayload = withScopedPayload({\n id: input.claimId,\n pricing: input.pricing,\n updatedAt: input.updatedAt,\n }, context.ctx, context.translate)\n return claimCreateReplacementOrderSchema.parse(scopedPayload)\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: ReplacementOrderRequest,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const requestInput = toReplacementOrderRequest(toRecord(await readJsonSafe(req, {})))\n const guarded = await runGuard(req, context, requestInput)\n if (!guarded.ok) {\n return guarded.response\n }\n const guardedInput = guarded.modifiedPayload\n ? toReplacementOrderRequest(guarded.modifiedPayload)\n : requestInput\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<ClaimCreateReplacementOrderInput, ReplacementOrderCommandResult>(\n 'warranty_claims.claim.create_replacement_order',\n { input: toCommandInput(guardedInput, context), ctx: context.ctx },\n )\n if (!result) throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n await guarded.runAfterSuccess()\n return NextResponse.json({\n replacementOrderId: result.replacementOrderId,\n skippedLineIds: result.skippedLineIds,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: 'warranty_claims.errors.invalidInput' }, { status: 400 })\n }\n logger.error('warranty_claims.replacement-order.post failed', { err })\n return NextResponse.json({ error: 'warranty_claims.errors.save_failed' }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create a replacement sales order from a warranty claim',\n methods: {\n POST: {\n summary: 'Create and link a replacement order from eligible replace-disposition claim lines',\n description: 'Zero pricing is the default. Original pricing copies the source order lines\\' pre-discount unit prices.',\n requestBody: { contentType: 'application/json', schema: replacementOrderRequestSchema },\n responses: [\n {\n status: 200,\n description: 'Replacement order created and linked; ineligible or unresolvable claim lines are reported as skipped',\n schema: replacementOrderResponseSchema,\n },\n { status: 400, description: 'Invalid request or claim is not eligible for replacement-order creation', schema: errorResponseSchema },\n { status: 401, description: 'Authentication required', schema: errorResponseSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorResponseSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,eAAe,uBAAuB;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,iBAAiB;AAiB7C,MAAM,gCAAgC,EACnC,OAAO;AAAA,EACN,SAAS,EAAE,OAAO,EAAE,KAAK;AAAA,EACzB,SAAS,EAAE,KAAK,CAAC,QAAQ,UAAU,CAAC,EAAE,SAAS;AAAA,EAC/C,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS;AACvD,CAAC,EACA,OAAO;AAIV,MAAM,iCAAiC,EAAE,OAAO;AAAA,EAC9C,oBAAoB,EAAE,OAAO,EAAE,KAAK;AAAA,EACpC,gBAAgB,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;AAC3C,CAAC;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,OAAO,EAAE,OAAO;AAClB,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,gCAAgC,qBAAqB,EAAE;AACtG;AAEA,SAAS,aAAa,KAAqB;AACzC,SAAO;AACT;AAEA,SAAS,SAAS,OAAyC;AACzD,SAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAI,QAAmC,CAAC;AAC3G;AAEA,eAA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AI,CAAC;AAAA,EAC3F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa,EAAE,aAAa,oBAAoB,QAAQ,8BAA8B;AAAA,MACtF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,QACA,EAAE,QAAQ,KAAK,aAAa,2EAA2E,QAAQ,oBAAoB;AAAA,QACnI,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,oBAAoB;AAAA,QACnF,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,oBAAoB;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,oBAAoB;AAAA,MACtF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n claimCreateReplacementOrderSchema,\n type ClaimCreateReplacementOrderInput,\n} from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype ReplacementOrderCommandResult = {\n claimId: string\n replacementOrderId: string\n replacementOrderUpdatedAt: string | null\n skippedLineIds: string[]\n pricing: 'zero' | 'original'\n}\n\nconst replacementOrderRequestSchema = z\n .object({\n claimId: z.string().uuid(),\n pricing: z.enum(['zero', 'original']).optional(),\n updatedAt: z.string().datetime().nullable().optional(),\n })\n .strict()\n\ntype ReplacementOrderRequest = z.infer<typeof replacementOrderRequestSchema>\n\nconst replacementOrderResponseSchema = z.object({\n replacementOrderId: z.string().uuid(),\n skippedLineIds: z.array(z.string().uuid()),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n})\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage', 'sales.orders.manage'] },\n}\n\nfunction translateKey(key: string): string {\n return key\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.organization_required' })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate: translateKey,\n }\n}\n\nfunction toReplacementOrderRequest(payload: Record<string, unknown>): ReplacementOrderRequest {\n return replacementOrderRequestSchema.parse(payload)\n}\n\nfunction toCommandInput(\n input: ReplacementOrderRequest,\n context: ActionRouteContext,\n): ClaimCreateReplacementOrderInput {\n const scopedPayload = withScopedPayload({\n id: input.claimId,\n pricing: input.pricing,\n updatedAt: input.updatedAt,\n }, context.ctx, context.translate)\n return claimCreateReplacementOrderSchema.parse(scopedPayload)\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: ReplacementOrderRequest,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const requestInput = toReplacementOrderRequest(toRecord(await readJsonSafe(req, {})))\n const guarded = await runGuard(req, context, requestInput)\n if (!guarded.ok) {\n return guarded.response\n }\n const guardedInput = guarded.modifiedPayload\n ? toReplacementOrderRequest(guarded.modifiedPayload)\n : requestInput\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<ClaimCreateReplacementOrderInput, ReplacementOrderCommandResult>(\n 'warranty_claims.claim.create_replacement_order',\n { input: toCommandInput(guardedInput, context), ctx: context.ctx },\n )\n if (!result) throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n await guarded.runAfterSuccess()\n return NextResponse.json({\n replacementOrderId: result.replacementOrderId,\n skippedLineIds: result.skippedLineIds,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: 'warranty_claims.errors.invalidInput' }, { status: 400 })\n }\n logger.error('warranty_claims.replacement-order.post failed', { err })\n return NextResponse.json({ error: 'warranty_claims.errors.save_failed' }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create a replacement sales order from a warranty claim',\n methods: {\n POST: {\n summary: 'Create and link a replacement order from eligible replace-disposition claim lines',\n description: 'Zero pricing is the default. Original pricing copies the source order lines\\' pre-discount unit prices.',\n requestBody: { contentType: 'application/json', schema: replacementOrderRequestSchema },\n responses: [\n {\n status: 200,\n description: 'Replacement order created and linked; ineligible or unresolvable claim lines are reported as skipped',\n schema: replacementOrderResponseSchema,\n },\n { status: 400, description: 'Invalid request or claim is not eligible for replacement-order creation', schema: errorResponseSchema },\n { status: 401, description: 'Authentication required', schema: errorResponseSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorResponseSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,eAAe,uBAAuB;AAC/C,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,iBAAiB;AAiB7C,MAAM,gCAAgC,EACnC,OAAO;AAAA,EACN,SAAS,EAAE,OAAO,EAAE,KAAK;AAAA,EACzB,SAAS,EAAE,KAAK,CAAC,QAAQ,UAAU,CAAC,EAAE,SAAS;AAAA,EAC/C,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS;AACvD,CAAC,EACA,OAAO;AAIV,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6 +4,7 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
4
4
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
5
5
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
6
6
  import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
7
+ import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
7
8
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
8
9
  import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
9
10
  import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
@@ -202,6 +203,10 @@ async function POST(req) {
202
203
  return NextResponse.json(response);
203
204
  } catch (err) {
204
205
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
206
+ const interceptorRejection = getCommandInterceptorHttpRejection(err);
207
+ if (interceptorRejection) {
208
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status });
209
+ }
205
210
  if (err instanceof z.ZodError) {
206
211
  return NextResponse.json({ error: firstTranslatableIssueKey(err) }, { status: 400 });
207
212
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/warranty_claims/api/return-label/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WarrantyClaim, WarrantyClaimLine } from '../../data/entities'\nimport { claimSetReturnLabelSchema, type ClaimSetReturnLabelInput } from '../../data/validators'\nimport type { WarrantyReturnLabelProvider } from '../../services/returnLabelProvider'\nimport {\n WARRANTY_CLAIM_RESOURCE_KIND,\n enforceWarrantyClaimOptimisticLock,\n requireScopedClaim,\n} from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype ReturnLabelCreatedResponse = {\n status: 'created'\n labelUrl: string | null\n trackingNumber: string | null\n carrier: string | null\n}\ntype ReturnLabelCommandResult = Omit<ReturnLabelCreatedResponse, 'status'> & { claimId: string }\n\nconst uuid = z.string().uuid()\nconst returnLabelText = (max: number) => z.string().trim().min(1).max(max).optional()\nconst optimisticLockTokenSchema = z.string().datetime().nullable().optional()\n\nconst returnLabelRequestSchema = z\n .object({\n claimId: uuid,\n manual: z.boolean().optional(),\n labelUrl: returnLabelText(2048),\n trackingNumber: returnLabelText(191),\n carrier: returnLabelText(120),\n updatedAt: optimisticLockTokenSchema,\n })\n .strict()\n\ntype ReturnLabelRequest = z.infer<typeof returnLabelRequestSchema>\n\nconst returnLabelResponseSchema = z.discriminatedUnion('status', [\n z.object({\n status: z.literal('created'),\n labelUrl: z.string().nullable(),\n trackingNumber: z.string().nullable(),\n carrier: z.string().nullable(),\n }),\n z.object({ status: z.literal('notConfigured') }),\n])\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction translateKey(key: string): string {\n return key\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.organization_required' })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate: translateKey,\n }\n}\n\nfunction toReturnLabelRequest(payload: Record<string, unknown>): ReturnLabelRequest {\n return returnLabelRequestSchema.parse({\n claimId: payload.claimId ?? payload.id,\n manual: payload.manual,\n labelUrl: payload.labelUrl,\n trackingNumber: payload.trackingNumber,\n carrier: payload.carrier,\n updatedAt: payload.updatedAt,\n })\n}\n\nfunction isManualRequest(input: ReturnLabelRequest): boolean {\n return input.manual === true\n || input.labelUrl !== undefined\n || input.trackingNumber !== undefined\n || input.carrier !== undefined\n}\n\nfunction toSetReturnLabelInput(\n input: ReturnLabelRequest,\n context: ActionRouteContext,\n): ClaimSetReturnLabelInput {\n const scopedPayload = withScopedPayload({\n id: input.claimId,\n labelUrl: input.labelUrl,\n trackingNumber: input.trackingNumber,\n carrier: input.carrier,\n updatedAt: input.updatedAt,\n }, context.ctx, context.translate)\n return claimSetReturnLabelSchema.parse(scopedPayload)\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: ReturnLabelRequest,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nasync function loadClaimAndLines(\n context: ActionRouteContext,\n claimId: string,\n): Promise<{ claim: WarrantyClaim; lines: WarrantyClaimLine[] }> {\n const scope = { tenantId: context.tenantId, organizationId: context.organizationId }\n const em = (context.ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, claimId, scope)\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 return { claim, lines }\n}\n\nfunction assertGeneratableStatus(claim: WarrantyClaim): void {\n if (claim.status !== 'approved' && claim.status !== 'awaiting_return') {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.returnLabelInvalidStatus' })\n }\n}\n\nasync function executeSetReturnLabel(\n commandBus: CommandBus,\n input: ClaimSetReturnLabelInput,\n ctx: CommandRuntimeContext,\n): Promise<ReturnLabelCreatedResponse> {\n const { result } = await commandBus.execute<ClaimSetReturnLabelInput, ReturnLabelCommandResult>(\n 'warranty_claims.claim.set_return_label',\n { input, ctx },\n )\n if (!result) throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n return {\n status: 'created',\n labelUrl: result.labelUrl,\n trackingNumber: result.trackingNumber,\n carrier: result.carrier,\n }\n}\n\nexport function firstTranslatableIssueKey(err: z.ZodError): string {\n const keyed = err.issues.find(\n (issue) => typeof issue.message === 'string' && issue.message.startsWith('warranty_claims.'),\n )?.message\n return keyed ?? 'warranty_claims.errors.invalidInput'\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const requestInput = toReturnLabelRequest(toRecord(await readJsonSafe(req, {})))\n const guarded = await runGuard(req, context, requestInput)\n if (!guarded.ok) {\n return guarded.response\n }\n const guardedInput = guarded.modifiedPayload ? toReturnLabelRequest(guarded.modifiedPayload) : requestInput\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n\n if (isManualRequest(guardedInput)) {\n const response = await executeSetReturnLabel(\n commandBus,\n toSetReturnLabelInput(guardedInput, context),\n context.ctx,\n )\n await guarded.runAfterSuccess()\n return NextResponse.json(response)\n }\n\n const { claim, lines } = await loadClaimAndLines(context, guardedInput.claimId)\n assertGeneratableStatus(claim)\n await enforceWarrantyClaimOptimisticLock(\n context.ctx,\n claim,\n WARRANTY_CLAIM_RESOURCE_KIND,\n guardedInput.updatedAt ?? undefined,\n )\n\n const provider = context.ctx.container.resolve<WarrantyReturnLabelProvider>('warrantyReturnLabelProvider')\n const result = await provider.createReturnLabel(\n { claim, lines },\n { tenantId: context.tenantId, organizationId: context.organizationId },\n context.ctx.container,\n )\n\n if (result.status === 'notConfigured') {\n return NextResponse.json({ status: 'notConfigured' })\n }\n\n const response = await executeSetReturnLabel(\n commandBus,\n toSetReturnLabelInput({\n ...guardedInput,\n labelUrl: result.labelUrl,\n trackingNumber: result.trackingNumber,\n carrier: result.carrier,\n }, context),\n context.ctx,\n )\n await guarded.runAfterSuccess()\n return NextResponse.json(response)\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: firstTranslatableIssueKey(err) }, { status: 400 })\n }\n logger.error('warranty_claims.return-label.post failed', { err })\n return NextResponse.json({ error: 'warranty_claims.errors.save_failed' }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create or record a return label for a warranty claim',\n methods: {\n POST: {\n summary: 'Generate a carrier return label or record manual label details',\n requestBody: { contentType: 'application/json', schema: returnLabelRequestSchema },\n responses: [\n {\n status: 200,\n description: 'Return label created or provider not configured',\n schema: returnLabelResponseSchema,\n },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oB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AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WarrantyClaim, WarrantyClaimLine } from '../../data/entities'\nimport { claimSetReturnLabelSchema, type ClaimSetReturnLabelInput } from '../../data/validators'\nimport type { WarrantyReturnLabelProvider } from '../../services/returnLabelProvider'\nimport {\n WARRANTY_CLAIM_RESOURCE_KIND,\n enforceWarrantyClaimOptimisticLock,\n requireScopedClaim,\n} from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype ReturnLabelCreatedResponse = {\n status: 'created'\n labelUrl: string | null\n trackingNumber: string | null\n carrier: string | null\n}\ntype ReturnLabelCommandResult = Omit<ReturnLabelCreatedResponse, 'status'> & { claimId: string }\n\nconst uuid = z.string().uuid()\nconst returnLabelText = (max: number) => z.string().trim().min(1).max(max).optional()\nconst optimisticLockTokenSchema = z.string().datetime().nullable().optional()\n\nconst returnLabelRequestSchema = z\n .object({\n claimId: uuid,\n manual: z.boolean().optional(),\n labelUrl: returnLabelText(2048),\n trackingNumber: returnLabelText(191),\n carrier: returnLabelText(120),\n updatedAt: optimisticLockTokenSchema,\n })\n .strict()\n\ntype ReturnLabelRequest = z.infer<typeof returnLabelRequestSchema>\n\nconst returnLabelResponseSchema = z.discriminatedUnion('status', [\n z.object({\n status: z.literal('created'),\n labelUrl: z.string().nullable(),\n trackingNumber: z.string().nullable(),\n carrier: z.string().nullable(),\n }),\n z.object({ status: z.literal('notConfigured') }),\n])\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction translateKey(key: string): string {\n return key\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.organization_required' })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate: translateKey,\n }\n}\n\nfunction toReturnLabelRequest(payload: Record<string, unknown>): ReturnLabelRequest {\n return returnLabelRequestSchema.parse({\n claimId: payload.claimId ?? payload.id,\n manual: payload.manual,\n labelUrl: payload.labelUrl,\n trackingNumber: payload.trackingNumber,\n carrier: payload.carrier,\n updatedAt: payload.updatedAt,\n })\n}\n\nfunction isManualRequest(input: ReturnLabelRequest): boolean {\n return input.manual === true\n || input.labelUrl !== undefined\n || input.trackingNumber !== undefined\n || input.carrier !== undefined\n}\n\nfunction toSetReturnLabelInput(\n input: ReturnLabelRequest,\n context: ActionRouteContext,\n): ClaimSetReturnLabelInput {\n const scopedPayload = withScopedPayload({\n id: input.claimId,\n labelUrl: input.labelUrl,\n trackingNumber: input.trackingNumber,\n carrier: input.carrier,\n updatedAt: input.updatedAt,\n }, context.ctx, context.translate)\n return claimSetReturnLabelSchema.parse(scopedPayload)\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: ReturnLabelRequest,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nasync function loadClaimAndLines(\n context: ActionRouteContext,\n claimId: string,\n): Promise<{ claim: WarrantyClaim; lines: WarrantyClaimLine[] }> {\n const scope = { tenantId: context.tenantId, organizationId: context.organizationId }\n const em = (context.ctx.container.resolve('em') as EntityManager).fork()\n const claim = await requireScopedClaim(em, claimId, scope)\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 return { claim, lines }\n}\n\nfunction assertGeneratableStatus(claim: WarrantyClaim): void {\n if (claim.status !== 'approved' && claim.status !== 'awaiting_return') {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.returnLabelInvalidStatus' })\n }\n}\n\nasync function executeSetReturnLabel(\n commandBus: CommandBus,\n input: ClaimSetReturnLabelInput,\n ctx: CommandRuntimeContext,\n): Promise<ReturnLabelCreatedResponse> {\n const { result } = await commandBus.execute<ClaimSetReturnLabelInput, ReturnLabelCommandResult>(\n 'warranty_claims.claim.set_return_label',\n { input, ctx },\n )\n if (!result) throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n return {\n status: 'created',\n labelUrl: result.labelUrl,\n trackingNumber: result.trackingNumber,\n carrier: result.carrier,\n }\n}\n\nexport function firstTranslatableIssueKey(err: z.ZodError): string {\n const keyed = err.issues.find(\n (issue) => typeof issue.message === 'string' && issue.message.startsWith('warranty_claims.'),\n )?.message\n return keyed ?? 'warranty_claims.errors.invalidInput'\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const requestInput = toReturnLabelRequest(toRecord(await readJsonSafe(req, {})))\n const guarded = await runGuard(req, context, requestInput)\n if (!guarded.ok) {\n return guarded.response\n }\n const guardedInput = guarded.modifiedPayload ? toReturnLabelRequest(guarded.modifiedPayload) : requestInput\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n\n if (isManualRequest(guardedInput)) {\n const response = await executeSetReturnLabel(\n commandBus,\n toSetReturnLabelInput(guardedInput, context),\n context.ctx,\n )\n await guarded.runAfterSuccess()\n return NextResponse.json(response)\n }\n\n const { claim, lines } = await loadClaimAndLines(context, guardedInput.claimId)\n assertGeneratableStatus(claim)\n await enforceWarrantyClaimOptimisticLock(\n context.ctx,\n claim,\n WARRANTY_CLAIM_RESOURCE_KIND,\n guardedInput.updatedAt ?? undefined,\n )\n\n const provider = context.ctx.container.resolve<WarrantyReturnLabelProvider>('warrantyReturnLabelProvider')\n const result = await provider.createReturnLabel(\n { claim, lines },\n { tenantId: context.tenantId, organizationId: context.organizationId },\n context.ctx.container,\n )\n\n if (result.status === 'notConfigured') {\n return NextResponse.json({ status: 'notConfigured' })\n }\n\n const response = await executeSetReturnLabel(\n commandBus,\n toSetReturnLabelInput({\n ...guardedInput,\n labelUrl: result.labelUrl,\n trackingNumber: result.trackingNumber,\n carrier: result.carrier,\n }, context),\n context.ctx,\n )\n await guarded.runAfterSuccess()\n return NextResponse.json(response)\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: firstTranslatableIssueKey(err) }, { status: 400 })\n }\n logger.error('warranty_claims.return-label.post failed', { err })\n return NextResponse.json({ error: 'warranty_claims.errors.save_failed' }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create or record a return label for a warranty claim',\n methods: {\n POST: {\n summary: 'Generate a carrier return label or record manual label details',\n requestBody: { contentType: 'application/json', schema: returnLabelRequestSchema },\n responses: [\n {\n status: 200,\n description: 'Return label created or provider not configured',\n schema: returnLabelResponseSchema,\n },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,eAAe,uBAAuB;AAC/C,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC,SAAS,0BAA0B;AACnC,SAAwB,yBAAyB;AACjD,SAAS,iCAAgE;AAEzE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,iBAAiB;AAiB7C,MAAM,OAAO,EAAE,OAAO,EAAE,KAAK;AAC7B,MAAM,kBAAkB,CAAC,QAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AACpF,MAAM,4BAA4B,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS;AAE5E,MA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,QAAQ,gBAAgB;AAC9B,WAAO,aAAa,KAAK,QAAQ;AAAA,EACnC,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,EAAG,QAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AACnF,UAAM,uBAAuB,mCAAmC,GAAG;AACnE,QAAI,sBAAsB;AACxB,aAAO,aAAa,KAAK,qBAAqB,MAAM,EAAE,QAAQ,qBAAqB,OAAO,CAAC;AAAA,IAC7F;AACA,QAAI,eAAe,EAAE,UAAU;AAC7B,aAAO,aAAa,KAAK,EAAE,OAAO,0BAA0B,GAAG,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrF;AACA,WAAO,MAAM,4CAA4C,EAAE,IAAI,CAAC;AAChE,WAAO,aAAa,KAAK,EAAE,OAAO,qCAAqC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,yBAAyB;AAAA,MACjF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": ["response"]
7
7
  }
@@ -4,6 +4,7 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
4
4
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
5
5
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
6
6
  import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
7
+ import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
7
8
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
8
9
  import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
9
10
  import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
@@ -111,6 +112,10 @@ async function POST(req) {
111
112
  return NextResponse.json({ salesReturnId: result.salesReturnId, skippedLineIds: result.skippedLineIds });
112
113
  } catch (err) {
113
114
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
115
+ const interceptorRejection = getCommandInterceptorHttpRejection(err);
116
+ if (interceptorRejection) {
117
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status });
118
+ }
114
119
  if (err instanceof z.ZodError) {
115
120
  return NextResponse.json({ error: "warranty_claims.errors.invalidInput" }, { status: 400 });
116
121
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/warranty_claims/api/sales-return/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { claimCreateSalesReturnSchema, type ClaimCreateSalesReturnInput } from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype SalesReturnCommandResult = {\n claimId: string\n salesReturnId: string\n salesReturnUpdatedAt: string | null\n skippedLineIds: string[]\n}\n\nconst uuid = z.string().uuid()\nconst optimisticLockTokenSchema = z.string().datetime().nullable().optional()\n\nconst salesReturnRequestSchema = z\n .object({\n claimId: uuid,\n updatedAt: optimisticLockTokenSchema,\n })\n .strict()\n\ntype SalesReturnRequest = z.infer<typeof salesReturnRequestSchema>\n\nconst salesReturnResponseSchema = z.object({\n salesReturnId: z.string(),\n skippedLineIds: z.array(z.string()),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n})\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage', 'sales.returns.create'] },\n}\n\nfunction translateKey(key: string): string {\n return key\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.organization_required' })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate: translateKey,\n }\n}\n\nfunction toSalesReturnRequest(payload: Record<string, unknown>): SalesReturnRequest {\n return salesReturnRequestSchema.parse({\n claimId: payload.claimId ?? payload.id,\n updatedAt: payload.updatedAt,\n })\n}\n\nfunction toCommandInput(input: SalesReturnRequest, context: ActionRouteContext): ClaimCreateSalesReturnInput {\n const scopedPayload = withScopedPayload({\n id: input.claimId,\n updatedAt: input.updatedAt,\n }, context.ctx, context.translate)\n return claimCreateSalesReturnSchema.parse(scopedPayload)\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: SalesReturnRequest,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const requestInput = toSalesReturnRequest(toRecord(await readJsonSafe(req, {})))\n const guarded = await runGuard(req, context, requestInput)\n if (!guarded.ok) {\n return guarded.response\n }\n const guardedInput = guarded.modifiedPayload ? toSalesReturnRequest(guarded.modifiedPayload) : requestInput\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<ClaimCreateSalesReturnInput, SalesReturnCommandResult>(\n 'warranty_claims.claim.create_sales_return',\n { input: toCommandInput(guardedInput, context), ctx: context.ctx },\n )\n if (!result) throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n await guarded.runAfterSuccess()\n return NextResponse.json({ salesReturnId: result.salesReturnId, skippedLineIds: result.skippedLineIds })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: 'warranty_claims.errors.invalidInput' }, { status: 400 })\n }\n logger.error('warranty_claims.sales-return.post failed', { err })\n return NextResponse.json({ error: 'warranty_claims.errors.save_failed' }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create a sales return from an approved warranty claim',\n methods: {\n POST: {\n summary: 'Create a sales return document from the claim\\'s eligible lines and link it to the claim',\n requestBody: {\n contentType: 'application/json',\n schema: salesReturnRequestSchema,\n description: 'Use claimId to identify the warranty claim. The id field is also accepted as an alias for claimId.',\n },\n responses: [\n {\n status: 200,\n description: 'Sales return created and linked; lines without an order-line reference are reported as skipped',\n schema: salesReturnResponseSchema,\n },\n { status: 400, description: 'Invalid request or claim is not eligible for sales-return creation', schema: errorResponseSchema },\n { status: 401, description: 'Authentication required', schema: errorResponseSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorResponseSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,eAAe,uBAAuB;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC,SAAS,oCAAsE;AAC/E,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,iBAAiB;AAgB7C,MAAM,OAAO,EAAE,OAAO,EAAE,KAAK;AAC7B,MAAM,4BAA4B,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS;AAE5E,MAAM,2BAA2B,EAC9B,OAAO;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AACb,CAAC,EACA,OAAO;AAIV,MAAM,4BAA4B,EAAE,OAAO;AAAA,EACzC,eAAe,EAAE,OAAO;AAAA,EACxB,gBAAgB,EAAE,MAAM,EAAE,OAAO,CAAC;AACpC,CAAC;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,OAAO,EAAE,OAAO;AAClB,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,gCAAgC,sBAAsB,EAAE;AACvG;AAEA,SAAS,aAAa,KA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a,KAAK,EAAE,OAAO,sCAAsC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC5F;AACA,WAAO,MAAM,4CAA4C,EAAE,IAAI,CAAC;AAChE,WAAO,aAAa,KAAK,EAAE,OAAO,qCAAqC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,QACR,aAAa;AAAA,MACf;AAAA,MACA,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,QACA,EAAE,QAAQ,KAAK,aAAa,sEAAsE,QAAQ,oBAAoB;AAAA,QAC9H,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,oBAAoB;AAAA,QACnF,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,oBAAoB;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,oBAAoB;AAAA,MACtF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { claimCreateSalesReturnSchema, type ClaimCreateSalesReturnInput } from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype SalesReturnCommandResult = {\n claimId: string\n salesReturnId: string\n salesReturnUpdatedAt: string | null\n skippedLineIds: string[]\n}\n\nconst uuid = z.string().uuid()\nconst optimisticLockTokenSchema = z.string().datetime().nullable().optional()\n\nconst salesReturnRequestSchema = z\n .object({\n claimId: uuid,\n updatedAt: optimisticLockTokenSchema,\n })\n .strict()\n\ntype SalesReturnRequest = z.infer<typeof salesReturnRequestSchema>\n\nconst salesReturnResponseSchema = z.object({\n salesReturnId: z.string(),\n skippedLineIds: z.array(z.string()),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n})\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage', 'sales.returns.create'] },\n}\n\nfunction translateKey(key: string): string {\n return key\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: 'warranty_claims.errors.organization_required' })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate: translateKey,\n }\n}\n\nfunction toSalesReturnRequest(payload: Record<string, unknown>): SalesReturnRequest {\n return salesReturnRequestSchema.parse({\n claimId: payload.claimId ?? payload.id,\n updatedAt: payload.updatedAt,\n })\n}\n\nfunction toCommandInput(input: SalesReturnRequest, context: ActionRouteContext): ClaimCreateSalesReturnInput {\n const scopedPayload = withScopedPayload({\n id: input.claimId,\n updatedAt: input.updatedAt,\n }, context.ctx, context.translate)\n return claimCreateSalesReturnSchema.parse(scopedPayload)\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: SalesReturnRequest,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: 'warranty_claims.errors.unauthorized' })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const requestInput = toSalesReturnRequest(toRecord(await readJsonSafe(req, {})))\n const guarded = await runGuard(req, context, requestInput)\n if (!guarded.ok) {\n return guarded.response\n }\n const guardedInput = guarded.modifiedPayload ? toSalesReturnRequest(guarded.modifiedPayload) : requestInput\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<ClaimCreateSalesReturnInput, SalesReturnCommandResult>(\n 'warranty_claims.claim.create_sales_return',\n { input: toCommandInput(guardedInput, context), ctx: context.ctx },\n )\n if (!result) throw new CrudHttpError(400, { error: 'warranty_claims.errors.save_failed' })\n await guarded.runAfterSuccess()\n return NextResponse.json({ salesReturnId: result.salesReturnId, skippedLineIds: result.skippedLineIds })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: 'warranty_claims.errors.invalidInput' }, { status: 400 })\n }\n logger.error('warranty_claims.sales-return.post failed', { err })\n return NextResponse.json({ error: 'warranty_claims.errors.save_failed' }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create a sales return from an approved warranty claim',\n methods: {\n POST: {\n summary: 'Create a sales return document from the claim\\'s eligible lines and link it to the claim',\n requestBody: {\n contentType: 'application/json',\n schema: salesReturnRequestSchema,\n description: 'Use claimId to identify the warranty claim. The id field is also accepted as an alias for claimId.',\n },\n responses: [\n {\n status: 200,\n description: 'Sales return created and linked; lines without an order-line reference are reported as skipped',\n schema: salesReturnResponseSchema,\n },\n { status: 400, description: 'Invalid request or claim is not eligible for sales-return creation', schema: errorResponseSchema },\n { status: 401, description: 'Authentication required', schema: errorResponseSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorResponseSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,eAAe,uBAAuB;AAC/C,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC,SAAS,oCAAsE;AAC/E,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,iBAAiB;AAgB7C,MAAM,OAAO,EAAE,OAAO,EAAE,KAAK;AAC7B,MAAM,4BAA4B,EAAE,OAAO,EAAE,SAAS,EAAE,SAA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AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,oBAAoB;AAAA,MACtF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
5
5
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
6
6
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
7
7
  import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
8
+ import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
8
9
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
9
10
  import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
10
11
  import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
@@ -127,6 +128,10 @@ async function PUT(req) {
127
128
  });
128
129
  } catch (err) {
129
130
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
131
+ const interceptorRejection = getCommandInterceptorHttpRejection(err);
132
+ if (interceptorRejection) {
133
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status });
134
+ }
130
135
  const { translate } = await resolveTranslations();
131
136
  if (err instanceof z.ZodError) {
132
137
  return NextResponse.json({ error: translate("warranty_claims.errors.invalidInput", "Invalid input") }, { status: 400 });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/warranty_claims/api/settings-general/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n warrantyClaimSettingsSaveSchema,\n warrantyClaimSettingsUpdateSchema,\n type WarrantyClaimSettingsSaveInput,\n} from '../../data/validators'\nimport {\n loadWarrantyClaimSettings,\n resolveEffectiveWarrantyClaimSettings,\n type WarrantyClaimEffectiveSettings,\n} from '../../lib/settings'\nimport { WARRANTY_CLAIM_SETTINGS_RESOURCE_KIND, type SaveWarrantyClaimSettingsResult } from '../../commands/settings'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['warranty_claims.settings.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['warranty_claims.settings.manage'] },\n}\n\ntype SettingsRouteContext = {\n ctx: CommandRuntimeContext\n em: EntityManager\n tenantId: string\n organizationId: string\n userId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype SettingsResponseResult = WarrantyClaimEffectiveSettings & {\n returnWindowDays: number | null\n updatedAt: string | null\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\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\nasync function resolveSettingsContext(req: Request): Promise<SettingsRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n const ctx: CommandRuntimeContext = {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n }\n return {\n ctx,\n em: container.resolve('em') as EntityManager,\n tenantId: auth.tenantId,\n organizationId,\n userId: auth.sub ?? '',\n translate,\n }\n}\n\nasync function buildSettingsResult(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n): Promise<SettingsResponseResult> {\n const record = await loadWarrantyClaimSettings(em, scope)\n const effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n return {\n ...effectiveSettings,\n returnWindowDays: record?.returnWindowDays ?? null,\n updatedAt: toIso(record?.updatedAt),\n }\n}\n\nexport async function GET(req: Request) {\n try {\n const { em, tenantId, organizationId } = await resolveSettingsContext(req)\n const result = await buildSettingsResult(em, { tenantId, organizationId })\n return NextResponse.json({ ok: true, result })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const { translate } = await resolveTranslations()\n logger.error('warranty_claims.settings-general.get failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.load_failed', 'Failed to load warranty claim data.') }, { status: 500 })\n }\n}\n\nexport async function PUT(req: Request) {\n try {\n const { ctx, em, tenantId, organizationId, userId, translate } = await resolveSettingsContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const parsed = warrantyClaimSettingsUpdateSchema.parse(payload)\n const parsedPayload: Record<string, unknown> = { ...parsed }\n const existing = await loadWarrantyClaimSettings(em, { tenantId, organizationId })\n const guarded = await runRouteMutationGuards({\n container: ctx.container,\n req,\n auth: { userId, tenantId, organizationId },\n input: {\n resourceKind: WARRANTY_CLAIM_SETTINGS_RESOURCE_KIND,\n resourceId: existing?.id ?? null,\n operation: existing ? 'update' : 'create',\n mutationPayload: parsedPayload,\n },\n })\n if (!guarded.ok) return guarded.response\n\n const guardedPayload = guarded.modifiedPayload\n ? warrantyClaimSettingsUpdateSchema.parse({ ...parsedPayload, ...guarded.modifiedPayload })\n : parsed\n const commandInput = warrantyClaimSettingsSaveSchema.parse(withScopedPayload({ ...guardedPayload }, ctx, translate))\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<\n WarrantyClaimSettingsSaveInput,\n SaveWarrantyClaimSettingsResult\n >('warranty_claims.settings.save', { input: commandInput, ctx })\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({\n ok: true,\n result: {\n slaHours: result.slaHours,\n slaPauseOnInfoRequested: result.slaPauseOnInfoRequested,\n slaAtRiskThresholdPct: result.slaAtRiskThresholdPct,\n autoApproveEnabled: result.autoApproveEnabled,\n autoApproveMaxAmount: result.autoApproveMaxAmount,\n autoApproveCurrencyCode: result.autoApproveCurrencyCode,\n autoApproveRequireInWarranty: result.autoApproveRequireInWarranty,\n defaultWarrantyMonths: result.defaultWarrantyMonths,\n businessHours: result.businessHours,\n escalationTiers: result.escalationTiers,\n adjudicationUseRules: result.adjudicationUseRules,\n quarantineGrades: result.quarantineGrades,\n returnLabelProvider: result.returnLabelProvider,\n returnWindowDays: result.returnWindowDays,\n updatedAt: result.updatedAt,\n },\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.settings-general.put failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nconst settingsResultSchema = z.object({\n slaHours: z.number(),\n slaPauseOnInfoRequested: z.boolean(),\n slaAtRiskThresholdPct: z.number(),\n autoApproveEnabled: z.boolean(),\n autoApproveMaxAmount: z.number().nullable(),\n autoApproveCurrencyCode: z.string().nullable(),\n autoApproveRequireInWarranty: z.boolean(),\n defaultWarrantyMonths: z.number().nullable(),\n businessHours: z.record(z.string(), z.unknown()).nullable(),\n escalationTiers: z.array(z.unknown()).nullable(),\n adjudicationUseRules: z.boolean(),\n quarantineGrades: z.array(z.string()).nullable(),\n returnLabelProvider: z.string().nullable(),\n returnWindowDays: z.number().nullable(),\n updatedAt: z.string().nullable(),\n})\n\nconst settingsResponseSchema = z.object({\n ok: z.boolean(),\n result: settingsResultSchema,\n})\n\nconst settingsErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Warranty claim general settings',\n methods: {\n GET: {\n summary: 'Get warranty claim general settings',\n responses: [\n { status: 200, description: 'Current warranty claim general settings', schema: settingsResponseSchema },\n { status: 401, description: 'Unauthorized', schema: settingsErrorSchema },\n { status: 400, description: 'Invalid scope', schema: settingsErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update warranty claim general settings',\n requestBody: {\n contentType: 'application/json',\n schema: warrantyClaimSettingsUpdateSchema,\n },\n responses: [\n { status: 200, description: 'Updated warranty claim general settings', schema: settingsResponseSchema },\n { status: 401, description: 'Unauthorized', schema: settingsErrorSchema },\n { status: 400, description: 'Invalid payload', schema: settingsErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: settingsErrorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAElC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;A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OAAO;AAAA,EACnC,OAAO,EAAE,OAAO;AAClB,CAAC;AAEM,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C,QAAQ,uBAAuB;AAAA,QACtG,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,MAC3E;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C,QAAQ,uBAAuB;AAAA,QACtG,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,oBAAoB;AAAA,QAC3E,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,oBAAoB;AAAA,MACtF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n warrantyClaimSettingsSaveSchema,\n warrantyClaimSettingsUpdateSchema,\n type WarrantyClaimSettingsSaveInput,\n} from '../../data/validators'\nimport {\n loadWarrantyClaimSettings,\n resolveEffectiveWarrantyClaimSettings,\n type WarrantyClaimEffectiveSettings,\n} from '../../lib/settings'\nimport { WARRANTY_CLAIM_SETTINGS_RESOURCE_KIND, type SaveWarrantyClaimSettingsResult } from '../../commands/settings'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['warranty_claims.settings.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['warranty_claims.settings.manage'] },\n}\n\ntype SettingsRouteContext = {\n ctx: CommandRuntimeContext\n em: EntityManager\n tenantId: string\n organizationId: string\n userId: string\n translate: (key: string, fallback?: string) => string\n}\n\ntype SettingsResponseResult = WarrantyClaimEffectiveSettings & {\n returnWindowDays: number | null\n updatedAt: string | null\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\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\nasync function resolveSettingsContext(req: Request): Promise<SettingsRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n const ctx: CommandRuntimeContext = {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n }\n return {\n ctx,\n em: container.resolve('em') as EntityManager,\n tenantId: auth.tenantId,\n organizationId,\n userId: auth.sub ?? '',\n translate,\n }\n}\n\nasync function buildSettingsResult(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n): Promise<SettingsResponseResult> {\n const record = await loadWarrantyClaimSettings(em, scope)\n const effectiveSettings = await resolveEffectiveWarrantyClaimSettings(em, scope)\n return {\n ...effectiveSettings,\n returnWindowDays: record?.returnWindowDays ?? null,\n updatedAt: toIso(record?.updatedAt),\n }\n}\n\nexport async function GET(req: Request) {\n try {\n const { em, tenantId, organizationId } = await resolveSettingsContext(req)\n const result = await buildSettingsResult(em, { tenantId, organizationId })\n return NextResponse.json({ ok: true, result })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const { translate } = await resolveTranslations()\n logger.error('warranty_claims.settings-general.get failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.load_failed', 'Failed to load warranty claim data.') }, { status: 500 })\n }\n}\n\nexport async function PUT(req: Request) {\n try {\n const { ctx, em, tenantId, organizationId, userId, translate } = await resolveSettingsContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const parsed = warrantyClaimSettingsUpdateSchema.parse(payload)\n const parsedPayload: Record<string, unknown> = { ...parsed }\n const existing = await loadWarrantyClaimSettings(em, { tenantId, organizationId })\n const guarded = await runRouteMutationGuards({\n container: ctx.container,\n req,\n auth: { userId, tenantId, organizationId },\n input: {\n resourceKind: WARRANTY_CLAIM_SETTINGS_RESOURCE_KIND,\n resourceId: existing?.id ?? null,\n operation: existing ? 'update' : 'create',\n mutationPayload: parsedPayload,\n },\n })\n if (!guarded.ok) return guarded.response\n\n const guardedPayload = guarded.modifiedPayload\n ? warrantyClaimSettingsUpdateSchema.parse({ ...parsedPayload, ...guarded.modifiedPayload })\n : parsed\n const commandInput = warrantyClaimSettingsSaveSchema.parse(withScopedPayload({ ...guardedPayload }, ctx, translate))\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<\n WarrantyClaimSettingsSaveInput,\n SaveWarrantyClaimSettingsResult\n >('warranty_claims.settings.save', { input: commandInput, ctx })\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({\n ok: true,\n result: {\n slaHours: result.slaHours,\n slaPauseOnInfoRequested: result.slaPauseOnInfoRequested,\n slaAtRiskThresholdPct: result.slaAtRiskThresholdPct,\n autoApproveEnabled: result.autoApproveEnabled,\n autoApproveMaxAmount: result.autoApproveMaxAmount,\n autoApproveCurrencyCode: result.autoApproveCurrencyCode,\n autoApproveRequireInWarranty: result.autoApproveRequireInWarranty,\n defaultWarrantyMonths: result.defaultWarrantyMonths,\n businessHours: result.businessHours,\n escalationTiers: result.escalationTiers,\n adjudicationUseRules: result.adjudicationUseRules,\n quarantineGrades: result.quarantineGrades,\n returnLabelProvider: result.returnLabelProvider,\n returnWindowDays: result.returnWindowDays,\n updatedAt: result.updatedAt,\n },\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.settings-general.put failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nconst settingsResultSchema = z.object({\n slaHours: z.number(),\n slaPauseOnInfoRequested: z.boolean(),\n slaAtRiskThresholdPct: z.number(),\n autoApproveEnabled: z.boolean(),\n autoApproveMaxAmount: z.number().nullable(),\n autoApproveCurrencyCode: z.string().nullable(),\n autoApproveRequireInWarranty: z.boolean(),\n defaultWarrantyMonths: z.number().nullable(),\n businessHours: z.record(z.string(), z.unknown()).nullable(),\n escalationTiers: z.array(z.unknown()).nullable(),\n adjudicationUseRules: z.boolean(),\n quarantineGrades: z.array(z.string()).nullable(),\n returnLabelProvider: z.string().nullable(),\n returnWindowDays: z.number().nullable(),\n updatedAt: z.string().nullable(),\n})\n\nconst settingsResponseSchema = z.object({\n ok: z.boolean(),\n result: settingsResultSchema,\n})\n\nconst settingsErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Warranty claim general settings',\n methods: {\n GET: {\n summary: 'Get warranty claim general settings',\n responses: [\n { status: 200, description: 'Current warranty claim general settings', schema: settingsResponseSchema },\n { status: 401, description: 'Unauthorized', schema: settingsErrorSchema },\n { status: 400, description: 'Invalid scope', schema: settingsErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update warranty claim general settings',\n requestBody: {\n contentType: 'application/json',\n schema: warrantyClaimSettingsUpdateSchema,\n },\n responses: [\n { status: 200, description: 'Updated warranty claim general settings', schema: settingsResponseSchema },\n { status: 401, description: 'Unauthorized', schema: settingsErrorSchema },\n { status: 400, description: 'Invalid payload', schema: settingsErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: settingsErrorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAElC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA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AC;AAED,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,IAAI,EAAE,QAAQ;AAAA,EACd,QAAQ;AACV,CAAC;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,OAAO,EAAE,OAAO;AAClB,CAAC;AAEM,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C,QAAQ,uBAAuB;AAAA,QACtG,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,MAC3E;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C,QAAQ,uBAAuB;AAAA,QACtG,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,oBAAoB;AAAA,QAC3E,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,oBAAoB;AAAA,MACtF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
5
5
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
6
6
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
7
7
  import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
8
+ import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
8
9
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
9
10
  import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
10
11
  import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
@@ -87,6 +88,10 @@ async function POST(req) {
87
88
  return NextResponse.json({ ok: true, claimId: result?.claimId ?? commandInput.id });
88
89
  } catch (err) {
89
90
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
91
+ const interceptorRejection = getCommandInterceptorHttpRejection(err);
92
+ if (interceptorRejection) {
93
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status });
94
+ }
90
95
  const { translate } = await resolveTranslations();
91
96
  if (err instanceof z.ZodError) {
92
97
  return NextResponse.json({ error: translate("warranty_claims.errors.invalidInput", "Invalid input") }, { status: 400 });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/warranty_claims/api/submit/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\n// Scope is derived from the authenticated principal, never accepted from the body \u2014\n// mirroring the sibling transition/assign routes. `withScopedPayload` prefers a\n// caller-supplied tenantId/organizationId over the actor's context, so admitting them\n// here would let the request choose its own scope.\nconst submitSchema = z\n .object({\n id: z.string().uuid(),\n })\n .strict()\n\ntype SubmitInput = z.infer<typeof submitSchema>\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate,\n }\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: SubmitInput,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: context.translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.id,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const scopedPayload = toRecord(withScopedPayload(payload, context.ctx, context.translate))\n const input = submitSchema.parse({ id: scopedPayload.id })\n const guarded = await runGuard(req, context, input)\n if (!guarded.ok) {\n return guarded.response\n }\n const commandInput = guarded.modifiedPayload ? submitSchema.parse(guarded.modifiedPayload) : input\n\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<SubmitInput, { claimId: string }>(\n 'warranty_claims.claim.submit',\n { input: commandInput, ctx: context.ctx },\n )\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({ ok: true, claimId: result?.claimId ?? commandInput.id })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.submit.post failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Submit warranty claim',\n methods: {\n POST: {\n summary: 'Submit a draft claim',\n requestBody: { contentType: 'application/json', schema: submitSchema },\n responses: [\n {\n status: 200,\n description: 'Claim submitted',\n schema: z.object({ ok: z.boolean(), claimId: z.string().uuid() }),\n },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,M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I,eAAe,EAAE,UAAU;AAC7B,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,uCAAuC,eAAe,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACxH;AACA,WAAO,MAAM,sCAAsC,EAAE,IAAI,CAAC;AAC1D,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,sCAAsC,+BAA+B,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACvI;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,aAAa;AAAA,MACrE,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,GAAG,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,QAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\n// Scope is derived from the authenticated principal, never accepted from the body \u2014\n// mirroring the sibling transition/assign routes. `withScopedPayload` prefers a\n// caller-supplied tenantId/organizationId over the actor's context, so admitting them\n// here would let the request choose its own scope.\nconst submitSchema = z\n .object({\n id: z.string().uuid(),\n })\n .strict()\n\ntype SubmitInput = z.infer<typeof submitSchema>\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate,\n }\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: SubmitInput,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: context.translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.id,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const scopedPayload = toRecord(withScopedPayload(payload, context.ctx, context.translate))\n const input = submitSchema.parse({ id: scopedPayload.id })\n const guarded = await runGuard(req, context, input)\n if (!guarded.ok) {\n return guarded.response\n }\n const commandInput = guarded.modifiedPayload ? submitSchema.parse(guarded.modifiedPayload) : input\n\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<SubmitInput, { claimId: string }>(\n 'warranty_claims.claim.submit',\n { input: commandInput, ctx: context.ctx },\n )\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({ ok: true, claimId: result?.claimId ?? commandInput.id })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.submit.post failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Submit warranty claim',\n methods: {\n POST: {\n summary: 'Submit a draft claim',\n requestBody: { contentType: 'application/json', schema: submitSchema },\n responses: [\n {\n status: 200,\n description: 'Claim submitted',\n schema: z.object({ ok: z.boolean(), claimId: z.string().uuid() }),\n },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAo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AQ,gBAAgB;AAE9B,WAAO,aAAa,KAAK,EAAE,IAAI,MAAM,SAAS,QAAQ,WAAW,aAAa,GAAG,CAAC;AAAA,EACpF,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,EAAG,QAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AACnF,UAAM,uBAAuB,mCAAmC,GAAG;AACnE,QAAI,sBAAsB;AACxB,aAAO,aAAa,KAAK,qBAAqB,MAAM,EAAE,QAAQ,qBAAqB,OAAO,CAAC;AAAA,IAC7F;AACA,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAI,eAAe,EAAE,UAAU;AAC7B,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,uCAAuC,eAAe,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACxH;AACA,WAAO,MAAM,sCAAsC,EAAE,IAAI,CAAC;AAC1D,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,sCAAsC,+BAA+B,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACvI;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,aAAa;AAAA,MACrE,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,GAAG,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,QAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
5
5
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
6
6
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
7
7
  import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
8
+ import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
8
9
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
9
10
  import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
10
11
  import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
@@ -93,6 +94,10 @@ async function POST(req) {
93
94
  return NextResponse.json({ ok: true, claimId: result?.claimId ?? commandInput.id });
94
95
  } catch (err) {
95
96
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
97
+ const interceptorRejection = getCommandInterceptorHttpRejection(err);
98
+ if (interceptorRejection) {
99
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status });
100
+ }
96
101
  const { translate } = await resolveTranslations();
97
102
  if (err instanceof z.ZodError) {
98
103
  return NextResponse.json({ error: translate("warranty_claims.errors.invalidInput", "Invalid input") }, { status: 400 });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/warranty_claims/api/transition/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { transitionClaimInputSchema, type TransitionClaimInput } from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate,\n }\n}\n\nfunction toTransitionInput(scopedPayload: Record<string, unknown>): TransitionClaimInput {\n return transitionClaimInputSchema.parse({\n id: scopedPayload.id,\n toStatus: scopedPayload.toStatus,\n rejectionReasonCode: scopedPayload.rejectionReasonCode,\n resolutionSummary: scopedPayload.resolutionSummary,\n })\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: TransitionClaimInput,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: context.translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.id,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const scopedPayload = withScopedPayload(payload, context.ctx, context.translate)\n const input = toTransitionInput(scopedPayload)\n const guarded = await runGuard(req, context, input)\n if (!guarded.ok) {\n return guarded.response\n }\n const commandInput = guarded.modifiedPayload ? toTransitionInput(guarded.modifiedPayload) : input\n\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<TransitionClaimInput, { claimId: string }>(\n 'warranty_claims.claim.transition',\n { input: commandInput, ctx: context.ctx },\n )\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({ ok: true, claimId: result?.claimId ?? commandInput.id })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.transition.post failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Transition warranty claim',\n methods: {\n POST: {\n summary: 'Move a claim through the lifecycle',\n requestBody: { contentType: 'application/json', schema: transitionClaimInputSchema },\n responses: [\n {\n status: 200,\n description: 'Claim transitioned',\n schema: z.object({ ok: z.boolean(), claimId: z.string().uuid() }),\n },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SA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AgB;AAE9B,WAAO,aAAa,KAAK,EAAE,IAAI,MAAM,SAAS,QAAQ,WAAW,aAAa,GAAG,CAAC;AAAA,EACpF,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,EAAG,QAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AACnF,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAI,eAAe,EAAE,UAAU;AAC7B,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,uCAAuC,eAAe,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACxH;AACA,WAAO,MAAM,0CAA0C,EAAE,IAAI,CAAC;AAC9D,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,sCAAsC,+BAA+B,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACvI;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,2BAA2B;AAAA,MACnF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,GAAG,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,QAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { transitionClaimInputSchema, type TransitionClaimInput } from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate,\n }\n}\n\nfunction toTransitionInput(scopedPayload: Record<string, unknown>): TransitionClaimInput {\n return transitionClaimInputSchema.parse({\n id: scopedPayload.id,\n toStatus: scopedPayload.toStatus,\n rejectionReasonCode: scopedPayload.rejectionReasonCode,\n resolutionSummary: scopedPayload.resolutionSummary,\n })\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: TransitionClaimInput,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: context.translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.id,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const scopedPayload = withScopedPayload(payload, context.ctx, context.translate)\n const input = toTransitionInput(scopedPayload)\n const guarded = await runGuard(req, context, input)\n if (!guarded.ok) {\n return guarded.response\n }\n const commandInput = guarded.modifiedPayload ? toTransitionInput(guarded.modifiedPayload) : input\n\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<TransitionClaimInput, { claimId: string }>(\n 'warranty_claims.claim.transition',\n { input: commandInput, ctx: context.ctx },\n )\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({ ok: true, claimId: result?.claimId ?? commandInput.id })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.transition.post failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Transition warranty claim',\n methods: {\n POST: {\n summary: 'Move a claim through the lifecycle',\n requestBody: { contentType: 'application/json', schema: transitionClaimInputSchema },\n responses: [\n {\n status: 200,\n description: 'Claim transitioned',\n schema: z.object({ ok: z.boolean(), claimId: z.string().uuid() }),\n },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC,SAAS,kCAA6D;AACtE,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,iBAAiB;AAStC,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,8BAA8B,EAAE;AAC/E;AAEA,SAAS,SAAS,OAAyC;AACzD,SAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAI,QAAmC,CAAC;AAC3G;AAEA,eAAe,qBAAqB,KAA2C;AAC7E,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,MAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,UAAU,uCAAuC,cAAc,EAAE,CAAC;AAAA,EAC1G;AACA,QAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,SAAS,IAAI,CAAC;AACxF,QAAM,iBAAiB,OAAO,cAAc,KAAK,SAAS;AAC1D,MAAI,CAAC,gBAAgB;AACnB,UAAM,I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UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,GAAG,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,QAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
5
5
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
6
6
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
7
7
  import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
8
+ import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
8
9
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
9
10
  import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
10
11
  import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
@@ -97,6 +98,10 @@ async function POST(req) {
97
98
  return NextResponse.json({ ok: true, claimId: createdClaimId });
98
99
  } catch (err) {
99
100
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
101
+ const interceptorRejection = getCommandInterceptorHttpRejection(err);
102
+ if (interceptorRejection) {
103
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status });
104
+ }
100
105
  const { translate } = await resolveTranslations();
101
106
  if (err instanceof z.ZodError) {
102
107
  return NextResponse.json({ error: translate("warranty_claims.errors.invalidInput", "Invalid input") }, { status: 400 });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/warranty_claims/api/vendor-recovery/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { vendorRecoveryInputSchema, type VendorRecoveryInput } from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate,\n }\n}\n\nfunction toVendorRecoveryInput(scopedPayload: Record<string, unknown>): VendorRecoveryInput {\n return vendorRecoveryInputSchema.parse({\n claimId: scopedPayload.claimId,\n lineIds: scopedPayload.lineIds,\n vendorName: scopedPayload.vendorName,\n vendorRef: scopedPayload.vendorRef,\n })\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: VendorRecoveryInput,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: context.translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const scopedPayload = withScopedPayload(payload, context.ctx, context.translate)\n const input = toVendorRecoveryInput(scopedPayload)\n const guarded = await runGuard(req, context, input)\n if (!guarded.ok) {\n return guarded.response\n }\n const commandInput = guarded.modifiedPayload ? toVendorRecoveryInput(guarded.modifiedPayload) : input\n\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<VendorRecoveryInput, { claimId: string }>(\n 'warranty_claims.claim.create_vendor_recovery',\n { input: commandInput, ctx: context.ctx },\n )\n const createdClaimId = result?.claimId\n if (typeof createdClaimId !== 'string') {\n throw new CrudHttpError(400, { error: context.translate('warranty_claims.errors.notFound', 'Warranty claim not found.') })\n }\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({ ok: true, claimId: createdClaimId })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.vendor-recovery.post failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create vendor recovery claim',\n methods: {\n POST: {\n summary: 'Create a linked vendor-recovery claim from resolved source lines',\n requestBody: { contentType: 'application/json', schema: vendorRecoveryInputSchema },\n responses: [\n {\n status: 200,\n description: 'Vendor recovery claim created',\n schema: z.object({ ok: z.boolean(), claimId: z.string().uuid() }),\n },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,8BAA6D;AACtE,SAAS,yBAAyB;AAElC,SAAS,iCAA2D;AACpE,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,iBAAiB;AAStC,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,8BAA8B,EAAE;AAC/E;AAEA,SAAS,SAAS,OAAyC;AACzD,SAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAI,QAAmC,CAAC;AAC3G;AAEA,eAAe,qBAAqB,KAA2C;AAC7E,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,MAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,UAAU,uCAAuC,cAAc,EAAE,CAAC;AAAA,EAC1G;AACA,QAAM,QAAQ,MA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SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,0BAA0B;AAAA,MAClF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,GAAG,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,QAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { runRouteMutationGuards, type RouteMutationGuardResult } from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { vendorRecoveryInputSchema, type VendorRecoveryInput } from '../../data/validators'\nimport { WARRANTY_CLAIM_RESOURCE_KIND } from '../../commands/shared'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('warranty_claims')\n\ntype ActionRouteContext = {\n ctx: CommandRuntimeContext\n tenantId: string\n organizationId: string\n translate: (key: string, fallback?: string) => string\n}\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['warranty_claims.claim.manage'] },\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nasync function resolveActionContext(req: Request): Promise<ActionRouteContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, { error: translate('warranty_claims.errors.organization_required', 'Organization context is required') })\n }\n return {\n ctx: {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n },\n tenantId: auth.tenantId,\n organizationId,\n translate,\n }\n}\n\nfunction toVendorRecoveryInput(scopedPayload: Record<string, unknown>): VendorRecoveryInput {\n return vendorRecoveryInputSchema.parse({\n claimId: scopedPayload.claimId,\n lineIds: scopedPayload.lineIds,\n vendorName: scopedPayload.vendorName,\n vendorRef: scopedPayload.vendorRef,\n })\n}\n\nasync function runGuard(\n req: Request,\n context: ActionRouteContext,\n input: VendorRecoveryInput,\n): Promise<RouteMutationGuardResult> {\n const userId = context.ctx.auth?.sub\n if (!userId) {\n throw new CrudHttpError(401, { error: context.translate('warranty_claims.errors.unauthorized', 'Unauthorized') })\n }\n return runRouteMutationGuards({\n container: context.ctx.container,\n req,\n auth: {\n userId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n },\n input: {\n resourceKind: WARRANTY_CLAIM_RESOURCE_KIND,\n resourceId: input.claimId,\n operation: 'custom',\n mutationPayload: { ...input },\n },\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const context = await resolveActionContext(req)\n const payload = toRecord(await readJsonSafe(req, {}))\n const scopedPayload = withScopedPayload(payload, context.ctx, context.translate)\n const input = toVendorRecoveryInput(scopedPayload)\n const guarded = await runGuard(req, context, input)\n if (!guarded.ok) {\n return guarded.response\n }\n const commandInput = guarded.modifiedPayload ? toVendorRecoveryInput(guarded.modifiedPayload) : input\n\n const commandBus = context.ctx.container.resolve('commandBus') as CommandBus\n const { result } = await commandBus.execute<VendorRecoveryInput, { claimId: string }>(\n 'warranty_claims.claim.create_vendor_recovery',\n { input: commandInput, ctx: context.ctx },\n )\n const createdClaimId = result?.claimId\n if (typeof createdClaimId !== 'string') {\n throw new CrudHttpError(400, { error: context.translate('warranty_claims.errors.notFound', 'Warranty claim not found.') })\n }\n\n await guarded.runAfterSuccess()\n\n return NextResponse.json({ ok: true, claimId: createdClaimId })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n const { translate } = await resolveTranslations()\n if (err instanceof z.ZodError) {\n return NextResponse.json({ error: translate('warranty_claims.errors.invalidInput', 'Invalid input') }, { status: 400 })\n }\n logger.error('warranty_claims.vendor-recovery.post failed', { err })\n return NextResponse.json({ error: translate('warranty_claims.errors.save_failed', 'Failed to save warranty claim') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Warranty Claims',\n summary: 'Create vendor recovery claim',\n methods: {\n POST: {\n summary: 'Create a linked vendor-recovery claim from resolved source lines',\n requestBody: { contentType: 'application/json', schema: vendorRecoveryInputSchema },\n responses: [\n {\n status: 200,\n description: 'Vendor recovery claim created',\n schema: z.object({ ok: z.boolean(), claimId: z.string().uuid() }),\n },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7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