-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathecommerce-orders.ts
More file actions
399 lines (343 loc) · 12.5 KB
/
ecommerce-orders.ts
File metadata and controls
399 lines (343 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/**
* E-Commerce Order System with Historical Embeds
*
* This example demonstrates using embeds for order history where
* you want to preserve the EXACT state of products at purchase time.
*
* Key Features:
* - Product snapshots in order items (NO auto-update)
* - Customer info in orders (auto-updates for contact changes)
* - Shipping address snapshots
*
* Run with: tsx examples/ecommerce-orders.ts
*/
import {
mizzle,
defineSchema,
mongoCollection,
embed,
objectId,
string,
number,
date,
array,
object,
publicId,
} from '../src/index';
// =============================================================================
// Collections
// =============================================================================
/**
* Products Collection
* Current product catalog (prices and details can change)
*/
const products = mongoCollection('products', {
_id: objectId().internalId(),
sku: string(),
name: string(),
description: string(),
price: number(), // Current price (may change over time)
category: string(),
inStock: number().int(),
imageUrl: string().url().optional(),
updatedAt: date().onUpdateNow(),
});
/**
* Customers Collection
* Customer profiles
*/
const customers = mongoCollection('customers', {
id: publicId('cus'),
email: string().email(),
name: string(),
phone: string().optional(),
createdAt: date().defaultNow(),
});
/**
* Orders Collection
* Order headers with customer snapshot
*/
const orders = mongoCollection(
'orders',
{
_id: objectId().internalId(),
orderNumber: string(),
customerId: string(), // Customer publicId
// Shipping info (snapshot at order time)
shippingAddress: object({
street: string(),
city: string(),
state: string(),
zipCode: string(),
country: string(),
}),
// Order details
status: string(), // 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled'
subtotal: number(),
tax: number(),
shipping: number(),
total: number(),
placedAt: date().defaultNow(),
updatedAt: date().onUpdateNow(),
},
{
relations: {
// EMBED: Customer contact info (auto-updates for email/phone changes)
customer: embed(customers, {
forward: {
from: 'customerId',
projection: { name: 1, email: 1, phone: 1 },
embedIdField: 'id',
},
reverse: {
enabled: true,
strategy: 'async',
// Update customer contact, but NOT if they change their name
// (orders should preserve customer name at time of purchase)
watchFields: ['email', 'phone'],
},
}),
},
}
);
/**
* Order Items Collection
* Individual items in an order with product SNAPSHOT
*/
const orderItems = mongoCollection(
'order_items',
{
_id: objectId().internalId(),
orderId: objectId(),
productId: objectId(),
// Purchase details
quantity: number().int(),
unitPrice: number(), // Price at time of purchase
total: number(),
createdAt: date().defaultNow(),
},
{
relations: {
// EMBED: Product snapshot (NO auto-update - preserve historical data)
product: embed(products, {
forward: {
from: 'productId',
projection: { sku: 1, name: 1, description: 1, category: 1, imageUrl: 1 },
},
// NO reverse config - we want the snapshot at purchase time!
}),
// EMBED: Order info (snapshot)
order: embed(orders, {
forward: {
from: 'orderId',
projection: { orderNumber: 1, status: 1 },
},
// NO auto-update - preserve order state at item creation
}),
},
}
);
// =============================================================================
// ORM Setup
// =============================================================================
const schema = defineSchema({
products,
customers,
orders,
orderItems,
});
const db = await mizzle({
uri: process.env.MONGO_URI || 'mongodb://localhost:27017',
dbName: 'ecommerce_example',
schema,
});
// =============================================================================
// Example Usage
// =============================================================================
async function main() {
console.log('🛒 E-Commerce Order System Example\n');
// ---------------------------------------------------------------------------
// 1. Create products
// ---------------------------------------------------------------------------
console.log('📦 Creating products...');
const laptop = await db().products.create({
sku: 'LAPTOP-001',
name: 'UltraBook Pro 15"',
description: 'Powerful laptop for professionals',
price: 1299.99,
category: 'Electronics',
inStock: 50,
imageUrl: 'https://example.com/laptop.jpg',
});
const mouse = await db().products.create({
sku: 'MOUSE-001',
name: 'Wireless Mouse',
description: 'Ergonomic wireless mouse',
price: 29.99,
category: 'Accessories',
inStock: 200,
});
console.log(`✅ Created ${laptop.name} - $${laptop.price}`);
console.log(`✅ Created ${mouse.name} - $${mouse.price}\n`);
// ---------------------------------------------------------------------------
// 2. Create customer
// ---------------------------------------------------------------------------
console.log('👤 Creating customer...');
const customer = await db().customers.create({
email: 'john@example.com',
name: 'John Doe',
phone: '+1-555-0123',
});
console.log(`✅ Created customer: ${customer.name} (${customer.id})\n`);
// ---------------------------------------------------------------------------
// 3. Place order
// ---------------------------------------------------------------------------
console.log('🛍️ Placing order...');
const subtotal = laptop.price + mouse.price;
const tax = subtotal * 0.08; // 8% tax
const shipping = 15.00;
const total = subtotal + tax + shipping;
const order = await db().orders.create({
orderNumber: `ORD-${Date.now()}`,
customerId: customer.id,
shippingAddress: {
street: '123 Main St',
city: 'San Francisco',
state: 'CA',
zipCode: '94102',
country: 'USA',
},
status: 'pending',
subtotal,
tax,
shipping,
total,
});
console.log(`✅ Created order ${order.orderNumber}`);
console.log(` Customer: ${order.customer?.name} (${order.customer?.email})`);
console.log(` Total: $${order.total.toFixed(2)}\n`);
// ---------------------------------------------------------------------------
// 4. Add order items with product snapshots
// ---------------------------------------------------------------------------
console.log('📝 Adding order items...');
const item1 = await db().orderItems.create({
orderId: order._id,
productId: laptop._id,
quantity: 1,
unitPrice: laptop.price,
total: laptop.price,
});
const item2 = await db().orderItems.create({
orderId: order._id,
productId: mouse._id,
quantity: 2,
unitPrice: mouse.price,
total: mouse.price * 2,
});
console.log(`✅ Added item: ${item1.product?.name} x${item1.quantity} @ $${item1.unitPrice}`);
console.log(` Product snapshot:`, item1.product);
console.log(`✅ Added item: ${item2.product?.name} x${item2.quantity} @ $${item2.unitPrice}`);
console.log(` Product snapshot:`, item2.product);
console.log();
// ---------------------------------------------------------------------------
// 5. Update product price (should NOT affect order)
// ---------------------------------------------------------------------------
console.log('💰 Updating product price...');
const oldPrice = laptop.price;
const newPrice = 1399.99;
await db().products.updateById(laptop._id, {
price: newPrice,
});
console.log(`✅ Updated laptop price: $${oldPrice} → $${newPrice}`);
// Check order item - should still have OLD price (historical snapshot)
const itemAfterPriceChange = await db().orderItems.findById(item1._id);
console.log(` Order item still shows: $${itemAfterPriceChange?.unitPrice}`);
console.log(` Product name: "${itemAfterPriceChange?.product?.name}"`);
console.log(` ✅ Historical snapshot preserved!\n`);
// ---------------------------------------------------------------------------
// 6. Update customer email (should update order)
// ---------------------------------------------------------------------------
console.log('📧 Updating customer email...');
await db().customers.updateOne(
{ id: customer.id },
{ email: 'john.doe@newmail.com' }
);
console.log(`✅ Updated customer email`);
// Check order - should have NEW email (auto-updated)
const orderAfterEmailChange = await db().orders.findById(order._id);
console.log(` Order now shows: ${orderAfterEmailChange?.customer?.email}`);
console.log(` ✅ Contact info auto-updated!\n`);
// ---------------------------------------------------------------------------
// 7. Update customer name (should NOT update order)
// ---------------------------------------------------------------------------
console.log('👤 Updating customer name...');
await db().customers.updateOne(
{ id: customer.id },
{ name: 'Jonathan Doe' }
);
console.log(`✅ Updated customer name to "Jonathan Doe"`);
// Check order - should still have OLD name (not in watchFields)
const orderAfterNameChange = await db().orders.findById(order._id);
console.log(` Order still shows: ${orderAfterNameChange?.customer?.name}`);
console.log(` ✅ Historical name preserved (not in watchFields)!\n`);
// ---------------------------------------------------------------------------
// 8. Display complete order
// ---------------------------------------------------------------------------
console.log('📋 Complete Order Details:\n');
const fullOrder = await db().orders.findById(order._id);
const items = await db().orderItems.findMany({ orderId: order._id });
console.log(` Order: ${fullOrder?.orderNumber}`);
console.log(` Status: ${fullOrder?.status}`);
console.log(` Customer: ${fullOrder?.customer?.name}`);
console.log(` Email: ${fullOrder?.customer?.email}`);
console.log(` Phone: ${fullOrder?.customer?.phone}`);
console.log();
console.log(` Shipping Address:`);
console.log(` ${fullOrder?.shippingAddress.street}`);
console.log(` ${fullOrder?.shippingAddress.city}, ${fullOrder?.shippingAddress.state} ${fullOrder?.shippingAddress.zipCode}`);
console.log();
console.log(` Items:`);
for (const item of items) {
console.log(` • ${item.product?.name} x${item.quantity}`);
console.log(` SKU: ${item.product?.sku}`);
console.log(` Price: $${item.unitPrice.toFixed(2)} each`);
console.log(` Total: $${item.total.toFixed(2)}`);
}
console.log();
console.log(` Subtotal: $${fullOrder?.subtotal.toFixed(2)}`);
console.log(` Tax: $${fullOrder?.tax.toFixed(2)}`);
console.log(` Shipping: $${fullOrder?.shipping.toFixed(2)}`);
console.log(` ─────────────────────`);
console.log(` Total: $${fullOrder?.total.toFixed(2)}\n`);
// ---------------------------------------------------------------------------
// 9. Show current vs historical prices
// ---------------------------------------------------------------------------
console.log('💡 Price Comparison:\n');
const currentLaptop = await db().products.findById(laptop._id);
console.log(` ${laptop.name}:`);
console.log(` Current price: $${currentLaptop?.price.toFixed(2)}`);
console.log(` Price at purchase: $${item1.unitPrice.toFixed(2)}`);
console.log(` Difference: $${(currentLaptop!.price - item1.unitPrice).toFixed(2)}`);
console.log();
// ---------------------------------------------------------------------------
// Summary
// ---------------------------------------------------------------------------
console.log('✨ E-Commerce Embed Summary:');
console.log(' ✅ Product snapshots: Preserve exact purchase-time details');
console.log(' ✅ Price history: Orders unaffected by price changes');
console.log(' ✅ Customer contact: Auto-updates for email/phone');
console.log(' ✅ Customer name: Preserved at order time (historical)');
console.log(' ✅ Perfect audit trail: See exactly what was ordered');
console.log();
console.log('🎉 Example complete!');
}
// Run example
main()
.then(async () => {
await db.close();
process.exit(0);
})
.catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});