@unifiedcommerce/core 0.1.0 → 0.1.1

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 (174) hide show
  1. package/package.json +1 -2
  2. package/src/adapters/console-email.ts +0 -43
  3. package/src/auth/access.ts +0 -187
  4. package/src/auth/auth-schema.ts +0 -139
  5. package/src/auth/middleware.ts +0 -161
  6. package/src/auth/org.ts +0 -41
  7. package/src/auth/permissions.ts +0 -28
  8. package/src/auth/setup.ts +0 -169
  9. package/src/auth/system-actor.ts +0 -19
  10. package/src/auth/types.ts +0 -10
  11. package/src/config/defaults.ts +0 -82
  12. package/src/config/define-config.ts +0 -53
  13. package/src/config/types.ts +0 -299
  14. package/src/generated/plugin-capabilities.d.ts +0 -20
  15. package/src/generated/plugin-manifest.ts +0 -23
  16. package/src/generated/plugin-repositories.d.ts +0 -20
  17. package/src/hooks/checkout-completion.ts +0 -262
  18. package/src/hooks/checkout.ts +0 -677
  19. package/src/hooks/order-emails.ts +0 -62
  20. package/src/index.ts +0 -214
  21. package/src/interfaces/mcp/agent-prompt.ts +0 -174
  22. package/src/interfaces/mcp/context-enrichment.ts +0 -177
  23. package/src/interfaces/mcp/server.ts +0 -617
  24. package/src/interfaces/mcp/transport.ts +0 -68
  25. package/src/interfaces/rest/customer-portal.ts +0 -299
  26. package/src/interfaces/rest/index.ts +0 -74
  27. package/src/interfaces/rest/router.ts +0 -334
  28. package/src/interfaces/rest/routes/admin-jobs.ts +0 -58
  29. package/src/interfaces/rest/routes/audit.ts +0 -50
  30. package/src/interfaces/rest/routes/carts.ts +0 -89
  31. package/src/interfaces/rest/routes/catalog.ts +0 -493
  32. package/src/interfaces/rest/routes/checkout.ts +0 -283
  33. package/src/interfaces/rest/routes/inventory.ts +0 -70
  34. package/src/interfaces/rest/routes/media.ts +0 -86
  35. package/src/interfaces/rest/routes/orders.ts +0 -78
  36. package/src/interfaces/rest/routes/payments.ts +0 -60
  37. package/src/interfaces/rest/routes/pricing.ts +0 -57
  38. package/src/interfaces/rest/routes/promotions.ts +0 -92
  39. package/src/interfaces/rest/routes/search.ts +0 -71
  40. package/src/interfaces/rest/routes/webhooks.ts +0 -46
  41. package/src/interfaces/rest/schemas/admin-jobs.ts +0 -40
  42. package/src/interfaces/rest/schemas/audit.ts +0 -46
  43. package/src/interfaces/rest/schemas/carts.ts +0 -125
  44. package/src/interfaces/rest/schemas/catalog.ts +0 -450
  45. package/src/interfaces/rest/schemas/checkout.ts +0 -66
  46. package/src/interfaces/rest/schemas/customer-portal.ts +0 -195
  47. package/src/interfaces/rest/schemas/inventory.ts +0 -138
  48. package/src/interfaces/rest/schemas/media.ts +0 -75
  49. package/src/interfaces/rest/schemas/orders.ts +0 -104
  50. package/src/interfaces/rest/schemas/pricing.ts +0 -80
  51. package/src/interfaces/rest/schemas/promotions.ts +0 -110
  52. package/src/interfaces/rest/schemas/responses.ts +0 -85
  53. package/src/interfaces/rest/schemas/search.ts +0 -58
  54. package/src/interfaces/rest/schemas/shared.ts +0 -62
  55. package/src/interfaces/rest/schemas/webhooks.ts +0 -68
  56. package/src/interfaces/rest/utils.ts +0 -104
  57. package/src/interfaces/rest/webhook-router.ts +0 -50
  58. package/src/kernel/compensation/executor.ts +0 -61
  59. package/src/kernel/compensation/types.ts +0 -26
  60. package/src/kernel/database/adapter.ts +0 -13
  61. package/src/kernel/database/drizzle-db.ts +0 -56
  62. package/src/kernel/database/migrate.ts +0 -76
  63. package/src/kernel/database/plugin-types.ts +0 -34
  64. package/src/kernel/database/schema.ts +0 -49
  65. package/src/kernel/database/scoped-db.ts +0 -68
  66. package/src/kernel/database/tx-context.ts +0 -46
  67. package/src/kernel/error-mapper.ts +0 -15
  68. package/src/kernel/errors.ts +0 -89
  69. package/src/kernel/factory/repository-factory.ts +0 -242
  70. package/src/kernel/hooks/create-context.ts +0 -43
  71. package/src/kernel/hooks/executor.ts +0 -88
  72. package/src/kernel/hooks/registry.ts +0 -74
  73. package/src/kernel/hooks/types.ts +0 -52
  74. package/src/kernel/http-error.ts +0 -44
  75. package/src/kernel/jobs/adapter.ts +0 -36
  76. package/src/kernel/jobs/drizzle-adapter.ts +0 -58
  77. package/src/kernel/jobs/runner.ts +0 -153
  78. package/src/kernel/jobs/schema.ts +0 -46
  79. package/src/kernel/jobs/types.ts +0 -30
  80. package/src/kernel/local-api.ts +0 -185
  81. package/src/kernel/plugin/manifest.ts +0 -253
  82. package/src/kernel/query/executor.ts +0 -184
  83. package/src/kernel/query/registry.ts +0 -46
  84. package/src/kernel/result.ts +0 -33
  85. package/src/kernel/schema/extra-columns.ts +0 -37
  86. package/src/kernel/service-registry.ts +0 -76
  87. package/src/kernel/service-timing.ts +0 -89
  88. package/src/kernel/state-machine/machine.ts +0 -101
  89. package/src/modules/analytics/drizzle-adapter.ts +0 -426
  90. package/src/modules/analytics/hooks.ts +0 -11
  91. package/src/modules/analytics/models.ts +0 -125
  92. package/src/modules/analytics/repository/index.ts +0 -6
  93. package/src/modules/analytics/service.ts +0 -245
  94. package/src/modules/analytics/types.ts +0 -180
  95. package/src/modules/audit/hooks.ts +0 -78
  96. package/src/modules/audit/schema.ts +0 -33
  97. package/src/modules/audit/service.ts +0 -151
  98. package/src/modules/cart/access.ts +0 -27
  99. package/src/modules/cart/matcher.ts +0 -26
  100. package/src/modules/cart/repository/index.ts +0 -234
  101. package/src/modules/cart/schema.ts +0 -42
  102. package/src/modules/cart/schemas.ts +0 -38
  103. package/src/modules/cart/service.ts +0 -541
  104. package/src/modules/catalog/repository/index.ts +0 -772
  105. package/src/modules/catalog/schema.ts +0 -203
  106. package/src/modules/catalog/schemas.ts +0 -104
  107. package/src/modules/catalog/service.ts +0 -1544
  108. package/src/modules/customers/repository/index.ts +0 -327
  109. package/src/modules/customers/schema.ts +0 -64
  110. package/src/modules/customers/service.ts +0 -171
  111. package/src/modules/fulfillment/repository/index.ts +0 -426
  112. package/src/modules/fulfillment/schema.ts +0 -101
  113. package/src/modules/fulfillment/service.ts +0 -555
  114. package/src/modules/fulfillment/types.ts +0 -59
  115. package/src/modules/inventory/repository/index.ts +0 -509
  116. package/src/modules/inventory/schema.ts +0 -94
  117. package/src/modules/inventory/schemas.ts +0 -38
  118. package/src/modules/inventory/service.ts +0 -490
  119. package/src/modules/media/adapter.ts +0 -17
  120. package/src/modules/media/repository/index.ts +0 -274
  121. package/src/modules/media/schema.ts +0 -41
  122. package/src/modules/media/service.ts +0 -151
  123. package/src/modules/orders/repository/index.ts +0 -287
  124. package/src/modules/orders/schema.ts +0 -66
  125. package/src/modules/orders/service.ts +0 -619
  126. package/src/modules/orders/stale-order-cleanup.ts +0 -76
  127. package/src/modules/organization/service.ts +0 -191
  128. package/src/modules/payments/adapter.ts +0 -47
  129. package/src/modules/payments/repository/index.ts +0 -6
  130. package/src/modules/payments/service.ts +0 -107
  131. package/src/modules/pricing/repository/index.ts +0 -291
  132. package/src/modules/pricing/schema.ts +0 -71
  133. package/src/modules/pricing/schemas.ts +0 -38
  134. package/src/modules/pricing/service.ts +0 -494
  135. package/src/modules/promotions/repository/index.ts +0 -325
  136. package/src/modules/promotions/schema.ts +0 -62
  137. package/src/modules/promotions/schemas.ts +0 -38
  138. package/src/modules/promotions/service.ts +0 -598
  139. package/src/modules/search/adapter.ts +0 -57
  140. package/src/modules/search/hooks.ts +0 -12
  141. package/src/modules/search/repository/index.ts +0 -6
  142. package/src/modules/search/service.ts +0 -315
  143. package/src/modules/shipping/calculator.ts +0 -188
  144. package/src/modules/shipping/repository/index.ts +0 -6
  145. package/src/modules/shipping/service.ts +0 -51
  146. package/src/modules/tax/adapter.ts +0 -60
  147. package/src/modules/tax/repository/index.ts +0 -6
  148. package/src/modules/tax/service.ts +0 -53
  149. package/src/modules/webhooks/hook.ts +0 -34
  150. package/src/modules/webhooks/repository/index.ts +0 -278
  151. package/src/modules/webhooks/schema.ts +0 -56
  152. package/src/modules/webhooks/service.ts +0 -117
  153. package/src/modules/webhooks/signing.ts +0 -6
  154. package/src/modules/webhooks/ssrf-guard.ts +0 -71
  155. package/src/modules/webhooks/tasks.ts +0 -52
  156. package/src/modules/webhooks/worker.ts +0 -134
  157. package/src/runtime/commerce.ts +0 -145
  158. package/src/runtime/kernel.ts +0 -419
  159. package/src/runtime/logger.ts +0 -36
  160. package/src/runtime/server.ts +0 -349
  161. package/src/runtime/shutdown.ts +0 -43
  162. package/src/test-utils/create-pglite-adapter.ts +0 -129
  163. package/src/test-utils/create-plugin-test-app.ts +0 -128
  164. package/src/test-utils/create-repository-test-harness.ts +0 -16
  165. package/src/test-utils/create-test-config.ts +0 -190
  166. package/src/test-utils/create-test-kernel.ts +0 -7
  167. package/src/test-utils/create-test-plugin-context.ts +0 -75
  168. package/src/test-utils/rest-api-test-utils.ts +0 -265
  169. package/src/test-utils/test-actors.ts +0 -62
  170. package/src/test-utils/typed-hooks.ts +0 -54
  171. package/src/types/commerce-types.ts +0 -34
  172. package/src/utils/id.ts +0 -3
  173. package/src/utils/logger.ts +0 -18
  174. package/src/utils/pagination.ts +0 -22
@@ -1,315 +0,0 @@
1
- import { Ok, type Result } from "../../kernel/result.js";
2
- import { resolveOrgId } from "../../auth/org.js";
3
- import type { TxContext } from "../../kernel/database/tx-context.js";
4
- import type { CatalogRepository, SellableEntity } from "../catalog/repository/index.js";
5
- import type {
6
- SearchAdapter,
7
- SearchDocument,
8
- SearchFilters,
9
- SearchQueryParams,
10
- SearchQueryResult,
11
- SearchSuggestParams,
12
- } from "./adapter.js";
13
-
14
- interface SearchServiceDeps {
15
- catalogRepository: CatalogRepository;
16
- adapter?: SearchAdapter;
17
- defaultFacets?: string[];
18
- }
19
-
20
- function unique(values: string[]): string[] {
21
- return [...new Set(values)];
22
- }
23
-
24
- function clamp(value: number, min: number, max: number): number {
25
- return Math.max(min, Math.min(max, value));
26
- }
27
-
28
- function tokenize(query: string): string[] {
29
- return query
30
- .toLowerCase()
31
- .split(/\s+/)
32
- .map((part) => part.trim())
33
- .filter(Boolean);
34
- }
35
-
36
- function includesAllTokens(haystack: string, tokens: string[]): boolean {
37
- if (tokens.length === 0) return true;
38
- const lower = haystack.toLowerCase();
39
- return tokens.every((token) => lower.includes(token));
40
- }
41
-
42
- function scoreText(document: SearchDocument, tokens: string[]): number {
43
- if (tokens.length === 0) return 1;
44
-
45
- const title = document.title.toLowerCase();
46
- const text = document.text.toLowerCase();
47
-
48
- let score = 0;
49
- for (const token of tokens) {
50
- if (title.includes(token)) score += 2;
51
- if (text.includes(token)) score += 1;
52
- }
53
-
54
- return score;
55
- }
56
-
57
- export class SearchService {
58
- constructor(private deps: SearchServiceDeps) {}
59
-
60
- private async entityCategories(
61
- entityId: string,
62
- ctx?: TxContext,
63
- ): Promise<string[]> {
64
- const entries = await this.deps.catalogRepository.findEntityCategories(
65
- entityId,
66
- ctx,
67
- );
68
-
69
- const slugs = (
70
- await Promise.all(
71
- entries.map(async (entry) => {
72
- const category = await this.deps.catalogRepository.findCategoryById(
73
- entry.categoryId,
74
- ctx,
75
- );
76
- return category?.slug;
77
- }),
78
- )
79
- ).filter((slug): slug is string => typeof slug === "string");
80
-
81
- return unique(slugs);
82
- }
83
-
84
- private async entityBrands(
85
- entityId: string,
86
- ctx?: TxContext,
87
- ): Promise<string[]> {
88
- const entries = await this.deps.catalogRepository.findEntityBrands(
89
- entityId,
90
- ctx,
91
- );
92
-
93
- const slugs = (
94
- await Promise.all(
95
- entries.map(async (entry) => {
96
- const brand = await this.deps.catalogRepository.findBrandById(
97
- entry.brandId,
98
- ctx,
99
- );
100
- return brand?.slug;
101
- }),
102
- )
103
- ).filter((slug): slug is string => typeof slug === "string");
104
-
105
- return unique(slugs);
106
- }
107
-
108
- private async buildDocument(
109
- entity: SellableEntity,
110
- ctx?: TxContext,
111
- ): Promise<SearchDocument> {
112
- const attributes =
113
- await this.deps.catalogRepository.findAttributesByEntityId(
114
- entity.id,
115
- ctx,
116
- );
117
- const primary = attributes[0];
118
- const title = primary?.title ?? entity.slug;
119
- const description = primary?.description;
120
- const categories = await this.entityCategories(entity.id, ctx);
121
- const brands = await this.entityBrands(entity.id, ctx);
122
-
123
- const textParts: string[] = [
124
- entity.slug,
125
- title,
126
- description ?? "",
127
- ...categories,
128
- ...brands,
129
- ...attributes.map((attr) => attr.title),
130
- ...attributes.map((attr) => attr.description ?? ""),
131
- ];
132
-
133
- return {
134
- id: entity.id,
135
- type: entity.type,
136
- slug: entity.slug,
137
- title,
138
- ...(description ? { description } : {}),
139
- status: entity.status,
140
- categories,
141
- brands,
142
- text: textParts.join(" ").trim(),
143
- payload: {
144
- metadata: entity.metadata ?? undefined,
145
- },
146
- };
147
- }
148
-
149
- private async allDocuments(ctx?: TxContext): Promise<SearchDocument[]> {
150
- const orgId = resolveOrgId(ctx?.actor ?? null);
151
- const entities = await this.deps.catalogRepository.findEntities(
152
- orgId,
153
- undefined,
154
- ctx,
155
- );
156
- return Promise.all(
157
- entities.map((entity) => this.buildDocument(entity, ctx)),
158
- );
159
- }
160
-
161
- private matchesFilters(
162
- document: SearchDocument,
163
- filters: SearchFilters | undefined,
164
- ): boolean {
165
- if (!filters) return true;
166
- if (filters.type && document.type !== filters.type) return false;
167
- if (filters.status && document.status !== filters.status) return false;
168
- if (filters.category && !document.categories.includes(filters.category))
169
- return false;
170
- if (filters.brand && !document.brands.includes(filters.brand)) return false;
171
- return true;
172
- }
173
-
174
- private computeFacets(
175
- documents: SearchDocument[],
176
- requested?: string[],
177
- ): Record<string, Record<string, number>> {
178
- const facets =
179
- requested && requested.length > 0
180
- ? requested
181
- : (this.deps.defaultFacets ?? ["type", "category", "brand", "status"]);
182
- const output: Record<string, Record<string, number>> = {};
183
-
184
- for (const facet of facets) {
185
- if (facet === "type") {
186
- output.type = {};
187
- for (const document of documents) {
188
- output.type[document.type] = (output.type[document.type] ?? 0) + 1;
189
- }
190
- }
191
-
192
- if (facet === "status") {
193
- output.status = {};
194
- for (const document of documents) {
195
- const status = document.status ?? "unknown";
196
- output.status[status] = (output.status[status] ?? 0) + 1;
197
- }
198
- }
199
-
200
- if (facet === "category" || facet === "categories") {
201
- output.category = {};
202
- for (const document of documents) {
203
- for (const category of document.categories) {
204
- output.category[category] = (output.category[category] ?? 0) + 1;
205
- }
206
- }
207
- }
208
-
209
- if (facet === "brand" || facet === "brands") {
210
- output.brand = {};
211
- for (const document of documents) {
212
- for (const brand of document.brands) {
213
- output.brand[brand] = (output.brand[brand] ?? 0) + 1;
214
- }
215
- }
216
- }
217
- }
218
-
219
- return output;
220
- }
221
-
222
- async syncEntity(entityId: string, ctx?: TxContext): Promise<Result<void>> {
223
- if (!this.deps.adapter) return Ok(undefined);
224
-
225
- const entity = await this.deps.catalogRepository.findEntityById(
226
- entityId,
227
- ctx,
228
- );
229
- if (!entity) {
230
- return this.deps.adapter.remove([entityId]);
231
- }
232
-
233
- return this.deps.adapter.index([await this.buildDocument(entity, ctx)]);
234
- }
235
-
236
- async query(
237
- params: SearchQueryParams,
238
- ctx?: TxContext,
239
- ): Promise<Result<SearchQueryResult>> {
240
- const page = clamp(params.page ?? 1, 1, 100000);
241
- const limit = clamp(params.limit ?? 20, 1, 100);
242
-
243
- if (this.deps.adapter) {
244
- return this.deps.adapter.search({
245
- ...params,
246
- page,
247
- limit,
248
- });
249
- }
250
-
251
- const tokens = tokenize(params.query);
252
- const allDocs = await this.allDocuments(ctx);
253
- const filtered = allDocs.filter((document) => {
254
- if (!this.matchesFilters(document, params.filters)) return false;
255
- if (tokens.length === 0) return true;
256
- return includesAllTokens(document.text, tokens);
257
- });
258
-
259
- const scored = filtered
260
- .map((document) => ({
261
- document,
262
- score: scoreText(document, tokens),
263
- }))
264
- .sort((first, second) => {
265
- if (second.score !== first.score) return second.score - first.score;
266
- return first.document.title.localeCompare(second.document.title);
267
- });
268
-
269
- const offset = (page - 1) * limit;
270
- const hits = scored.slice(offset, offset + limit).map((row) => ({
271
- id: row.document.id,
272
- score: row.score,
273
- document: row.document,
274
- }));
275
-
276
- return Ok({
277
- hits,
278
- total: scored.length,
279
- page,
280
- limit,
281
- facets: this.computeFacets(filtered, params.facets),
282
- });
283
- }
284
-
285
- async suggest(
286
- params: SearchSuggestParams,
287
- ctx?: TxContext,
288
- ): Promise<Result<string[]>> {
289
- const limit = clamp(params.limit ?? 10, 1, 25);
290
- const prefix = params.prefix.trim().toLowerCase();
291
-
292
- if (prefix.length === 0) return Ok([]);
293
-
294
- if (this.deps.adapter) {
295
- return this.deps.adapter.suggest({
296
- ...params,
297
- prefix,
298
- limit,
299
- });
300
- }
301
-
302
- const allDocs = await this.allDocuments(ctx);
303
- const titles = allDocs
304
- .filter(
305
- (document) =>
306
- (!params.type || document.type === params.type) &&
307
- document.title.toLowerCase().startsWith(prefix),
308
- )
309
- .map((document) => document.title)
310
- .filter((title, index, list) => list.indexOf(title) === index)
311
- .slice(0, limit);
312
-
313
- return Ok(titles);
314
- }
315
- }
@@ -1,188 +0,0 @@
1
- import type { CommerceConfig } from "../../config/types.js";
2
- import type { TxContext } from "../../kernel/database/tx-context.js";
3
- import type { CatalogRepository } from "../catalog/repository/index.js";
4
-
5
- export interface ShippingAddress {
6
- country: string;
7
- postalCode: string;
8
- state?: string;
9
- city?: string;
10
- line1?: string;
11
- }
12
-
13
- export interface ShippingLineItem {
14
- entityId: string;
15
- variantId?: string;
16
- quantity: number;
17
- resolvedTotal: number;
18
- }
19
-
20
- export type ShippingStrategy =
21
- | {
22
- type: "flat";
23
- flatRate: number;
24
- freeShippingThreshold?: number;
25
- }
26
- | {
27
- type: "weight_based";
28
- brackets: Array<{ upToGrams: number; cost: number }>;
29
- fallbackCost: number;
30
- freeShippingThreshold?: number;
31
- };
32
-
33
- export interface ShippingCalculationInput {
34
- lineItems: ShippingLineItem[];
35
- subtotalAfterDiscount: number;
36
- currency: string;
37
- address?: ShippingAddress;
38
- isFreeShipping: boolean;
39
- }
40
-
41
- async function resolveWeightGrams(
42
- catalogRepo: CatalogRepository,
43
- entityId: string,
44
- variantId: string | undefined,
45
- ctx?: TxContext,
46
- ): Promise<number> {
47
- if (variantId !== undefined) {
48
- const variant = await catalogRepo.findVariantById(variantId, ctx);
49
- const weightFromVariant = (
50
- variant?.metadata as Record<string, unknown> | null
51
- )?.weightGrams;
52
- if (
53
- typeof weightFromVariant === "number" &&
54
- Number.isFinite(weightFromVariant)
55
- ) {
56
- return Math.max(0, Math.round(weightFromVariant));
57
- }
58
- }
59
-
60
- const entity = await catalogRepo.findEntityById(entityId, ctx);
61
- const weightFromEntity = (entity?.metadata as Record<string, unknown> | null)
62
- ?.weightGrams;
63
- if (
64
- typeof weightFromEntity === "number" &&
65
- Number.isFinite(weightFromEntity)
66
- ) {
67
- return Math.max(0, Math.round(weightFromEntity));
68
- }
69
-
70
- return 0;
71
- }
72
-
73
- async function isShippableEntity(
74
- config: CommerceConfig,
75
- catalogRepo: CatalogRepository,
76
- entityId: string,
77
- ctx?: TxContext,
78
- ): Promise<boolean> {
79
- const entity = await catalogRepo.findEntityById(entityId, ctx);
80
- if (!entity) return false;
81
- const fulfillment = config.entities?.[entity.type]?.fulfillment;
82
- return (
83
- fulfillment === "physical" ||
84
- fulfillment === "internal-transfer" ||
85
- fulfillment === undefined
86
- );
87
- }
88
-
89
- function resolveStrategy(config: CommerceConfig): ShippingStrategy {
90
- const shipping = config.shipping;
91
- if (!shipping) {
92
- return {
93
- type: "flat",
94
- flatRate: 0,
95
- };
96
- }
97
-
98
- if (shipping.type === "weight_based") {
99
- return {
100
- type: "weight_based",
101
- brackets: [...shipping.brackets].sort(
102
- (a, b) => a.upToGrams - b.upToGrams,
103
- ),
104
- fallbackCost: shipping.fallbackCost,
105
- ...(shipping.freeShippingThreshold !== undefined
106
- ? { freeShippingThreshold: shipping.freeShippingThreshold }
107
- : {}),
108
- };
109
- }
110
-
111
- return {
112
- type: "flat",
113
- flatRate: shipping.flatRate,
114
- ...(shipping.freeShippingThreshold !== undefined
115
- ? { freeShippingThreshold: shipping.freeShippingThreshold }
116
- : {}),
117
- };
118
- }
119
-
120
- export async function calculateShippingCost(
121
- config: CommerceConfig,
122
- catalogRepo: CatalogRepository,
123
- input: ShippingCalculationInput,
124
- ctx?: TxContext,
125
- ): Promise<{ amount: number; strategy: string; weightGrams: number }> {
126
- if (input.isFreeShipping) {
127
- return { amount: 0, strategy: "promotion:free_shipping", weightGrams: 0 };
128
- }
129
-
130
- const strategy = resolveStrategy(config);
131
- if (
132
- strategy.freeShippingThreshold !== undefined &&
133
- input.subtotalAfterDiscount >= strategy.freeShippingThreshold
134
- ) {
135
- return { amount: 0, strategy: "threshold:free_shipping", weightGrams: 0 };
136
- }
137
-
138
- // Filter to shippable items
139
- const shippableFlags = await Promise.all(
140
- input.lineItems.map((lineItem) =>
141
- isShippableEntity(config, catalogRepo, lineItem.entityId, ctx),
142
- ),
143
- );
144
- const shippableItems = input.lineItems.filter((_, i) => shippableFlags[i]);
145
-
146
- if (shippableItems.length === 0) {
147
- return {
148
- amount: 0,
149
- strategy: `${strategy.type}:digital_only`,
150
- weightGrams: 0,
151
- };
152
- }
153
-
154
- // Calculate total weight
155
- const weights = await Promise.all(
156
- shippableItems.map((lineItem) =>
157
- resolveWeightGrams(
158
- catalogRepo,
159
- lineItem.entityId,
160
- lineItem.variantId,
161
- ctx,
162
- ),
163
- ),
164
- );
165
- const weightGrams = shippableItems.reduce(
166
- (sum, lineItem, i) => sum + (weights[i] ?? 0) * lineItem.quantity,
167
- 0,
168
- );
169
-
170
- if (strategy.type === "flat") {
171
- return {
172
- amount: Math.max(0, Math.round(strategy.flatRate)),
173
- strategy: "flat",
174
- weightGrams,
175
- };
176
- }
177
-
178
- const matchedBracket = strategy.brackets.find(
179
- (bracket) => weightGrams <= bracket.upToGrams,
180
- );
181
- return {
182
- amount: matchedBracket
183
- ? Math.max(0, Math.round(matchedBracket.cost))
184
- : Math.max(0, Math.round(strategy.fallbackCost)),
185
- strategy: "weight_based",
186
- weightGrams,
187
- };
188
- }
@@ -1,6 +0,0 @@
1
- import type { TxContext } from "../../../kernel/database/tx-context.js";
2
-
3
- export interface ShippingRepository {
4
- // RFC-002 scaffold: module repositories become the only persistence boundary.
5
- ping(ctx: TxContext): Promise<void>;
6
- }
@@ -1,51 +0,0 @@
1
- import type { CommerceConfig } from "../../config/types.js";
2
- import { Ok, type Result } from "../../kernel/result.js";
3
- import type { TxContext } from "../../kernel/database/tx-context.js";
4
- import type { CatalogRepository } from "../catalog/repository/index.js";
5
- import {
6
- calculateShippingCost,
7
- type ShippingAddress,
8
- type ShippingLineItem,
9
- } from "./calculator.js";
10
-
11
- interface ShippingServiceDeps {
12
- config: CommerceConfig;
13
- catalogRepository: CatalogRepository;
14
- }
15
-
16
- export interface CalculateShippingInput {
17
- lineItems: ShippingLineItem[];
18
- subtotalAfterDiscount: number;
19
- currency: string;
20
- address?: ShippingAddress;
21
- isFreeShipping?: boolean;
22
- }
23
-
24
- export class ShippingService {
25
- private readonly catalogRepo: CatalogRepository;
26
-
27
- constructor(private deps: ShippingServiceDeps) {
28
- this.catalogRepo = deps.catalogRepository;
29
- }
30
-
31
- async calculate(
32
- input: CalculateShippingInput,
33
- ctx?: TxContext,
34
- ): Promise<
35
- Result<{ amount: number; strategy: string; weightGrams: number }>
36
- > {
37
- const result = await calculateShippingCost(
38
- this.deps.config,
39
- this.catalogRepo,
40
- {
41
- lineItems: input.lineItems,
42
- subtotalAfterDiscount: input.subtotalAfterDiscount,
43
- currency: input.currency,
44
- isFreeShipping: input.isFreeShipping ?? false,
45
- ...(input.address !== undefined ? { address: input.address } : {}),
46
- },
47
- ctx,
48
- );
49
- return Ok(result);
50
- }
51
- }
@@ -1,60 +0,0 @@
1
- import type { Result } from "../../kernel/result.js";
2
-
3
- export interface TaxAddress {
4
- country: string;
5
- postalCode: string;
6
- state?: string;
7
- city?: string;
8
- line1?: string;
9
- }
10
-
11
- export interface TaxLineItem {
12
- id: string;
13
- entityId: string;
14
- description: string;
15
- quantity: number;
16
- unitPrice: number;
17
- discount?: number;
18
- productTaxCode?: string;
19
- }
20
-
21
- export interface TaxCalculationParams {
22
- currency: string;
23
- customerId?: string;
24
- orderId?: string;
25
- fromAddress?: TaxAddress;
26
- toAddress?: TaxAddress;
27
- shippingAmount: number;
28
- lineItems: TaxLineItem[];
29
- }
30
-
31
- export interface TaxCalculationResult {
32
- amountToCollect: number;
33
- taxableAmount: number;
34
- rate: number;
35
- breakdown?: Record<string, unknown>;
36
- }
37
-
38
- export interface TaxReportParams {
39
- transactionId: string;
40
- transactionDate: Date;
41
- currency: string;
42
- customerId?: string;
43
- fromAddress?: TaxAddress;
44
- toAddress?: TaxAddress;
45
- amount: number;
46
- shipping: number;
47
- salesTax: number;
48
- lineItems: TaxLineItem[];
49
- }
50
-
51
- export interface TaxVoidParams {
52
- transactionId: string;
53
- }
54
-
55
- export interface TaxAdapter {
56
- readonly providerId: string;
57
- calculateTax(params: TaxCalculationParams): Promise<Result<TaxCalculationResult>>;
58
- reportTransaction(params: TaxReportParams): Promise<Result<{ transactionId: string }>>;
59
- voidTransaction(params: TaxVoidParams): Promise<Result<{ transactionId: string }>>;
60
- }
@@ -1,6 +0,0 @@
1
- import type { TxContext } from "../../../kernel/database/tx-context.js";
2
-
3
- export interface TaxRepository {
4
- // RFC-002 scaffold: module repositories become the only persistence boundary.
5
- ping(ctx: TxContext): Promise<void>;
6
- }
@@ -1,53 +0,0 @@
1
- import { CommerceValidationError } from "../../kernel/errors.js";
2
- import { Err, Ok, type Result } from "../../kernel/result.js";
3
- import type {
4
- TaxAdapter,
5
- TaxCalculationParams,
6
- TaxCalculationResult,
7
- TaxReportParams,
8
- TaxVoidParams,
9
- } from "./adapter.js";
10
-
11
- interface TaxServiceDeps {
12
- adapter: TaxAdapter | undefined;
13
- }
14
-
15
- export class TaxService {
16
- private adapter: TaxAdapter | undefined;
17
-
18
- constructor(deps: TaxServiceDeps) {
19
- this.adapter = deps.adapter;
20
- }
21
-
22
- async calculate(params: TaxCalculationParams): Promise<Result<TaxCalculationResult>> {
23
- if (!this.adapter) {
24
- return Ok({
25
- amountToCollect: 0,
26
- taxableAmount:
27
- params.lineItems.reduce(
28
- (sum, lineItem) => sum + lineItem.unitPrice * lineItem.quantity - (lineItem.discount ?? 0),
29
- 0,
30
- ) + params.shippingAmount,
31
- rate: 0,
32
- });
33
- }
34
- return this.adapter.calculateTax(params);
35
- }
36
-
37
- async reportTransaction(params: TaxReportParams): Promise<Result<{ transactionId: string }>> {
38
- if (!this.adapter) return Ok({ transactionId: params.transactionId });
39
- return this.adapter.reportTransaction(params);
40
- }
41
-
42
- async voidTransaction(params: TaxVoidParams): Promise<Result<{ transactionId: string }>> {
43
- if (!this.adapter) return Ok({ transactionId: params.transactionId });
44
- return this.adapter.voidTransaction(params);
45
- }
46
-
47
- requireConfigured(): Result<TaxAdapter> {
48
- if (!this.adapter) {
49
- return Err(new CommerceValidationError("Tax adapter is not configured."));
50
- }
51
- return Ok(this.adapter);
52
- }
53
- }