AECC database project.
1function editProduct(obj) {
2 productEditorID.value = obj[0];
3 productEditorDollars.value = (obj[1] / 100.0).toFixed(2);
4 productEditorDescription.value = obj[2];
5 next('productEditor');
6}
7
8function productCreatorFormHandler(event) {
9 event.preventDefault();
10
11 const dollars = event.srcElement[1].value;
12 const description = event.srcElement[2].value;
13 const cents = dollars * 100;
14
15 if (confirm('Do you want to create a product called: "' + description + '" costing $' + dollars + " (¢" + cents + " cents)?")) {
16 try {
17 fetch(URL + "/api/v1/create/", {
18 method: "POST",
19 body: JSON.stringify({
20 t: "product",
21 cents: cents,
22 description: description
23 })
24 }).then(resp => {
25 alert("Succesfully created product");
26 restart();
27 });
28 } catch (error) {
29 alert("Error inserting");
30 console.error(error.message);
31 }
32 }
33}
34
35function editProductHandler(event) {
36 event.preventDefault();
37
38 const p_id = event.target[4].value;
39 const cents = event.target[1].value * 100;
40 const description = event.target[2].value;
41
42 try {
43 if (confirm(`Are you sure you want to edit product with ID: ${p_id}`)) {
44 const payload = JSON.stringify({
45 t: "product",
46 p_id: p_id,
47 cents: cents,
48 description: description
49 })
50 fetch(URL + "/api/v1/update/", {
51 method: "POST",
52 headers: {
53 "Content-Type": "application/json"
54 },
55 body: payload
56 }).then(resp => {
57 if (resp.status != 201) {
58 const msg = `Error updating product, status: ${resp.status}`;
59 alert(msg);
60 throw msg;
61 }
62 return resp.json();
63 }).then(json => {
64 alert(`Succesfully updated product with ID: ${json.p_id}`);
65 restart();
66 });
67 }
68 } catch (e) {
69 console.error(e.message);
70 }
71}
72
73function deleteProduct(obj) {
74 const p_id = obj[0];
75 try {
76 const payload = JSON.stringify({
77 t: "product",
78 p_id: p_id
79 });
80 if (confirm(`Are you sure you want to delete the product with ID: ${p_id}`)) {
81 fetch(URL + "/api/v1/delete/", {
82 method: "POST",
83 headers: { "Content-Type": "application/json" },
84 body: payload
85 }).then(resp => {
86 if (resp.status != 204) {
87 const msg = `Error deleting product, status: ${resp.status}`;
88 alert(msg);
89 throw msg;
90 } else {
91 alert(`Succesfully deleted product with ID: ${p_id}`);
92 initTable(allProductsTable, 'product', 'editProduct', 'deleteProduct');
93 }
94 });
95 }
96 } catch(e) {
97 console.error(e);
98 }
99}