@unifiedcommerce/core 0.0.4 → 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 (179) hide show
  1. package/dist/auth/auth-schema.d.ts +92 -0
  2. package/dist/auth/auth-schema.d.ts.map +1 -1
  3. package/dist/auth/auth-schema.js +7 -0
  4. package/dist/auth/setup.d.ts.map +1 -1
  5. package/dist/auth/setup.js +3 -1
  6. package/package.json +1 -2
  7. package/src/adapters/console-email.ts +0 -43
  8. package/src/auth/access.ts +0 -187
  9. package/src/auth/auth-schema.ts +0 -131
  10. package/src/auth/middleware.ts +0 -161
  11. package/src/auth/org.ts +0 -41
  12. package/src/auth/permissions.ts +0 -28
  13. package/src/auth/setup.ts +0 -165
  14. package/src/auth/system-actor.ts +0 -19
  15. package/src/auth/types.ts +0 -10
  16. package/src/config/defaults.ts +0 -82
  17. package/src/config/define-config.ts +0 -53
  18. package/src/config/types.ts +0 -299
  19. package/src/generated/plugin-capabilities.d.ts +0 -20
  20. package/src/generated/plugin-manifest.ts +0 -23
  21. package/src/generated/plugin-repositories.d.ts +0 -20
  22. package/src/hooks/checkout-completion.ts +0 -262
  23. package/src/hooks/checkout.ts +0 -677
  24. package/src/hooks/order-emails.ts +0 -62
  25. package/src/index.ts +0 -214
  26. package/src/interfaces/mcp/agent-prompt.ts +0 -174
  27. package/src/interfaces/mcp/context-enrichment.ts +0 -177
  28. package/src/interfaces/mcp/server.ts +0 -617
  29. package/src/interfaces/mcp/transport.ts +0 -68
  30. package/src/interfaces/rest/customer-portal.ts +0 -299
  31. package/src/interfaces/rest/index.ts +0 -74
  32. package/src/interfaces/rest/router.ts +0 -334
  33. package/src/interfaces/rest/routes/admin-jobs.ts +0 -58
  34. package/src/interfaces/rest/routes/audit.ts +0 -50
  35. package/src/interfaces/rest/routes/carts.ts +0 -89
  36. package/src/interfaces/rest/routes/catalog.ts +0 -493
  37. package/src/interfaces/rest/routes/checkout.ts +0 -283
  38. package/src/interfaces/rest/routes/inventory.ts +0 -70
  39. package/src/interfaces/rest/routes/media.ts +0 -86
  40. package/src/interfaces/rest/routes/orders.ts +0 -78
  41. package/src/interfaces/rest/routes/payments.ts +0 -60
  42. package/src/interfaces/rest/routes/pricing.ts +0 -57
  43. package/src/interfaces/rest/routes/promotions.ts +0 -92
  44. package/src/interfaces/rest/routes/search.ts +0 -71
  45. package/src/interfaces/rest/routes/webhooks.ts +0 -46
  46. package/src/interfaces/rest/schemas/admin-jobs.ts +0 -40
  47. package/src/interfaces/rest/schemas/audit.ts +0 -46
  48. package/src/interfaces/rest/schemas/carts.ts +0 -125
  49. package/src/interfaces/rest/schemas/catalog.ts +0 -450
  50. package/src/interfaces/rest/schemas/checkout.ts +0 -66
  51. package/src/interfaces/rest/schemas/customer-portal.ts +0 -195
  52. package/src/interfaces/rest/schemas/inventory.ts +0 -138
  53. package/src/interfaces/rest/schemas/media.ts +0 -75
  54. package/src/interfaces/rest/schemas/orders.ts +0 -104
  55. package/src/interfaces/rest/schemas/pricing.ts +0 -80
  56. package/src/interfaces/rest/schemas/promotions.ts +0 -110
  57. package/src/interfaces/rest/schemas/responses.ts +0 -85
  58. package/src/interfaces/rest/schemas/search.ts +0 -58
  59. package/src/interfaces/rest/schemas/shared.ts +0 -62
  60. package/src/interfaces/rest/schemas/webhooks.ts +0 -68
  61. package/src/interfaces/rest/utils.ts +0 -104
  62. package/src/interfaces/rest/webhook-router.ts +0 -50
  63. package/src/kernel/compensation/executor.ts +0 -61
  64. package/src/kernel/compensation/types.ts +0 -26
  65. package/src/kernel/database/adapter.ts +0 -13
  66. package/src/kernel/database/drizzle-db.ts +0 -56
  67. package/src/kernel/database/migrate.ts +0 -76
  68. package/src/kernel/database/plugin-types.ts +0 -34
  69. package/src/kernel/database/schema.ts +0 -49
  70. package/src/kernel/database/scoped-db.ts +0 -68
  71. package/src/kernel/database/tx-context.ts +0 -46
  72. package/src/kernel/error-mapper.ts +0 -15
  73. package/src/kernel/errors.ts +0 -89
  74. package/src/kernel/factory/repository-factory.ts +0 -242
  75. package/src/kernel/hooks/create-context.ts +0 -43
  76. package/src/kernel/hooks/executor.ts +0 -88
  77. package/src/kernel/hooks/registry.ts +0 -74
  78. package/src/kernel/hooks/types.ts +0 -52
  79. package/src/kernel/http-error.ts +0 -44
  80. package/src/kernel/jobs/adapter.ts +0 -36
  81. package/src/kernel/jobs/drizzle-adapter.ts +0 -58
  82. package/src/kernel/jobs/runner.ts +0 -153
  83. package/src/kernel/jobs/schema.ts +0 -46
  84. package/src/kernel/jobs/types.ts +0 -30
  85. package/src/kernel/local-api.ts +0 -185
  86. package/src/kernel/plugin/manifest.ts +0 -253
  87. package/src/kernel/query/executor.ts +0 -184
  88. package/src/kernel/query/registry.ts +0 -46
  89. package/src/kernel/result.ts +0 -33
  90. package/src/kernel/schema/extra-columns.ts +0 -37
  91. package/src/kernel/service-registry.ts +0 -76
  92. package/src/kernel/service-timing.ts +0 -89
  93. package/src/kernel/state-machine/machine.ts +0 -101
  94. package/src/modules/analytics/drizzle-adapter.ts +0 -426
  95. package/src/modules/analytics/hooks.ts +0 -11
  96. package/src/modules/analytics/models.ts +0 -125
  97. package/src/modules/analytics/repository/index.ts +0 -6
  98. package/src/modules/analytics/service.ts +0 -245
  99. package/src/modules/analytics/types.ts +0 -180
  100. package/src/modules/audit/hooks.ts +0 -78
  101. package/src/modules/audit/schema.ts +0 -33
  102. package/src/modules/audit/service.ts +0 -151
  103. package/src/modules/cart/access.ts +0 -27
  104. package/src/modules/cart/matcher.ts +0 -26
  105. package/src/modules/cart/repository/index.ts +0 -234
  106. package/src/modules/cart/schema.ts +0 -42
  107. package/src/modules/cart/schemas.ts +0 -38
  108. package/src/modules/cart/service.ts +0 -541
  109. package/src/modules/catalog/repository/index.ts +0 -772
  110. package/src/modules/catalog/schema.ts +0 -203
  111. package/src/modules/catalog/schemas.ts +0 -104
  112. package/src/modules/catalog/service.ts +0 -1544
  113. package/src/modules/customers/repository/index.ts +0 -327
  114. package/src/modules/customers/schema.ts +0 -64
  115. package/src/modules/customers/service.ts +0 -171
  116. package/src/modules/fulfillment/repository/index.ts +0 -426
  117. package/src/modules/fulfillment/schema.ts +0 -101
  118. package/src/modules/fulfillment/service.ts +0 -555
  119. package/src/modules/fulfillment/types.ts +0 -59
  120. package/src/modules/inventory/repository/index.ts +0 -509
  121. package/src/modules/inventory/schema.ts +0 -94
  122. package/src/modules/inventory/schemas.ts +0 -38
  123. package/src/modules/inventory/service.ts +0 -490
  124. package/src/modules/media/adapter.ts +0 -17
  125. package/src/modules/media/repository/index.ts +0 -274
  126. package/src/modules/media/schema.ts +0 -41
  127. package/src/modules/media/service.ts +0 -151
  128. package/src/modules/orders/repository/index.ts +0 -287
  129. package/src/modules/orders/schema.ts +0 -66
  130. package/src/modules/orders/service.ts +0 -619
  131. package/src/modules/orders/stale-order-cleanup.ts +0 -76
  132. package/src/modules/organization/service.ts +0 -191
  133. package/src/modules/payments/adapter.ts +0 -47
  134. package/src/modules/payments/repository/index.ts +0 -6
  135. package/src/modules/payments/service.ts +0 -107
  136. package/src/modules/pricing/repository/index.ts +0 -291
  137. package/src/modules/pricing/schema.ts +0 -71
  138. package/src/modules/pricing/schemas.ts +0 -38
  139. package/src/modules/pricing/service.ts +0 -494
  140. package/src/modules/promotions/repository/index.ts +0 -325
  141. package/src/modules/promotions/schema.ts +0 -62
  142. package/src/modules/promotions/schemas.ts +0 -38
  143. package/src/modules/promotions/service.ts +0 -598
  144. package/src/modules/search/adapter.ts +0 -57
  145. package/src/modules/search/hooks.ts +0 -12
  146. package/src/modules/search/repository/index.ts +0 -6
  147. package/src/modules/search/service.ts +0 -315
  148. package/src/modules/shipping/calculator.ts +0 -188
  149. package/src/modules/shipping/repository/index.ts +0 -6
  150. package/src/modules/shipping/service.ts +0 -51
  151. package/src/modules/tax/adapter.ts +0 -60
  152. package/src/modules/tax/repository/index.ts +0 -6
  153. package/src/modules/tax/service.ts +0 -53
  154. package/src/modules/webhooks/hook.ts +0 -34
  155. package/src/modules/webhooks/repository/index.ts +0 -278
  156. package/src/modules/webhooks/schema.ts +0 -56
  157. package/src/modules/webhooks/service.ts +0 -117
  158. package/src/modules/webhooks/signing.ts +0 -6
  159. package/src/modules/webhooks/ssrf-guard.ts +0 -71
  160. package/src/modules/webhooks/tasks.ts +0 -52
  161. package/src/modules/webhooks/worker.ts +0 -134
  162. package/src/runtime/commerce.ts +0 -145
  163. package/src/runtime/kernel.ts +0 -419
  164. package/src/runtime/logger.ts +0 -36
  165. package/src/runtime/server.ts +0 -349
  166. package/src/runtime/shutdown.ts +0 -43
  167. package/src/test-utils/create-pglite-adapter.ts +0 -129
  168. package/src/test-utils/create-plugin-test-app.ts +0 -128
  169. package/src/test-utils/create-repository-test-harness.ts +0 -16
  170. package/src/test-utils/create-test-config.ts +0 -190
  171. package/src/test-utils/create-test-kernel.ts +0 -7
  172. package/src/test-utils/create-test-plugin-context.ts +0 -75
  173. package/src/test-utils/rest-api-test-utils.ts +0 -265
  174. package/src/test-utils/test-actors.ts +0 -62
  175. package/src/test-utils/typed-hooks.ts +0 -54
  176. package/src/types/commerce-types.ts +0 -34
  177. package/src/utils/id.ts +0 -3
  178. package/src/utils/logger.ts +0 -18
  179. 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
- }