summaryrefslogtreecommitdiff
path: root/client/src/attractionArticle.js
blob: 493417e90cb5ae839bbbbfbad6b7d2f49b7feef9 (plain)
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
import {
    fetchAttractions,
    findParent,
    dutchCurrencyFormat,
    dutchCurrencyFormatWithSign,
    displayNumberOfItemsInShoppingBasketWithBadge
} from "./utils.js"

export function disableButton(name, button) {
    return function receiver(payload) {
        console.log('checking if button should be disabled');
        const inputs = button.parentNode.querySelectorAll("input");
        var inputTickets = 0;
        for (let i = 0; i < inputs.length; i++) {
            if (inputs[i].value > 0) {
                inputTickets = inputTickets + Number.parseInt(inputs[i].value);
            }
        }

        const shoppingBasketArray = JSON.parse(localStorage.getItem("shoppingBasketArray"));
        // console.log(shoppingBasketArray);
        var shoppingBasketTickets = 0;

        if (shoppingBasketArray) {
            for (let i = 0; i < shoppingBasketArray.length; i++) {
                if (shoppingBasketArray[i].name === name) {
                    shoppingBasketTickets = shoppingBasketTickets + shoppingBasketArray[i].numberOfKids + shoppingBasketArray[i].numberOfAdults;
                }
            }
        }
        const totalTickets = inputTickets + shoppingBasketTickets;

        function disablerHelper(payload) {
            var attraction;
            if (Array.isArray(payload)) {
                for (let i = 0; i < payload.length; i++) {
                    if (payload[i].name === name) {
                        attraction = payload[i];
                    }
                }
            } else attraction = payload;

            var front = button.querySelector(".front");
            if (attraction.available < totalTickets || attraction.available === 0 || attraction.available === shoppingBasketTickets) {
                console.log("---> disabling " + attraction.name + " button since the available tickets are " + attraction.available + " and tickets among current order is " + totalTickets);
                front.classList.add("disabled");
                button.removeEventListener("click", orderButtonClicked);
            } else {
                console.log("---> enabling " + attraction.name + " button since the available tickets are " + attraction.available + " and tickets among current order is " + totalTickets);
                front.classList.remove("disabled");
                button.addEventListener("click", orderButtonClicked);
            }

        }

        // console.log(payload)
        if (payload && payload.name) {
            if (payload.name) {
                // console.log("prevented unnecesary fetch")
                disablerHelper(payload);
            }
        } else {
            // console.log("unnecesary fetch")
            fetchAttractions()
                .then(disablerHelper)
                .catch(error => {console.error(error)});
        }
    }
}

export function orderButtonClicked(event) {
    console.log("button click");
    var button;

    if (event.target.classList.contains("orderbutton")) {
        button = event.target;
    } else {
        button = event.target.parentNode;
    }

    const order = button.parentNode;
    const parkArticle = order.parentNode;

    const orderClientSideInfo = {
        name: parkArticle.querySelector(".parkname").textContent,
        numberOfKids: Number(order.querySelector(".numberofkids").value),
        numberOfAdults: Number(order.querySelector(".numberofadults").value),
    }

    console.log("---> found this info on the client side:")
    console.log(orderClientSideInfo);

    if ((orderClientSideInfo.numberOfKids > 0 && orderClientSideInfo.numberOfAdults >= 0) || (orderClientSideInfo.numberOfAdults > 0 && orderClientSideInfo.numberOfKids >= 0)) {
        fetchAttractions()
            .then(checkTicketAvailability(button, orderClientSideInfo))
            .then(saveOrderInShoppingBasket(orderClientSideInfo))
            .then(disableButton(orderClientSideInfo.name, button))
            .catch((error) => {console.error(error)})
    }
}

class TicketsNotAvailableError extends Error {
    constructor(message) {
        super(message);
        this.name = "TicketsNotAvailableError";
    }
}


export function checkTicketAvailability(button, orderClientSideInfo) {

    return function serverAttractionsAccepter(serverAttractionsArray) {
        var attraction;
        for (let i = 0; i < serverAttractionsArray.length; i++) {
            if (serverAttractionsArray[i].name === orderClientSideInfo.name) {
                attraction = serverAttractionsArray[i]
            }
        }

        if (attraction.available < orderClientSideInfo.numberOfKids + orderClientSideInfo.numberOfAdults) {
            throw new TicketsNotAvailableError("The tickets of the order exceed the available tickets!");
        }

        return serverAttractionsArray;
    }
}

export function saveOrderInShoppingBasket(orderClientSideInfo) {
    console.log("---> ---> saving info in shopping basket");

    return function serverAttractionsAccepter(serverAttractionsArray) {
        // const orderClientSideInfo = this;

        var price;
        var attraction;
        for (let i = 0; i < serverAttractionsArray.length; i++) {
            if (serverAttractionsArray[i].name === orderClientSideInfo.name) {
                 price = calulateTotal(
                    orderClientSideInfo.numberOfKids,
                    orderClientSideInfo.numberOfAdults,
                    serverAttractionsArray[i]
                 );
                attraction = serverAttractionsArray[i];
            }
        }

        orderClientSideInfo.price = price;
        console.log("---> ---> price is saved in the shopping basket order");
        console.log(orderClientSideInfo);

        var shoppingBasketArray;

        if (localStorage.getItem("shoppingBasketArray") === null) {
            shoppingBasketArray = [];
            shoppingBasketArray.push(orderClientSideInfo);
        } else {
            shoppingBasketArray = JSON.parse(localStorage.getItem("shoppingBasketArray"));
            shoppingBasketArray.push(orderClientSideInfo);
        }

        localStorage.setItem("shoppingBasketArray", JSON.stringify(shoppingBasketArray));
        console.log("---> ---> order is saved in array in localstorage");
        console.log(localStorage);
        displayNumberOfItemsInShoppingBasketWithBadge();
        return attraction;
    }
}

export function calulateTotal(numberOfKids, numberOfAdults, serverSideAttraction) {
    console.log("---> calculating total of order in shoppingbasket!");
    console.log("---> ---> fetched this attraction to calculate actual prices!");
    console.log(serverSideAttraction);

    const adultPrice = serverSideAttraction.adultPrice;
    const kidsPrice = serverSideAttraction.kidsPrice;

    const discountPercentage = serverSideAttraction.discount;
    const minNumberkids = serverSideAttraction.minimumNumberOfKids;
    const minNumberAdults = serverSideAttraction.minimumNumberOfAdults;

    var totalPrice = 0;
    if (numberOfKids > 0) {
        totalPrice = totalPrice +  numberOfKids * kidsPrice;
    }
    if (numberOfAdults > 0) {
        totalPrice = totalPrice + numberOfAdults * adultPrice;
    }

    if (numberOfKids >= minNumberkids && numberOfAdults >= minNumberAdults) {
        var discount = totalPrice * discountPercentage / 100;
        totalPrice = totalPrice - discount;
    }

    if (discount) {
        return {total:totalPrice, discount: discount}
    } else {
        return {total: totalPrice};
    }
}

export function displayTotal(event) {
    console.log("displaying a total price based on client side info");
    var order = findParent(parent => {return parent.classList.contains("order")})(event.target)
    console.log(order)
    var total = order.querySelector(".total");

    var kids = order.querySelector(".numberofkids").value;
    var adults = order.querySelector(".numberofadults").value;
    if (kids === "") kids = 0;
    if (adults === "") adults = 0;

    let re = /\d+/;
    var kidsPrice = order.querySelector(".kidsprice")
        .textContent
        .match(re)[0];
    var adultPrice = order.querySelector(".adultprice")
        .textContent
        .match(re)[0];

    var discountReq = order.querySelector(".discountrequirement")
    var minNumberkids = discountReq.querySelector(".child")
        .textContent
        .match(re)[0]
    var minNumberadults = discountReq.querySelector(".adults")
        .textContent
        .match(re)[0]
    var discountPercentage = discountReq.querySelector(".percentage")
        .textContent
        .match(re)[0];
    // console.log(discountPercentage);

    var value = 0;
    if (kids > 0) {
        value = value + Number.parseInt(kids) * Number.parseFloat(kidsPrice);
    }
    if (adults > 0) {
        value = value + Number.parseInt(adults) * Number.parseFloat(adultPrice);
    }

    var discount;
    if (Number.parseInt(kids) >= Number.parseInt(minNumberkids) && Number.parseInt(adults) >= Number.parseInt(minNumberadults)) {
        discount = value * Number.parseFloat(discountPercentage) / 100
        value = value - discount;
        console.log("---> applying the discount of " + discountPercentage + "%, resulting in " + discount + " discount")
    }
    // console.log(value);

    var priceString = dutchCurrencyFormat(value);
    if (!(discount === undefined)) {
        priceString = priceString + " discount: " + dutchCurrencyFormatWithSign(discount);
    }
    total.querySelector(".price").textContent = priceString;
}