-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
92 lines (79 loc) · 1.95 KB
/
api.js
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
async function getProducts() {
return products;
}
async function getProduct(id) {
return products.find((product) => product.id === id);
}
async function createProduct(product) {
product.id = Date.now().toString();
products.push(product);
saveData();
return product;
}
async function updateProduct(id, product) {
const index = products.findIndex((p) => p.id === id);
if (index !== -1) {
products[index] = { ...products[index], ...product };
saveData();
return products[index];
}
return null;
}
async function deleteProduct(id) {
const index = products.findIndex((p) => p.id === id);
if (index !== -1) {
products.splice(index, 1);
saveData();
}
}
async function getOrders() {
return orders;
}
async function getOrder(id) {
return orders.find((order) => order.id === id);
}
async function createOrder(order) {
if (
!order.productData ||
!Array.isArray(order.productData) ||
order.productData.length === 0
) {
throw new Error("No products selected!");
}
for (const item of order.productData) {
if (!item.productId || !item.quantity) {
throw new Error("Invalid product data!");
}
const product = products.find(
(p) => p.id.toString() === item.productId.toString()
);
if (!product) {
throw new Error("Invalid product selection!");
}
if (product.stock < item.quantity) {
throw new Error(
`Not enough stock for ${product.name}! Available: ${product.stock}`
);
}
}
order.id = Date.now().toString();
orders.push(order);
saveData();
return order;
}
async function updateOrder(id, order) {
const index = orders.findIndex((o) => o.id === id);
if (index !== -1) {
orders[index] = { ...orders[index], ...order };
saveData();
return orders[index];
}
return null;
}
async function deleteOrder(id) {
const index = orders.findIndex((o) => o.id === id);
if (index !== -1) {
orders.splice(index, 1);
saveData();
}
}