-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.js
More file actions
79 lines (72 loc) · 1.98 KB
/
checkout.js
File metadata and controls
79 lines (72 loc) · 1.98 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
/**
* Triggers BootsTrap's validation
* @param form
* @returns {Boolean} - true, if there was no validation error
*/
function validateForm(form) {
form.classList.add('was-validated')
return form.checkValidity()
}
/**
* Creates a new order
* @param form - the HTML form element
*/
function checkout(form) {
const billing = {
firstname: form.firstname.value,
lastname: form.lastname.value,
company: form.company.value,
country: form.country.value,
address: form.address.value,
city: form.city.value,
state: form.state.value,
zip: form.zip.value,
phone: form.phone.value,
email: form.email.value,
paymentMethod: form.paymentMethod.value,
}
const today = new Date()
const orderDate = today.toLocaleString('en-US')
const newOrder = {
billing: billing,
orderDate: orderDate,
items: cart.items,
numOfItems: cart.numOfItems,
grandTotal: cart.grandTotal
}
const orderNumber = placeOrder(newOrder)
clearCart()
location.href = 'order.html?id=' + orderNumber
}
/**
* Saves the new order to localStorage
* @param newOrder - the new order
* @returns {number} - the new order number
*/
function placeOrder(newOrder) {
const orders = readOrders()
const orderNumber = nextOrderNumber()
newOrder.id = orderNumber
orders[orderNumber.toString()] = newOrder
localStorage.setItem("orders", JSON.stringify(orders))
localStorage.setItem('orderCounter', JSON.stringify(orderNumber))
return orderNumber
}
/**
* Reads the current order counter from localStorage and increases it
* @returns {number} - the current order counter + 1
*/
function nextOrderNumber() {
let orderCounter = localStorage.getItem('orderCounter') || '0'
orderCounter = Number(orderCounter)
orderCounter++
return orderCounter
}
/**
* Reads the orders from localStorage
* @returns {any} - a Map of the orders, so far
*/
function readOrders() {
const ordersInStorage = localStorage.getItem("orders") || '{}'
return JSON.parse(ordersInStorage)
}