@porulle/core 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/setup.d.ts.map +1 -1
- package/dist/auth/setup.js +1 -0
- package/dist/config/defaults.d.ts.map +1 -1
- package/dist/config/defaults.js +5 -0
- package/dist/config/types.d.ts +17 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/generated/plugin-manifest.d.ts +3 -0
- package/dist/generated/plugin-manifest.d.ts.map +1 -1
- package/dist/generated/plugin-manifest.js +1 -0
- package/dist/hooks/checkout.d.ts.map +1 -1
- package/dist/hooks/checkout.js +16 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/interfaces/rest/index.d.ts.map +1 -1
- package/dist/interfaces/rest/index.js +12 -0
- package/dist/interfaces/rest/routes/admin/staff.d.ts +12 -0
- package/dist/interfaces/rest/routes/admin/staff.d.ts.map +1 -0
- package/dist/interfaces/rest/routes/admin/staff.js +172 -0
- package/dist/interfaces/rest/routes/analytics.d.ts +5 -0
- package/dist/interfaces/rest/routes/analytics.d.ts.map +1 -0
- package/dist/interfaces/rest/routes/analytics.js +24 -0
- package/dist/interfaces/rest/routes/carts.d.ts.map +1 -1
- package/dist/interfaces/rest/routes/carts.js +39 -2
- package/dist/interfaces/rest/routes/catalog.d.ts.map +1 -1
- package/dist/interfaces/rest/routes/catalog.js +17 -1
- package/dist/interfaces/rest/routes/checkout.d.ts.map +1 -1
- package/dist/interfaces/rest/routes/checkout.js +17 -0
- package/dist/interfaces/rest/routes/documents.d.ts +10 -0
- package/dist/interfaces/rest/routes/documents.d.ts.map +1 -0
- package/dist/interfaces/rest/routes/documents.js +40 -0
- package/dist/interfaces/rest/routes/orders.d.ts.map +1 -1
- package/dist/interfaces/rest/routes/orders.js +122 -1
- package/dist/interfaces/rest/routes/pricing.d.ts.map +1 -1
- package/dist/interfaces/rest/routes/pricing.js +36 -1
- package/dist/interfaces/rest/routes/settings.d.ts +5 -0
- package/dist/interfaces/rest/routes/settings.d.ts.map +1 -0
- package/dist/interfaces/rest/routes/settings.js +50 -0
- package/dist/interfaces/rest/routes/shipping.d.ts +5 -0
- package/dist/interfaces/rest/routes/shipping.d.ts.map +1 -0
- package/dist/interfaces/rest/routes/shipping.js +68 -0
- package/dist/interfaces/rest/routes/tax.d.ts +5 -0
- package/dist/interfaces/rest/routes/tax.d.ts.map +1 -0
- package/dist/interfaces/rest/routes/tax.js +68 -0
- package/dist/interfaces/rest/schemas/admin-staff.d.ts +899 -0
- package/dist/interfaces/rest/schemas/admin-staff.d.ts.map +1 -0
- package/dist/interfaces/rest/schemas/admin-staff.js +98 -0
- package/dist/interfaces/rest/schemas/analytics.d.ts +252 -0
- package/dist/interfaces/rest/schemas/analytics.d.ts.map +1 -0
- package/dist/interfaces/rest/schemas/analytics.js +33 -0
- package/dist/interfaces/rest/schemas/carts.d.ts +656 -0
- package/dist/interfaces/rest/schemas/carts.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/carts.js +38 -0
- package/dist/interfaces/rest/schemas/catalog.d.ts +1230 -2
- package/dist/interfaces/rest/schemas/catalog.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/catalog.js +48 -0
- package/dist/interfaces/rest/schemas/checkout.d.ts +2 -0
- package/dist/interfaces/rest/schemas/checkout.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/checkout.js +4 -0
- package/dist/interfaces/rest/schemas/customer-portal.d.ts +35 -0
- package/dist/interfaces/rest/schemas/customer-portal.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/documents.d.ts +509 -0
- package/dist/interfaces/rest/schemas/documents.d.ts.map +1 -0
- package/dist/interfaces/rest/schemas/documents.js +65 -0
- package/dist/interfaces/rest/schemas/orders.d.ts +4467 -7
- package/dist/interfaces/rest/schemas/orders.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/orders.js +330 -0
- package/dist/interfaces/rest/schemas/pricing.d.ts +405 -0
- package/dist/interfaces/rest/schemas/pricing.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/pricing.js +70 -0
- package/dist/interfaces/rest/schemas/responses.d.ts +156 -0
- package/dist/interfaces/rest/schemas/responses.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/search.d.ts +17 -0
- package/dist/interfaces/rest/schemas/search.d.ts.map +1 -1
- package/dist/interfaces/rest/schemas/settings.d.ts +397 -0
- package/dist/interfaces/rest/schemas/settings.d.ts.map +1 -0
- package/dist/interfaces/rest/schemas/settings.js +79 -0
- package/dist/interfaces/rest/schemas/shipping.d.ts +1093 -0
- package/dist/interfaces/rest/schemas/shipping.d.ts.map +1 -0
- package/dist/interfaces/rest/schemas/shipping.js +146 -0
- package/dist/interfaces/rest/schemas/tax.d.ts +1074 -0
- package/dist/interfaces/rest/schemas/tax.d.ts.map +1 -0
- package/dist/interfaces/rest/schemas/tax.js +132 -0
- package/dist/kernel/database/schema.d.ts +4 -0
- package/dist/kernel/database/schema.d.ts.map +1 -1
- package/dist/kernel/database/schema.js +8 -0
- package/dist/kernel/error-mapper.d.ts.map +1 -1
- package/dist/kernel/error-mapper.js +1 -0
- package/dist/kernel/errors.d.ts +5 -0
- package/dist/kernel/errors.d.ts.map +1 -1
- package/dist/kernel/errors.js +9 -0
- package/dist/kernel/hooks/types.d.ts +1 -1
- package/dist/kernel/hooks/types.d.ts.map +1 -1
- package/dist/kernel/plugin/manifest.d.ts +23 -0
- package/dist/kernel/plugin/manifest.d.ts.map +1 -1
- package/dist/kernel/plugin/manifest.js +17 -2
- package/dist/modules/analytics/module.d.ts.map +1 -1
- package/dist/modules/analytics/module.js +6 -0
- package/dist/modules/analytics/reports.d.ts +58 -0
- package/dist/modules/analytics/reports.d.ts.map +1 -0
- package/dist/modules/analytics/reports.js +249 -0
- package/dist/modules/analytics/service.d.ts +10 -0
- package/dist/modules/analytics/service.d.ts.map +1 -1
- package/dist/modules/analytics/service.js +14 -0
- package/dist/modules/cart/repository/index.d.ts +7 -0
- package/dist/modules/cart/repository/index.d.ts.map +1 -1
- package/dist/modules/cart/repository/index.js +25 -1
- package/dist/modules/cart/schema.d.ts +17 -0
- package/dist/modules/cart/schema.d.ts.map +1 -1
- package/dist/modules/cart/schema.js +2 -0
- package/dist/modules/cart/schemas.d.ts +1 -0
- package/dist/modules/cart/schemas.d.ts.map +1 -1
- package/dist/modules/cart/schemas.js +1 -0
- package/dist/modules/cart/service.d.ts +32 -0
- package/dist/modules/cart/service.d.ts.map +1 -1
- package/dist/modules/cart/service.js +58 -0
- package/dist/modules/catalog/entity-service.d.ts +21 -0
- package/dist/modules/catalog/entity-service.d.ts.map +1 -1
- package/dist/modules/catalog/entity-service.js +151 -6
- package/dist/modules/catalog/schema.d.ts +34 -0
- package/dist/modules/catalog/schema.d.ts.map +1 -1
- package/dist/modules/catalog/schema.js +5 -0
- package/dist/modules/catalog/schemas.d.ts +15 -1
- package/dist/modules/catalog/schemas.d.ts.map +1 -1
- package/dist/modules/catalog/schemas.js +17 -1
- package/dist/modules/catalog/service.d.ts +43 -1
- package/dist/modules/catalog/service.d.ts.map +1 -1
- package/dist/modules/catalog/service.js +6 -0
- package/dist/modules/documents/module.d.ts +7 -0
- package/dist/modules/documents/module.d.ts.map +1 -0
- package/dist/modules/documents/module.js +12 -0
- package/dist/modules/documents/pdf.d.ts +25 -0
- package/dist/modules/documents/pdf.d.ts.map +1 -0
- package/dist/modules/documents/pdf.js +80 -0
- package/dist/modules/documents/render.d.ts +32 -0
- package/dist/modules/documents/render.d.ts.map +1 -0
- package/dist/modules/documents/render.js +190 -0
- package/dist/modules/documents/repository/index.d.ts +25 -0
- package/dist/modules/documents/repository/index.d.ts.map +1 -0
- package/dist/modules/documents/repository/index.js +47 -0
- package/dist/modules/documents/schema.d.ts +214 -0
- package/dist/modules/documents/schema.d.ts.map +1 -0
- package/dist/modules/documents/schema.js +42 -0
- package/dist/modules/documents/service.d.ts +51 -0
- package/dist/modules/documents/service.d.ts.map +1 -0
- package/dist/modules/documents/service.js +119 -0
- package/dist/modules/fulfillment/service.d.ts +18 -0
- package/dist/modules/fulfillment/service.d.ts.map +1 -1
- package/dist/modules/fulfillment/service.js +85 -1
- package/dist/modules/media/service.d.ts +18 -0
- package/dist/modules/media/service.d.ts.map +1 -1
- package/dist/modules/media/service.js +26 -0
- package/dist/modules/orders/repository/index.d.ts +18 -1
- package/dist/modules/orders/repository/index.d.ts.map +1 -1
- package/dist/modules/orders/repository/index.js +86 -1
- package/dist/modules/orders/schema.d.ts +374 -0
- package/dist/modules/orders/schema.d.ts.map +1 -1
- package/dist/modules/orders/schema.js +52 -1
- package/dist/modules/orders/service.d.ts +102 -2
- package/dist/modules/orders/service.d.ts.map +1 -1
- package/dist/modules/orders/service.js +494 -23
- package/dist/modules/pricing/repository/index.d.ts +5 -0
- package/dist/modules/pricing/repository/index.d.ts.map +1 -1
- package/dist/modules/pricing/repository/index.js +19 -0
- package/dist/modules/pricing/service.d.ts +18 -0
- package/dist/modules/pricing/service.d.ts.map +1 -1
- package/dist/modules/pricing/service.js +57 -1
- package/dist/modules/settings/module.d.ts +6 -0
- package/dist/modules/settings/module.d.ts.map +1 -0
- package/dist/modules/settings/module.js +11 -0
- package/dist/modules/settings/repository/index.d.ts +16 -0
- package/dist/modules/settings/repository/index.d.ts.map +1 -0
- package/dist/modules/settings/repository/index.js +41 -0
- package/dist/modules/settings/schema.d.ts +121 -0
- package/dist/modules/settings/schema.d.ts.map +1 -0
- package/dist/modules/settings/schema.js +24 -0
- package/dist/modules/settings/service.d.ts +26 -0
- package/dist/modules/settings/service.d.ts.map +1 -0
- package/dist/modules/settings/service.js +51 -0
- package/dist/modules/shipping/calculator.d.ts +5 -0
- package/dist/modules/shipping/calculator.d.ts.map +1 -1
- package/dist/modules/shipping/calculator.js +10 -0
- package/dist/modules/shipping/module.d.ts +5 -1
- package/dist/modules/shipping/module.d.ts.map +1 -1
- package/dist/modules/shipping/module.js +4 -1
- package/dist/modules/shipping/repository/index.d.ts +27 -2
- package/dist/modules/shipping/repository/index.d.ts.map +1 -1
- package/dist/modules/shipping/repository/index.js +105 -1
- package/dist/modules/shipping/schema.d.ts +419 -0
- package/dist/modules/shipping/schema.d.ts.map +1 -0
- package/dist/modules/shipping/schema.js +56 -0
- package/dist/modules/shipping/service.d.ts +54 -0
- package/dist/modules/shipping/service.d.ts.map +1 -1
- package/dist/modules/shipping/service.js +161 -2
- package/dist/modules/tax/adapter.d.ts +13 -0
- package/dist/modules/tax/adapter.d.ts.map +1 -1
- package/dist/modules/tax/module.d.ts +5 -1
- package/dist/modules/tax/module.d.ts.map +1 -1
- package/dist/modules/tax/module.js +4 -1
- package/dist/modules/tax/repository/index.d.ts +38 -2
- package/dist/modules/tax/repository/index.d.ts.map +1 -1
- package/dist/modules/tax/repository/index.js +138 -1
- package/dist/modules/tax/schema.d.ts +355 -0
- package/dist/modules/tax/schema.d.ts.map +1 -0
- package/dist/modules/tax/schema.js +55 -0
- package/dist/modules/tax/service.d.ts +60 -1
- package/dist/modules/tax/service.d.ts.map +1 -1
- package/dist/modules/tax/service.js +227 -2
- package/dist/runtime/kernel-modules.d.ts +15 -2
- package/dist/runtime/kernel-modules.d.ts.map +1 -1
- package/dist/runtime/kernel-modules.js +4 -0
- package/dist/runtime/kernel-types.d.ts +5 -1
- package/dist/runtime/kernel-types.d.ts.map +1 -1
- package/dist/runtime/kernel-types.js +2 -0
- package/dist/runtime/server.d.ts.map +1 -1
- package/dist/runtime/server.js +35 -3
- package/dist/test-utils/create-plugin-test-app.d.ts +3 -0
- package/dist/test-utils/create-plugin-test-app.d.ts.map +1 -1
- package/dist/test-utils/create-plugin-test-app.js +15 -3
- package/dist/test-utils/rest-api-test-utils.d.ts.map +1 -1
- package/dist/test-utils/rest-api-test-utils.js +6 -0
- package/package.json +3 -3
- package/src/auth/setup.ts +1 -0
- package/src/config/defaults.ts +5 -0
- package/src/config/types.ts +17 -1
- package/src/generated/plugin-capabilities.d.ts +1 -0
- package/src/generated/plugin-manifest.ts +1 -0
- package/src/generated/plugin-repositories.d.ts +1 -0
- package/src/hooks/checkout.ts +25 -3
- package/src/index.ts +1 -0
- package/src/interfaces/rest/index.ts +12 -0
- package/src/interfaces/rest/routes/admin/staff.ts +218 -0
- package/src/interfaces/rest/routes/analytics.ts +33 -0
- package/src/interfaces/rest/routes/carts.ts +52 -2
- package/src/interfaces/rest/routes/catalog.ts +34 -0
- package/src/interfaces/rest/routes/checkout.ts +22 -0
- package/src/interfaces/rest/routes/documents.ts +61 -0
- package/src/interfaces/rest/routes/orders.ts +172 -1
- package/src/interfaces/rest/routes/pricing.ts +44 -1
- package/src/interfaces/rest/routes/settings.ts +61 -0
- package/src/interfaces/rest/routes/shipping.ts +92 -0
- package/src/interfaces/rest/routes/tax.ts +90 -0
- package/src/interfaces/rest/schemas/admin-staff.ts +110 -0
- package/src/interfaces/rest/schemas/analytics.ts +39 -0
- package/src/interfaces/rest/schemas/carts.ts +40 -0
- package/src/interfaces/rest/schemas/catalog.ts +53 -0
- package/src/interfaces/rest/schemas/checkout.ts +4 -0
- package/src/interfaces/rest/schemas/documents.ts +72 -0
- package/src/interfaces/rest/schemas/orders.ts +361 -0
- package/src/interfaces/rest/schemas/pricing.ts +75 -0
- package/src/interfaces/rest/schemas/settings.ts +93 -0
- package/src/interfaces/rest/schemas/shipping.ts +164 -0
- package/src/interfaces/rest/schemas/tax.ts +148 -0
- package/src/kernel/database/schema.ts +12 -0
- package/src/kernel/error-mapper.ts +1 -0
- package/src/kernel/errors.ts +11 -0
- package/src/kernel/hooks/types.ts +1 -0
- package/src/kernel/plugin/manifest.ts +38 -2
- package/src/modules/analytics/module.ts +10 -0
- package/src/modules/analytics/reports.ts +311 -0
- package/src/modules/analytics/service.ts +23 -0
- package/src/modules/cart/repository/index.ts +30 -1
- package/src/modules/cart/schema.ts +2 -0
- package/src/modules/cart/schemas.ts +1 -0
- package/src/modules/cart/service.ts +101 -0
- package/src/modules/catalog/entity-service.ts +195 -6
- package/src/modules/catalog/schema.ts +5 -0
- package/src/modules/catalog/schemas.ts +18 -1
- package/src/modules/catalog/service.ts +32 -2
- package/src/modules/documents/module.ts +19 -0
- package/src/modules/documents/pdf.ts +101 -0
- package/src/modules/documents/render.ts +231 -0
- package/src/modules/documents/repository/index.ts +68 -0
- package/src/modules/documents/schema.ts +44 -0
- package/src/modules/documents/service.ts +176 -0
- package/src/modules/fulfillment/service.ts +139 -1
- package/src/modules/media/service.ts +40 -0
- package/src/modules/orders/repository/index.ts +127 -1
- package/src/modules/orders/schema.ts +54 -1
- package/src/modules/orders/service.ts +739 -24
- package/src/modules/pricing/repository/index.ts +34 -0
- package/src/modules/pricing/service.ts +100 -1
- package/src/modules/settings/module.ts +18 -0
- package/src/modules/settings/repository/index.ts +59 -0
- package/src/modules/settings/schema.ts +25 -0
- package/src/modules/settings/service.ts +82 -0
- package/src/modules/shipping/calculator.ts +27 -0
- package/src/modules/shipping/module.ts +6 -2
- package/src/modules/shipping/repository/index.ts +136 -2
- package/src/modules/shipping/schema.ts +58 -0
- package/src/modules/shipping/service.ts +260 -1
- package/src/modules/tax/adapter.ts +9 -0
- package/src/modules/tax/module.ts +6 -2
- package/src/modules/tax/repository/index.ts +169 -2
- package/src/modules/tax/schema.ts +57 -0
- package/src/modules/tax/service.ts +313 -2
- package/src/runtime/kernel-modules.ts +4 -0
- package/src/runtime/kernel-types.ts +6 -0
- package/src/runtime/server.ts +36 -3
- package/src/test-utils/create-plugin-test-app.ts +17 -4
- package/src/test-utils/rest-api-test-utils.ts +6 -0
|
@@ -2,6 +2,7 @@ import { resolveOrgId } from "../../auth/org.js";
|
|
|
2
2
|
import { assertOwnership, assertPermission } from "../../auth/permissions.js";
|
|
3
3
|
import type { Actor } from "../../auth/types.js";
|
|
4
4
|
import {
|
|
5
|
+
CommerceForbiddenError,
|
|
5
6
|
CommerceInvalidTransitionError,
|
|
6
7
|
CommerceNotFoundError,
|
|
7
8
|
CommerceValidationError,
|
|
@@ -31,11 +32,15 @@ import {
|
|
|
31
32
|
OrdersRepository,
|
|
32
33
|
type Order,
|
|
33
34
|
type OrderLineItem,
|
|
35
|
+
type OrderNote,
|
|
36
|
+
type OrderRefund,
|
|
34
37
|
type OrderStatusHistory,
|
|
35
38
|
} from "./repository/index.js";
|
|
36
39
|
|
|
37
40
|
export interface CreateOrderInput {
|
|
38
41
|
customerId?: string;
|
|
42
|
+
/** Client-supplied retry key — a repeat create with the same key returns the original order. */
|
|
43
|
+
idempotencyKey?: string | undefined;
|
|
39
44
|
currency: string;
|
|
40
45
|
subtotal: number;
|
|
41
46
|
taxTotal: number;
|
|
@@ -78,6 +83,11 @@ export interface ChangeStatusInput {
|
|
|
78
83
|
orderId: string;
|
|
79
84
|
newStatus: OrderState;
|
|
80
85
|
reason?: string;
|
|
86
|
+
/**
|
|
87
|
+
* Explicit refund amount (minor units) for a `refunded` transition. Clamped
|
|
88
|
+
* to the captured amount. Omit to refund the full captured amount.
|
|
89
|
+
*/
|
|
90
|
+
refundAmount?: number;
|
|
81
91
|
}
|
|
82
92
|
|
|
83
93
|
export interface OrderServiceDeps {
|
|
@@ -171,30 +181,59 @@ export class OrderService {
|
|
|
171
181
|
hookCtx,
|
|
172
182
|
);
|
|
173
183
|
|
|
174
|
-
const orderNumber = await this.repo.getNextOrderNumber(ctx);
|
|
175
184
|
const orgId = resolveOrgId(actor);
|
|
176
185
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
186
|
+
// Idempotent replay: offline POS queues and network retries re-submit the
|
|
187
|
+
// same create — return the original order instead of double-creating.
|
|
188
|
+
if (processed.idempotencyKey) {
|
|
189
|
+
const existing = await this.repo.findByIdempotencyKey(
|
|
190
|
+
orgId,
|
|
191
|
+
processed.idempotencyKey,
|
|
192
|
+
ctx,
|
|
193
|
+
);
|
|
194
|
+
if (existing) {
|
|
195
|
+
return Ok(await this.hydrateOrder(existing, ctx));
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const orderNumber = await this.repo.getNextOrderNumber(ctx);
|
|
200
|
+
|
|
201
|
+
let order: Order;
|
|
202
|
+
try {
|
|
203
|
+
order = await this.repo.create(
|
|
204
|
+
{
|
|
205
|
+
organizationId: orgId,
|
|
206
|
+
orderNumber,
|
|
207
|
+
status: "pending",
|
|
208
|
+
currency: processed.currency,
|
|
209
|
+
subtotal: processed.subtotal,
|
|
210
|
+
taxTotal: processed.taxTotal,
|
|
211
|
+
shippingTotal: processed.shippingTotal,
|
|
212
|
+
discountTotal: processed.discountTotal ?? 0,
|
|
213
|
+
grandTotal: processed.grandTotal,
|
|
214
|
+
...(processed.paymentIntentId != null ? { paymentIntentId: processed.paymentIntentId } : {}),
|
|
215
|
+
...(processed.paymentMethodId != null ? { paymentMethodId: processed.paymentMethodId } : {}),
|
|
216
|
+
...(processed.idempotencyKey != null ? { idempotencyKey: processed.idempotencyKey } : {}),
|
|
217
|
+
metadata: processed.metadata ?? {},
|
|
218
|
+
placedAt: new Date(),
|
|
219
|
+
...(processed.customerId !== undefined
|
|
220
|
+
? { customerId: processed.customerId }
|
|
221
|
+
: {}),
|
|
222
|
+
},
|
|
223
|
+
ctx,
|
|
224
|
+
);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
// Concurrent replay lost the unique-index race — return the winner.
|
|
227
|
+
if (processed.idempotencyKey) {
|
|
228
|
+
const winner = await this.repo.findByIdempotencyKey(
|
|
229
|
+
orgId,
|
|
230
|
+
processed.idempotencyKey,
|
|
231
|
+
ctx,
|
|
232
|
+
);
|
|
233
|
+
if (winner) return Ok(await this.hydrateOrder(winner, ctx));
|
|
234
|
+
}
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
198
237
|
|
|
199
238
|
const lineItemsData = processed.lineItems.map((item) => ({
|
|
200
239
|
orderId: order.id,
|
|
@@ -289,6 +328,18 @@ export class OrderService {
|
|
|
289
328
|
return this.getById(order.id, actor, ctx);
|
|
290
329
|
}
|
|
291
330
|
|
|
331
|
+
/** Returns the order previously created with this idempotency key, or null. */
|
|
332
|
+
async getByIdempotencyKey(
|
|
333
|
+
idempotencyKey: string,
|
|
334
|
+
actor?: Actor | null,
|
|
335
|
+
ctx?: TxContext,
|
|
336
|
+
): Promise<Result<HydratedOrder | null>> {
|
|
337
|
+
const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
|
|
338
|
+
const order = await this.repo.findByIdempotencyKey(orgId, idempotencyKey, ctx);
|
|
339
|
+
if (!order) return Ok(null);
|
|
340
|
+
return Ok(await this.hydrateOrder(order, ctx));
|
|
341
|
+
}
|
|
342
|
+
|
|
292
343
|
async list(
|
|
293
344
|
params: ListOrdersParams,
|
|
294
345
|
actor: Actor | null,
|
|
@@ -540,10 +591,14 @@ export class OrderService {
|
|
|
540
591
|
| undefined;
|
|
541
592
|
|
|
542
593
|
if (payments?.refund) {
|
|
543
|
-
const
|
|
594
|
+
const maxRefund = Math.min(
|
|
544
595
|
order.grandTotal,
|
|
545
596
|
order.amountCaptured ?? order.grandTotal,
|
|
546
597
|
);
|
|
598
|
+
const refundAmount =
|
|
599
|
+
input.refundAmount != null
|
|
600
|
+
? Math.min(input.refundAmount, maxRefund)
|
|
601
|
+
: maxRefund;
|
|
547
602
|
await payments.refund(
|
|
548
603
|
paymentIntentId,
|
|
549
604
|
refundAmount,
|
|
@@ -675,14 +730,481 @@ export class OrderService {
|
|
|
675
730
|
actor: Actor | null,
|
|
676
731
|
reason = "refunded",
|
|
677
732
|
ctx?: TxContext,
|
|
733
|
+
opts?: { amount?: number },
|
|
678
734
|
): Promise<Result<HydratedOrder>> {
|
|
679
735
|
return this.changeStatus(
|
|
680
|
-
{
|
|
736
|
+
{
|
|
737
|
+
orderId,
|
|
738
|
+
newStatus: "refunded",
|
|
739
|
+
reason,
|
|
740
|
+
...(opts?.amount != null ? { refundAmount: opts.amount } : {}),
|
|
741
|
+
},
|
|
681
742
|
actor,
|
|
682
743
|
ctx,
|
|
683
744
|
);
|
|
684
745
|
}
|
|
685
746
|
|
|
747
|
+
// ── Line-level refund policy primitives (issue #52) ─────────────────────
|
|
748
|
+
|
|
749
|
+
private async refundPolicies(orgId: string, ctx?: TxContext): Promise<{
|
|
750
|
+
cap: number | null;
|
|
751
|
+
undoWindowMinutes: number;
|
|
752
|
+
timezone: string;
|
|
753
|
+
}> {
|
|
754
|
+
const settings = this.deps.services.settings as
|
|
755
|
+
| { read(orgId: string, group: string, ctx?: TxContext): Promise<Record<string, unknown>> }
|
|
756
|
+
| undefined;
|
|
757
|
+
const policies = (await settings?.read(orgId, "policies", ctx)) ?? {};
|
|
758
|
+
const general = (await settings?.read(orgId, "general", ctx)) ?? {};
|
|
759
|
+
return {
|
|
760
|
+
cap: typeof policies.refundDailyCap === "number" ? policies.refundDailyCap : null,
|
|
761
|
+
undoWindowMinutes:
|
|
762
|
+
typeof policies.refundUndoWindowMinutes === "number"
|
|
763
|
+
? policies.refundUndoWindowMinutes
|
|
764
|
+
: 15,
|
|
765
|
+
timezone: typeof general.timezone === "string" ? general.timezone : "UTC",
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Refunds specific line-item quantities (issue #52). Enforces per-line
|
|
771
|
+
* refundable quantity (`quantity - refundedQuantity`), the operator's daily
|
|
772
|
+
* refund cap (`policies.refundDailyCap`, 403 with the cap surfaced), moves
|
|
773
|
+
* money through the payment adapter when the order has a captured payment,
|
|
774
|
+
* and records an auditable `order_refunds` ledger row.
|
|
775
|
+
*/
|
|
776
|
+
async refundLines(
|
|
777
|
+
orderId: string,
|
|
778
|
+
input: { lines: Array<{ lineItemId: string; quantity: number }>; reason?: string | undefined },
|
|
779
|
+
actor: Actor | null,
|
|
780
|
+
ctx?: TxContext,
|
|
781
|
+
): Promise<Result<{ order: HydratedOrder; refund: OrderRefund }>> {
|
|
782
|
+
try {
|
|
783
|
+
assertPermission(actor, "orders:update");
|
|
784
|
+
} catch (error) {
|
|
785
|
+
return Err(toCommerceError(error));
|
|
786
|
+
}
|
|
787
|
+
const orgId = resolveOrgId(actor);
|
|
788
|
+
const found = await this.repo.findWithLineItems(orgId, orderId, ctx);
|
|
789
|
+
if (!found) return Err(new CommerceNotFoundError("Order not found."));
|
|
790
|
+
if (input.lines.length === 0) {
|
|
791
|
+
return Err(new CommerceValidationError("At least one line is required."));
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const byId = new Map(found.lineItems.map((li) => [li.id, li]));
|
|
795
|
+
const refundLines: Array<{ lineItemId: string; quantity: number; amount: number }> = [];
|
|
796
|
+
for (const line of input.lines) {
|
|
797
|
+
const lineItem = byId.get(line.lineItemId);
|
|
798
|
+
if (!lineItem) {
|
|
799
|
+
return Err(new CommerceNotFoundError(`Line item ${line.lineItemId} not found on this order.`));
|
|
800
|
+
}
|
|
801
|
+
if (!Number.isInteger(line.quantity) || line.quantity < 1) {
|
|
802
|
+
return Err(new CommerceValidationError("Refund quantity must be a positive integer."));
|
|
803
|
+
}
|
|
804
|
+
const refundable = lineItem.quantity - lineItem.refundedQuantity;
|
|
805
|
+
if (line.quantity > refundable) {
|
|
806
|
+
return Err(
|
|
807
|
+
new CommerceValidationError(
|
|
808
|
+
`Line "${lineItem.title}" has ${refundable} refundable unit(s); requested ${line.quantity}.`,
|
|
809
|
+
),
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
// Effective paid per unit: line total + tax − discount, split evenly.
|
|
813
|
+
const lineValue = lineItem.totalPrice + lineItem.taxAmount - lineItem.discountAmount;
|
|
814
|
+
const amount = Math.round((lineValue * line.quantity) / lineItem.quantity);
|
|
815
|
+
refundLines.push({ lineItemId: lineItem.id, quantity: line.quantity, amount });
|
|
816
|
+
}
|
|
817
|
+
const totalAmount = refundLines.reduce((sum, l) => sum + l.amount, 0);
|
|
818
|
+
|
|
819
|
+
const performedBy = actor?.userId ?? "system";
|
|
820
|
+
const policies = await this.refundPolicies(orgId, ctx);
|
|
821
|
+
if (policies.cap != null) {
|
|
822
|
+
const usedToday = await this.repo.sumRefundsByOperatorToday(
|
|
823
|
+
orgId,
|
|
824
|
+
performedBy,
|
|
825
|
+
policies.timezone,
|
|
826
|
+
ctx,
|
|
827
|
+
);
|
|
828
|
+
if (usedToday + totalAmount > policies.cap) {
|
|
829
|
+
return Err(
|
|
830
|
+
new CommerceForbiddenError(
|
|
831
|
+
`Daily refund cap exceeded: cap ${policies.cap}, used ${usedToday} today, requested ${totalAmount}.`,
|
|
832
|
+
),
|
|
833
|
+
);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// Move money if a captured payment exists — clamped to what remains.
|
|
838
|
+
if (found.order.paymentIntentId && (found.order.amountCaptured ?? 0) > 0) {
|
|
839
|
+
const payments = this.deps.services.payments as
|
|
840
|
+
| { refund(paymentId: string, amount: number, reason?: string): Promise<unknown> }
|
|
841
|
+
| undefined;
|
|
842
|
+
if (payments?.refund) {
|
|
843
|
+
const priorRefunds = await this.repo.findRefundsByOrderId(orderId, ctx);
|
|
844
|
+
const alreadyRefunded = priorRefunds
|
|
845
|
+
.filter((r) => r.status === "completed")
|
|
846
|
+
.reduce((sum, r) => sum + r.amount, 0);
|
|
847
|
+
const refundable = Math.max(0, (found.order.amountCaptured ?? 0) - alreadyRefunded);
|
|
848
|
+
await payments.refund(
|
|
849
|
+
found.order.paymentIntentId,
|
|
850
|
+
Math.min(totalAmount, refundable),
|
|
851
|
+
input.reason ?? "line_refund",
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
for (const line of refundLines) {
|
|
857
|
+
const lineItem = byId.get(line.lineItemId)!;
|
|
858
|
+
await this.repo.updateLineItem(
|
|
859
|
+
line.lineItemId,
|
|
860
|
+
{ refundedQuantity: lineItem.refundedQuantity + line.quantity },
|
|
861
|
+
ctx,
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
const refund = await this.repo.createRefund(
|
|
865
|
+
{
|
|
866
|
+
organizationId: orgId,
|
|
867
|
+
orderId,
|
|
868
|
+
amount: totalAmount,
|
|
869
|
+
reason: input.reason ?? null,
|
|
870
|
+
lines: refundLines,
|
|
871
|
+
performedBy,
|
|
872
|
+
},
|
|
873
|
+
ctx,
|
|
874
|
+
);
|
|
875
|
+
await this.repo.createStatusHistory(
|
|
876
|
+
{
|
|
877
|
+
orderId,
|
|
878
|
+
fromStatus: found.order.status,
|
|
879
|
+
toStatus: found.order.status,
|
|
880
|
+
reason: `refund ${refund.id}: ${totalAmount} (${input.reason ?? "line refund"})`,
|
|
881
|
+
changedBy: performedBy,
|
|
882
|
+
},
|
|
883
|
+
ctx,
|
|
884
|
+
);
|
|
885
|
+
|
|
886
|
+
const hydrated = await this.hydrateOrder(
|
|
887
|
+
(await this.repo.findById(orgId, orderId, ctx))!,
|
|
888
|
+
ctx,
|
|
889
|
+
);
|
|
890
|
+
return Ok({ order: hydrated, refund });
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Undoes a refund within the configured window
|
|
895
|
+
* (`policies.refundUndoWindowMinutes`, default 15). Restores line
|
|
896
|
+
* refundedQuantity and marks the ledger row `undone` — an audited,
|
|
897
|
+
* compensating ledger operation; re-collecting the money (cash back into
|
|
898
|
+
* the drawer) is the operator's side of the exchange.
|
|
899
|
+
*/
|
|
900
|
+
async undoRefund(
|
|
901
|
+
orderId: string,
|
|
902
|
+
refundId: string,
|
|
903
|
+
actor: Actor | null,
|
|
904
|
+
ctx?: TxContext,
|
|
905
|
+
): Promise<Result<{ order: HydratedOrder; refund: OrderRefund }>> {
|
|
906
|
+
try {
|
|
907
|
+
assertPermission(actor, "orders:update");
|
|
908
|
+
} catch (error) {
|
|
909
|
+
return Err(toCommerceError(error));
|
|
910
|
+
}
|
|
911
|
+
const orgId = resolveOrgId(actor);
|
|
912
|
+
const refund = await this.repo.findRefundById(orgId, refundId, ctx);
|
|
913
|
+
if (!refund || refund.orderId !== orderId) {
|
|
914
|
+
return Err(new CommerceNotFoundError("Refund not found."));
|
|
915
|
+
}
|
|
916
|
+
if (refund.status !== "completed") {
|
|
917
|
+
return Err(new CommerceValidationError("Refund has already been undone."));
|
|
918
|
+
}
|
|
919
|
+
const policies = await this.refundPolicies(orgId, ctx);
|
|
920
|
+
const ageMs = Date.now() - refund.createdAt.getTime();
|
|
921
|
+
if (ageMs > policies.undoWindowMinutes * 60_000) {
|
|
922
|
+
return Err(
|
|
923
|
+
new CommerceValidationError(
|
|
924
|
+
`Refund undo window (${policies.undoWindowMinutes} minutes) has passed.`,
|
|
925
|
+
),
|
|
926
|
+
);
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
const performedBy = actor?.userId ?? "system";
|
|
930
|
+
const undone = await this.repo.markRefundUndone(refundId, performedBy, ctx);
|
|
931
|
+
if (!undone) {
|
|
932
|
+
return Err(new CommerceValidationError("Refund has already been undone."));
|
|
933
|
+
}
|
|
934
|
+
for (const line of refund.lines) {
|
|
935
|
+
const lineItem = await this.repo.findLineItemById(line.lineItemId, ctx);
|
|
936
|
+
if (lineItem) {
|
|
937
|
+
await this.repo.updateLineItem(
|
|
938
|
+
line.lineItemId,
|
|
939
|
+
{ refundedQuantity: Math.max(0, lineItem.refundedQuantity - line.quantity) },
|
|
940
|
+
ctx,
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
await this.repo.createStatusHistory(
|
|
945
|
+
{
|
|
946
|
+
orderId,
|
|
947
|
+
fromStatus: "refund_completed",
|
|
948
|
+
toStatus: "refund_undone",
|
|
949
|
+
reason: `refund ${refundId} undone (${refund.amount})`,
|
|
950
|
+
changedBy: performedBy,
|
|
951
|
+
},
|
|
952
|
+
ctx,
|
|
953
|
+
);
|
|
954
|
+
|
|
955
|
+
const order = await this.repo.findById(orgId, orderId, ctx);
|
|
956
|
+
const hydrated = await this.hydrateOrder(order!, ctx);
|
|
957
|
+
return Ok({ order: hydrated, refund: undone });
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
async listRefunds(
|
|
961
|
+
orderId: string,
|
|
962
|
+
actor: Actor | null,
|
|
963
|
+
ctx?: TxContext,
|
|
964
|
+
): Promise<Result<OrderRefund[]>> {
|
|
965
|
+
try {
|
|
966
|
+
assertPermission(actor, "orders:read");
|
|
967
|
+
} catch (error) {
|
|
968
|
+
return Err(toCommerceError(error));
|
|
969
|
+
}
|
|
970
|
+
const orgId = resolveOrgId(actor);
|
|
971
|
+
const order = await this.repo.findById(orgId, orderId, ctx);
|
|
972
|
+
if (!order) return Err(new CommerceNotFoundError("Order not found."));
|
|
973
|
+
return Ok(await this.repo.findRefundsByOrderId(orderId, ctx));
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/** The acting operator's daily refund-cap status (issue #52). */
|
|
977
|
+
async refundCapStatus(
|
|
978
|
+
actor: Actor | null,
|
|
979
|
+
ctx?: TxContext,
|
|
980
|
+
): Promise<Result<{ cap: number | null; usedToday: number; remaining: number | null }>> {
|
|
981
|
+
try {
|
|
982
|
+
assertPermission(actor, "orders:read");
|
|
983
|
+
} catch (error) {
|
|
984
|
+
return Err(toCommerceError(error));
|
|
985
|
+
}
|
|
986
|
+
const orgId = resolveOrgId(actor);
|
|
987
|
+
const policies = await this.refundPolicies(orgId, ctx);
|
|
988
|
+
const usedToday = await this.repo.sumRefundsByOperatorToday(
|
|
989
|
+
orgId,
|
|
990
|
+
actor?.userId ?? "system",
|
|
991
|
+
policies.timezone,
|
|
992
|
+
ctx,
|
|
993
|
+
);
|
|
994
|
+
return Ok({
|
|
995
|
+
cap: policies.cap,
|
|
996
|
+
usedToday,
|
|
997
|
+
remaining: policies.cap != null ? Math.max(0, policies.cap - usedToday) : null,
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
// ── Order notes + activity timeline (issue #56) ─────────────────────────
|
|
1002
|
+
|
|
1003
|
+
private async requireOrderAccess(
|
|
1004
|
+
orderId: string,
|
|
1005
|
+
actor: Actor | null,
|
|
1006
|
+
perm: "orders:read" | "orders:update",
|
|
1007
|
+
ctx?: TxContext,
|
|
1008
|
+
): Promise<Result<Order>> {
|
|
1009
|
+
try {
|
|
1010
|
+
assertPermission(actor, perm);
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
return Err(toCommerceError(error));
|
|
1013
|
+
}
|
|
1014
|
+
const orgId = resolveOrgId(actor);
|
|
1015
|
+
const order = await this.repo.findById(orgId, orderId, ctx);
|
|
1016
|
+
if (!order) return Err(new CommerceNotFoundError("Order not found."));
|
|
1017
|
+
return Ok(order);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
async addNote(
|
|
1021
|
+
orderId: string,
|
|
1022
|
+
input: { body: string; pinned?: boolean | undefined },
|
|
1023
|
+
actor: Actor | null,
|
|
1024
|
+
ctx?: TxContext,
|
|
1025
|
+
): Promise<Result<OrderNote>> {
|
|
1026
|
+
const order = await this.requireOrderAccess(orderId, actor, "orders:update", ctx);
|
|
1027
|
+
if (!order.ok) return order;
|
|
1028
|
+
if (!input.body.trim()) {
|
|
1029
|
+
return Err(new CommerceValidationError("Note body must not be empty."));
|
|
1030
|
+
}
|
|
1031
|
+
const note = await this.repo.createNote(
|
|
1032
|
+
{
|
|
1033
|
+
organizationId: order.value.organizationId,
|
|
1034
|
+
orderId,
|
|
1035
|
+
author: actor?.userId ?? "system",
|
|
1036
|
+
body: input.body,
|
|
1037
|
+
pinned: input.pinned ?? false,
|
|
1038
|
+
},
|
|
1039
|
+
ctx,
|
|
1040
|
+
);
|
|
1041
|
+
return Ok(note);
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
async listNotes(
|
|
1045
|
+
orderId: string,
|
|
1046
|
+
actor: Actor | null,
|
|
1047
|
+
ctx?: TxContext,
|
|
1048
|
+
): Promise<Result<OrderNote[]>> {
|
|
1049
|
+
const order = await this.requireOrderAccess(orderId, actor, "orders:read", ctx);
|
|
1050
|
+
if (!order.ok) return order;
|
|
1051
|
+
return Ok(await this.repo.findNotesByOrderId(orderId, ctx));
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
async deleteNote(
|
|
1055
|
+
orderId: string,
|
|
1056
|
+
noteId: string,
|
|
1057
|
+
actor: Actor | null,
|
|
1058
|
+
ctx?: TxContext,
|
|
1059
|
+
): Promise<Result<{ deleted: true }>> {
|
|
1060
|
+
const order = await this.requireOrderAccess(orderId, actor, "orders:update", ctx);
|
|
1061
|
+
if (!order.ok) return order;
|
|
1062
|
+
const deleted = await this.repo.deleteNote(order.value.organizationId, orderId, noteId, ctx);
|
|
1063
|
+
if (!deleted) return Err(new CommerceNotFoundError("Note not found."));
|
|
1064
|
+
return Ok({ deleted: true });
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/**
|
|
1068
|
+
* One merged per-order activity view (issue #56): status history + operator
|
|
1069
|
+
* notes + refund ledger events (both directions), newest first.
|
|
1070
|
+
*/
|
|
1071
|
+
async timeline(
|
|
1072
|
+
orderId: string,
|
|
1073
|
+
actor: Actor | null,
|
|
1074
|
+
ctx?: TxContext,
|
|
1075
|
+
): Promise<Result<Array<{
|
|
1076
|
+
type: "status" | "note" | "refund";
|
|
1077
|
+
at: Date;
|
|
1078
|
+
actor: string;
|
|
1079
|
+
summary: string;
|
|
1080
|
+
data: Record<string, unknown>;
|
|
1081
|
+
}>>> {
|
|
1082
|
+
const order = await this.requireOrderAccess(orderId, actor, "orders:read", ctx);
|
|
1083
|
+
if (!order.ok) return order;
|
|
1084
|
+
|
|
1085
|
+
const [history, notes, refunds] = await Promise.all([
|
|
1086
|
+
this.repo.findStatusHistoryByOrderId(orderId, ctx),
|
|
1087
|
+
this.repo.findNotesByOrderId(orderId, ctx),
|
|
1088
|
+
this.repo.findRefundsByOrderId(orderId, ctx),
|
|
1089
|
+
]);
|
|
1090
|
+
|
|
1091
|
+
const events: Array<{
|
|
1092
|
+
type: "status" | "note" | "refund";
|
|
1093
|
+
at: Date;
|
|
1094
|
+
actor: string;
|
|
1095
|
+
summary: string;
|
|
1096
|
+
data: Record<string, unknown>;
|
|
1097
|
+
}> = [];
|
|
1098
|
+
|
|
1099
|
+
for (const entry of history) {
|
|
1100
|
+
events.push({
|
|
1101
|
+
type: "status",
|
|
1102
|
+
at: entry.changedAt,
|
|
1103
|
+
actor: entry.changedBy,
|
|
1104
|
+
summary: `Status ${entry.fromStatus} → ${entry.toStatus}${entry.reason ? ` (${entry.reason})` : ""}`,
|
|
1105
|
+
data: { fromStatus: entry.fromStatus, toStatus: entry.toStatus, reason: entry.reason },
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
for (const note of notes) {
|
|
1109
|
+
events.push({
|
|
1110
|
+
type: "note",
|
|
1111
|
+
at: note.createdAt,
|
|
1112
|
+
actor: note.author,
|
|
1113
|
+
summary: note.body,
|
|
1114
|
+
data: { noteId: note.id, pinned: note.pinned },
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1117
|
+
for (const refund of refunds) {
|
|
1118
|
+
events.push({
|
|
1119
|
+
type: "refund",
|
|
1120
|
+
at: refund.createdAt,
|
|
1121
|
+
actor: refund.performedBy,
|
|
1122
|
+
summary: `Refund of ${refund.amount}${refund.reason ? ` (${refund.reason})` : ""}`,
|
|
1123
|
+
data: { refundId: refund.id, amount: refund.amount, lines: refund.lines, status: refund.status },
|
|
1124
|
+
});
|
|
1125
|
+
if (refund.status === "undone" && refund.undoneAt) {
|
|
1126
|
+
events.push({
|
|
1127
|
+
type: "refund",
|
|
1128
|
+
at: refund.undoneAt,
|
|
1129
|
+
actor: refund.undoneBy ?? "system",
|
|
1130
|
+
summary: `Refund of ${refund.amount} undone`,
|
|
1131
|
+
data: { refundId: refund.id, amount: refund.amount, undone: true },
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
events.sort((a, b) => b.at.getTime() - a.at.getTime());
|
|
1137
|
+
return Ok(events);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/**
|
|
1141
|
+
* Capture an authorized payment for an order via the payment adapter and
|
|
1142
|
+
* record the captured amount. Does not transition order status — capture is a
|
|
1143
|
+
* payment operation, not a fulfillment one.
|
|
1144
|
+
*/
|
|
1145
|
+
async capture(
|
|
1146
|
+
orderId: string,
|
|
1147
|
+
actor: Actor | null,
|
|
1148
|
+
opts?: { amount?: number },
|
|
1149
|
+
ctx?: TxContext,
|
|
1150
|
+
): Promise<Result<HydratedOrder>> {
|
|
1151
|
+
const orgId = resolveOrgId(actor);
|
|
1152
|
+
const order = await this.repo.findById(orgId, orderId, ctx);
|
|
1153
|
+
if (!order) return Err(new CommerceNotFoundError("Order not found."));
|
|
1154
|
+
|
|
1155
|
+
try {
|
|
1156
|
+
assertPermission(actor, "orders:update");
|
|
1157
|
+
} catch (error) {
|
|
1158
|
+
return Err(toCommerceError(error));
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
const paymentIntentId =
|
|
1162
|
+
((order as Record<string, unknown>).paymentIntentId as string | undefined) ??
|
|
1163
|
+
((order.metadata as Record<string, unknown> | null)?.paymentIntentId as
|
|
1164
|
+
| string
|
|
1165
|
+
| undefined);
|
|
1166
|
+
if (!paymentIntentId) {
|
|
1167
|
+
return Err(
|
|
1168
|
+
new CommerceValidationError("Order has no authorized payment to capture."),
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
const payments = this.deps.services.payments as
|
|
1173
|
+
| {
|
|
1174
|
+
capture(
|
|
1175
|
+
paymentIntentId: string,
|
|
1176
|
+
amount?: number,
|
|
1177
|
+
paymentMethodId?: string,
|
|
1178
|
+
): Promise<{ ok: boolean; value?: { amountCaptured?: number }; error?: unknown }>;
|
|
1179
|
+
}
|
|
1180
|
+
| undefined;
|
|
1181
|
+
if (!payments?.capture) {
|
|
1182
|
+
return Err(
|
|
1183
|
+
new CommerceValidationError("No payment adapter configured for capture."),
|
|
1184
|
+
);
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
const paymentMethodId = (order as Record<string, unknown>).paymentMethodId as
|
|
1188
|
+
| string
|
|
1189
|
+
| undefined;
|
|
1190
|
+
const captureResult = await payments.capture(
|
|
1191
|
+
paymentIntentId,
|
|
1192
|
+
opts?.amount,
|
|
1193
|
+
paymentMethodId,
|
|
1194
|
+
);
|
|
1195
|
+
if (!captureResult.ok) {
|
|
1196
|
+
return Err(toCommerceError(captureResult.error));
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
const amountCaptured =
|
|
1200
|
+
captureResult.value?.amountCaptured ?? opts?.amount ?? order.grandTotal;
|
|
1201
|
+
await this.repo.update(orderId, { amountCaptured }, ctx);
|
|
1202
|
+
|
|
1203
|
+
const refreshed = await this.repo.findById(orgId, orderId, ctx);
|
|
1204
|
+
const hydrated = await this.hydrateOrder(refreshed ?? order, ctx);
|
|
1205
|
+
return Ok(hydrated);
|
|
1206
|
+
}
|
|
1207
|
+
|
|
686
1208
|
async getStatusHistory(
|
|
687
1209
|
orderId: string,
|
|
688
1210
|
actor?: Actor | null,
|
|
@@ -701,6 +1223,199 @@ export class OrderService {
|
|
|
701
1223
|
return Ok(items);
|
|
702
1224
|
}
|
|
703
1225
|
|
|
1226
|
+
/** Line items may not be edited on terminal or fully-captured orders. */
|
|
1227
|
+
private lineItemEditGuard(order: Order): CommerceValidationError | null {
|
|
1228
|
+
if (this.machine.terminal.includes(order.status)) {
|
|
1229
|
+
return new CommerceValidationError(
|
|
1230
|
+
`Order in terminal status "${order.status}" cannot be edited.`,
|
|
1231
|
+
);
|
|
1232
|
+
}
|
|
1233
|
+
if (
|
|
1234
|
+
order.amountCaptured != null &&
|
|
1235
|
+
order.amountCaptured >= order.grandTotal
|
|
1236
|
+
) {
|
|
1237
|
+
return new CommerceValidationError(
|
|
1238
|
+
"Order payment is fully captured; line items cannot be edited.",
|
|
1239
|
+
);
|
|
1240
|
+
}
|
|
1241
|
+
return null;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/**
|
|
1245
|
+
* Recomputes subtotal/taxTotal/grandTotal from the order's line items
|
|
1246
|
+
* (shippingTotal and order-level discountTotal are preserved), persists
|
|
1247
|
+
* them, and records an audit entry in the status history.
|
|
1248
|
+
*/
|
|
1249
|
+
private async recalcOrderTotals(
|
|
1250
|
+
order: Order,
|
|
1251
|
+
actor: Actor | null,
|
|
1252
|
+
reason: string,
|
|
1253
|
+
ctx?: TxContext,
|
|
1254
|
+
): Promise<HydratedOrder> {
|
|
1255
|
+
const lineItems = await this.repo.findLineItemsByOrderId(order.id, ctx);
|
|
1256
|
+
const subtotal = lineItems.reduce((sum, li) => sum + li.totalPrice, 0);
|
|
1257
|
+
const taxTotal = lineItems.reduce((sum, li) => sum + li.taxAmount, 0);
|
|
1258
|
+
const grandTotal =
|
|
1259
|
+
subtotal + taxTotal + order.shippingTotal - order.discountTotal;
|
|
1260
|
+
const updated = await this.repo.update(
|
|
1261
|
+
order.id,
|
|
1262
|
+
{ subtotal, taxTotal, grandTotal },
|
|
1263
|
+
ctx,
|
|
1264
|
+
);
|
|
1265
|
+
await this.repo.createStatusHistory(
|
|
1266
|
+
{
|
|
1267
|
+
orderId: order.id,
|
|
1268
|
+
fromStatus: order.status,
|
|
1269
|
+
toStatus: order.status,
|
|
1270
|
+
reason,
|
|
1271
|
+
changedBy: actor?.userId ?? "system",
|
|
1272
|
+
},
|
|
1273
|
+
ctx,
|
|
1274
|
+
);
|
|
1275
|
+
return { ...(updated ?? order), lineItems };
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
async addLineItem(
|
|
1279
|
+
orderId: string,
|
|
1280
|
+
input: {
|
|
1281
|
+
entityId: string;
|
|
1282
|
+
entityType: string;
|
|
1283
|
+
variantId?: string | undefined;
|
|
1284
|
+
sku?: string | undefined;
|
|
1285
|
+
title: string;
|
|
1286
|
+
quantity: number;
|
|
1287
|
+
unitPrice: number;
|
|
1288
|
+
totalPrice?: number | undefined;
|
|
1289
|
+
taxAmount?: number | undefined;
|
|
1290
|
+
discountAmount?: number | undefined;
|
|
1291
|
+
metadata?: Record<string, unknown> | undefined;
|
|
1292
|
+
},
|
|
1293
|
+
actor: Actor | null,
|
|
1294
|
+
ctx?: TxContext,
|
|
1295
|
+
): Promise<Result<HydratedOrder>> {
|
|
1296
|
+
try {
|
|
1297
|
+
assertPermission(actor, "orders:update");
|
|
1298
|
+
} catch (error) {
|
|
1299
|
+
return Err(toCommerceError(error));
|
|
1300
|
+
}
|
|
1301
|
+
const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
|
|
1302
|
+
const order = await this.repo.findById(orgId, orderId, ctx);
|
|
1303
|
+
if (!order) return Err(new CommerceNotFoundError("Order not found."));
|
|
1304
|
+
const guard = this.lineItemEditGuard(order);
|
|
1305
|
+
if (guard) return Err(guard);
|
|
1306
|
+
|
|
1307
|
+
await this.repo.createLineItems(
|
|
1308
|
+
[
|
|
1309
|
+
{
|
|
1310
|
+
orderId: order.id,
|
|
1311
|
+
entityId: input.entityId,
|
|
1312
|
+
entityType: input.entityType,
|
|
1313
|
+
title: input.title,
|
|
1314
|
+
quantity: input.quantity,
|
|
1315
|
+
unitPrice: input.unitPrice,
|
|
1316
|
+
totalPrice: input.totalPrice ?? input.unitPrice * input.quantity,
|
|
1317
|
+
taxAmount: input.taxAmount ?? 0,
|
|
1318
|
+
discountAmount: input.discountAmount ?? 0,
|
|
1319
|
+
fulfillmentStatus: "unfulfilled",
|
|
1320
|
+
metadata: input.metadata ?? {},
|
|
1321
|
+
...(input.variantId !== undefined ? { variantId: input.variantId } : {}),
|
|
1322
|
+
...(input.sku !== undefined ? { sku: input.sku } : {}),
|
|
1323
|
+
},
|
|
1324
|
+
],
|
|
1325
|
+
ctx,
|
|
1326
|
+
);
|
|
1327
|
+
|
|
1328
|
+
return Ok(await this.recalcOrderTotals(order, actor, "line_item_added", ctx));
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
async updateOrderLineItem(
|
|
1332
|
+
orderId: string,
|
|
1333
|
+
lineItemId: string,
|
|
1334
|
+
patch: { quantity: number },
|
|
1335
|
+
actor: Actor | null,
|
|
1336
|
+
ctx?: TxContext,
|
|
1337
|
+
): Promise<Result<HydratedOrder>> {
|
|
1338
|
+
try {
|
|
1339
|
+
assertPermission(actor, "orders:update");
|
|
1340
|
+
} catch (error) {
|
|
1341
|
+
return Err(toCommerceError(error));
|
|
1342
|
+
}
|
|
1343
|
+
const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
|
|
1344
|
+
const order = await this.repo.findById(orgId, orderId, ctx);
|
|
1345
|
+
if (!order) return Err(new CommerceNotFoundError("Order not found."));
|
|
1346
|
+
const guard = this.lineItemEditGuard(order);
|
|
1347
|
+
if (guard) return Err(guard);
|
|
1348
|
+
|
|
1349
|
+
const line = await this.repo.findLineItemById(lineItemId, ctx);
|
|
1350
|
+
if (!line || line.orderId !== order.id) {
|
|
1351
|
+
return Err(new CommerceNotFoundError("Line item not found on this order."));
|
|
1352
|
+
}
|
|
1353
|
+
if (line.fulfillmentStatus !== "unfulfilled") {
|
|
1354
|
+
return Err(
|
|
1355
|
+
new CommerceValidationError(
|
|
1356
|
+
"Line items with fulfillment progress cannot be adjusted.",
|
|
1357
|
+
),
|
|
1358
|
+
);
|
|
1359
|
+
}
|
|
1360
|
+
if (patch.quantity < 1) {
|
|
1361
|
+
return Err(new CommerceValidationError("Quantity must be at least 1."));
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
// Scale line totals with the quantity change (tax scales per-unit).
|
|
1365
|
+
const perUnitTax = line.quantity > 0 ? line.taxAmount / line.quantity : 0;
|
|
1366
|
+
await this.repo.updateLineItem(
|
|
1367
|
+
lineItemId,
|
|
1368
|
+
{
|
|
1369
|
+
quantity: patch.quantity,
|
|
1370
|
+
totalPrice: line.unitPrice * patch.quantity,
|
|
1371
|
+
taxAmount: Math.round(perUnitTax * patch.quantity),
|
|
1372
|
+
},
|
|
1373
|
+
ctx,
|
|
1374
|
+
);
|
|
1375
|
+
|
|
1376
|
+
return Ok(await this.recalcOrderTotals(order, actor, "line_item_updated", ctx));
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
async removeLineItem(
|
|
1380
|
+
orderId: string,
|
|
1381
|
+
lineItemId: string,
|
|
1382
|
+
actor: Actor | null,
|
|
1383
|
+
ctx?: TxContext,
|
|
1384
|
+
): Promise<Result<HydratedOrder>> {
|
|
1385
|
+
try {
|
|
1386
|
+
assertPermission(actor, "orders:update");
|
|
1387
|
+
} catch (error) {
|
|
1388
|
+
return Err(toCommerceError(error));
|
|
1389
|
+
}
|
|
1390
|
+
const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
|
|
1391
|
+
const order = await this.repo.findById(orgId, orderId, ctx);
|
|
1392
|
+
if (!order) return Err(new CommerceNotFoundError("Order not found."));
|
|
1393
|
+
const guard = this.lineItemEditGuard(order);
|
|
1394
|
+
if (guard) return Err(guard);
|
|
1395
|
+
|
|
1396
|
+
const line = await this.repo.findLineItemById(lineItemId, ctx);
|
|
1397
|
+
if (!line || line.orderId !== order.id) {
|
|
1398
|
+
return Err(new CommerceNotFoundError("Line item not found on this order."));
|
|
1399
|
+
}
|
|
1400
|
+
if (line.fulfillmentStatus !== "unfulfilled") {
|
|
1401
|
+
return Err(
|
|
1402
|
+
new CommerceValidationError(
|
|
1403
|
+
"Line items with fulfillment progress cannot be removed.",
|
|
1404
|
+
),
|
|
1405
|
+
);
|
|
1406
|
+
}
|
|
1407
|
+
const existing = await this.repo.findLineItemsByOrderId(order.id, ctx);
|
|
1408
|
+
if (existing.length <= 1) {
|
|
1409
|
+
return Err(
|
|
1410
|
+
new CommerceValidationError("An order must keep at least one line item."),
|
|
1411
|
+
);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
await this.repo.deleteLineItem(lineItemId, ctx);
|
|
1415
|
+
|
|
1416
|
+
return Ok(await this.recalcOrderTotals(order, actor, "line_item_removed", ctx));
|
|
1417
|
+
}
|
|
1418
|
+
|
|
704
1419
|
async updateOrder(
|
|
705
1420
|
orderId: string,
|
|
706
1421
|
data: {
|