aboutsummaryrefslogtreecommitdiffstats
path: root/src/wwwroot/scripts/back/bestillinger.js
blob: 17b56d51a32bf93e5f14e63b27389596d23f69c6 (plain) (blame)
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
import Grid from "../grid";
import {strings} from "../i10n";
import {$, doc, pageInit, toaster} from "../base";
import {eyeIcon} from "../icons";
import {utilites} from "../utilities";
import {messages} from "../messages";
import {cancelOrder, captureVippsOrder, getOrderDetails, getOrders, refundOrder} from "../api/order-api";
import Modal from "bootstrap/js/src/modal";

if (location.pathname.startsWith("/kontoret/bestillinger")) {
    const ordersLoader = $("#orders-loader");
    const ordersWrapper = $("#orders-wrapper");
    const orderInfoModalEl = $("#order-info-modal");
    const orderInfoModal = new Modal(orderInfoModalEl);

    const grid = new Grid({
        search: {
            dataIds: ["orderReference", ["contactInfo", "name"], ["contactInfo", "emailAddress"], ["contactInfo", "phoneNumber"]],
        },
        strings: {
            search: strings.languageSpesific.search,
            nextPage: strings.languageSpesific.next_page,
            previousPage: strings.languageSpesific.previous_page,
        },
        debug: location.href.includes("localhost"),
        classes: {
            table: "table table-bordered mt-3",
            thead: "table-primary",
        },
        columns: [
            {
                dataId: "orderReference",
                minWidth: "150px",
                columnName: "Referanse",
                className: "btn-link cursor-pointer",
                click: (row) => openViewOrderModal(row),
            },
            {
                columnName: "Navn",
                dataId: ["contactInfo", "name"],
                minWidth: "200px",
            },
            {
                columnName: "E-postadresse",
                dataId: ["contactInfo", "emailAddress"],
                minWidth: "200px",
            },
            {
                columnName: "Telefonnummer",
                dataId: ["contactInfo", "phoneNumber"],
                minWidth: "150px",
            },
            {
                dataId: "created",
                minWidth: "175px",
                cellValue: (row) => utilites.toReadableDateString(new Date(row.created)),
                columnName: "Dato",
            },
            {
                minWidth: "150px",
                columnName: "Status",
                cellValue: (row) => {
                    const status = doc.createElement("span");
                    switch (row.status) {
                        case 0: {
                            status.innerText = "Pågående";
                            break;
                        }
                        case 1: {
                            status.innerText = "Kansellert";
                            break;
                        }
                        case 2: {
                            status.innerText = "Feilet";
                            status.classList.add("text-danger");
                            break;
                        }
                        case 3: {
                            status.innerText = "Fullført";
                            status.classList.add("text-success");
                            break;
                        }
                        case 4: {
                            status.innerText = "Venter på faktura";
                            break;
                        }
                        case 5: {
                            status.innerText = "Venter på vipps";
                            break;
                        }
                    }
                    return status;
                },
            },
            {
                columnName: "",
                width: "40px",
                minWidth: "40px",
                cellValue: (row) => {
                    const viewOrder = doc.createElement("button");
                    viewOrder.className = "btn btn-link text-info shadow-none";
                    viewOrder.title = strings.languageSpesific.view + ` "${row.orderReference}"`;
                    viewOrder.innerHTML = eyeIcon();
                    viewOrder.onclick = () => openViewOrderModal(row);
                    return viewOrder;
                },
            },
        ],
    });

    if (location.pathname.startsWith("/kontoret/bestillinger")) {
        pageInit(() => {
            renderProductsView();
        });
    }

    function openViewOrderModal({id, orderReference}) {
        orderInfoModalEl.querySelector(".modal-title").innerText = orderReference;
        $("#loader").style.display = "";
        $("#loaded").style.display = "none";

        orderInfoModal.show();

        getOrderDetails(id).then(res => {
            if (res.ok) {
                res.json().then(order => {
                    order = utilites.resolveReferences(order);
                    $("#contact-info-name").innerText = order.contactInformation.name;
                    $("#contact-info-emailAddress").innerHTML = `<a href='mailto:${order.contactInformation.emailAddress}'>${order.contactInformation.emailAddress}</a>`;
                    $("#contact-info-phoneNumber").innerHTML = `<a href='tel:${order.contactInformation.phoneNumber}'>${order.contactInformation.phoneNumber}</a>`;
                    $("#order-reference").innerText = order.orderReference;
                    $("#order-date").innerText = new Date(order.orderDate).toLocaleDateString();
                    $("#order-payment-type").innerText = utilites.getOrderPaymentName(order.paymentType);
                    $("#order-status").innerText = utilites.getOrderStatusName(order.status);
                    if (order.comment && order.comment !== "") {
                        $("#order-comment").innerText = order.comment;
                        $("#order-comment").style.display = "inline-block";
                    } else {
                        $("#order-comment").style.display = "none";
                    }

                    if (order.paymentType === 0) {
                        if ([
                            "SALE",
                            "RESERVED",
                        ].includes(order.vippsTransactionStatus)) {
                            $("#vipps-order-refund").classList.remove("d-none");
                            $("#vipps-order-refund").onclick = () => {
                                if (confirm("Er du sikker på at du vil refundere ordren " + order.orderReference)) {
                                    $("#vipps-order-refund").classList.add("loading");
                                    refundOrder(order.id).then(res => {
                                        if (res.ok) {
                                            toaster.success("Refundert", "Ordren er refundert, og vipps har startet refundering");
                                        } else {
                                            console.error("Received non-successful status code when submitting refund order command");
                                            toaster.error("En feil oppstod", "Prøv å refundere i vipps portalen");
                                        }
                                        $("#vipps-order-refund").classList.remove("loading");
                                    }).catch(err => {
                                        $("#vipps-order-refund").classList.remove("loading");

                                        console.error("refund order NetworkRequest failed");
                                        toaster.error("En uventet feil oppstod");
                                        console.error(err);
                                    });
                                }
                            };
                        }

                        if ([
                            "SALE",
                            "RESERVED",
                        ].includes(order.vippsTransactionStatus)) {
                            $("#vipps-order-capture").classList.remove("d-none");
                            $("#vipps-order-capture").onclick = () => {
                                if (confirm("Er du sikker på at du vil fullføre ordren " + order.orderReference)) {
                                    $("#vipps-order-capture").classList.add("loading");
                                    captureVippsOrder(order.id).then(res => {
                                        if (res.ok) {
                                            toaster.success("Fullført", "Ordren er fullført, og vipps har registrert transaksjonen");
                                        } else {
                                            console.error("Received non-successful status code when submitting fulfill order command");
                                            toaster.error("En feil oppstod", "Prøv å fullføre i vipps portalen");
                                        }
                                        $("#vipps-order-capture").classList.remove("loading");
                                    }).catch(err => {
                                        $("#vipps-order-capture").classList.remove("loading");
                                        console.error("fulfill order NetworkRequest failed");
                                        toaster.error("En uventet feil oppstod");
                                        console.error(err);
                                    });
                                }
                            };
                        }

                        if ([
                            "SALE",
                            "RESERVED",
                        ].includes(order.vippsTransactionStatus)) {
                            $("#vipps-order-cancel").classList.remove("d-none");
                            $("#vipps-order-cancel").onclick = () => {
                                if (confirm("Er du sikker på at du vil kansellere ordren " + order.orderReference)) {
                                    $("#vipps-order-cancel").classList.add("loading");
                                    cancelOrder(order.id).then(res => {
                                        if (res.ok) {
                                            toaster.success("Kansellert", "Ordren er kansellert");
                                        } else {
                                            console.error("Received non-successful status code when submitting cancel order command");
                                            toaster.error("En feil oppstod", "Prøv å kansellere i vipps portalen");
                                        }
                                        $("#vipps-order-cancel").classList.remove("loading");
                                    }).catch(err => {
                                        $("#vipps-order-cancel").classList.remove("loading");
                                        console.error("cancel order NetworkRequest failed");
                                        toaster.error("En uventet feil oppstod");
                                        console.error(err);
                                    });
                                }
                            };
                        }


                        switch (order.vippsTransactionStatus) {
                            case "SALE":
                                $("#vipps-status").innerText = "Salg (fullført og overført)";
                                break;
                            case "RESERVED":
                                $("#vipps-status").innerText = "Reservert";
                                break;
                            case "CANCELLED":
                                $("#vipps-status").innerText = "Kansellert";
                                break;
                            case "REJECTED":
                                $("#vipps-status").innerText = "Avslått";
                                break;
                            case "SALE_FAILED":
                                $("#vipps-status").innerText = "Salg feilet";
                                break;
                            case "AUTO_CANCEL":
                                $("#vipps-status").innerText = "Automatisk kansellering";
                                break;
                            case "RESERVE_FAILED":
                                $("#vipps-status").innerText = "Reservering feilet";
                                break;
                        }
                        $("#vipps-link").innerHTML = `<a href='https://portal.vipps.no/61861/transactions/${order.vippsId}' target="_blank">Åpne bestillingen i Vipps-portalen</a>`;
                        $("#vipps-section").classList.remove("d-none");
                    } else {
                        $("#vipps-section").classList.add("d-none");
                    }

                    orderInfoModalEl.querySelector(".modal-body").style.display = "";

                    const productsBody = orderInfoModalEl.querySelector("tbody");
                    productsBody.innerHTML = "";
                    let productIndex = 1;
                    let totalPrice = 0;
                    for (const product of order.products) {
                        const rowItem = doc.createElement("tr");
                        const nrCell = doc.createElement("td");
                        nrCell.innerText = productIndex.toString();
                        const nameCell = doc.createElement("td");
                        nameCell.innerText = product.name;
                        const countCell = doc.createElement("td");
                        countCell.innerText = product.count;
                        const priceCell = doc.createElement("td");
                        const totalSum = product.payedPrice * product.count;
                        priceCell.innerText = `${product.payedPrice} (totalt: ${totalSum})`;

                        rowItem.appendChild(nrCell);
                        rowItem.appendChild(nameCell);
                        rowItem.appendChild(countCell);
                        rowItem.appendChild(priceCell);
                        productsBody.appendChild(rowItem);
                        productIndex++;
                        totalPrice += totalSum;
                    }
                    $("#order-total").innerText = totalPrice;
                    $("#loader").style.display = "none";
                    $("#loaded").style.display = "";
                    orderInfoModal.show();
                });
            } else {
                toaster.error("En feil oppstod", "Kunne ikke hente ordren, prøv igjen snart!");
            }
        }).catch(error => {
            console.error(error);
        });
    }

    function renderProductsView() {
        ordersWrapper.innerHTML = "";
        ordersWrapper.classList.add("d-none");
        ordersLoader.classList.remove("d-none");

        getOrders("not-cancelled").then(res => {
            if (res.ok) {
                res.json().then(products => {
                    grid.render(ordersWrapper);
                    products = utilites.resolveReferences(products);
                    grid.refresh(products);
                    const queryOrderRef = new URL(location.href).searchParams.get("order");
                    if (queryOrderRef) {
                        const product = products.find(c => c.orderReference === queryOrderRef);
                        openViewOrderModal(product);
                    }
                });
                ordersWrapper.classList.remove("d-none");
                ordersLoader.classList.add("d-none");
            } else {
                utilites.handleError(res, {
                    title: strings.languageSpesific.could_not_retrieve_orders,
                    message: strings.languageSpesific.try_again_soon,
                });
            }
        }).catch(error => {
            console.error(error);
            toaster.errorObj(messages.networkRequestFailed);
        });
    }
}