-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreactServer.cjs
More file actions
1018 lines (820 loc) · 27.7 KB
/
Copy pathreactServer.cjs
File metadata and controls
1018 lines (820 loc) · 27.7 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// reactServer.cjs
const express = require('express');
const path = require('path');
const db = require('./db.cjs');
const app = express();
const PORT = 23327;
app.use(express.json());
// ----------------- API ROUTES -----------------
// RESET database → CALL sp_pokebase_reset()
app.post('/api/reset', async (req, res) => {
try {
await db.query('CALL sp_pokebase_reset()');
res.status(200).json({ ok: true });
}
catch (err) {
console.error('RESET failed:', err);
res.status(500).json({ error: 'Reset failed' });
}
});
// ================= Helpers =================
async function recalcOrderTotals(orderID) {
try {
// Compute subtotal from OrderItems
const [rows] = await db.query(
'SELECT COALESCE(SUM(quantity * unitPrice), 0) AS subtotal FROM OrderItems WHERE orderID = ?',
[orderID]
);
const subtotal = Number(rows[0]?.subtotal ?? 0);
// For now: tax = 0, total = subtotal
const tax = 0;
const total = subtotal + tax;
await db.query(
'UPDATE Orders SET subtotal = ?, tax = ?, total = ? WHERE orderID = ?',
[subtotal, tax, total, orderID]
);
console.log(
`Recalculated totals for order ${orderID}: subtotal=${subtotal}, tax=${tax}, total=${total}`
);
}
catch (err) {
console.error('recalcOrderTotals failed for order', orderID, err);
}
}
function logDbError(label, err) {
console.error(label, {
code: err.code,
errno: err.errno,
sqlState: err.sqlState,
message: err.sqlMessage,
});
}
// ================= GRADING COMPANIES =================
// READ grading companies
app.get('/api/grading-companies', async (req, res) => {
try {
const [rows] = await db.query(
'SELECT companyID, name, gradeScale, url FROM GradingCompanies ORDER BY companyID'
);
res.json(rows);
}
catch (err) {
console.error('GET grading companies failed:', err);
res.status(500).json({ error: 'Failed to load grading companies' });
}
});
// UPDATE grading company → CALL sp_update_grading_company(?,?,?)
app.put('/api/grading-companies/:id', async (req, res) => {
const id = Number(req.params.id);
const { name, gradeScale, url } = req.body || {};
// invalid input check
if (!Number.isInteger(id))
return res.status(400).json({ error: 'Invalid companyID' });
if (!name || !gradeScale)
return res
.status(400)
.json({ error: 'name and gradeScale are required to update a grading company' });
try {
await db.query('CALL sp_update_grading_company(?,?,?,?)', [
id,
name,
gradeScale,
url ?? null,
]);
res.status(200).json({ ok: true });
}
catch (err) {
console.error('UPDATE grading company failed:', err);
res.status(500).json({ error: 'Update failed' });
}
});
// DELETE /api/grading-companies/:id → delete grading company
app.delete('/api/grading-companies/:id', async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id <= 0)
return res.status(400).json({ error: 'Invalid grading company ID' });
try {
console.log('DELETE /api/grading-companies/:id → companyID =', id);
const [result] = await db.query('CALL sp_delete_grading_company(?)', [id]);
console.log('sp_delete_grading_company result:', JSON.stringify(result));
return res.status(204).send();
} catch (err) {
logDbError('DELETE grading company failed', err);
// If GradeSlabs (or other tables) still reference this company
if (err.code === 'ER_ROW_IS_REFERENCED_2' || err.errno === 1451) {
return res.status(409).json({
error:
'Cannot delete grading company because one or more GradeSlabs still reference it. ' +
'Delete those slabs first or enable ON DELETE CASCADE on GradeSlabs.companyID.',
});
}
return res.status(500).json({ error: 'Failed to delete grading company' });
}
});
// CREATE grading company → CALL sp_create_grading_company(?,?,?)
app.post('/api/grading-companies', async (req, res) => {
const { name, gradeScale, url } = req.body || {};
if (!name || !gradeScale) {
return res
.status(400)
.json({ error: 'name and gradeScale are required to create a grading company' });
}
try {
await db.query('CALL sp_create_grading_company(?,?,?)', [
name,
gradeScale,
url ?? null,
]);
// You can just say "ok" and let the client refetch:
res.status(201).json({ ok: true });
// or if you later modify the proc to return LAST_INSERT_ID(),
// you can send back the new companyID here.
} catch (err) {
console.error('CREATE grading company failed:', err);
res.status(500).json({ error: 'Create failed' });
}
});
// ================= CUSTOMERS =================
// READ all customers → CALL sp_select_all_customers()
app.get('/api/customers', async (req, res) => {
try {
const [resultSets] = await db.query('CALL sp_select_all_customers()');
// mysql2 returns an array of result sets for CALL:
// resultSets[0] is the actual row array
const customers =
Array.isArray(resultSets) && Array.isArray(resultSets[0])
? resultSets[0]
: resultSets;
res.json(customers);
} catch (err) {
console.error('GET customers failed:', err);
res.status(500).json({ error: 'Failed to load customers' });
}
});
// CREATE customer → CALL sp_create_customer(?,?,?,?)
app.post('/api/customers', async (req, res) => {
const { email, name, phone, shippingAddress } = req.body || {};
// invalid input check
if (!email || !name) {
return res
.status(400)
.json({ error: 'email and name are required to create a customer' });
}
try {
await db.query('CALL sp_create_customer(?,?,?,?)', [
email,
name,
phone ?? null,
shippingAddress ?? null,
]);
// return ok + let the frontend refetch
res.status(201).json({ ok: true });
}
catch (err) {
console.error('CREATE customer failed:', err);
res.status(500).json({ error: 'Failed to create customer' });
}
});
// UPDATE customer → CALL sp_update_customer(?,?,?,?,?)
app.put('/api/customers/:id', async (req, res) => {
const id = Number(req.params.id);
const { email, name, phone, shippingAddress } = req.body || {};
if (!Number.isInteger(id)) {
return res.status(400).json({ error: 'Invalid customerID' });
}
if (!email || !name) {
return res
.status(400)
.json({ error: 'email and name are required to update a customer' });
}
try {
await db.query('CALL sp_update_customer(?,?,?,?,?)', [
id,
email,
name,
phone ?? null,
shippingAddress ?? null,
]);
res.status(200).json({ ok: true });
}
catch (err) {
console.error('UPDATE customer failed:', err);
res.status(500).json({ error: 'Failed to update customer' });
}
});
// DELETE /api/customers/:id → delete customer
app.delete('/api/customers/:id', async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id <= 0)
return res.status(400).json({ error: 'Invalid customer ID' });
try {
console.log('DELETE /api/customers/:id → customerID =', id);
const [result] = await db.query('CALL sp_delete_customer(?)', [id]);
console.log('sp_delete_customer result:', JSON.stringify(result));
return res.status(204).send();
}
catch (err) {
logDbError('DELETE customer failed', err);
// Orders.customerID FK -> Customers.customerID
if (err.code === 'ER_ROW_IS_REFERENCED_2' || err.errno === 1451) {
return res.status(409).json({
error:
'Cannot delete customer because one or more Orders still reference them. ' +
'Either delete those orders first or make Orders.customerID ON DELETE CASCADE.',
});
}
return res.status(500).json({ error: 'Failed to delete customer' });
}
});
// ================= CARDS =================
// GET /api/cards → list all cards
app.get('/api/cards', async (req, res) => {
try {
const [rows] = await db.query(
'SELECT cardID, setName, cardNumber, name, variant, year FROM Cards ORDER BY cardID'
);
res.json(rows);
} catch (err) {
console.error('GET /api/cards failed:', err);
res.status(500).json({ error: 'Failed to load cards' });
}
});
// POST /api/cards → create card
app.post('/api/cards', async (req, res) => {
const { setName, cardNumber, name, variant, year } = req.body || {};
// basic validation: required fields
if (!setName || !cardNumber || !name || !variant) {
return res.status(400).json({
error: 'setName, cardNumber, name, and variant are required to create a card',
});
}
// normalize year: allow null
const yearValue =
year === null || year === undefined || year === ''
? null
: Number(year);
try {
await db.query(
'INSERT INTO Cards (setName, cardNumber, name, variant, year) VALUES (?,?,?,?,?)',
[setName, cardNumber, name, variant, yearValue]
);
res.status(201).json({ ok: true });
} catch (err) {
console.error('POST /api/cards failed:', err);
res.status(500).json({ error: 'Failed to create card' });
}
});
// PUT /api/cards/:id → update card
app.put('/api/cards/:id', async (req, res) => {
const id = Number(req.params.id);
const { setName, cardNumber, name, variant, year } = req.body || {};
if (!Number.isInteger(id)) {
return res.status(400).json({ error: 'Invalid cardID' });
}
if (!setName || !cardNumber || !name || !variant) {
return res.status(400).json({
error: 'setName, cardNumber, name, and variant are required to update a card',
});
}
const yearValue =
year === null || year === undefined || year === ''
? null
: Number(year);
try {
await db.query(
'UPDATE Cards SET setName = ?, cardNumber = ?, name = ?, variant = ?, year = ? WHERE cardID = ?',
[setName, cardNumber, name, variant, yearValue, id]
);
res.status(200).json({ ok: true });
} catch (err) {
console.error('PUT /api/cards/:id failed:', err);
res.status(500).json({ error: 'Failed to update card' });
}
});
// DELETE /api/cards/:id → delete a card AND children via CASCADE
app.delete('/api/cards/:id', async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id <= 0) {
return res.status(400).json({ error: 'Invalid card ID' });
}
try {
console.log('DELETE /api/cards/:id → attempting delete for cardID =', id);
// Use your stored procedure
const [result] = await db.query('CALL sp_delete_card(?)', [id]);
console.log('sp_delete_card result:', JSON.stringify(result));
// Even if no row matched, 204 is fine (idempotent delete)
return res.status(204).send();
}
catch (err) {
console.error('DELETE /api/cards/:id failed:', {
code: err.code,
errno: err.errno,
message: err.sqlMessage,
sqlState: err.sqlState,
});
// Common MySQL FK error when a row is still referenced
if (err.code === 'ER_ROW_IS_REFERENCED_2' || err.errno === 1451) {
return res.status(409).json({
error:
'Cannot delete card because related Listings / OrderItems / GradeSlabs still reference it. ' +
'Either delete those first or ensure ON DELETE CASCADE is enabled.',
});
}
return res.status(500).json({ error: 'Failed to delete card' });
}
});
// ================= Listings =================
// GET /api/listings → list all listings
app.get('/api/listings', async (req, res) => {
try {
const [rows] = await db.query(
'SELECT listingID, cardID, price, type, cardCondition, quantityAvailable, status FROM Listings ORDER BY listingID'
);
res.json(rows);
}
catch (err) {
console.error('GET /api/listings failed:', err);
res.status(500).json({ error: 'Failed to load listings' });
}
});
// POST /api/listings → create listing
app.post('/api/listings', async (req, res) => {
const {
cardID,
price,
type,
cardCondition,
quantityAvailable,
status,
} = req.body || {};
// Normalize / coerce
const cardIdNum = Number(cardID);
const priceNum = Number(price);
const qtyNum = Number(quantityAvailable);
const statusValue = status ?? 'active'; // default
const conditionValue = cardCondition ?? null; // allow null
// Basic validation: required fields
if (!Number.isInteger(cardIdNum) || cardIdNum <= 0)
return res.status(400).json({ error: 'Valid cardID is required' });
if (!Number.isFinite(priceNum) || priceNum <= 0)
return res.status(400).json({ error: 'Valid price is required' });
if (type !== 'raw' && type !== 'graded')
return res.status(400).json({ error: "type must be 'raw' or 'graded'" });
if (!Number.isInteger(qtyNum) || qtyNum < 0) {
return res
.status(400)
.json({ error: 'quantityAvailable must be a non-negative integer' });
}
const validStatuses = ['active', 'sold_out', 'hidden'];
if (statusValue && !validStatuses.includes(statusValue)) {
return res.status(400).json({
error: `status must be one of: ${validStatuses.join(', ')}`,
});
}
try {
await db.query(
`INSERT INTO Listings
(cardID, price, type, cardCondition, quantityAvailable, status)
VALUES (?,?,?,?,?,?)`,
[cardIdNum, priceNum, type, conditionValue, qtyNum, statusValue]
);
res.status(201).json({ ok: true });
} catch (err) {
console.error('POST /api/listings failed:', err);
res.status(500).json({ error: 'Failed to create listing' });
}
});
// PUT /api/listings/:id → update listing
app.put('/api/listings/:id', async (req, res) => {
const id = Number(req.params.id);
const {
cardID,
price,
type,
cardCondition,
quantityAvailable,
status,
} = req.body || {};
if (!Number.isInteger(id) || id <= 0) {
return res.status(400).json({ error: 'Invalid listingID' });
}
const cardIdNum = Number(cardID);
const priceNum = Number(price);
const qtyNum = Number(quantityAvailable);
const statusValue = status ?? 'active';
const conditionValue = cardCondition ?? null;
// ----- validation -----
if (!Number.isInteger(cardIdNum) || cardIdNum <= 0) {
return res.status(400).json({ error: 'Valid cardID is required' });
}
if (!Number.isFinite(priceNum) || priceNum <= 0) {
return res.status(400).json({ error: 'Valid price is required' });
}
if (type !== 'raw' && type !== 'graded') {
return res.status(400).json({ error: "type must be 'raw' or 'graded'" });
}
if (!Number.isInteger(qtyNum) || qtyNum < 0) {
return res
.status(400)
.json({ error: 'quantityAvailable must be a non-negative integer' });
}
const validStatuses = ['active', 'sold_out', 'hidden'];
if (statusValue && !validStatuses.includes(statusValue)) {
return res.status(400).json({
error: `status must be one of: ${validStatuses.join(', ')}`,
});
}
try {
await db.query(
`UPDATE Listings
SET cardID = ?,
price = ?,
type = ?,
cardCondition = ?,
quantityAvailable = ?,
status = ?
WHERE listingID = ?`,
[cardIdNum, priceNum, type, conditionValue, qtyNum, statusValue, id]
);
res.status(200).json({ ok: true });
}
catch (err) {
console.error('PUT /api/listings/:id failed:', err);
res.status(500).json({ error: 'Failed to update listing' });
}
});
// DELETE /api/listings/:id → delete listing
app.delete('/api/listings/:id', async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id <= 0) {
return res.status(400).json({ error: 'Invalid listingID' });
}
try {
console.log('DELETE /api/listings/:id → listingID =', id);
const [result] = await db.query(
'DELETE FROM Listings WHERE listingID = ?',
[id]
);
console.log('DELETE FROM Listings result:', JSON.stringify(result));
return res.status(204).send();
} catch (err) {
logDbError('DELETE listing failed', err);
// If something else references Listings.listingID without CASCADE
if (err.code === 'ER_ROW_IS_REFERENCED_2' || err.errno === 1451) {
return res.status(409).json({
error:
'Cannot delete listing because other records still reference it (e.g., OrderItems or GradeSlabs). ' +
'Ensure those FKs use ON DELETE CASCADE or delete children first.',
});
}
return res.status(500).json({ error: 'Failed to delete listing' });
}
});
// ================= GRADE SLABS =================
// GET /api/grade-slabs/for-dropdown -> list graded listings for dropdown
app.get('/api/grade-slabs/for-dropdown', async (req, res) => {
try {
const [resultSets] = await db.query(
'CALL sp_select_graded_listings_for_dropdown()'
);
const rows = unwrapCallResult(resultSets);
res.json(rows);
} catch (err) {
logDbError('GET /api/grade-slabs/for-dropdown failed', err);
res.status(500).json({ error: 'Failed to load graded listings' });
}
});
// ================= ORDER ITEMS =================
// helper to unwrap CALL results (since CALL returns [ [rows], extra ])
function unwrapCallResult(resultSets) {
if (Array.isArray(resultSets) && Array.isArray(resultSets[0])) {
return resultSets[0];
}
return resultSets;
}
// GET /api/order-items → list all order items
app.get('/api/order-items', async (req, res) => {
try {
const [resultSets] = await db.query('CALL sp_select_all_order_items()');
const rows = unwrapCallResult(resultSets);
res.json(rows);
}
catch (err) {
console.error('GET /api/order-items failed:', err);
res.status(500).json({ error: 'Failed to load order items' });
}
});
// GET /api/order-items/:orderID/:listingID → get one order item
app.get('/api/order-items/:orderID/:listingID', async (req, res) => {
const orderID = Number(req.params.orderID);
const listingID = Number(req.params.listingID);
if (!Number.isInteger(orderID) || orderID <= 0 ||
!Number.isInteger(listingID) || listingID <= 0) {
return res.status(400).json({ error: 'Invalid orderID or listingID' });
}
try {
const [resultSets] = await db.query(
'CALL sp_select_order_item(?, ?)',
[orderID, listingID]
);
const rows = unwrapCallResult(resultSets);
if (!rows || rows.length === 0) {
return res.status(404).json({ error: 'Order item not found' });
}
res.json(rows[0]);
} catch (err) {
console.error('GET /api/order-items/:orderID/:listingID failed:', err);
res.status(500).json({ error: 'Failed to load order item' });
}
});
// POST /api/order-items → create new order item
app.post('/api/order-items', async (req, res) => {
const { orderID, listingID, quantity, unitPrice } = req.body || {};
const orderIdNum = Number(orderID);
const listingIdNum = Number(listingID);
const qtyNum = Number(quantity);
const priceNum = Number(unitPrice);
// Basic validation
if (!Number.isInteger(orderIdNum) || orderIdNum <= 0) {
return res.status(400).json({ error: 'Valid orderID is required' });
}
if (!Number.isInteger(listingIdNum) || listingIdNum <= 0) {
return res.status(400).json({ error: 'Valid listingID is required' });
}
if (!Number.isInteger(qtyNum) || qtyNum <= 0) {
return res
.status(400)
.json({ error: 'quantity must be a positive integer' });
}
if (!Number.isFinite(priceNum) || priceNum < 0) {
return res
.status(400)
.json({ error: 'unitPrice must be a non-negative number' });
}
try {
await db.query(
'CALL sp_insert_order_item(?, ?, ?, ?)',
[orderIdNum, listingIdNum, qtyNum, priceNum]
);
// Recalculate order totals
await recalcOrderTotals(orderIdNum);
res.status(201).json({
ok: true,
orderID: orderIdNum,
listingID: listingIdNum,
});
}
catch (err) {
console.error('POST /api/order-items failed:', err);
// FK failures: invalid orderID or listingID
if (err.code === 'ER_NO_REFERENCED_ROW_2' || err.errno === 1452) {
return res.status(409).json({
error:
'orderID or listingID does not exist (foreign key constraint).',
});
}
res.status(500).json({ error: 'Failed to create order item' });
}
});
// PUT /api/order-items/:orderID/:listingID → update existing order item
app.put('/api/order-items/:orderID/:listingID', async (req, res) => {
const orderID = Number(req.params.orderID);
const listingID = Number(req.params.listingID);
const { quantity, unitPrice } = req.body || {};
if (!Number.isInteger(orderID) || orderID <= 0 ||
!Number.isInteger(listingID) || listingID <= 0) {
return res.status(400).json({ error: 'Invalid orderID or listingID' });
}
const qtyNum = Number(quantity);
const priceNum = Number(unitPrice);
if (!Number.isInteger(qtyNum) || qtyNum <= 0) {
return res
.status(400)
.json({ error: 'quantity must be a positive integer' });
}
if (!Number.isFinite(priceNum) || priceNum < 0) {
return res
.status(400)
.json({ error: 'unitPrice must be a non-negative number' });
}
try {
await db.query(
'CALL sp_update_order_item(?, ?, ?, ?)',
[orderID, listingID, qtyNum, priceNum]
);
// Recalculate order totals
await recalcOrderTotals(orderID);
res.status(200).json({ ok: true });
}
catch (err) {
console.error('PUT /api/order-items/:orderID/:listingID failed:', err);
res.status(500).json({ error: 'Failed to update order item' });
}
});
// DELETE /api/order-items/:orderID/:listingID → delete order item
app.delete('/api/order-items/:orderID/:listingID', async (req, res) => {
const orderID = Number(req.params.orderID);
const listingID = Number(req.params.listingID);
if (!Number.isInteger(orderID) || orderID <= 0 ||
!Number.isInteger(listingID) || listingID <= 0) {
return res.status(400).json({ error: 'Invalid orderID or listingID' });
}
try {
console.log(
'DELETE /api/order-items/:orderID/:listingID →',
{ orderID, listingID }
);
const [result] = await db.query(
'CALL sp_delete_order_item(?, ?)',
[orderID, listingID]
);
await recalcOrderTotals(orderID);
console.log('sp_delete_order_item result:', JSON.stringify(result));
return res.status(204).send();
}
catch (err) {
logDbError('DELETE order item failed', err);
return res.status(500).json({ error: 'Failed to delete order item' });
}
});
// ================= ORDERS =================
// GET /api/orders → list all orders
app.get('/api/orders', async (req, res) => {
try {
const [rows] = await db.query(
`SELECT
orderID,
customerID,
orderDate,
status,
subtotal,
tax,
total
FROM Orders
ORDER BY orderID`
);
res.json(rows);
}
catch (err) {
console.error('GET /api/orders failed:', err);
res.status(500).json({ error: 'Failed to load orders' });
}
});
// Helper: normalize/validate an order payload
function normalizeOrderBody(body) {
const {
customerID,
orderDate,
status,
subtotal,
tax,
total,
} = body || {};
const customerIdNum = Number(customerID);
const subtotalNum = Number(subtotal);
const taxNum = Number(tax);
const totalNum = Number(total);
const validStatuses = ['pending', 'paid', 'shipped', 'canceled', 'refunded'];
if (!Number.isInteger(customerIdNum) || customerIdNum <= 0) {
return { error: 'Valid customerID is required' };
}
if (!validStatuses.includes(status)) {
return {
error: `status must be one of: ${validStatuses.join(', ')}`,
};
}
if (!Number.isFinite(subtotalNum) || subtotalNum < 0) {
return { error: 'subtotal must be a non-negative number' };
}
if (!Number.isFinite(taxNum) || taxNum < 0) {
return { error: 'tax must be a non-negative number' };
}
if (!Number.isFinite(totalNum) || totalNum < 0) {
return { error: 'total must be a non-negative number' };
}
// orderDate: if missing, default to "now" in MySQL DATETIME format
const orderDateValue =
orderDate && typeof orderDate === 'string'
? orderDate
: new Date().toISOString().slice(0, 19).replace('T', ' ');
return {
customerIdNum,
orderDateValue,
status,
subtotalNum,
taxNum,
totalNum,
};
}
// POST /api/orders → create new order (uses sp_insert_order)
app.post('/api/orders', async (req, res) => {
const normalized = normalizeOrderBody(req.body);
if ('error' in normalized)
return res.status(400).json({ error: normalized.error });
const {
customerIdNum,
orderDateValue,
status,
subtotalNum,
taxNum,
totalNum,
} = normalized;
try {
await db.query('CALL sp_insert_order(?,?,?,?,?,?)', [
customerIdNum,
orderDateValue,
status,
subtotalNum,
taxNum,
totalNum,
]);
// We’re not using insertId here; frontend can just refetch /api/orders
res.status(201).json({ ok: true });
}
catch (err) {
console.error('POST /api/orders failed:', err);
// Foreign-key failure for customerID
if (err.code === 'ER_NO_REFERENCED_ROW_2' || err.errno === 1452) {
return res.status(409).json({
error: 'customerID does not exist (foreign key constraint).',
});
}
res.status(500).json({ error: 'Failed to create order' });
}
});
// PUT /api/orders/:id → update existing order (uses sp_update_order)
app.put('/api/orders/:id', async (req, res) => {
const orderID = Number(req.params.id);
if (!Number.isInteger(orderID) || orderID <= 0)
return res.status(400).json({ error: 'Invalid orderID' });
const normalized = normalizeOrderBody(req.body);
if ('error' in normalized)
return res.status(400).json({ error: normalized.error });
const {
customerIdNum,
orderDateValue,
status,
subtotalNum,
taxNum,
totalNum,
} = normalized;
try {
await db.query('CALL sp_update_order(?,?,?,?,?,?,?)', [
orderID,
customerIdNum,
orderDateValue,
status,
subtotalNum,
taxNum,
totalNum,
]);
res.status(200).json({ ok: true });
} catch (err) {
console.error('PUT /api/orders/:id failed:', err);
if (err.code === 'ER_NO_REFERENCED_ROW_2' || err.errno === 1452) {
return res.status(409).json({
error: 'customerID does not exist (foreign key constraint).',
});
}
res.status(500).json({ error: 'Failed to update order' });
}
});
// DELETE /api/orders/:id → delete order
app.delete('/api/orders/:id', async (req, res) => {
const orderID = Number(req.params.id);
if (!Number.isInteger(orderID) || orderID <= 0)
return res.status(400).json({ error: 'Invalid orderID' });
try {
console.log('DELETE /api/orders/:id → orderID =', orderID);
const [result] = await db.query('CALL sp_delete_order(?)', [orderID]);
console.log('sp_delete_order result:', JSON.stringify(result));
return res.status(204).send();
} catch (err) {
logDbError('DELETE order failed', err);
// If OrderItems.orderID FK isn’t ON DELETE CASCADE
if (err.code === 'ER_ROW_IS_REFERENCED_2' || err.errno === 1451) {
return res.status(409).json({
error:
'Cannot delete order because one or more OrderItems still reference it. ' +
'Either delete those order items first or use ON DELETE CASCADE on OrderItems.orderID.',
});
}
return res.status(500).json({ error: 'Failed to delete order' });
}
});
// ----------------- STATIC REACT BUILD -----------------
const distPath = path.join(__dirname, 'dist');
// Serve static assets (JS, CSS, images)
app.use(express.static(distPath));