@unifiedcommerce/core 0.2.0 → 0.2.2

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 (186) hide show
  1. package/package.json +2 -1
  2. package/src/adapters/console-email.ts +43 -0
  3. package/src/auth/access.ts +187 -0
  4. package/src/auth/auth-schema.ts +139 -0
  5. package/src/auth/middleware.ts +161 -0
  6. package/src/auth/org.ts +41 -0
  7. package/src/auth/permissions.ts +28 -0
  8. package/src/auth/setup.ts +171 -0
  9. package/src/auth/system-actor.ts +19 -0
  10. package/src/auth/types.ts +10 -0
  11. package/src/config/defaults.ts +82 -0
  12. package/src/config/define-config.ts +53 -0
  13. package/src/config/types.ts +301 -0
  14. package/src/generated/plugin-capabilities.d.ts +20 -0
  15. package/src/generated/plugin-manifest.ts +23 -0
  16. package/src/generated/plugin-repositories.d.ts +20 -0
  17. package/src/hooks/checkout-completion.ts +262 -0
  18. package/src/hooks/checkout.ts +677 -0
  19. package/src/hooks/order-emails.ts +62 -0
  20. package/src/index.ts +215 -0
  21. package/src/interfaces/mcp/agent-prompt.ts +174 -0
  22. package/src/interfaces/mcp/context-enrichment.ts +177 -0
  23. package/src/interfaces/mcp/server.ts +47 -0
  24. package/src/interfaces/mcp/tool-builder.ts +261 -0
  25. package/src/interfaces/mcp/tools/analytics.ts +76 -0
  26. package/src/interfaces/mcp/tools/cart.ts +57 -0
  27. package/src/interfaces/mcp/tools/catalog.ts +299 -0
  28. package/src/interfaces/mcp/tools/index.ts +22 -0
  29. package/src/interfaces/mcp/tools/inventory.ts +161 -0
  30. package/src/interfaces/mcp/tools/orders.ts +104 -0
  31. package/src/interfaces/mcp/tools/pricing.ts +94 -0
  32. package/src/interfaces/mcp/tools/promotions.ts +106 -0
  33. package/src/interfaces/mcp/tools/registry.ts +101 -0
  34. package/src/interfaces/mcp/tools/search.ts +42 -0
  35. package/src/interfaces/mcp/tools/webhooks.ts +48 -0
  36. package/src/interfaces/mcp/transport.ts +128 -0
  37. package/src/interfaces/rest/customer-portal.ts +299 -0
  38. package/src/interfaces/rest/index.ts +74 -0
  39. package/src/interfaces/rest/router.ts +333 -0
  40. package/src/interfaces/rest/routes/admin-jobs.ts +58 -0
  41. package/src/interfaces/rest/routes/audit.ts +50 -0
  42. package/src/interfaces/rest/routes/carts.ts +89 -0
  43. package/src/interfaces/rest/routes/catalog.ts +493 -0
  44. package/src/interfaces/rest/routes/checkout.ts +284 -0
  45. package/src/interfaces/rest/routes/inventory.ts +70 -0
  46. package/src/interfaces/rest/routes/media.ts +86 -0
  47. package/src/interfaces/rest/routes/orders.ts +78 -0
  48. package/src/interfaces/rest/routes/payments.ts +60 -0
  49. package/src/interfaces/rest/routes/pricing.ts +57 -0
  50. package/src/interfaces/rest/routes/promotions.ts +93 -0
  51. package/src/interfaces/rest/routes/search.ts +71 -0
  52. package/src/interfaces/rest/routes/webhooks.ts +46 -0
  53. package/src/interfaces/rest/schemas/admin-jobs.ts +40 -0
  54. package/src/interfaces/rest/schemas/audit.ts +46 -0
  55. package/src/interfaces/rest/schemas/carts.ts +125 -0
  56. package/src/interfaces/rest/schemas/catalog.ts +450 -0
  57. package/src/interfaces/rest/schemas/checkout.ts +66 -0
  58. package/src/interfaces/rest/schemas/customer-portal.ts +195 -0
  59. package/src/interfaces/rest/schemas/inventory.ts +138 -0
  60. package/src/interfaces/rest/schemas/media.ts +75 -0
  61. package/src/interfaces/rest/schemas/orders.ts +104 -0
  62. package/src/interfaces/rest/schemas/pricing.ts +80 -0
  63. package/src/interfaces/rest/schemas/promotions.ts +110 -0
  64. package/src/interfaces/rest/schemas/responses.ts +85 -0
  65. package/src/interfaces/rest/schemas/search.ts +58 -0
  66. package/src/interfaces/rest/schemas/shared.ts +62 -0
  67. package/src/interfaces/rest/schemas/webhooks.ts +68 -0
  68. package/src/interfaces/rest/utils.ts +104 -0
  69. package/src/interfaces/rest/webhook-router.ts +50 -0
  70. package/src/kernel/compensation/executor.ts +61 -0
  71. package/src/kernel/compensation/types.ts +26 -0
  72. package/src/kernel/database/adapter.ts +21 -0
  73. package/src/kernel/database/drizzle-db.ts +56 -0
  74. package/src/kernel/database/migrate.ts +76 -0
  75. package/src/kernel/database/plugin-types.ts +34 -0
  76. package/src/kernel/database/schema.ts +49 -0
  77. package/src/kernel/database/scoped-db.ts +68 -0
  78. package/src/kernel/database/tx-context.ts +46 -0
  79. package/src/kernel/error-mapper.ts +15 -0
  80. package/src/kernel/errors.ts +89 -0
  81. package/src/kernel/factory/repository-factory.ts +244 -0
  82. package/src/kernel/hooks/create-context.ts +43 -0
  83. package/src/kernel/hooks/executor.ts +88 -0
  84. package/src/kernel/hooks/registry.ts +74 -0
  85. package/src/kernel/hooks/types.ts +52 -0
  86. package/src/kernel/http-error.ts +44 -0
  87. package/src/kernel/jobs/adapter.ts +36 -0
  88. package/src/kernel/jobs/drizzle-adapter.ts +58 -0
  89. package/src/kernel/jobs/runner.ts +153 -0
  90. package/src/kernel/jobs/schema.ts +46 -0
  91. package/src/kernel/jobs/types.ts +30 -0
  92. package/src/kernel/local-api.ts +187 -0
  93. package/src/kernel/plugin/manifest.ts +271 -0
  94. package/src/kernel/query/executor.ts +184 -0
  95. package/src/kernel/query/registry.ts +46 -0
  96. package/src/kernel/result.ts +33 -0
  97. package/src/kernel/schema/extra-columns.ts +37 -0
  98. package/src/kernel/service-registry.ts +76 -0
  99. package/src/kernel/service-timing.ts +89 -0
  100. package/src/kernel/state-machine/machine.ts +101 -0
  101. package/src/modules/analytics/drizzle-adapter.ts +426 -0
  102. package/src/modules/analytics/hooks.ts +11 -0
  103. package/src/modules/analytics/models.ts +125 -0
  104. package/src/modules/analytics/repository/index.ts +6 -0
  105. package/src/modules/analytics/service.ts +245 -0
  106. package/src/modules/analytics/types.ts +180 -0
  107. package/src/modules/audit/hooks.ts +78 -0
  108. package/src/modules/audit/schema.ts +33 -0
  109. package/src/modules/audit/service.ts +151 -0
  110. package/src/modules/cart/access.ts +27 -0
  111. package/src/modules/cart/matcher.ts +26 -0
  112. package/src/modules/cart/repository/index.ts +234 -0
  113. package/src/modules/cart/schema.ts +42 -0
  114. package/src/modules/cart/schemas.ts +38 -0
  115. package/src/modules/cart/service.ts +541 -0
  116. package/src/modules/catalog/repository/index.ts +772 -0
  117. package/src/modules/catalog/schema.ts +203 -0
  118. package/src/modules/catalog/schemas.ts +104 -0
  119. package/src/modules/catalog/service.ts +1544 -0
  120. package/src/modules/customers/repository/index.ts +327 -0
  121. package/src/modules/customers/schema.ts +64 -0
  122. package/src/modules/customers/service.ts +171 -0
  123. package/src/modules/fulfillment/repository/index.ts +426 -0
  124. package/src/modules/fulfillment/schema.ts +101 -0
  125. package/src/modules/fulfillment/service.ts +555 -0
  126. package/src/modules/fulfillment/types.ts +59 -0
  127. package/src/modules/inventory/repository/index.ts +509 -0
  128. package/src/modules/inventory/schema.ts +94 -0
  129. package/src/modules/inventory/schemas.ts +38 -0
  130. package/src/modules/inventory/service.ts +490 -0
  131. package/src/modules/media/adapter.ts +17 -0
  132. package/src/modules/media/repository/index.ts +274 -0
  133. package/src/modules/media/schema.ts +41 -0
  134. package/src/modules/media/service.ts +151 -0
  135. package/src/modules/orders/repository/index.ts +287 -0
  136. package/src/modules/orders/schema.ts +66 -0
  137. package/src/modules/orders/service.ts +619 -0
  138. package/src/modules/orders/stale-order-cleanup.ts +76 -0
  139. package/src/modules/organization/service.ts +191 -0
  140. package/src/modules/payments/adapter.ts +47 -0
  141. package/src/modules/payments/repository/index.ts +6 -0
  142. package/src/modules/payments/service.ts +107 -0
  143. package/src/modules/pricing/repository/index.ts +291 -0
  144. package/src/modules/pricing/schema.ts +71 -0
  145. package/src/modules/pricing/schemas.ts +38 -0
  146. package/src/modules/pricing/service.ts +494 -0
  147. package/src/modules/promotions/repository/index.ts +325 -0
  148. package/src/modules/promotions/schema.ts +62 -0
  149. package/src/modules/promotions/schemas.ts +38 -0
  150. package/src/modules/promotions/service.ts +598 -0
  151. package/src/modules/search/adapter.ts +57 -0
  152. package/src/modules/search/hooks.ts +12 -0
  153. package/src/modules/search/repository/index.ts +6 -0
  154. package/src/modules/search/service.ts +315 -0
  155. package/src/modules/shipping/calculator.ts +188 -0
  156. package/src/modules/shipping/repository/index.ts +6 -0
  157. package/src/modules/shipping/service.ts +51 -0
  158. package/src/modules/tax/adapter.ts +60 -0
  159. package/src/modules/tax/repository/index.ts +6 -0
  160. package/src/modules/tax/service.ts +53 -0
  161. package/src/modules/webhooks/hook.ts +34 -0
  162. package/src/modules/webhooks/repository/index.ts +278 -0
  163. package/src/modules/webhooks/schema.ts +56 -0
  164. package/src/modules/webhooks/service.ts +117 -0
  165. package/src/modules/webhooks/signing.ts +6 -0
  166. package/src/modules/webhooks/ssrf-guard.ts +71 -0
  167. package/src/modules/webhooks/tasks.ts +52 -0
  168. package/src/modules/webhooks/worker.ts +134 -0
  169. package/src/runtime/commerce.ts +145 -0
  170. package/src/runtime/kernel.ts +426 -0
  171. package/src/runtime/logger.ts +36 -0
  172. package/src/runtime/server.ts +355 -0
  173. package/src/runtime/shutdown.ts +43 -0
  174. package/src/test-utils/create-pglite-adapter.ts +129 -0
  175. package/src/test-utils/create-plugin-test-app.ts +128 -0
  176. package/src/test-utils/create-repository-test-harness.ts +16 -0
  177. package/src/test-utils/create-test-config.ts +190 -0
  178. package/src/test-utils/create-test-kernel.ts +7 -0
  179. package/src/test-utils/create-test-plugin-context.ts +75 -0
  180. package/src/test-utils/rest-api-test-utils.ts +265 -0
  181. package/src/test-utils/test-actors.ts +62 -0
  182. package/src/test-utils/typed-hooks.ts +54 -0
  183. package/src/types/commerce-types.ts +34 -0
  184. package/src/utils/id.ts +3 -0
  185. package/src/utils/logger.ts +18 -0
  186. package/src/utils/pagination.ts +22 -0
@@ -0,0 +1,151 @@
1
+ import { eq, and, desc, gte, lte } from "drizzle-orm";
2
+ import type { InferSelectModel } from "drizzle-orm";
3
+ import type { DrizzleDatabase } from "../../kernel/database/drizzle-db.js";
4
+ import type { TxContext } from "../../kernel/database/tx-context.js";
5
+ import type { HookContext } from "../../kernel/hooks/types.js";
6
+ import { resolveOrgId } from "../../auth/org.js";
7
+ import { auditLog } from "./schema.js";
8
+
9
+ export type AuditEntry = InferSelectModel<typeof auditLog>;
10
+
11
+ export interface RecordArgs {
12
+ entityType: string;
13
+ entityId: string;
14
+ event: string;
15
+ payload?: Record<string, unknown>;
16
+ ctx: HookContext;
17
+ }
18
+
19
+ export interface ListForEntityArgs {
20
+ organizationId?: string;
21
+ entityType: string;
22
+ entityId: string;
23
+ limit?: number;
24
+ ctx?: TxContext;
25
+ }
26
+
27
+ export interface ListArgs {
28
+ organizationId?: string | undefined;
29
+ entityType?: string | undefined;
30
+ entityId?: string | undefined;
31
+ event?: string | undefined;
32
+ actorId?: string | undefined;
33
+ from?: Date | undefined;
34
+ to?: Date | undefined;
35
+ limit?: number | undefined;
36
+ }
37
+
38
+ export interface AuditService {
39
+ record(args: RecordArgs): Promise<void>;
40
+ listForEntity(args: ListForEntityArgs): Promise<AuditEntry[]>;
41
+ list(args: ListArgs): Promise<AuditEntry[]>;
42
+ }
43
+
44
+ export function createNullAuditService(): AuditService {
45
+ const entries: AuditEntry[] = [];
46
+ return {
47
+ async record(args) {
48
+ entries.push({
49
+ id: crypto.randomUUID(),
50
+ organizationId: resolveOrgId(args.ctx.actor),
51
+ entityType: args.entityType,
52
+ entityId: args.entityId,
53
+ event: args.event,
54
+ payload: args.payload ?? {},
55
+ actorId: args.ctx.actor?.userId ?? null,
56
+ actorType: args.ctx.actor != null ? "user" : null,
57
+ requestId: args.ctx.requestId,
58
+ createdAt: new Date(),
59
+ });
60
+ },
61
+ async listForEntity(args) {
62
+ return entries
63
+ .filter(
64
+ (e) =>
65
+ e.entityType === args.entityType && e.entityId === args.entityId,
66
+ )
67
+ .sort(
68
+ (a, b) => b.createdAt.getTime() - a.createdAt.getTime(),
69
+ )
70
+ .slice(0, args.limit ?? 50);
71
+ },
72
+ async list(args) {
73
+ let result = entries;
74
+ if (args.entityType) result = result.filter((e) => e.entityType === args.entityType);
75
+ if (args.entityId) result = result.filter((e) => e.entityId === args.entityId);
76
+ if (args.event) result = result.filter((e) => e.event === args.event);
77
+ if (args.actorId) result = result.filter((e) => e.actorId === args.actorId);
78
+ if (args.from) result = result.filter((e) => e.createdAt >= args.from!);
79
+ if (args.to) result = result.filter((e) => e.createdAt <= args.to!);
80
+ return result
81
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
82
+ .slice(0, args.limit ?? 50);
83
+ },
84
+ };
85
+ }
86
+
87
+ export function createAuditService(db: DrizzleDatabase): AuditService {
88
+ return {
89
+ async record(args) {
90
+ const { entityType, entityId, event, payload, ctx } = args;
91
+ const dbOrTx =
92
+ ctx.tx != null
93
+ ? (ctx.tx as typeof db)
94
+ : db;
95
+
96
+ await dbOrTx.insert(auditLog).values({
97
+ organizationId: resolveOrgId(ctx.actor),
98
+ entityType,
99
+ entityId,
100
+ event,
101
+ payload: payload ?? {},
102
+ actorId: ctx.actor?.userId ?? null,
103
+ actorType: ctx.actor != null ? "user" : null,
104
+ requestId: ctx.requestId,
105
+ });
106
+ },
107
+
108
+ async listForEntity(args) {
109
+ const { organizationId, entityType, entityId, limit = 50, ctx } = args;
110
+ const dbOrTx =
111
+ ctx?.tx != null
112
+ ? (ctx.tx as typeof db)
113
+ : db;
114
+
115
+ const conditions = [
116
+ eq(auditLog.entityType, entityType),
117
+ eq(auditLog.entityId, entityId),
118
+ ];
119
+ if (organizationId) {
120
+ conditions.push(eq(auditLog.organizationId, organizationId));
121
+ }
122
+
123
+ return dbOrTx
124
+ .select()
125
+ .from(auditLog)
126
+ .where(and(...conditions))
127
+ .orderBy(desc(auditLog.createdAt))
128
+ .limit(limit);
129
+ },
130
+
131
+ async list(args) {
132
+ const conditions = [];
133
+ if (args.organizationId) conditions.push(eq(auditLog.organizationId, args.organizationId));
134
+ if (args.entityType) conditions.push(eq(auditLog.entityType, args.entityType));
135
+ if (args.entityId) conditions.push(eq(auditLog.entityId, args.entityId));
136
+ if (args.event) conditions.push(eq(auditLog.event, args.event));
137
+ if (args.actorId) conditions.push(eq(auditLog.actorId, args.actorId));
138
+ if (args.from) conditions.push(gte(auditLog.createdAt, args.from));
139
+ if (args.to) conditions.push(lte(auditLog.createdAt, args.to));
140
+
141
+ let query = db.select().from(auditLog).$dynamic();
142
+ if (conditions.length > 0) {
143
+ query = query.where(conditions.length === 1 ? conditions[0]! : and(...conditions));
144
+ }
145
+
146
+ return query
147
+ .orderBy(desc(auditLog.createdAt))
148
+ .limit(args.limit ?? 50);
149
+ },
150
+ };
151
+ }
@@ -0,0 +1,27 @@
1
+ import type { Actor } from "../../auth/types.js";
2
+ import type { Cart } from "./repository/index.js";
3
+
4
+ /**
5
+ * Determines whether an actor can access a cart.
6
+ *
7
+ * Access is granted if:
8
+ * 1. The actor is authenticated and owns the cart (customerId match)
9
+ * 2. The provided secret matches the cart's secret (guest access)
10
+ */
11
+ export function canAccessCart(
12
+ actor: Actor | null,
13
+ cart: Cart,
14
+ providedSecret?: string,
15
+ ): boolean {
16
+ // Authenticated owner
17
+ if (actor && cart.customerId && actor.userId === cart.customerId) {
18
+ return true;
19
+ }
20
+
21
+ // Valid secret (guest access)
22
+ if (providedSecret && cart.secret && providedSecret === cart.secret) {
23
+ return true;
24
+ }
25
+
26
+ return false;
27
+ }
@@ -0,0 +1,26 @@
1
+ import type { CartLineItem } from "./repository/index.js";
2
+
3
+ /**
4
+ * Determines whether a new item matches an existing cart line item.
5
+ * Used by addItem to decide whether to increment quantity (match)
6
+ * or insert a new line (no match).
7
+ *
8
+ * The default matcher compares entityId + variantId.
9
+ * Developers selling customizable products (engraving, gift notes)
10
+ * can provide a custom matcher that includes metadata fields.
11
+ */
12
+ export type CartItemMatcher = (args: {
13
+ existingItem: CartLineItem;
14
+ newItem: {
15
+ entityId: string;
16
+ variantId: string | null;
17
+ [key: string]: unknown;
18
+ };
19
+ }) => boolean;
20
+
21
+ export const defaultCartItemMatcher: CartItemMatcher = ({
22
+ existingItem,
23
+ newItem,
24
+ }) =>
25
+ existingItem.entityId === newItem.entityId &&
26
+ existingItem.variantId === (newItem.variantId ?? null);
@@ -0,0 +1,234 @@
1
+ import { eq, and, lt } from "drizzle-orm";
2
+ import type { TxContext } from "../../../kernel/database/tx-context.js";
3
+ import type {
4
+ DrizzleDatabase,
5
+ DbOrTx,
6
+ } from "../../../kernel/database/drizzle-db.js";
7
+ import { carts, cartLineItems } from "../schema.js";
8
+
9
+ // Infer types from Drizzle schema
10
+ export type Cart = typeof carts.$inferSelect;
11
+ export type CartInsert = typeof carts.$inferInsert;
12
+ export type CartLineItem = typeof cartLineItems.$inferSelect;
13
+ export type CartLineItemInsert = typeof cartLineItems.$inferInsert;
14
+
15
+ /**
16
+ * CartRepository provides type-safe database operations for shopping carts.
17
+ *
18
+ * This repository manages carts and cart line items.
19
+ * All methods support an optional TxContext parameter for transaction participation.
20
+ */
21
+ export class CartRepository {
22
+ constructor(private readonly db: DrizzleDatabase) {}
23
+
24
+ private getDb(ctx?: TxContext): DbOrTx {
25
+ return (ctx?.tx as DbOrTx | undefined) ?? this.db;
26
+ }
27
+
28
+ // ─────────────────────────────────────────────────────────────────────────────
29
+ // Carts
30
+ // ─────────────────────────────────────────────────────────────────────────────
31
+
32
+ async findById(orgId: string, id: string, ctx?: TxContext): Promise<Cart | undefined> {
33
+ const db = this.getDb(ctx);
34
+ const rows = await db
35
+ .select()
36
+ .from(carts)
37
+ .where(and(eq(carts.organizationId, orgId), eq(carts.id, id)));
38
+ return rows[0];
39
+ }
40
+
41
+ async findByCustomerId(
42
+ orgId: string,
43
+ customerId: string,
44
+ ctx?: TxContext,
45
+ ): Promise<Cart | undefined> {
46
+ const db = this.getDb(ctx);
47
+ const rows = await db
48
+ .select()
49
+ .from(carts)
50
+ .where(and(eq(carts.organizationId, orgId), eq(carts.customerId, customerId), eq(carts.status, "active")));
51
+ return rows[0];
52
+ }
53
+
54
+ async findActiveByCustomerId(
55
+ orgId: string,
56
+ customerId: string,
57
+ ctx?: TxContext,
58
+ ): Promise<Cart | undefined> {
59
+ const db = this.getDb(ctx);
60
+ const rows = await db
61
+ .select()
62
+ .from(carts)
63
+ .where(and(eq(carts.organizationId, orgId), eq(carts.customerId, customerId), eq(carts.status, "active")));
64
+ return rows[0];
65
+ }
66
+
67
+ async findExpiredCarts(ctx?: TxContext): Promise<Cart[]> {
68
+ const db = this.getDb(ctx);
69
+ return db
70
+ .select()
71
+ .from(carts)
72
+ .where(and(eq(carts.status, "active"), lt(carts.expiresAt, new Date())));
73
+ }
74
+
75
+ async create(data: CartInsert, ctx?: TxContext): Promise<Cart> {
76
+ const db = this.getDb(ctx);
77
+ const rows = await db.insert(carts).values(data).returning();
78
+ return rows[0]!;
79
+ }
80
+
81
+ async update(
82
+ id: string,
83
+ data: Partial<Omit<CartInsert, "id">>,
84
+ ctx?: TxContext,
85
+ ): Promise<Cart | undefined> {
86
+ const db = this.getDb(ctx);
87
+ const rows = await db
88
+ .update(carts)
89
+ .set({ ...data, updatedAt: new Date() })
90
+ .where(eq(carts.id, id))
91
+ .returning();
92
+ return rows[0];
93
+ }
94
+
95
+ async updateStatus(
96
+ id: string,
97
+ status: Cart["status"],
98
+ ctx?: TxContext,
99
+ ): Promise<Cart | undefined> {
100
+ return this.update(id, { status }, ctx);
101
+ }
102
+
103
+ /**
104
+ * Atomically transitions a cart from "active" to "checking_out".
105
+ * Returns the updated cart if the transition succeeded, or undefined if
106
+ * the cart was not in "active" status (e.g., a concurrent checkout already
107
+ * claimed it). This prevents TOCTOU race conditions on double-checkout.
108
+ */
109
+ async transitionToCheckingOut(
110
+ id: string,
111
+ ctx?: TxContext,
112
+ ): Promise<Cart | undefined> {
113
+ const db = this.getDb(ctx);
114
+ const rows = await db
115
+ .update(carts)
116
+ .set({ status: "checking_out", updatedAt: new Date() })
117
+ .where(and(eq(carts.id, id), eq(carts.status, "active")))
118
+ .returning();
119
+ return rows[0];
120
+ }
121
+
122
+ async delete(id: string, ctx?: TxContext): Promise<boolean> {
123
+ const db = this.getDb(ctx);
124
+ const result = await db.delete(carts).where(eq(carts.id, id)).returning();
125
+ return result.length > 0;
126
+ }
127
+
128
+ // ─────────────────────────────────────────────────────────────────────────────
129
+ // Cart Line Items
130
+ // ─────────────────────────────────────────────────────────────────────────────
131
+
132
+ async findLineItemById(
133
+ id: string,
134
+ ctx?: TxContext,
135
+ ): Promise<CartLineItem | undefined> {
136
+ const db = this.getDb(ctx);
137
+ const rows = await db
138
+ .select()
139
+ .from(cartLineItems)
140
+ .where(eq(cartLineItems.id, id));
141
+ return rows[0];
142
+ }
143
+
144
+ async findLineItemsByCartId(
145
+ cartId: string,
146
+ ctx?: TxContext,
147
+ ): Promise<CartLineItem[]> {
148
+ const db = this.getDb(ctx);
149
+ return db
150
+ .select()
151
+ .from(cartLineItems)
152
+ .where(eq(cartLineItems.cartId, cartId));
153
+ }
154
+
155
+ async findLineItemByEntity(
156
+ cartId: string,
157
+ entityId: string,
158
+ variantId?: string,
159
+ ctx?: TxContext,
160
+ ): Promise<CartLineItem | undefined> {
161
+ const db = this.getDb(ctx);
162
+ const conditions = [
163
+ eq(cartLineItems.cartId, cartId),
164
+ eq(cartLineItems.entityId, entityId),
165
+ ];
166
+
167
+ if (variantId !== undefined) {
168
+ conditions.push(eq(cartLineItems.variantId, variantId));
169
+ }
170
+
171
+ const rows = await db
172
+ .select()
173
+ .from(cartLineItems)
174
+ .where(and(...conditions));
175
+
176
+ // Filter for exact variantId match
177
+ return rows.find((r) => r.variantId === (variantId ?? null));
178
+ }
179
+
180
+ async createLineItem(
181
+ data: CartLineItemInsert,
182
+ ctx?: TxContext,
183
+ ): Promise<CartLineItem> {
184
+ const db = this.getDb(ctx);
185
+ const rows = await db.insert(cartLineItems).values(data).returning();
186
+ return rows[0]!;
187
+ }
188
+
189
+ async updateLineItem(
190
+ id: string,
191
+ data: Partial<Omit<CartLineItemInsert, "id">>,
192
+ ctx?: TxContext,
193
+ ): Promise<CartLineItem | undefined> {
194
+ const db = this.getDb(ctx);
195
+ const rows = await db
196
+ .update(cartLineItems)
197
+ .set(data)
198
+ .where(eq(cartLineItems.id, id))
199
+ .returning();
200
+ return rows[0];
201
+ }
202
+
203
+ async deleteLineItem(id: string, ctx?: TxContext): Promise<boolean> {
204
+ const db = this.getDb(ctx);
205
+ const result = await db
206
+ .delete(cartLineItems)
207
+ .where(eq(cartLineItems.id, id))
208
+ .returning();
209
+ return result.length > 0;
210
+ }
211
+
212
+ async deleteLineItemsByCartId(
213
+ cartId: string,
214
+ ctx?: TxContext,
215
+ ): Promise<void> {
216
+ const db = this.getDb(ctx);
217
+ await db.delete(cartLineItems).where(eq(cartLineItems.cartId, cartId));
218
+ }
219
+
220
+ // ─────────────────────────────────────────────────────────────────────────────
221
+ // Cart with Line Items (Aggregate)
222
+ // ─────────────────────────────────────────────────────────────────────────────
223
+
224
+ async findWithLineItems(
225
+ orgId: string,
226
+ id: string,
227
+ ctx?: TxContext,
228
+ ): Promise<{ cart: Cart; lineItems: CartLineItem[] } | undefined> {
229
+ const cart = await this.findById(orgId, id, ctx);
230
+ if (!cart) return undefined;
231
+ const lineItems = await this.findLineItemsByCartId(id, ctx);
232
+ return { cart, lineItems };
233
+ }
234
+ }
@@ -0,0 +1,42 @@
1
+ import { index, integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
2
+ import { organization } from "../../auth/auth-schema.js";
3
+ import { sellableEntities, variants } from "../catalog/schema.js";
4
+
5
+ export const carts = pgTable("carts", {
6
+ id: uuid("id").defaultRandom().primaryKey(),
7
+ organizationId: text("organization_id").notNull().references(() => organization.id, { onDelete: "cascade" }),
8
+ customerId: uuid("customer_id"),
9
+ status: text("status", {
10
+ enum: ["active", "checking_out", "merged", "checked_out", "abandoned"],
11
+ })
12
+ .notNull()
13
+ .default("active"),
14
+ currency: text("currency").notNull().default("USD"),
15
+ secret: text("secret"),
16
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().default({}),
17
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
18
+ createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
19
+ updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
20
+ }, (table) => ({
21
+ orgIdx: index("idx_carts_org").on(table.organizationId),
22
+ customerIdIdx: index("idx_carts_customer_id").on(table.customerId),
23
+ statusIdx: index("idx_carts_status").on(table.status),
24
+ expiresAtIdx: index("idx_carts_expires_at").on(table.expiresAt),
25
+ }));
26
+
27
+ export const cartLineItems = pgTable("cart_line_items", {
28
+ id: uuid("id").defaultRandom().primaryKey(),
29
+ cartId: uuid("cart_id")
30
+ .references(() => carts.id, { onDelete: "cascade" })
31
+ .notNull(),
32
+ entityId: uuid("entity_id").references(() => sellableEntities.id).notNull(),
33
+ variantId: uuid("variant_id").references(() => variants.id),
34
+ quantity: integer("quantity").notNull().default(1),
35
+ unitPriceSnapshot: integer("unit_price_snapshot").notNull(),
36
+ currency: text("currency").notNull(),
37
+ notes: text("notes"),
38
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().default({}),
39
+ addedAt: timestamp("added_at", { withTimezone: true }).defaultNow().notNull(),
40
+ }, (table) => [
41
+ index("idx_cart_line_items_cart_id").on(table.cartId),
42
+ ]);
@@ -0,0 +1,38 @@
1
+ import { z } from "@hono/zod-openapi";
2
+
3
+ // ─── Cart Body Schemas (single source of truth) ─────────────────────────────
4
+
5
+ export const CreateCartBodySchema = z.object({
6
+ customerId: z.string().optional().openapi({ example: "customer-uuid" }),
7
+ currency: z.string().length(3).optional().openapi({ example: "USD" }),
8
+ }).openapi("CreateCartRequest");
9
+
10
+ export const AddCartItemBodySchema = z.object({
11
+ entityId: z.string().openapi({ example: "product-uuid" }),
12
+ variantId: z.string().nullable().optional().openapi({ example: "variant-uuid" }),
13
+ quantity: z.number().int().min(1).max(9999).openapi({ example: 1 }),
14
+ }).openapi("AddCartItemRequest");
15
+
16
+ export const UpdateCartItemQuantityBodySchema = z.object({
17
+ quantity: z.number().int().min(1).max(9999).openapi({ example: 2 }),
18
+ }).openapi("UpdateCartItemQuantityRequest");
19
+
20
+ // ─── Derived Input Types ─────────────────────────────────────────────────────
21
+
22
+ export type CreateCartInput = z.infer<typeof CreateCartBodySchema> & {
23
+ metadata?: Record<string, unknown>;
24
+ };
25
+
26
+ export type AddCartItemInput = z.infer<typeof AddCartItemBodySchema> & {
27
+ cartId: string;
28
+ unitPriceSnapshot?: number;
29
+ currency?: string;
30
+ metadata?: Record<string, unknown>;
31
+ };
32
+
33
+ /** Hand-written: all fields come from path params + body; schema only has quantity. */
34
+ export interface UpdateCartItemInput {
35
+ cartId: string;
36
+ itemId: string;
37
+ quantity: number;
38
+ }