Subversion Repositories munaweb

Rev

Rev 134 | Rev 147 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
<!DOCTYPE html>
2
<html lang="en">
3
 
4
<head>
5
    <title>Order Reports</title>
6
    <meta charset="UTF-8">
7
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
8
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
9
    <link rel="icon" href="favicon.ico" type="image/x-icon">
10
 
30 - 11
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
12
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
13
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
14
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
15
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
16
    <script src="js/XMLWriter.js"></script>
17
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
18
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
19
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
2 - 20
    <link rel="stylesheet" href="css/style.css">
21
    <script src="js/muna-tools.js"></script>
22
</head>
23
 
24
<body onload="return initConfig();">
30 - 25
    <div>
26
        <div>
27
            <div class="container-fluid bg-secondary">
28
                <div class="clearfix">
29
                    <img class="img-fluid float-right" src="images/MUNA%20-%20Logo%20100x100.png" alt="MUNA Trading Logo" />
30
                    <h1 id="connected">Order Reports
31
                    <input id="login" type="button" class="btn bg-success mb-2 w3-hide" onclick="eBayLogin();" value="Login" /></h1>
32
                </div>
2 - 33
            </div>
34
 
30 - 35
            <div class="border">
36
                <form id="searchForm" class="container-fluid bg-light" onsubmit="return getOrders();">
37
                    <div class="row">
38
                    <div class="col border">
39
                        <h4>Date Range</h4>
40
                            <div class="input-group mb-3">
41
                              <div class="input-group-prepend">
42
                                <span class="input-group-text bg-light"> &#9655;</span>
43
                              </div>
44
                              <input type="date" class="form-control" id="startDate" name="startDate" required>
2 - 45
                            </div>
30 - 46
                            <div class="input-group">
47
                              <div class="input-group-prepend">
48
                                <span class="input-group-text bg-light"> &#9665;</span>
49
                              </div>
50
                              <input type="date" class="form-control" id="endDate" name="endDate" required>
7 - 51
                            </div>
30 - 52
                    </div>
53
                    <div class="col border">
54
                        <h4>Report Type</h4>
55
                        <div class="form-check">
56
                            <label for="shippingList">
57
                                <input id="shippingList" class="form-check-input" type="radio" name="rptType" value="shippingList" checked>Awaiting Shipment
58
                            </label>
2 - 59
                        </div>
30 - 60
                        <div class="form-check">
61
                            <label for="orderList">
62
                                <input id="orderList" class="form-check-input" type="radio" name="rptType" value="orderList">Orders
63
                            </label>
64
                        </div>
65
                        <div class="form-check">
66
                            <label for="feeList">
67
                                <input id="feeList" class="form-check-input" type="radio" name="rptType" value="feeList">eBay Fees and Credits
68
                            </label>
69
                        </div>
70
                        <div class="form-check">
71
                            <label for="cancelReturnList">
72
                                <input id="cancelReturnList" class="form-check-input" type="radio" name="rptType" value="cancelReturnList">eBay Cancellations/Returns
73
                            </label>
74
                        </div>
75
                        <div class="form-check">
76
                            <label for="trackingList">
77
                                <input id="trackingList" class="form-check-input" type="radio" name="rptType" value="trackingList">Tracking Status
78
                            </label>
79
                        </div>
80
                        <div class="form-check">
81
                            <label for="customerList">
82
                                <input id="customerList" class="form-check-input" type="radio" name="rptType" value="customerList">eBay Customer Export
83
                            </label>
84
                        </div>
85
 
86
                        <input id="printButton" type="button" class="btn btn-dark float-right mx-2 w3-hide" onclick="printData();" value="Print" />
87
                        <input id="dlOrderListButton" type="button" class="btn btn-dark float-right mx-2 w3-hide" onclick="exportTableToCSV('orderTable', 'orders.csv');" value="CSV" />
88
                        <input id="dlFeeListButton" type="button" class="btn btn-dark float-right mx-2 w3-hide" onclick="exportTableToCSV('feeTable', 'fees.csv');" value="CSV" />
34 - 89
                        <input id="dlCancelReturnListButton" type="button" class="btn btn-dark float-right mx-2 w3-hide" onclick="exportTableToCSV('cancelReturnTable', 'returns.csv');" value="CSV" />
30 - 90
                        <input id="dlCustomerListButton" type="button" class="btn btn-dark float-right mx-2 w3-hide" onclick="exportTableToCSV('customerTable', 'customers.csv');" value="CSV" />
91
                        <input id="startButton" type="button" class="btn btn-danger float-right mx-2" onclick="getOrders();" value="Start" />
6 - 92
                    </div>
30 - 93
                    <div id="summary" class="col border"></div>
7 - 94
                    </div>
95
                </form>
96
            </div>
30 - 97
            <div class="modal" id="progressBarDiv">
98
                <div class="modal-dialog">
99
                    <div class="modal-content">
100
                        <div class="modal-header">
101
                            <h4 id="progressBarHeader"></h4>
102
                        </div>
103
                        <div class="modal-body">
104
                            <div class="progress">
105
                                <div id="progressBar" class="progress-bar" style="width:0%">0%</div>
106
                            </div>
107
                        </div>
108
                    </div>
6 - 109
                </div>
2 - 110
            </div>
30 - 111
            <div id="results" class="border bg-info w3-hide"></div>
7 - 112
            <div id="printTable">
30 - 113
                <div id="logging"></div>
7 - 114
            </div>
115
            <div id="modals"></div>
2 - 116
        </div>
117
 
30 - 118
        <footer class="container-fluid text-center border border-bottom-0 border-left-0 border-right-0">
17 - 119
            <div w3-include-html="php/footer.php"></div>
2 - 120
        </footer>
121
 
122
    </div>
123
 
124
    <script>
125
 
126
// Globals
127
var pagesToProcess = 0;
6 - 128
var pagesProcessed = 0;
129
var maxPagesToProcess = 0;
2 - 130
var shippingsToProcess = 0;
6 - 131
var shippingsProcessed = 0;
2 - 132
var thumbnailsToProcess = 0;
6 - 133
var thumbnailsProcessed = 0;
134
var maxThumbnailsToProcess = 0;
2 - 135
var trackingNumbersToProcess = 0;
6 - 136
var trackingNumbersProcessed = 0;
137
var maxTrackingNumbersToProcess = 0;
2 - 138
var html = [];
139
var url;
140
var trackingList = [];
141
var trackingListDedupe = [];
142
 
143
var itemsSold;
144
var grossSales;
145
var shippingRcvd;
146
var returnCost;
147
var shippingCost;
148
var eBayFees;
149
var PayPalFees;
150
var totalAmount;
151
 
152
// Initialize Configuration Variables
153
function initConfig() {
6 - 154
    eBayAuthToken = readCookie();
155
    if (eBayAuthToken.length > 0) {
156
        connected();
157
    }
2 - 158
 
6 - 159
    if (eBayAuthTokenFlag === false) {
160
        var x = document.getElementById("login");
161
        if (x.className.indexOf("w3-show") == -1) {
162
            x.className += " w3-show";
163
        }
164
    }
2 - 165
 
6 - 166
    var currentDate = moment();
7 - 167
    var weekDayName =  moment().format('dddd');
168
    var yesterday = moment().subtract((weekDayName == "Monday" ? 2 : 1), "days");
2 - 169
 
7 - 170
    x = document.getElementById("startDate");
171
    if (x.value.length < 1) {
172
        x.value = yesterday.format('YYYY-MM-DD');
6 - 173
    }
7 - 174
 
175
    x = document.getElementById("endDate");
176
    if (x.value.length < 1) {
177
        x.value = currentDate.format('YYYY-MM-DD');
6 - 178
    }
2 - 179
}
180
 
181
function requireNewLogin() {
6 - 182
    // dummy
2 - 183
}
184
 
185
function getOrders() {
6 - 186
    var x;
2 - 187
 
6 - 188
    itemsSold = 0;
189
    grossSales = 0.0;
190
    shippingRcvd = 0.0;
191
    returnCost = 0.0;
192
    shippingCost = 0.0;
193
    eBayFees = 0.0;
194
    PayPalFees = 0.0;
2 - 195
 
6 - 196
    document.getElementById("summary").innerHTML = '';
197
    document.getElementById("results").innerHTML = '';
198
    document.getElementById("logging").innerHTML = '';
2 - 199
 
6 - 200
    var sDate = moment(document.getElementById("startDate").value, 'YYYY-MM-DD', true);
201
    var eDate = moment(document.getElementById("endDate").value, 'YYYY-MM-DD', true);
2 - 202
 
6 - 203
    if (!sDate.isValid()) {
204
        document.getElementById("startDate").value = '';
205
        return;
206
    }
2 - 207
 
6 - 208
    if (!eDate.isValid()) {
209
        document.getElementById("endDate").value = '';
210
        return;
211
    }
2 - 212
 
6 - 213
    if (moment(document.getElementById("startDate").value).isAfter(document.getElementById("endDate").value, 'day')) {
214
        document.getElementById("endDate").value = '';
215
        return;
216
    }
2 - 217
 
6 - 218
    x = document.getElementById("printButton");
219
    x.className = x.className.replace(" w3-show", "");
220
    x = document.getElementById("dlOrderListButton");
221
    x.className = x.className.replace(" w3-show", "");
222
    x = document.getElementById("dlFeeListButton");
223
    x.className = x.className.replace(" w3-show", "");
17 - 224
    x = document.getElementById("dlCancelReturnListButton");
225
    x.className = x.className.replace(" w3-show", "");
6 - 226
    x = document.getElementById("dlCustomerListButton");
227
    x.className = x.className.replace(" w3-show", "");
2 - 228
 
6 - 229
    x = document.getElementById("results");
230
    if (x.className.indexOf("w3-show") == -1) {
231
        x.className += " w3-show";
232
    }
2 - 233
 
6 - 234
    pagesToProcess = 1;
235
    pagesProcessed = 0;
236
    maxPagesToProcess = 1;
2 - 237
 
6 - 238
    if (getRadioValue('rptType') == 'feeList') {
239
        document.getElementById("results").innerHTML = '<p><strong>Retrieving Fees and Credits...</strong></p>';
240
        initProgressBar("Retrieving eBay Fees and Credits...");
2 - 241
 
6 - 242
        retrieveFees(1);
17 - 243
    } else if (getRadioValue('rptType') == 'cancelReturnList') {
244
        document.getElementById("results").innerHTML = '<p><strong>Retrieving Cancellations and Returns...</strong></p>';
245
        initProgressBar("Retrieving Returns...");
246
 
247
        retrieveCancelReturn(1);
6 - 248
    } else {
249
        document.getElementById("results").innerHTML = '<p><strong>Retrieving Orders...</strong></p>';
250
        document.getElementById("modals").innerHTML = '';
2 - 251
 
6 - 252
        retrieveeBayOrders(1);
253
        initProgressBar("Retrieving Orders...");
2 - 254
 
6 - 255
        function checkpagesToProcess() {
256
            if (pagesToProcess > 0) {
257
                window.setTimeout(checkpagesToProcess, 100); // wait 100 milliseconds
258
            } else {
259
                endProgressBar();
2 - 260
 
6 - 261
                if (getRadioValue('rptType') == 'shippingList') {
262
                    retrieveShopifyShippings(1);
263
                } else if (getRadioValue('rptType') == 'trackingList') {
264
                    retrieveShopifyTrackings(1);
265
                } else if (getRadioValue('rptType') == 'customerList') {
139 - 266
                    sortTable("customerTable");
6 - 267
                    x = document.getElementById("results");
268
                    x.innerHTML = '<p><strong>Report Finished!</strong></p>';
269
                    if (!x.className.includes("process-errors")) {
270
                        setTimeout(function() {
271
                            x.className = x.className.replace(" w3-show", "");
272
                        }, 3000);
273
                    }
274
                } else {
275
                    retrieveShopifyOrders(1);
276
                }
277
            }
278
        }
2 - 279
 
6 - 280
        checkpagesToProcess();
281
 
282
        if (getRadioValue('rptType') == 'shippingList') {
283
            x = document.getElementById("printButton");
284
            if (x.className.indexOf("w3-show") == -1) {
285
                x.className += " w3-show";
286
            }
287
        } else if (getRadioValue('rptType') == 'orderList') {
288
            x = document.getElementById("dlOrderListButton");
289
            if (x.className.indexOf("w3-show") == -1) {
290
                x.className += " w3-show";
291
            }
292
        } else if (getRadioValue('rptType') == 'customerList') {
293
            x = document.getElementById("dlCustomerListButton");
294
            if (x.className.indexOf("w3-show") == -1) {
295
                x.className += " w3-show";
296
            }
297
        }
298
    }
2 - 299
}
300
 
301
function retrieveeBayOrders(pageNumber) {
6 - 302
    var i;
303
    var xml;
304
    var authErrorFlag = false;
2 - 305
 
6 - 306
    if (eBayAuthTokenFlag === false) {
307
        return;
308
    }
2 - 309
 
6 - 310
    var valueStartDate = moment(document.getElementById('startDate').value + " 00:00:00", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
311
    var valueEndDate = moment(document.getElementById('endDate').value + " 23:59:59", "YYYY-MM-DD HH:mm:ss").tz("UTC").toISOString();
2 - 312
 
6 - 313
    var xw = new XMLWriter('UTF-8', '1.0');
314
    var xhr = new XMLHttpRequest();
2 - 315
 
6 - 316
    xw.writeStartDocument();
317
    xw.writeStartElement("GetOrdersRequest");
318
    xw.writeAttributeString('xmlns', 'urn:ebay:apis:eBLBaseComponents');
2 - 319
 
6 - 320
    xw.writeStartElement('RequesterCredentials');
321
    xw.writeElementString('eBayAuthToken', eBayAuthToken);
322
    xw.writeEndElement(); /* RequesterCredentials */
2 - 323
 
6 - 324
    xw.writeElementString('CreateTimeFrom', valueStartDate);
325
    xw.writeElementString('CreateTimeTo', valueEndDate);
2 - 326
 
6 - 327
    xw.writeElementString('IncludeFinalValueFee', 'true');
328
    xw.writeElementString('OrderRole', 'Seller');
329
    xw.writeElementString('OrderStatus', 'All');
2 - 330
 
6 - 331
    xw.writeStartElement('Pagination');
332
    xw.writeElementString('EntriesPerPage', configXmlRequestEntriesPerPage);
333
    xw.writeElementString('PageNumber', pageNumber.toString());
334
    xw.writeEndElement(); /* Pagination */
2 - 335
 
6 - 336
    xw.writeElementString('DetailLevel', 'ReturnAll');
2 - 337
 
6 - 338
    xw.writeElementString('ErrorLanguage', 'en_US');
339
    xw.writeElementString('Version', configeBayTradingVersion);
340
    xw.writeElementString('WarningLevel', configWarningLevel);
2 - 341
 
6 - 342
    xw.writeEndElement(); /* GetOrdersRequest */
343
    xw.writeEndDocument();
2 - 344
 
6 - 345
    xhr.open('POST', configProxyUrl, true);
346
    xhr.setRequestHeader('Content-Type', 'text/xml');
347
    xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
348
    xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
349
    xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'GetOrders');
350
    xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
351
    xhr.setRequestHeader('X-EBAY-API-DEV-NAME', '');
352
    xhr.setRequestHeader('X-EBAY-API-CERT-NAME', '');
353
    xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
2 - 354
 
6 - 355
    xml = xw.flush();
356
    xw.close();
2 - 357
 
6 - 358
    xhr.onload = () => {
12 - 359
        var jsonObj = XMLparse(xhr.responseXML, false);
360
        var obj = jsonObj.GetOrdersResponse;
6 - 361
        var returnCode = obj.Ack;
19 - 362
        var str;
2 - 363
 
6 - 364
        var x = document.getElementById("results");
365
        if (x.className.indexOf("w3-show") == -1) {
366
            x.className += " w3-show";
367
        }
2 - 368
 
6 - 369
        if (obj.Message) {
370
            x.innerHTML += "<p>" + obj.Message + "</p>";
371
        }
2 - 372
 
6 - 373
        if (returnCode == 'Success' || (returnCode == 'Warning' && obj.Errors.ErrorCode == '21917182')) {
374
            if (getRadioValue('rptType') == 'shippingList') {
375
                createShipmentTable(obj, pageNumber);
376
            } else if (getRadioValue('rptType') == 'trackingList') {
377
                createTrackingTable(obj, pageNumber);
378
            } else if (getRadioValue('rptType') == 'customerList') {
379
                createCustomerTable(obj, pageNumber);
380
            } else {
381
                createOrderTable(obj, pageNumber);
382
            }
2 - 383
 
6 - 384
            x.innerHTML += '<p><strong>' + returnCode + ' (Orders ' + pageNumber + ' / ' + obj.PaginationResult.TotalNumberOfPages + ')</strong></p>';
2 - 385
 
6 - 386
            if (getRadioValue('rptType') == 'orderList') {
387
                printSummary();
388
            }
2 - 389
 
6 - 390
            if (obj.HasMoreOrders == 'true') {
391
                ++pagesToProcess;
392
                ++maxPagesToProcess;
393
                updateProgressBar(maxPagesToProcess, pagesProcessed);
394
                retrieveeBayOrders(pageNumber + 1);
395
            }
2 - 396
 
6 - 397
            document.getElementById("logging").innerHTML = html.join('');
398
            --pagesToProcess;
399
            ++pagesProcessed;
400
            updateProgressBar(maxPagesToProcess, pagesProcessed);
401
        } else {
402
            x.className += " process-errors";
19 - 403
            str = "<p><strong>" + returnCode + ":</strong></p>";
2 - 404
 
6 - 405
            var errors = getJsonArray(obj.Errors);
19 - 406
            str += "<p>";
6 - 407
            for (i = 0; i < errors.length; i++) {
19 - 408
                str += errors[i].SeverityCode + " (" + errors[i].ErrorCode + "): " + escapeHtml(errors[i].LongMessage) + "<br/>";
6 - 409
                if (errors[i].LongMessage.includes('Auth')) {
410
                    authErrorFlag = true;
411
                }
412
            }
19 - 413
            str += "</p>";
2 - 414
 
19 - 415
            x.innerHTML += str;
416
 
6 - 417
            if (authErrorFlag === true) {
418
                eBayAuthTokenFlag = false;
419
                x = document.getElementById("login");
420
                if (x.className.indexOf("w3-show") == -1) {
421
                    x.className += " w3-show";
422
                }
423
            }
424
        }
425
    };
2 - 426
 
6 - 427
    xhr.send(xml);
2 - 428
}
429
 
430
function retrieveShopifyOrders(page) {
6 - 431
    var sDate = moment(document.getElementById("startDate").value + " 00:00:00").format("YYYY-MM-DDTHH:mm:ssZ");
432
    var eDate = moment(document.getElementById("endDate").value + " 23:59:59").format("YYYY-MM-DDTHH:mm:ssZ");
2 - 433
 
6 - 434
    var xhttp = new XMLHttpRequest();
435
    xhttp.onreadystatechange = function() {
436
        if (this.readyState == 4 && this.status == 200) {
437
            var json = JSON.parse(this.responseText);
438
            if (json.orders.length > 0) {
439
                retrieveShopifyOrder(json);
440
            } else {
12 - 441
                // xxxxx last steps in the chain
442
                printOrderTotals();
443
                document.getElementById("logging").innerHTML = html.join('');
444
 
139 - 445
                sortTable("orderTable");
12 - 446
                document.getElementById("results").innerHTML += '<p><strong>Retrieving Shipping Costs...</strong></p>';
447
                findShippingCosts();
6 - 448
            }
449
        }
450
    };
2 - 451
 
6 - 452
    xhttp.open("GET", configProxyUrl, true);
453
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + configShopifyOrdersUrl + '?page=' + ((page - 1) * configShopifyOrderLimit) + '&limit=' + configShopifyOrderLimit + '&status=any&created_at_min=' + sDate + '&created_at_max=' + eDate));
454
    xhttp.send();
2 - 455
}
456
 
457
function retrieveShopifyOrder(json) {
6 - 458
    var i, j;
459
    var title;
460
    var quantity;
461
    var itemId;
462
    var trackingNumber;
463
    var trackingStatus;
464
    var shipmentState;
465
    var shipmentDate;
2 - 466
 
6 - 467
    for (i = 0; i < json.orders.length; i++) {
468
        html.push('<tr>');
469
        html.push(tableCell(json.orders[i].created_at.substr(0, 10)));
470
        if (json.orders[i].fulfillment_status !== null) {
471
            html.push(tableCell(json.orders[i].fulfillment_status));
472
        } else {
473
            html.push(tableCell('created'));
474
        }
475
        html.push(tableCell(json.orders[i].id + ' (' + json.orders[i].name + ')'));
2 - 476
 
6 - 477
        title = '';
478
        quantity = '';
479
        itemId = '';
480
        for (j = 0; j < json.orders[i].line_items.length; j++) {
481
            itemsSold++;
482
            if (j > 0) {
483
                title += '<br/>';
484
                quantity += '<br/>';
485
                itemId += '<br/>';
486
            }
487
            title += json.orders[i].line_items[j].title;
488
            quantity += json.orders[i].line_items[j].quantity;
489
            itemId += json.orders[i].line_items[j].product_id === null ? '' : json.orders[i].line_items[j].product_id;
490
        }
2 - 491
 
6 - 492
        html.push(tableCell(title));
493
        html.push(tableCell(itemId));
494
        html.push(tableCell('Shopify'));
495
        html.push(tableCell(quantity));
496
        html.push(tableCell('$' + json.orders[i].total_price_usd));
497
        html.push(tableCell('$0.00'));
498
        html.push(tableCell('N/A'));
499
        html.push(tableCell('$0.00'));
500
        html.push(tableCellLabel('Fee' + json.orders[i].id));
501
        html.push(tableCell(json.orders[i].total_tax));
2 - 502
 
6 - 503
        if (json.orders[i].shipping_address !== undefined) {
504
            shipmentState = json.orders[i].shipping_address.province_code;
505
        } else {
506
            shipmentState = configTaxStateId;
507
        }
508
        html.push(tableCell(shipmentState));
509
        html.push(tableCellLabel('PaidDate' + json.orders[i].id));
510
        html.push(tableCell(json.orders[i].payment_gateway_names !== undefined ? json.orders[i].payment_gateway_names.join(', ') : ''));
511
        html.push(tableCellLabel('TransactionId' + json.orders[i].id));
2 - 512
 
6 - 513
        shipmentDate = '';
514
        trackingNumber = '';
515
        trackingStatus = '';
516
        for (j = 0; j < json.orders[i].fulfillments.length; j++) {
517
            if (j > 0) {
518
                trackingNumber += '<br/>';
519
                trackingStatus += '<br/>';
520
                shipmentDate += '<br/>';
521
            }
2 - 522
 
6 - 523
            if (json.orders[i].fulfillments[j].tracking_number !== null) {
524
                trackingNumber = json.orders[i].fulfillments[j].tracking_company + ' ' + json.orders[i].fulfillments[j].tracking_number;
525
                trackingStatus = json.orders[i].fulfillments[j].shipment_status;
526
                shipmentDate += json.orders[i].fulfillments[j].created_at.substr(0, 10);
527
            }
528
        }
2 - 529
 
6 - 530
        html.push(tableCell(shipmentDate));
531
        html.push(tableCell(trackingNumber));
532
        html.push(tableCell(trackingStatus));
533
        html.push('</tr>');
2 - 534
 
6 - 535
        grossSales += Number(json.orders[i].total_price_usd);
536
    }
2 - 537
 
6 - 538
    // xxxxx last steps in the chain
539
    printOrderTotals();
540
    document.getElementById("logging").innerHTML = html.join('');
2 - 541
 
139 - 542
    sortTable("orderTable");
6 - 543
    document.getElementById("results").innerHTML += '<p><strong>Retrieving Shipping Costs...</strong></p>';
544
    findShippingCosts();
2 - 545
}
546
 
547
function retrieveShopifyShippings(page) {
6 - 548
    var xhttp = new XMLHttpRequest();
549
    xhttp.onreadystatechange = function() {
550
        if (this.readyState == 4 && this.status == 200) {
551
            //window.alert(this.responseText);
552
            var json = JSON.parse(this.responseText);
553
            if (json.orders[0] !== undefined) {
554
                retrieveShopifyShipping(json);
555
            }
2 - 556
 
6 - 557
            // xxxxx last steps in the chain
558
            printShipmentTotals();
559
            document.getElementById("logging").innerHTML = html.join('');
2 - 560
 
139 - 561
            sortTable("shippingTable", true);
6 - 562
            findThumbNails();
563
        }
564
    };
2 - 565
 
6 - 566
    xhttp.open("GET", configProxyUrl, true);
567
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + configShopifyOrdersUrl + '?page=' + ((page - 1) * configShopifyOrderLimit) + '&limit=' + configShopifyOrderLimit + '&fulfillment_status=unshipped'));
568
    xhttp.send();
2 - 569
}
570
 
571
function retrieveShopifyShipping(json) {
6 - 572
    var i;
2 - 573
 
6 - 574
    for (i = 0; i < json.orders.length; i++) {
575
        totalAmount += parseFloat(json.orders[i].total_price);
2 - 576
 
6 - 577
        for (j = 0; j < json.orders[i].line_items.length; j++) {
578
            html.push('<tr>');
2 - 579
 
6 - 580
            html.push(tableCellSKU(json.orders[i].line_items[j].sku, json.orders[i].line_items[j].title));
581
            html.push(tableCell(json.orders[i].line_items[j].quantity));
582
            if (json.orders[i].line_items[j].product_id !== null) {
583
                html.push(tableCellAndLabel(json.orders[i].line_items[j].product_id, 'PictureURL' + json.orders[i].line_items[j].product_id));
584
            } else {
585
                html.push(tableCell(''));
586
            }
587
            html.push(tableCell(json.orders[i].line_items[j].title));
588
            html.push(tableCell(json.orders[i].name));
589
            html.push(tableCellDate(json.orders[i].created_at.substr(0, 10)));
590
            html.push(tableCell('$' + parseFloat(json.orders[i].line_items[j].price).toFixed(2)));
591
            html.push(tableCellHidden('Shopify'));
2 - 592
 
6 - 593
            itemsSold += Number(json.orders[i].line_items[j].quantity);
2 - 594
 
6 - 595
            html.push('</tr>');
596
        }
597
    }
2 - 598
}
599
 
600
function retrieveShopifyTrackings(page) {
6 - 601
    var sDate = moment(document.getElementById("startDate").value + " 00:00:00").format("YYYY-MM-DDTHH:mm:ssZ");
602
    var eDate = moment(document.getElementById("endDate").value + " 23:59:59").format("YYYY-MM-DDTHH:mm:ssZ");
2 - 603
 
6 - 604
    var xhttp = new XMLHttpRequest();
605
    xhttp.onreadystatechange = function() {
606
        if (this.readyState == 4 && this.status == 200) {
607
            //window.alert(this.responseText);
608
            var json = JSON.parse(this.responseText);
609
            if (json.orders[0] !== undefined) {
610
                retrieveShopifyTracking(json);
611
            }
2 - 612
 
6 - 613
            // xxxxx last in the chain
614
            printTrackingTotals();
615
            document.getElementById("logging").innerHTML = html.join('');
139 - 616
            sortTable("trackingTable");
6 - 617
            document.getElementById("results").innerHTML += '<p><strong>Retrieving Shipping Costs...</strong></p>';
618
            findShippingCosts();
619
        }
620
    };
2 - 621
 
6 - 622
    xhttp.open("GET", configProxyUrl, true);
623
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + configShopifyOrdersUrl + '?page=' + ((page - 1) * configShopifyOrderLimit) + '&limit=' + configShopifyOrderLimit + '&fulfillment_status=shipped&status=closed&created_at_min=' + sDate + '&created_at_max=' + eDate));
624
    xhttp.send();
2 - 625
}
626
 
627
function retrieveShopifyTracking(json) {
6 - 628
    var i, j;
629
    var title;
2 - 630
 
6 - 631
    for (i = 0; i < json.orders.length; i++) {
632
        if (json.orders[i].shipping_lines[0] === undefined) {
633
            continue;
634
        }
2 - 635
 
6 - 636
        html.push('<tr>');
637
        html.push(tableCell(json.orders[i].created_at.substr(0, 10)));
2 - 638
 
6 - 639
        title = '';
640
        for (j = 0; j < json.orders[i].line_items.length; j++) {
641
            if (j > 0) {
642
                title += '<br/>';
643
            }
644
            title += json.orders[i].line_items[j].title;
645
        }
2 - 646
 
6 - 647
        html.push(tableCell(title));
648
        html.push(tableCell('N/A'));
649
        html.push(tableCellAndLabel(json.orders[i].shipping_address.city + ', ' + json.orders[i].shipping_address.province_code + ' ' + json.orders[i].shipping_address.zip, 'DeliveryAddress' + json.orders[i].fulfillments[0].tracking_number));
650
        html.push(tableCell(json.orders[i].fulfillments[0].created_at.substr(0, 10))); // best guess
651
        html.push(tableCell(json.orders[i].fulfillments[0].created_at.substr(0, 10)));
652
        html.push(tableCellAndLabel(json.orders[i].fulfillments[0].tracking_company + ' ' + json.orders[i].fulfillments[0].tracking_number, json.orders[i].fulfillments[0].tracking_number));
653
        html.push(tableCell(getCarrierService(json.orders[i].fulfillments[0].tracking_company, json.orders[i].fulfillments[0].tracking_number, true)));
654
        html.push(tableCellLabel('DeliveryDate' + json.orders[i].fulfillments[0].tracking_number));
655
        html.push(tableCellLabel('DeliveryDays' + json.orders[i].fulfillments[0].tracking_number));
656
        html.push(tableCellLabel('DeliveryStatus' + json.orders[i].fulfillments[0].tracking_number));
2 - 657
 
6 - 658
        html.push('</tr>');
659
    }
2 - 660
}
661
 
662
function createOrderTable(obj, pageNumber) {
6 - 663
    var i;
664
    var title;
665
    var trackingNumber;
666
    var quantity;
667
    var finalValueFee;
668
    var finalValueFeeAmount;
669
    var itemId;
670
    var taxAmount;
671
    var payAmount;
2 - 672
 
6 - 673
    if (pageNumber == 1) {
674
        document.getElementById("logging").innerHTML = '';
675
        html = [];
2 - 676
 
30 - 677
        html.push('<div class="border table-responsive">');
6 - 678
        html.push('<h3>Order List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
30 - 679
    	html.push('<table id="orderTable" class="table table-hover table-striped table-bordered small">');
680
        html.push('<thead class="thead-dark">');
6 - 681
        html.push('<tr>');
2 - 682
 
6 - 683
        html.push(tableHeader('Order Date'));
684
        html.push(tableHeader('Order Status'));
685
        html.push(tableHeader('Order Id'));
686
        html.push(tableHeader('Ttitle'));
687
        html.push(tableHeader('Item Id'));
688
        html.push(tableHeader('Sales Channel'));
689
        html.push(tableHeader('Quantity Purchased'));
690
        html.push(tableHeader('Payment Amount'));
691
        html.push(tableHeader('Shipping Received'));
692
        html.push(tableHeader('Shipping Cost'));
693
        html.push(tableHeader('eBay Final Value Fee'));
694
        html.push(tableHeader('Payment Processor Fee'));
695
        html.push(tableHeader('Sales Tax Amount'));
696
        html.push(tableHeader('Ship To State'));
697
        html.push(tableHeader('Paid Date'));
698
        html.push(tableHeader('Payment Methods'));
2 - 699
 
6 - 700
        html.push(tableHeader('Payment Transaction ID'));
701
        html.push(tableHeader('Shipped Date'));
702
        html.push(tableHeader('Shipping Tracking Number'));
703
        html.push(tableHeader('Delivery Status'));
2 - 704
 
6 - 705
        html.push('</tr>');
706
        html.push('</thead>');
707
        html.push('<tbody>');
708
    }
2 - 709
 
6 - 710
    var orders = getJsonArray(obj.OrderArray);
12 - 711
    for (var entry = 0; entry < orders[0].Order.length; entry++) {
712
        var order = orders[0].Order[entry];
713
 
6 - 714
        html.push('<tr>');
2 - 715
 
12 - 716
        html.push(tableCellDate(order.CreatedTime));
717
        html.push(tableCell(order.OrderStatus));
718
        html.push(tableCell(order.OrderID));
2 - 719
 
6 - 720
        title = '';
721
        trackingNumber = '';
722
        quantity = '';
723
        finalValueFee = '';
724
        finalValueFeeAmount = 0.0;
725
        itemId = '';
134 - 726
        taxAmount = 0.0;
2 - 727
 
12 - 728
        var transactions = getJsonArray(orders[0].Order[entry].TransactionArray.Transaction);
6 - 729
        for (i = 0; i < transactions.length; i++) {
730
            itemsSold++;
731
            if (i > 0) {
732
                title += '<br/>';
733
                quantity += '<br/>';
734
                itemId += '<br/>';
735
            }
736
            title += transactions[i].Item.Title;
737
            quantity += transactions[i].QuantityPurchased;
738
            finalValueFeeAmount += parseFloat(transactions[i].FinalValueFee.text);
739
            eBayFees += parseFloat(transactions[i].FinalValueFee.text);
740
            itemId += transactions[i].Item.ItemID;
134 - 741
            if (order.eBayCollectAndRemitTax == "true") {
742
                taxAmount += parseFloat(transactions[i].eBayCollectAndRemitTaxes.TotalTaxAmount.text);
743
            }
6 - 744
        }
745
        html.push(tableCell(title));
746
        html.push(tableCell(itemId));
747
        finalValueFee = '$' + finalValueFeeAmount.toFixed(2);
2 - 748
 
6 - 749
        var trackingDetails = getJsonArray(transactions[0].ShippingDetails.ShipmentTrackingDetails);
750
        for (i = 0; i < trackingDetails.length; i++) {
751
            trackingNumber += (i > 0 ? '<br/>' : '') + trackingDetails[i].ShippingCarrierUsed + ' ' + trackingDetails[i].ShipmentTrackingNumber;
752
        }
2 - 753
 
6 - 754
        html.push(tableCell('eBay'));
755
        html.push(tableCell(quantity));
12 - 756
        html.push(tableCell('$' + parseFloat(order.AmountPaid.text).toFixed(2)));
757
        grossSales += parseFloat(order.AmountPaid.text);
2 - 758
 
12 - 759
        html.push(tableCell('$' + parseFloat(order.ShippingServiceSelected.ShippingServiceCost.text).toFixed(2)));
760
        shippingRcvd += parseFloat(order.ShippingServiceSelected.ShippingServiceCost.text);
2 - 761
 
12 - 762
        html.push(tableCellLabel('ShippingCost' + order.OrderID));
6 - 763
        html.push(tableCell(finalValueFee));
2 - 764
 
12 - 765
        if (order.ExternalTransaction !== undefined && order.ExternalTransaction.FeeOrCreditAmount !== undefined) {
134 - 766
/* bugbug hardcoded 2.7%
12 - 767
            html.push(tableCell('$' + parseFloat(order.ExternalTransaction.FeeOrCreditAmount.text).toFixed(2)));
768
            PayPalFees += parseFloat(order.ExternalTransaction.FeeOrCreditAmount.text);
134 - 769
*/
770
            paymentProcessingFees = parseFloat(order.AmountPaid.text) * 0.027;
771
            html.push(tableCell('$' + parseFloat(paymentProcessingFees).toFixed(2)));
772
            PayPalFees += paymentProcessingFees;
6 - 773
        } else {
774
            html.push(tableCell(''));
775
        }
2 - 776
 
134 - 777
        if (order.eBayCollectAndRemitTax == "true") {
778
            html.push(tableCell('$' + taxAmount.toFixed(2) + '*'));
34 - 779
        } else {
134 - 780
            html.push(tableCell('$0.00'));
6 - 781
        }
34 - 782
 
12 - 783
        html.push(tableCell(order.ShippingAddress.StateOrProvince));
2 - 784
 
12 - 785
        if (order.PaidTime !== undefined) {
786
            html.push(tableCellDate(order.PaidTime));
6 - 787
        } else {
788
            html.push(tableCell(''));
789
        }
134 - 790
        html.push(tableCell(order.CheckoutStatus.PaymentMethod));
2 - 791
 
12 - 792
        if (order.ExternalTransaction !== undefined && order.ExternalTransaction.ExternalTransactionID !== undefined) {
793
            html.push(tableCell(order.ExternalTransaction.ExternalTransactionID));
6 - 794
        } else {
795
            html.push(tableCell(''));
796
        }
2 - 797
 
12 - 798
        if (order.ShippedTime === undefined) {
6 - 799
            html.push(tableCell(''));
800
        } else {
12 - 801
            html.push(tableCellDate(order.ShippedTime));
6 - 802
        }
803
        html.push(tableCell(trackingNumber));
12 - 804
        html.push(tableCellLabel('Delivery' + order.OrderID));
6 - 805
 
806
        html.push('</tr>');
807
    }
2 - 808
}
809
 
810
function printOrderTotals() {
6 - 811
    html.push('</tbody>');
812
    html.push('<tfoot>');
813
    html.push('<tr>');
814
    html.push(tableCell('<strong>Totals</strong>'));
815
    html.push(tableCell(''));
816
    html.push(tableCell(''));
817
    html.push(tableCell(''));
818
    html.push(tableCell(''));
819
    html.push(tableCell(''));
820
    html.push(tableCell('<strong>' + itemsSold + '</strong>'));
821
    html.push(tableCell('<strong>$' + grossSales.toFixed(2) + '</strong>'));
822
    html.push(tableCell('<strong>$' + shippingRcvd.toFixed(2) + '</strong>'));
823
    html.push(tableCellLabel('ShippingTotal'));
824
    html.push(tableCell('<strong>$' + eBayFees.toFixed(2) + '</strong>'));
825
    html.push(tableCell('<strong>$' + PayPalFees.toFixed(2) + '</strong>'));
826
    html.push(tableCell(''));
827
    html.push(tableCell(''));
828
    html.push(tableCell(''));
829
    html.push(tableCell(''));
830
    html.push(tableCell(''));
831
    html.push(tableCell(''));
832
    html.push(tableCell(''));
134 - 833
    html.push(tableCell(''));
6 - 834
    html.push('</tr>');
835
    html.push('</tfoot>');
836
    html.push('</table>');
837
    html.push('</div>');
2 - 838
}
839
 
840
function createCustomerTable(obj, pageNumber) {
6 - 841
    var i;
842
    var firstName;
843
    var lastName;
844
    var emailAddress;
2 - 845
 
6 - 846
    if (pageNumber == 1) {
847
        document.getElementById("logging").innerHTML = '';
848
        html = [];
2 - 849
 
30 - 850
        html.push('<div class="border table-responsive">');
6 - 851
        html.push('<h3>Customer List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
30 - 852
    	html.push('<table id="customerTable" class="table table-hover table-striped table-bordered small">');
853
        html.push('<thead class="thead-dark">');
6 - 854
        html.push('<tr>');
2 - 855
 
6 - 856
        html.push(tableHeader('First Name'));
857
        html.push(tableHeader('Last Name'));
858
        html.push(tableHeader('Email'));
859
        html.push(tableHeader('Company'));
860
        html.push(tableHeader('Address1'));
861
        html.push(tableHeader('Address2'));
862
        html.push(tableHeader('City'));
863
        html.push(tableHeader('Province'));
864
        html.push(tableHeader('Province Code'));
865
        html.push(tableHeader('Country'));
866
        html.push(tableHeader('Country Code'));
867
        html.push(tableHeader('Zip'));
868
        html.push(tableHeader('Phone'));
869
        html.push(tableHeader('Accepts Marketing'));
870
        html.push(tableHeader('Total Spent'));
871
        html.push(tableHeader('Total Orders'));
872
        html.push(tableHeader('Tags'));
873
        html.push(tableHeader('Note'));
874
        html.push(tableHeader('Tax Exempt'));
2 - 875
 
6 - 876
        html.push('</tr>');
877
        html.push('</thead>');
878
        html.push('<tbody>');
879
    }
2 - 880
 
12 - 881
    var orders = getJsonArray(obj.OrderArray.Order);
6 - 882
    for (var entry = 0; entry < orders.length; entry++) {
12 - 883
        var order = obj.OrderArray.Order[entry];
884
 
6 - 885
        html.push('<tr>');
2 - 886
 
6 - 887
        firstName = '';
888
        lastName = '';
889
        emailAddress = '';
2 - 890
 
12 - 891
        var transactions = getJsonArray(order.TransactionArray.Transaction);
6 - 892
        for (i = 0; i < transactions.length; i++) {
893
            firstName = transactions[i].Buyer.UserFirstName;
894
            lastName = transactions[i].Buyer.UserLastName;
895
            emailAddress = transactions[i].Buyer.Email;
896
        }
2 - 897
 
6 - 898
        html.push(tableCell(firstName.toProperCase()));
899
        html.push(tableCell(lastName.toProperCase()));
900
        html.push(tableCell(emailAddress != 'Invalid Request' ? emailAddress : ""));
901
        html.push(tableCell(''));
12 - 902
        html.push(tableCell(order.ShippingAddress.Street1.toProperCase()));
903
        html.push(tableCell(order.ShippingAddress.Street2.toProperCase()));
6 - 904
        html.push(tableCell(orders[entry].ShippingAddress.CityName.toProperCase()));
905
        html.push(tableCell(''));
12 - 906
        html.push(tableCell(order.ShippingAddress.StateOrProvince));
907
        html.push(tableCell(order.ShippingAddress.CountryName.toProperCase()));
908
        html.push(tableCell(order.ShippingAddress.Country));
909
        html.push(tableCell(order.ShippingAddress.PostalCode));
910
        html.push(tableCell(order.ShippingAddress.Phone));
6 - 911
        html.push(tableCell('no'));
912
        html.push(tableCell(''));
913
        html.push(tableCell(''));
914
        html.push(tableCell('ebay'));
12 - 915
        html.push(tableCell(order.BuyerUserID));
6 - 916
        html.push(tableCell('no'));
2 - 917
 
6 - 918
        html.push('</tr>');
919
    }
2 - 920
 
921
 
6 - 922
    if (obj.HasMoreOrders != 'true') {
923
        html.push('</tbody>');
924
        html.push('<tfoot>');
925
        html.push('<tr>');
926
        html.push(tableCell(''));
927
        html.push('</tr>');
928
        html.push('</tfoot>');
929
        html.push('</table>');
930
        html.push('</div>');
931
    }
2 - 932
}
933
 
934
function createShipmentTable(obj, pageNumber) {
34 - 935
    var i, j;
2 - 936
 
6 - 937
    if (pageNumber == 1) {
938
        totalAmount = 0.00;
939
        itemsSold = 0;
2 - 940
 
6 - 941
        document.getElementById("logging").innerHTML = '';
942
        html = [];
2 - 943
 
30 - 944
        html.push('<div class="border table-responsive">');
945
        html.push('<h3>Awaiting Shipments List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
946
    	html.push('<table id="shippingTable" class="table table-hover table-striped table-bordered small">');
947
        html.push('<thead class="thead-dark">');
6 - 948
        html.push('<tr>');
2 - 949
 
6 - 950
        html.push(tableHeader('SKU'));
951
        html.push(tableHeader('Quantity'));
952
        html.push(tableHeader('Thumbnail'));
953
        html.push(tableHeader('Ttitle'));
954
        html.push(tableHeader('Item Id'));
955
        html.push(tableHeader('Date'));
34 - 956
        html.push(tableHeader('Amount'));
6 - 957
        html.push(tableHeaderHidden('Sales Channel'));
2 - 958
 
6 - 959
        html.push('</tr>');
960
        html.push('</thead>');
961
        html.push('<tbody>');
962
    }
2 - 963
 
12 - 964
    var orders = getJsonArray(obj.OrderArray.Order);
6 - 965
    for (var entry = 0; entry < orders.length; entry++) {
966
        if (orders[entry].OrderStatus == 'Completed' && orders[entry].ShippedTime === undefined && orders[entry].PaidTime !== undefined) {
12 - 967
            var transactions = getJsonArray(orders[entry].TransactionArray.Transaction);
6 - 968
            for (i = 0; i < transactions.length; i++) {
969
                itemsSold++;
2 - 970
 
10 - 971
                var title = getJsonValue(transactions[i].Item.Title);
972
                var buyerMessage = getJsonValue(orders[entry].BuyerCheckoutMessage);
973
                if (buyerMessage.length > 0) {
34 - 974
                    var s = buyerMessage.split("|||", 80);
975
                    title += '<br/><br/>Buyer Message: ';
976
                    for (j = 0; j < s.length; j++) {
977
                        title += s[j] + '<br/>';
978
                    }
10 - 979
                }
980
 
6 - 981
                html.push('<tr>');
2 - 982
 
6 - 983
                html.push(tableCellSKU(transactions[i].Item.SKU, transactions[i].Item.Title));
984
                html.push(tableCell(transactions[i].QuantityPurchased));
985
                html.push(tableCellLabel('PictureURL' + transactions[i].Item.ItemID));
10 - 986
                html.push(tableCell(title));
6 - 987
                html.push(tableCell(transactions[i].Item.ItemID));
988
                html.push(tableCellDate(orders[entry].CreatedTime));
10 - 989
                html.push(tableCell('$' + parseFloat(orders[entry].AmountPaid.text).toFixed(2) + (transactions.length > 1 ?'*' : '')));
6 - 990
                if (i === 0) {
991
                    totalAmount += parseFloat(orders[entry].AmountPaid.text);
992
                }
993
                html.push(tableCellHidden('eBay'));
2 - 994
 
6 - 995
                html.push('</tr>');
996
            }
997
        }
998
    }
2 - 999
}
1000
 
1001
function printShipmentTotals() {
6 - 1002
    html.push('</tbody>');
1003
    html.push('<tfoot>');
1004
    html.push('<tr>');
1005
    html.push(tableCell('<strong>Totals</strong>'));
1006
    html.push(tableCell(''));
1007
    html.push(tableCell(''));
1008
    html.push(tableCell(''));
1009
    html.push(tableCell(''));
1010
    html.push(tableCell('<strong>' + itemsSold + '</strong>'));
1011
    html.push(tableCell('<strong>$' + totalAmount.toFixed(2) + '</strong>'));
1012
    html.push(tableCellHidden(''));
1013
    html.push('</tr>');
1014
    html.push('</tfoot>');
1015
    html.push('</table>');
30 - 1016
    html.push('</div');
2 - 1017
}
1018
 
1019
function createTrackingTable(obj, pageNumber) {
6 - 1020
    var i;
1021
    var title;
1022
    var trackingNumber;
1023
    var service;
1024
    var quantity;
1025
    var html_temp;
1026
    var finalValueFee;
1027
    var finalValueFeeAmount;
1028
    var itemId;
2 - 1029
 
6 - 1030
    if (pageNumber == 1) {
1031
        document.getElementById("logging").innerHTML = '';
1032
        html = [];
1033
        trackingList = [];
1034
        trackingListDedupe = [];
2 - 1035
 
30 - 1036
        html.push('<div class="border table-responsive">');
1037
        html.push('<h3>Shipment Tracking List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
1038
    	html.push('<table id="trackingTable" class="table table-hover table-striped table-bordered small">');
1039
        html.push('<thead class="thead-dark">');
6 - 1040
        html.push('<tr>');
2 - 1041
 
6 - 1042
        html.push(tableHeader('Order Date'));
1043
        html.push(tableHeader('Ttitle'));
1044
        html.push(tableHeaderHidden('Order Id'));
1045
        html.push(tableHeader('Shipping Cost'));
1046
        html.push(tableHeader('Shipping Address'));
1047
        html.push(tableHeader('Paid Date'));
1048
        html.push(tableHeader('Shipped Date'));
1049
        html.push(tableHeader('Shipping Tracking Number'));
1050
        html.push(tableHeader('Service'));
1051
        html.push(tableHeader('Delivery Date'));
1052
        html.push(tableHeader('Duration (Days)'));
1053
        html.push(tableHeader('Delivery Status'));
2 - 1054
 
6 - 1055
        html.push('</tr>');
1056
        html.push('</thead>');
1057
        html.push('<tbody>');
1058
    }
2 - 1059
 
12 - 1060
    var orders = getJsonArray(obj.OrderArray.Order);
6 - 1061
    for (var entry = 0; entry < orders.length; entry++) {
1062
        html_temp = [];
36 - 1063
        var order = orders[entry];
2 - 1064
 
6 - 1065
        html_temp.push('<tr>');
2 - 1066
 
12 - 1067
        html_temp.push(tableCellDate(order.CreatedTime));
2 - 1068
 
6 - 1069
        title = '';
1070
        trackingNumber = '';
1071
        service = '';
1072
        quantity = '';
1073
        finalValueFee = '';
1074
        finalValueFeeAmount = 0.0;
1075
        itemId = '';
2 - 1076
 
12 - 1077
        var transactions = getJsonArray(order.TransactionArray.Transaction);
6 - 1078
        for (title = '', i = 0; i < transactions.length; i++) {
1079
            if (i > 0) {
1080
                title += '<br/>';
1081
                quantity += '<br/>';
1082
                itemId += '<br/>';
1083
            }
1084
            title += transactions[i].Item.Title;
1085
        }
1086
        html_temp.push(tableCell(title));
2 - 1087
 
6 - 1088
        var trackingDetails = getJsonArray(transactions[0].ShippingDetails.ShipmentTrackingDetails);
1089
        // only last 1
1090
        for (i = 0; i < trackingDetails.length; i++) {
1091
            trackingNumber = trackingDetails[i].ShippingCarrierUsed + ' ' + trackingDetails[i].ShipmentTrackingNumber;
1092
            service = getCarrierService(trackingDetails[i].ShippingCarrierUsed, trackingDetails[i].ShipmentTrackingNumber, true);
1093
        }
2 - 1094
 
12 - 1095
        html_temp.push(tableCellHidden(order.OrderID));
1096
        html_temp.push(tableCellLabel('ShippingCost' + order.OrderID));
1097
        html_temp.push(tableCellAndLabel(order.ShippingAddress.CityName + ', ' + order.ShippingAddress.StateOrProvince + ' ' + order.ShippingAddress.PostalCode, 'DeliveryAddress' + trackingNumber.substr(trackingNumber.indexOf(' ') + 1)));
2 - 1098
 
12 - 1099
        if (order.PaidTime !== undefined) {
1100
            html_temp.push(tableCellDate(order.PaidTime));
6 - 1101
        } else {
1102
            html_temp.push(tableCell(''));
1103
        }
2 - 1104
 
12 - 1105
        if (order.ShippedTime === undefined) {
6 - 1106
            html_temp.push(tableCellLabel('ShippedDate' + trackingNumber.substr(trackingNumber.indexOf(' ') + 1)));
1107
        } else {
12 - 1108
            html_temp.push(tableCellDate(order.ShippedTime));
6 - 1109
        }
2 - 1110
 
6 - 1111
        html_temp.push(tableCellAndLabel(trackingNumber, trackingNumber.substr(trackingNumber.indexOf(' ') + 1)));
1112
        html_temp.push(tableCell(service));
1113
        html_temp.push(tableCellLabel('DeliveryDate' + trackingNumber.substr(trackingNumber.indexOf(' ') + 1)));
1114
        html_temp.push(tableCellLabel('DeliveryDays' + trackingNumber.substr(trackingNumber.indexOf(' ') + 1)));
1115
        html_temp.push(tableCellLabel('DeliveryStatus' + trackingNumber.substr(trackingNumber.indexOf(' ') + 1)));
2 - 1116
 
6 - 1117
        html_temp.push('</tr>');
1118
 
1119
        if (trackingListDedupe.indexOf(trackingNumber.substr(trackingNumber.indexOf(' ') + 1)) == -1) {
1120
            html.push(html_temp.join(''));
1121
            trackingListDedupe.push(trackingNumber.substr(trackingNumber.indexOf(' ') + 1));
1122
        }
1123
    }
2 - 1124
}
1125
 
1126
function printTrackingTotals() {
6 - 1127
    html.push('</tbody>');
1128
    html.push('<tfoot class="w3-hide">');
1129
    html.push('<tr>');
1130
    html.push(tableCell(''));
1131
    html.push('</tr>');
1132
    html.push('</tfoot>');
1133
    html.push('</table>');
1134
    html.push('</div>');
2 - 1135
}
1136
 
1137
function getCarrierService(carrier, trackingNumber, flag) {
6 - 1138
    if (flag && trackingList.indexOf(trackingNumber) == -1) {
1139
        trackingList.push(trackingNumber);
1140
    }
2 - 1141
 
6 - 1142
    if (carrier == "USPS") {
1143
        if (trackingNumber.startsWith("9449")) {
1144
            return ("Media Mail");
1145
        } else if (trackingNumber.startsWith("9450")) {
1146
            return ("Media Mail, Insured");
1147
        } else if (trackingNumber.startsWith("94001")) {
1148
            return ("First Class");
1149
        } else if (trackingNumber.startsWith("9416")) {
1150
            return ("First Class, Insured");
1151
        } else if (trackingNumber.startsWith("92055")) {
1152
            return ("Priority Mail");
1153
        } else if (trackingNumber.startsWith("94073")) {
1154
            return ("Certified Mail");
1155
        } else if (trackingNumber.startsWith("93033")) {
1156
            return ("Collect on Delivery");
83 - 1157
        } else if (trackingNumber.startsWith("9405")) {
1158
            return ("Regional Box A");
6 - 1159
        } else if (trackingNumber.startsWith("82")) {
1160
            return ("Global Express");
1161
        } else if (trackingNumber.startsWith("EC")) {
1162
            return ("Priority Mail Express International");
97 - 1163
        } else if (trackingNumber.startsWith("92701") || trackingNumber.startsWith("9481") || trackingNumber.startsWith("EA")) {
6 - 1164
            return ("Priority Mail Express");
1165
        } else if (trackingNumber.startsWith("CP")) {
97 - 1166
            return ("Priority Mail International");
6 - 1167
        } else if (trackingNumber.startsWith("92088")) {
1168
            return ("Registered Mail");
1169
        } else if (trackingNumber.startsWith("9461") || trackingNumber.startsWith("9462")) {
1170
            return ("Parcel Select Ground");
1171
        } else if (trackingNumber.startsWith("92021")) {
1172
            return ("Signature Confirmation");
1173
        }
1174
    } else if (carrier == "UPS") {
1175
        if (trackingNumber.startsWith("1Z")) {
1176
            var service = trackingNumber.substr(8, 2);
2 - 1177
 
6 - 1178
            if (service == '01') {
1179
                return ('Next Day Air ("Red")');
1180
            } else if (service == '02') {
1181
                return ('UPS United States Second Day Air ("Blue")');
1182
            } else if (service == '03') {
1183
                return ('Ground');
1184
            } else if (service == '12') {
1185
                return ('Third Day Select');
1186
            } else if (service == '13') {
1187
                return ('Next Day Air Saver ("Red Saver")');
1188
            } else if (service == '15') {
1189
                return ('Next Day Air Early A.M.');
1190
            } else if (service == '22') {
1191
                return ('Ground - Returns Plus - Three Pickup Attempts');
1192
            } else if (service == '32') {
1193
                return ('Next Day Air Early A.M. - COD');
1194
            } else if (service == '33') {
1195
                return ('Next Day Air Early A.M. - Saturday Delivery, COD');
1196
            } else if (service == '41') {
1197
                return ('Next Day Air Early A.M. - Saturday Delivery');
1198
            } else if (service == '42') {
1199
                return ('Ground - Signature Required');
1200
            } else if (service == '44') {
1201
                return ('Next Day Air - Saturday Delivery');
1202
            } else if (service == '66') {
1203
                return ('Worldwide Express');
1204
            } else if (service == '72') {
1205
                return ('Ground - Collect on Delivery');
1206
            } else if (service == '78') {
1207
                return ('Ground - Returns Plus - One Pickup Attempt');
1208
            } else if (service == '90') {
1209
                return ('Ground - Returns - UPS Prints and Mails Label');
1210
            } else if (service == 'A0') {
1211
                return ('Next Day Air Early A.M. - Adult Signature Required');
1212
            } else if (service == 'A1') {
1213
                return ('Next Day Air Early A.M. - Saturday Delivery, Adult Signature Required');
1214
            } else if (service == 'A2') {
1215
                return ('Next Day Air - Adult Signature Required');
1216
            } else if (service == 'A8') {
1217
                return ('Ground - Adult Signature Required');
1218
            } else if (service == 'A9') {
1219
                return ('Next Day Air Early A.M. - Adult Signature Required, COD');
1220
            } else if (service == 'AA') {
1221
                return ('Next Day Air Early A.M. - Saturday Delivery, Adult Signature Required, COD');
1222
            }
1223
        }
1224
    }
2 - 1225
 
6 - 1226
    return ("");
2 - 1227
}
1228
 
1229
function retrieveFees(pageNumber) {
6 - 1230
    var i;
1231
    var xml;
1232
    var authErrorFlag = false;
2 - 1233
 
6 - 1234
    if (eBayAuthTokenFlag === false) {
1235
        return;
1236
    }
2 - 1237
 
6 - 1238
    var valueStartDate = document.getElementById('startDate').value + "T00:00:00.000Z";
1239
    var valueEndDate = document.getElementById('endDate').value + "T23:59:59.999Z";
2 - 1240
 
6 - 1241
    var xw = new XMLWriter('UTF-8', '1.0');
1242
    var xhr = new XMLHttpRequest();
2 - 1243
 
6 - 1244
    xw.writeStartDocument();
1245
    xw.writeStartElement("GetAccountRequest");
1246
    xw.writeAttributeString('xmlns', 'urn:ebay:apis:eBLBaseComponents');
2 - 1247
 
6 - 1248
    xw.writeStartElement('RequesterCredentials');
1249
    xw.writeElementString('eBayAuthToken', eBayAuthToken);
1250
    xw.writeEndElement(); /* RequesterCredentials */
2 - 1251
 
6 - 1252
    xw.writeElementString('AccountEntrySortType', 'AccountEntryCreatedTimeAscending');
1253
    xw.writeElementString('AccountHistorySelection', 'BetweenSpecifiedDates');
1254
    xw.writeElementString('BeginDate', valueStartDate);
1255
    xw.writeElementString('EndDate', valueEndDate);
1256
    xw.writeElementString('ExcludeBalance', 'true');
1257
    xw.writeElementString('ExcludeSummary', 'true');
2 - 1258
 
6 - 1259
    xw.writeStartElement('Pagination');
1260
    xw.writeElementString('EntriesPerPage', configXmlRequestEntriesPerPage);
1261
    xw.writeElementString('PageNumber', pageNumber.toString());
1262
    xw.writeEndElement(); /* Pagination */
2 - 1263
 
6 - 1264
    xw.writeElementString('ErrorLanguage', 'en_US');
1265
    xw.writeElementString('Version', configeBayTradingVersion);
1266
    xw.writeElementString('WarningLevel', configWarningLevel);
2 - 1267
 
6 - 1268
    xw.writeEndElement(); /* GetAccountRequest */
1269
    xw.writeEndDocument();
2 - 1270
 
6 - 1271
    xhr.open('POST', configProxyUrl, true);
1272
    xhr.setRequestHeader('Content-Type', 'text/xml');
1273
    xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
1274
    xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
1275
    xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'GetAccount');
1276
    xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
1277
    xhr.setRequestHeader('X-EBAY-API-DEV-NAME', '');
1278
    xhr.setRequestHeader('X-EBAY-API-CERT-NAME', '');
1279
    xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
2 - 1280
 
6 - 1281
    xml = xw.flush();
1282
    xw.close();
2 - 1283
 
6 - 1284
    xhr.onload = () => {
12 - 1285
        var jsonObj = XMLparse(xhr.responseXML, false);
1286
        var obj = jsonObj.GetAccountResponse;
6 - 1287
        var returnCode = obj.Ack;
19 - 1288
        var str;
2 - 1289
 
6 - 1290
        var x = document.getElementById("results");
1291
        if (x.className.indexOf("w3-show") == -1) {
1292
            x.className += " w3-show";
1293
        }
2 - 1294
 
6 - 1295
        if (obj.Message) {
1296
            x.innerHTML += "<p>" + obj.Message + "</p>";
1297
        }
2 - 1298
 
6 - 1299
        if (returnCode == 'Success' || (returnCode == 'Warning' && obj.Errors.ErrorCode == '21917182')) {
1300
            createFeeTable(obj, pageNumber);
2 - 1301
 
12 - 1302
            x.innerHTML += '<p><strong>' + returnCode + ' (Fees/Credits ' + pageNumber + ' / ' + obj.PaginationResult.TotalNumberOfPages + ')</strong></p>';
2 - 1303
 
6 - 1304
            if (obj.HasMoreEntries == 'true') {
1305
                ++pagesToProcess;
1306
                ++maxPagesToProcess;
1307
                updateProgressBar(maxPagesToProcess, pagesProcessed);
1308
                retrieveFees(pageNumber + 1);
1309
            }
2 - 1310
 
6 - 1311
            document.getElementById("logging").innerHTML = html.join('');
2 - 1312
 
6 - 1313
            --pagesToProcess;
1314
            ++pagesProcessed;
1315
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1316
        } else {
1317
            x.className += " process-errors";
19 - 1318
            str = "<p><strong>" + returnCode + ":</strong></p>";
2 - 1319
 
6 - 1320
            var errors = getJsonArray(obj.Errors);
19 - 1321
            str += "<p>";
6 - 1322
            for (i = 0; i < errors.length; i++) {
19 - 1323
                str += errors[i].SeverityCode + " (" + errors[i].ErrorCode + "): " + escapeHtml(errors[i].LongMessage) + "<br/>";
6 - 1324
                if (errors[i].LongMessage.includes('Auth')) {
1325
                    authErrorFlag = true;
1326
                }
1327
            }
19 - 1328
            str += "</p>";
2 - 1329
 
19 - 1330
            x.innerHTML += str;
1331
 
6 - 1332
            if (authErrorFlag === true) {
1333
                eBayAuthTokenFlag = false;
1334
                x = document.getElementById("login");
1335
                if (x.className.indexOf("w3-show") == -1) {
1336
                    x.className += " w3-show";
1337
                }
1338
            }
2 - 1339
 
6 - 1340
            --pagesToProcess;
1341
            ++pagesProcessed;
1342
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1343
        }
1344
    };
2 - 1345
 
6 - 1346
    xhr.send(xml);
2 - 1347
 
6 - 1348
    function checkpagesToProcess() {
1349
        if (pagesToProcess > 0) {
1350
            window.setTimeout(checkpagesToProcess, 100); // wait 100 milliseconds
1351
        } else {
139 - 1352
            sortTable("feeTable");
6 - 1353
            x = document.getElementById("results");
1354
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
2 - 1355
 
6 - 1356
            endProgressBar();
1357
 
1358
            var y = document.getElementById("dlFeeListButton");
1359
            if (y.className.indexOf("w3-show") == -1) {
1360
                y.className += " w3-show";
1361
            }
1362
 
1363
            if (!x.className.includes("process-errors")) {
1364
                setTimeout(function() {
1365
                    x.className = x.className.replace(" w3-show", "");
1366
                }, 3000);
1367
            }
1368
        }
1369
    }
1370
 
1371
    if (pageNumber == 1) {
1372
        checkpagesToProcess();
1373
    }
2 - 1374
}
1375
 
1376
function createFeeTable(obj, pageNumber) {
6 - 1377
    var i;
2 - 1378
 
6 - 1379
    if (pageNumber == 1) {
1380
        totalAmount = 0;
2 - 1381
 
6 - 1382
        document.getElementById("logging").innerHTML = '';
1383
        html = [];
30 - 1384
        html.push('<div class="border table-responsive">');
6 - 1385
        html.push('<h3>Fees and Credits List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
30 - 1386
    	html.push('<table id="feeTable" class="table table-hover table-striped table-bordered small">');
1387
        html.push('<thead class="thead-dark">');
6 - 1388
        html.push('<tr>');
2 - 1389
 
6 - 1390
        html.push(tableHeader('Item ID'));
1391
        html.push(tableHeader('Title'));
1392
        html.push(tableHeader('Date'));
1393
        html.push(tableHeader('Fee Type'));
1394
        html.push(tableHeader('Amount'));
2 - 1395
 
6 - 1396
        html.push('</tr>');
1397
        html.push('</thead>');
1398
        html.push('<tbody>');
1399
    }
2 - 1400
 
12 - 1401
    for (i = 0; i < obj.AccountEntries.AccountEntry.length; i++) {
1402
        var AccountEntry = obj.AccountEntries.AccountEntry[i];
1403
        if ((!AccountEntry.Description.includes('Payment') && !AccountEntry.Description.includes('Final Value Fee') && AccountEntry.GrossDetailAmount.text != '0.0' && AccountEntry.NetDetailAmount.text != '0.0') ||
1404
            (AccountEntry.Description.includes('Final Value Fee') && AccountEntry.NetDetailAmount.text.substr(0, 1) == '-')) {
6 - 1405
            html.push('<tr>');
2 - 1406
 
12 - 1407
            html.push(tableCell(AccountEntry.ItemID));
1408
            html.push(tableCell(AccountEntry.Title));
1409
            html.push(tableCellDate(AccountEntry.Date));
1410
            html.push(tableCell(AccountEntry.Description));
1411
            html.push(tableCell('$' + parseFloat(AccountEntry.GrossDetailAmount.text).toFixed(2)));
1412
            totalAmount += parseFloat(AccountEntry.GrossDetailAmount.text);
2 - 1413
 
6 - 1414
            html.push('</tr>');
1415
        }
1416
    }
2 - 1417
 
6 - 1418
    if (obj.HasMoreEntries != 'true') {
1419
        html.push('</tbody>');
1420
        html.push('<tfoot>');
1421
        html.push('<tr>');
1422
        html.push(tableCell('<strong>Totals</strong>'));
1423
        html.push(tableCell(''));
1424
        html.push(tableCell(''));
1425
        html.push(tableCell(''));
1426
        html.push(tableCell('<strong>$' + totalAmount.toFixed(2) + '</strong>'));
1427
        html.push('</tr>');
1428
        html.push('</tfoot>');
1429
        html.push('</table>');
30 - 1430
        html.push('</div>');
6 - 1431
    }
2 - 1432
}
1433
 
1434
 
1435
function tableCellDate(utcDate) {
6 - 1436
    var localDate = new Date(utcDate);
1437
    return ('<td>' + localDate.yyyymmdd() + '</td>');
2 - 1438
}
1439
 
1440
function tableCellSKU(str, title) {
6 - 1441
    if (str === undefined) {
1442
        str = '';
1443
    }
2 - 1444
 
6 - 1445
    if (str.indexOf(" - ") > 0) {
1446
        str = str.substr(0, str.indexOf(" - "));
1447
    }
2 - 1448
 
139 - 1449
    if (str.startsWith("Batch") && !isNaN(str.substr(6))) {
6 - 1450
        var batchNo = Number(str.substr(6));
1451
        str = "Batch " + pad(batchNo, 2);
1452
    }
2 - 1453
 
6 - 1454
    if (title.includes('(DVD') || title.includes('(HD') || title.includes('(Blu')) {
1455
        str = 'DVD ' + str;
1456
    } else if (title.includes('(CD')) {
1457
        str = 'CD ' + str;
1458
    } else if (title.includes('Hardcover') || title.includes('Paperback')) {
1459
        str = 'Book ' + str;
1460
    }
2 - 1461
 
6 - 1462
    return ('<td>' + str + '</td>');
2 - 1463
}
1464
 
17 - 1465
function retrieveCancelReturn(pageNumber) {
1466
    if (eBayAuthTokenFlag === false) {
1467
        return;
1468
    }
1469
 
1470
    var valueStartDate = document.getElementById('startDate').value + "T00:00:00.000Z";
1471
    var valueEndDate = document.getElementById('endDate').value + "T23:59:59.999Z";
1472
 
1473
    url = configeBayPostOrder + "/return/search?";
1474
    url += "creation_date_range_from=" + valueStartDate;
1475
    url += "&creation_date_range_to=" + valueEndDate;
1476
    url += "&return_state=CLOSED";
1477
 
1478
    var xhttp = new XMLHttpRequest();
1479
 
1480
    xhttp.onreadystatechange = function() {
1481
        if (this.readyState == 4) {
1482
            var obj = JSON.parse(this.responseText);
30 - 1483
 
17 - 1484
            createCancelReturnTable(obj, pageNumber, true);
1485
 
1486
            if (obj.paginationOutput.totalPages > pageNumber) {
1487
                ++pagesToProcess;
1488
                ++maxPagesToProcess;
1489
                updateProgressBar(maxPagesToProcess, pagesProcessed);
1490
                retrieveCancelReturn(pageNumber + 1);
1491
            }
1492
 
1493
            document.getElementById("logging").innerHTML = html.join('');
1494
 
1495
            --pagesToProcess;
1496
            ++pagesProcessed;
1497
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1498
        }
1499
    };
1500
 
1501
    xhttp.open("GET", configProxyUrl, true);
1502
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
1503
    xhttp.setRequestHeader("X-Authorization", "TOKEN " + eBayAuthToken);
1504
    xhttp.setRequestHeader("Content-Type", "application/json");
1505
    xhttp.setRequestHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
1506
    xhttp.send();
1507
 
1508
    function checkpagesToProcess() {
1509
        if (pagesToProcess > 0) {
1510
            window.setTimeout(checkpagesToProcess, 100); // wait 100 milliseconds
1511
        } else {
1512
            endProgressBar();
1513
 
1514
            pagesToProcess = 1;
1515
            maxPagesToProcess = 1;
1516
            pagesProcessed = 0;
1517
            initProgressBar("Retrieving Cancellations...");
1518
 
1519
            retrieveCancel(1);
1520
        }
1521
    }
1522
 
1523
    if (pageNumber == 1) {
1524
        checkpagesToProcess();
1525
    }
1526
}
1527
 
1528
function retrieveCancel(pageNumber) {
1529
    if (eBayAuthTokenFlag === false) {
1530
        return;
1531
    }
1532
 
1533
    var valueStartDate = document.getElementById('startDate').value + "T00:00:00.000Z";
1534
    var valueEndDate = document.getElementById('endDate').value + "T23:59:59.999Z";
1535
 
1536
    url = configeBayPostOrder + "/cancellation/search?";
1537
    url += "creation_date_range_from=" + valueStartDate;
1538
    url += "&creation_date_range_to=" + valueEndDate;
1539
    url += "&return_state=CLOSED";
1540
 
1541
    var xhttp = new XMLHttpRequest();
1542
 
1543
    xhttp.onreadystatechange = function() {
1544
        if (this.readyState == 4) {
1545
            var obj = JSON.parse(this.responseText);
30 - 1546
 
17 - 1547
            createCancelReturnTable(obj, pageNumber, false);
1548
 
1549
            if (obj.paginationOutput.totalPages > pageNumber) {
1550
                ++pagesToProcess;
1551
                ++maxPagesToProcess;
1552
                updateProgressBar(maxPagesToProcess, pagesProcessed);
1553
                retrieveCancel(pageNumber + 1);
1554
            }
1555
 
1556
            document.getElementById("logging").innerHTML = html.join('');
1557
 
1558
            --pagesToProcess;
1559
            ++pagesProcessed;
1560
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1561
        }
1562
    };
1563
 
1564
    xhttp.open("GET", configProxyUrl, true);
1565
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
1566
    xhttp.setRequestHeader("X-Authorization", "TOKEN " + eBayAuthToken);
1567
    xhttp.setRequestHeader("Content-Type", "application/json");
1568
    xhttp.setRequestHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
1569
    xhttp.send();
1570
 
1571
    function checkpagesToProcess() {
1572
        if (pagesToProcess > 0) {
1573
            window.setTimeout(checkpagesToProcess, 100); // wait 100 milliseconds
1574
        } else {
139 - 1575
            sortTable("cancelReturnTable");
17 - 1576
            x = document.getElementById("results");
1577
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1578
 
1579
            endProgressBar();
1580
 
1581
            var y = document.getElementById("dlCancelReturnListButton");
1582
            if (y.className.indexOf("w3-show") == -1) {
1583
                y.className += " w3-show";
1584
            }
1585
 
1586
            if (!x.className.includes("process-errors")) {
1587
                setTimeout(function() {
1588
                    x.className = x.className.replace(" w3-show", "");
1589
                }, 3000);
1590
            }
1591
        }
1592
    }
1593
 
1594
    if (pageNumber == 1) {
1595
        checkpagesToProcess();
1596
    }
1597
}
1598
function createCancelReturnTable(obj, pageNumber, flag) {
1599
    var i;
1600
 
1601
    if (pageNumber == 1 && flag) {
1602
        totalAmount = 0;
1603
 
1604
        document.getElementById("logging").innerHTML = '';
1605
        html = [];
1606
 
30 - 1607
        html.push('<div class="border table-responsive">');
17 - 1608
        html.push('<h3>Cancellations and Returns List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
30 - 1609
    	html.push('<table id="cancelReturnTable" class="table table-hover table-striped table-bordered small">');
1610
        html.push('<thead class="thead-dark">');
17 - 1611
        html.push('<tr>');
1612
 
1613
        html.push(tableHeader('Item ID'));
1614
        html.push(tableHeader('Date'));
1615
        html.push(tableHeader('Reason'));
1616
        html.push(tableHeader('Status'));
1617
        html.push(tableHeader('Amount'));
1618
 
1619
        html.push('</tr>');
1620
        html.push('</thead>');
1621
        html.push('<tbody>');
1622
    }
1623
 
1624
    if (flag) {
1625
        for (i = 0; obj.members !== undefined && i < obj.members.length; i++) {
1626
            var returnEntry = obj.members[i];
1627
            html.push('<tr>');
1628
 
1629
            html.push(tableCell(returnEntry.creationInfo.item.itemId));
1630
            html.push(tableCellDate(returnEntry.creationInfo.creationDate.value.substr(0,10)));
1631
            html.push(tableCell(returnEntry.creationInfo.type + ' / ' + returnEntry.creationInfo.reason));
1632
            html.push(tableCell(returnEntry.status));
1633
            html.push(tableCell('$' + parseFloat(returnEntry.sellerTotalRefund.actualRefundAmount.value).toFixed(2)));
1634
            totalAmount += parseFloat(returnEntry.sellerTotalRefund.actualRefundAmount.value);
1635
 
1636
            html.push('</tr>');
1637
        }
1638
    } else{
1639
        for (i = 0; obj.cancellations !== undefined && i < obj.cancellations.length; i++) {
1640
            var cancelEntry = obj.cancellations[i];
30 - 1641
 
17 - 1642
            if (cancelEntry.cancelStatus == 'CANCEL_CLOSED_WITH_REFUND') {
1643
                html.push('<tr>');
1644
 
1645
                html.push(tableCell(cancelEntry.legacyOrderId.substr(0, cancelEntry.legacyOrderId.indexOf('-'))));
1646
                html.push(tableCellDate(cancelEntry.cancelCloseDate.value.substr(0,10)));
1647
                html.push(tableCell(cancelEntry.requestorType + ' / ' + cancelEntry.cancelCloseReason));
1648
                html.push(tableCell(cancelEntry.cancelStatus));
1649
                html.push(tableCell('$' + parseFloat(cancelEntry.requestRefundAmount.value).toFixed(2)));
1650
                totalAmount += parseFloat(cancelEntry.requestRefundAmount.value);
1651
 
1652
                html.push('</tr>');
1653
            }
1654
        }
1655
    }
1656
 
1657
    if (!flag) {
1658
        if (obj.HasMoreEntries != 'true') {
1659
            html.push('</tbody>');
1660
            html.push('<tfoot>');
1661
            html.push('<tr>');
1662
            html.push(tableCell('<strong>Totals</strong>'));
1663
            html.push(tableCell(''));
1664
            html.push(tableCell(''));
1665
            html.push(tableCell(''));
1666
            html.push(tableCell('<strong>$' + totalAmount.toFixed(2) + '</strong>'));
1667
            html.push('</tr>');
1668
            html.push('</tfoot>');
1669
            html.push('</table>');
30 - 1670
            html.push('</div>');
17 - 1671
        }
1672
    }
1673
}
1674
 
139 - 1675
function sortTable(tableName, stringSortFlag = false){
1676
    var tbl = document.getElementById(tableName).tBodies[0];
1677
    var sortnr;
1678
    var store = [];
1679
    for (var i = 0, len = tbl.rows.length; i < len; i++) {
1680
        var row = tbl.rows[i];
1681
        if (stringSortFlag) {
1682
            sortnr = row.cells[0].textContent || row.cells[0].innerText;
1683
            store.push([sortnr, row]);
1684
        } else {
1685
            sortnr = parseInt(row.cells[0].textContent || row.cells[0].innerText);
1686
            if(!isNaN(sortnr)) store.push([sortnr, row]);
6 - 1687
        }
139 - 1688
    }
1689
    store.sort(function(x,y){
1690
        if (stringSortFlag) {
1691
            return x[0] > y[0];
1692
        } else {
1693
            return x[0] - y[0];
6 - 1694
        }
139 - 1695
    });
1696
    for(var i=0, len=store.length; i<len; i++){
1697
        tbl.appendChild(store[i][1]);
6 - 1698
    }
139 - 1699
    store = null;
2 - 1700
}
1701
 
1702
function printData() {
6 - 1703
    var printContent = document.getElementById("printTable");
2 - 1704
 
6 - 1705
    var num;
1706
    var cssReference = [];
1707
    var uniqueName = new Date();
2 - 1708
 
6 - 1709
    var windowName = 'Print' + uniqueName.getTime();
1710
    var printWindow = window.open(num, windowName, 'left=50000,top=50000,width=0,height=0');
1711
    cssReference[0] = printWindow.document.createElement("link");
30 - 1712
    cssReference[0].href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css";
6 - 1713
    cssReference[0].rel = "stylesheet";
1714
    cssReference[0].type = "text/css";
1715
    cssReference[1] = printWindow.document.createElement("link");
1716
    cssReference[1].href = "css/style.css";
1717
    cssReference[1].rel = "stylesheet";
1718
    cssReference[1].type = "text/css";
2 - 1719
 
34 - 1720
    printWindow.document.write(printContent.outerHTML.replace("table-bordered", "").replace("table-striped", "").replace("table-hover", ""));
6 - 1721
    printWindow.document.getElementsByTagName('head')[0].appendChild(cssReference[0]);
1722
    printWindow.document.getElementsByTagName('head')[0].appendChild(cssReference[1]);
2 - 1723
 
6 - 1724
    printWindow.document.close();
1725
    printWindow.focus();
1726
    printWindow.print();
1727
    printWindow.close();
2 - 1728
}
1729
 
1730
function printSummary() {
134 - 1731
    var profit = grossSales + shippingRcvd - shippingCost - eBayFees - PayPalFees;
2 - 1732
 
30 - 1733
    document.getElementById("summary").innerHTML = '<h2>Profit: ' + profit.toFixed(2) + '</h3>';
2 - 1734
}
1735
 
1736
function findThumbNails() {
6 - 1737
    var i;
1738
    var x = document.getElementById("shippingTable");
2 - 1739
 
6 - 1740
    thumbnailsToProcess = 0;
1741
    thumbnailsProcessed = 0;
1742
    maxThumbnailsToProcess = 0;
1743
    initProgressBar("");
2 - 1744
 
6 - 1745
    for (i = 1; i < (x.rows.length - 1); i++) {
1746
        if (x.rows[i].cells[7].innerHTML == 'eBay' && x.rows[i].cells[2] !== undefined && x.rows[i].cells[2].innerHTML.length < 1) {
1747
            ++thumbnailsToProcess;
1748
            ++maxThumbnailsToProcess;
1749
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1750
            getThumbNail(x.rows[i].cells[4].innerHTML);
1751
        } else if (x.rows[i].cells[7].innerHTML == 'Shopify' && x.rows[i].cells[2] !== undefined && x.rows[i].cells[2].innerHTML.length > 0) {
1752
            ++thumbnailsToProcess;
1753
            ++maxThumbnailsToProcess;
1754
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1755
            getShopifyThumbNail(x.rows[i].cells[2].innerHTML);
1756
        }
1757
    }
2 - 1758
 
6 - 1759
    function checkthumbnailsToProcess() {
1760
        if (thumbnailsToProcess > 0) {
1761
            window.setTimeout(checkthumbnailsToProcess, 100); // wait 100 milliseconds
1762
        } else {
1763
            endProgressBar();
1764
            x = document.getElementById("results");
1765
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1766
            if (!x.className.includes("process-errors")) {
1767
                setTimeout(function() {
1768
                    x.className = x.className.replace(" w3-show", "");
1769
                }, 3000);
1770
            }
1771
        }
1772
    }
2 - 1773
 
6 - 1774
    checkthumbnailsToProcess();
2 - 1775
}
1776
 
1777
function getThumbNail(itemId) {
6 - 1778
    // Construct the getSingleItem request
1779
    url = configeBayShopping + "?";
1780
    url += "callname=GetSingleItem";
1781
    url += "&responseencoding=JSON";
1782
    url += "&appid=" + configAppid;
1783
    url += "&version=" + configeBayShoppingVersion;
1784
    url += "&ItemID=";
1785
    url += itemId;
2 - 1786
 
6 - 1787
    var xhttp = new XMLHttpRequest();
2 - 1788
 
6 - 1789
    xhttp.onreadystatechange = function() {
1790
        if (this.readyState == 4) {
1791
            _cb_getThumbNail(JSON.parse(this.responseText));
1792
        }
1793
    };
2 - 1794
 
6 - 1795
    xhttp.open("GET", configProxyUrl, true);
1796
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
1797
    xhttp.send();
2 - 1798
}
1799
 
1800
function _cb_getThumbNail(root) {
6 - 1801
    var ack = root.Ack;
2 - 1802
 
6 - 1803
    if (ack == 'Failure' || ack == 'PartialFailure') {
1804
        return;
1805
    }
2 - 1806
 
6 - 1807
    var JsonObj = typeof root.Item != 'object' ? JSON.parse(root.Item) : root.Item;
1808
    var ItemID = JsonObj.ItemID;
1809
    var PictureURL = getJsonArray(JsonObj.PictureURL);
2 - 1810
 
6 - 1811
    document.getElementById('PictureURL' + ItemID).innerHTML = '<img src="' + PictureURL[0] + '" style="max-height:100px">';
1812
    --thumbnailsToProcess;
1813
    ++thumbnailsProcessed;
1814
    updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
2 - 1815
}
1816
 
1817
function getShopifyThumbNail(productId) {
6 - 1818
    var xhttp = new XMLHttpRequest();
1819
    xhttp.onreadystatechange = function() {
1820
        if (this.readyState == 4 && this.status == 200) {
1821
            //window.alert(this.responseText);
1822
            var json = JSON.parse(this.responseText);
1823
            if (json.product !== undefined) {
1824
                document.getElementById('PictureURL' + productId).innerHTML = '<img src="' + json.product.image.src + '" style="max-height:100px">';
1825
            }
1826
            --thumbnailsToProcess;
1827
            ++thumbnailsProcessed;
1828
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1829
        }
1830
    };
2 - 1831
 
6 - 1832
    xhttp.open("GET", configProxyUrl, true);
1833
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + 'products/' + productId + '.json?fields=image'));
1834
    xhttp.send();
2 - 1835
}
1836
 
1837
function findShippingCosts() {
6 - 1838
    var i;
1839
    var x;
2 - 1840
 
6 - 1841
    shippingsToProcess = 0;
1842
    shippingsProcessed = 0;
1843
    maxShippingsToProcess = 0;
1844
    initProgressBar("Retrieving Shipping Costs...");
2 - 1845
 
6 - 1846
    if (getRadioValue('rptType') == 'trackingList') {
1847
        x = document.getElementById("trackingTable");
1848
    } else {
1849
        x = document.getElementById("orderTable");
1850
    }
2 - 1851
 
6 - 1852
    for (i = (x.rows.length - 1); i > 0; i--) {
1853
        if (getRadioValue('rptType') == 'trackingList') {
1854
            if (x.rows[i].cells[3] !== undefined && x.rows[i].cells[3].innerHTML.length < 1) {
1855
                if (x.rows[i].cells[7] !== undefined && x.rows[i].cells[7].innerHTML.length < 1) {
1856
                    document.getElementById("trackingTable").deleteRow(i);
1857
                } else {
1858
                    ++shippingsToProcess;
1859
                    ++maxShippingsToProcess;
1860
                    updateProgressBar(maxShippingsToProcess, shippingsProcessed);
1861
                    getShippingCost(x.rows[i].cells[2].innerHTML);
1862
                }
1863
            }
1864
        } else {
1865
            if (x.rows[i].cells[5].innerHTML == 'eBay' && x.rows[i].cells[9] !== undefined && x.rows[i].cells[9].innerHTML.length < 1) {
1866
                ++shippingsToProcess;
1867
                ++maxShippingsToProcess;
1868
                updateProgressBar(maxShippingsToProcess, shippingsProcessed);
1869
                getShippingCost(x.rows[i].cells[2].innerHTML);
1870
            } else if (x.rows[i].cells[5].innerHTML == 'Shopify') {
1871
                ++shippingsToProcess;
1872
                ++maxShippingsToProcess;
1873
                updateProgressBar(maxShippingsToProcess, shippingsProcessed);
1874
                getPaymentTransaction(x.rows[i].cells[2].innerHTML);
1875
            }
1876
        }
1877
    }
2 - 1878
 
6 - 1879
    function checkshippingsToProcess() {
1880
        if (shippingsToProcess > 0) {
1881
            window.setTimeout(checkshippingsToProcess, 100); // wait 100 milliseconds
1882
        } else {
1883
            endProgressBar();
1884
            x = document.getElementById("results");
1885
            if (getRadioValue('rptType') != 'trackingList') {
1886
                document.getElementById("ShippingTotal").innerHTML = '<strong>$' + shippingCost.toFixed(2) + '</strong>';
1887
                x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1888
                if (!x.className.includes("process-errors")) {
1889
                    setTimeout(function() {
1890
                        x.className = x.className.replace(" w3-show", "");
1891
                    }, 3000);
1892
                }
1893
            } else {
1894
                x.innerHTML += '<p><strong>Retrieving Carrier Tracking...</strong></p>';
1895
                getTrackingDetails();
1896
            }
1897
        }
1898
    }
1899
 
1900
    checkshippingsToProcess();
2 - 1901
}
1902
 
1903
function getShippingCost(OrderId) {
6 - 1904
    var i;
1905
    var xml;
1906
    var correlationId;
1907
    var shippingCostStr;
1908
    var deliveryStatus;
1909
    var authErrorFlag = false;
2 - 1910
 
6 - 1911
    var xw = new XMLWriter('UTF-8', '1.0');
1912
    var xhr = new XMLHttpRequest();
2 - 1913
 
6 - 1914
    xw.writeStartDocument();
1915
    xw.writeStartElement("GetSellingManagerSaleRecordRequest");
1916
    xw.writeAttributeString('xmlns', 'urn:ebay:apis:eBLBaseComponents');
2 - 1917
 
6 - 1918
    xw.writeStartElement('RequesterCredentials');
1919
    xw.writeElementString('eBayAuthToken', eBayAuthToken);
1920
    xw.writeEndElement(); /* RequesterCredentials */
2 - 1921
 
6 - 1922
    xw.writeElementString('OrderID', OrderId);
1923
    xw.writeElementString('MessageID', OrderId);
2 - 1924
 
6 - 1925
    xw.writeElementString('ErrorLanguage', 'en_US');
1926
    xw.writeElementString('Version', configeBayTradingVersion);
1927
    xw.writeElementString('WarningLevel', configWarningLevel);
2 - 1928
 
6 - 1929
    xw.writeEndElement(); /* GetSellingManagerSaleRecordRequest */
1930
    xw.writeEndDocument();
2 - 1931
 
6 - 1932
    xhr.open('POST', configProxyUrl, true);
1933
    xhr.setRequestHeader('Content-Type', 'text/xml');
1934
    xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
1935
    xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
1936
    xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'GetSellingManagerSaleRecord');
1937
    xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
1938
    xhr.setRequestHeader('X-EBAY-API-DEV-NAME', '');
1939
    xhr.setRequestHeader('X-EBAY-API-CERT-NAME', '');
1940
    xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
2 - 1941
 
6 - 1942
    xml = xw.flush();
1943
    xw.close();
2 - 1944
 
6 - 1945
    xhr.onload = () => {
12 - 1946
        var jsonObj = XMLparse(xhr.responseXML, false);
1947
        var obj = jsonObj.GetSellingManagerSaleRecordResponse;
6 - 1948
        var returnCode = obj.Ack;
19 - 1949
        var str;
2 - 1950
 
6 - 1951
        var x = document.getElementById("results");
1952
        if (x.className.indexOf("w3-show") == -1) {
1953
            x.className += " w3-show";
1954
        }
2 - 1955
 
6 - 1956
        if (obj.Message) {
1957
            x.innerHTML += "<p>" + obj.Message + "</p>";
1958
        }
2 - 1959
 
6 - 1960
        if (returnCode == 'Success' || (returnCode == 'Warning' && obj.Errors.ErrorCode == '21917182')) {
1961
            correlationId = obj.CorrelationID;
1962
            deliveryStatus = '';
1963
            shippingCostStr = '';
2 - 1964
 
6 - 1965
            if (obj.SellingManagerSoldOrder.ActualShippingCost !== undefined &&
1966
                obj.SellingManagerSoldOrder.ActualShippingCost.text != '0.0' &&
1967
                document.getElementById('ShippingCost' + correlationId).innerHTML.length < 1) {
1968
                shippingCostStr = '$' + parseFloat(obj.SellingManagerSoldOrder.ActualShippingCost.text).toFixed(2);
1969
                shippingCost += parseFloat(obj.SellingManagerSoldOrder.ActualShippingCost.text);
1970
                document.getElementById('ShippingCost' + correlationId).innerHTML = shippingCostStr;
1971
                if (getRadioValue('rptType') == 'orderList') {
1972
                    printSummary();
1973
                }
1974
            }
2 - 1975
 
6 - 1976
            if (getRadioValue('rptType') != 'trackingList') {
1977
                var soldTransactions = getJsonArray(obj.SellingManagerSoldOrder.SellingManagerSoldTransaction);
1978
                for (i = 0; i < soldTransactions.length; i++) {
97 - 1979
                    if (soldTransactions[i].Shipment !== undefined && soldTransactions[i].Shipment.DeliveryStatus !== undefined) {
6 - 1980
                        deliveryStatus += (i > 0 ? '<br/>' : '') + soldTransactions[i].Shipment.DeliveryStatus;
1981
                    }
1982
                }
1983
                document.getElementById('Delivery' + correlationId).innerHTML = deliveryStatus;
1984
            }
1985
        } else {
1986
            x.className += " process-errors";
19 - 1987
            str = "<p><strong>" + returnCode + ":</strong></p>";
2 - 1988
 
6 - 1989
            var errors = getJsonArray(obj.Errors);
19 - 1990
            str += "<p>";
6 - 1991
            for (i = 0; i < errors.length; i++) {
19 - 1992
                str += errors[i].SeverityCode + " (" + errors[i].ErrorCode + "): " + escapeHtml(errors[i].LongMessage) + "<br/>";
6 - 1993
                if (errors[i].LongMessage.includes('Auth')) {
1994
                    authErrorFlag = true;
1995
                }
1996
            }
19 - 1997
            str += "</p>";
2 - 1998
 
19 - 1999
            x.innerHTML += str;
2000
 
6 - 2001
            if (authErrorFlag === true) {
2002
                eBayAuthTokenFlag = false;
2003
                x = document.getElementById("login");
2004
                if (x.className.indexOf("w3-show") == -1) {
2005
                    x.className += " w3-show";
2006
                }
2007
            }
2008
        }
2 - 2009
 
6 - 2010
        --shippingsToProcess;
2011
        ++shippingsProcessed;
2012
        updateProgressBar(maxShippingsToProcess, shippingsProcessed);
2013
    };
2 - 2014
 
6 - 2015
    xhr.send(xml);
2 - 2016
}
2017
 
2018
function getPaymentTransaction(fullId) {
6 - 2019
    var id = fullId.substr(0, fullId.indexOf(' '));
2020
    var i;
2021
    var transFee = 0.00;
2022
    var transFeeStr = '';
2023
    var transDate = '';
2024
    var transId = '';
2 - 2025
 
6 - 2026
    var xhttp = new XMLHttpRequest();
2027
    xhttp.onreadystatechange = function() {
2028
        if (this.readyState == 4 && this.status == 200) {
2029
            //window.alert(this.responseText);
2030
            var json = JSON.parse(this.responseText);
10 - 2031
            var transactions = getJsonArray(json.transactions);
2032
            for (i = 0; i < transactions.length; i++) {
2033
                transDate = getJsonValue(transactions[i].created_at).substr(0, 10);
2034
                document.getElementById('PaidDate' + id).innerHTML = transDate;
2 - 2035
 
10 - 2036
                var gateway = getJsonValue(transactions[i].gateway);
2037
                if (gateway == 'shopify_payments') {
2038
                    transId = getJsonValue(transactions[i].id);
2039
                    transFee = Number(getJsonValue(transactions[i].receipt.fee_amount)) / 100;
2040
                } else if (gateway == 'paypal') {
2041
                    transId = getJsonValue(transactions[i].authorization);
2042
                    transFee = Number(getJsonValue(transactions[i].receipt.fee_amount));
2043
                } else if (gateway == 'manual') {
2044
                    transId = getJsonValue(json.transactions[i].id);
2045
                }
2 - 2046
 
10 - 2047
                document.getElementById('TransactionId' + id).innerHTML = transId;
2 - 2048
 
10 - 2049
                transFeeStr = '$' + parseFloat(transFee).toFixed(2);
2050
                PayPalFees += transFee;
2051
                document.getElementById('Fee' + id).innerHTML = transFeeStr;
6 - 2052
            }
2 - 2053
 
6 - 2054
            --shippingsToProcess;
2055
            ++shippingsProcessed;
2056
            updateProgressBar(maxShippingsToProcess, shippingsProcessed);
2057
        }
2058
    };
2 - 2059
 
6 - 2060
    xhttp.open("GET", configProxyUrl, true);
2061
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + configShopifyTransactionsUrl1 + id + configShopifyTransactionsUrl2));
2062
    xhttp.send();
2 - 2063
}
2064
 
2065
function getTrackingDetails() {
6 - 2066
    var i;
2067
    var x;
2 - 2068
 
6 - 2069
    trackingNumbersToProcess = 0;
2070
    trackingNumbersProcessed = 0;
2071
    maxTrackingNumbersToProcess = 0;
2072
    initProgressBar("Retrieving Carrier Tracking...");
2 - 2073
 
6 - 2074
    for (i = 0; i < trackingList.length; i++) {
2075
        ++trackingNumbersToProcess;
2076
        ++maxTrackingNumbersToProcess;
2077
        if (trackingList[i].substr(0, 2) == '1Z') {
2078
            getUPSTracking(trackingList[i]);
2079
        } else {
2080
            getUSPSTracking(trackingList[i]);
2081
        }
2082
    }
2 - 2083
 
6 - 2084
    function checkTrackingsToProcess() {
2085
        if (trackingNumbersToProcess > 0) {
2086
            window.setTimeout(checkTrackingsToProcess, 100); // wait 100 milliseconds
2087
        } else {
2088
            endProgressBar();
2089
            x = document.getElementById("results");
2090
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
2091
            if (!x.className.includes("process-errors")) {
2092
                setTimeout(function() {
2093
                    x.className = x.className.replace(" w3-show", "");
2094
                }, 3000);
2095
            }
2096
        }
2097
    }
2 - 2098
 
6 - 2099
    checkTrackingsToProcess();
2 - 2100
}
2101
 
2102
function getUSPSTracking(searchNumber) {
6 - 2103
    var j;
2104
    var str;
2105
    var url;
2106
    var trackingNumber;
2107
    var summary;
2108
    var detail;
2109
    var deliveryDate;
2110
    var createDate;
2111
    var duration;
2112
    var lastUpdate;
2113
    var lastEvent;
2114
    var footer;
2 - 2115
 
6 - 2116
    var xhttp = new XMLHttpRequest();
2117
    xhttp.onreadystatechange = function() {
2118
        if (this.readyState == 4 && this.status == 200) {
12 - 2119
            var obj = XMLparse(this.responseXML, false);
2 - 2120
 
12 - 2121
            if (obj.TrackResponse.TrackInfo.TrackSummary === undefined) {
6 - 2122
                --trackingNumbersToProcess;
2123
                ++trackingNumbersProcessed;
2124
                updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2125
                return;
2126
            }
2 - 2127
 
12 - 2128
            var trackingInfo = obj.TrackResponse.TrackInfo;
2129
 
2130
            trackingNumber = trackingInfo.ID;
2131
            summary = formatUSPSTrackingLine(trackingInfo.TrackSummary);
6 - 2132
            detail = '';
2133
            footer = '';
2134
            deliveryDate = '';
2135
            duration = '';
2136
            lastUpdate = summary.substr(8, 10);
12 - 2137
            lastEvent = trackingInfo.TrackSummary.Event;
2 - 2138
 
6 - 2139
            if (document.getElementById('DeliveryStatus' + trackingNumber) === null) {
2140
                --trackingNumbersToProcess;
2141
                ++trackingNumbersProcessed;
2142
                updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2143
                return;
2144
            }
2 - 2145
 
12 - 2146
            if (trackingInfo.TrackDetail !== undefined && trackingInfo.TrackDetail.length > 0) {
2147
                for (j = 0; j < trackingInfo.TrackDetail.length; j++) {
2148
                    detail += formatUSPSTrackingLine(trackingInfo.TrackDetail[j]);
6 - 2149
                }
2 - 2150
 
12 - 2151
                createDate = moment(trackingInfo.TrackDetail[(trackingInfo.TrackDetail.length - 1)].EventDate, "MMMM DD, YYYY").format('YYYY-MM-DD');
6 - 2152
                footer = 'Enroute since ' + createDate + ' (' + moment().diff(createDate, 'days') + ' days)';
2 - 2153
 
6 - 2154
                if (summary.includes("Delivered")) {
2155
                    deliveryDate = summary.substr(8, 10);
2156
                    duration = moment(deliveryDate).diff(createDate, 'days');
2157
                    document.getElementById('DeliveryStatus' + trackingNumber).style.color = "green";
2158
                    footer = 'Delivered in ' + moment(deliveryDate).to(createDate, 'days');
2159
                } else if (moment().diff(lastUpdate, 'days') > 3) {
2160
                    document.getElementById('DeliveryStatus' + trackingNumber).style.color = "red";
2161
                }
2162
            }
2 - 2163
 
6 - 2164
            document.getElementById('DeliveryStatus' + trackingNumber).innerHTML = lastEvent;
2165
            document.getElementById('DeliveryDays' + trackingNumber).innerHTML = duration;
2166
            document.getElementById('DeliveryDate' + trackingNumber).innerHTML = deliveryDate;
2 - 2167
 
6 - 2168
            str = document.getElementById(trackingNumber).innerHTML;
2169
            if (!str.startsWith('<button')) {
30 - 2170
                document.getElementById(trackingNumber).innerHTML = '<button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#mod' + trackingNumber + '">' + str + '</button>';
2 - 2171
 
30 - 2172
                str = '<div id="mod' + trackingNumber + '" class="modal">';
2173
                str += '<div class="modal-dialog modal-lg">';
2174
                str += '<div class="modal-content">';
2175
                str += '<div class="modal-header">';
2176
                str += '<h3>' + trackingNumber + ' (USPS ' + getCarrierService("USPS", trackingNumber, false) + ')</h3>';
2177
                str += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
2178
                str += '</div>';
2179
                str += '<div class="modal-body">';
2180
                str += '<table class="table border small">';
2181
                str += '<thead class="thead-dark">';
2182
                str += '<tr>';
2183
                str += '<th>DATE</th>';
2184
                str += '<th>TIME</th>';
2185
                str += '<th>STATUS</th>';
2186
                str += '<th>LOCATION</th>';
2187
                str += '</tr>';
2188
                str += '</thead>';
2189
                str += '<tbody>';
6 - 2190
                str += summary;
2191
                str += detail;
30 - 2192
                str += '</tbody>';
2193
                str += '</table>';
2194
                str += '</div>';
2195
                str += '<div class="modal-footer">';
2196
                str += '<p>' + document.getElementById('DeliveryAddress' + trackingNumber).innerHTML + ' - ' + footer + '</p>';
2197
                str += '</div>';
2198
                str += '</div>';
2199
                str += '</div>';
2200
                str += '</div>';
2 - 2201
 
6 - 2202
                document.getElementById("modals").innerHTML += str;
2203
            }
2 - 2204
 
6 - 2205
            --trackingNumbersToProcess;
2206
            ++trackingNumbersProcessed;
2207
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2208
        }
2209
    };
2 - 2210
 
6 - 2211
    url = configUSPSUrl + '?API=TrackV2&XML=';
2212
    url += '<TrackFieldRequest USERID="';
2213
    url += configUSPSUserId;
2214
    url += '">';
2215
    url += '<TrackID ID="' + searchNumber + '"></TrackID>';
2216
    url += '</TrackFieldRequest>';
2217
    url = url.replace(/ /g, '%20');
2 - 2218
 
6 - 2219
    xhttp.open("GET", configProxyUrl, true);
2220
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
2221
    xhttp.send();
2 - 2222
}
2223
 
2224
function formatUSPSTrackingLine(t) {
6 - 2225
    var str = '';
2 - 2226
 
6 - 2227
    if (t !== undefined) {
2228
        str = '<tr>';
2 - 2229
 
6 - 2230
        str += '<td>' + moment(t.EventDate, "MMMM DD, YYYY").format('YYYY-MM-DD') + '</td>';
2 - 2231
 
6 - 2232
        str += '<td>';
2233
        if (t.EventTime.length > 0) {
2234
            str += ' ' + moment(t.EventTime, "hh:mm a").format('HH:mm');
2235
        }
2236
        str += '</td>';
2 - 2237
 
6 - 2238
        str += '<td>' + t.Event + '</td>';
2 - 2239
 
6 - 2240
        str += '<td>';
2241
        if (t.EventCity.length > 0) {
2242
            str += t.EventCity;
2243
            if (t.EventState.length > 0) {
2244
                str += ", " + t.EventState + ' ' + t.EventZIPCode;
2245
            }
2246
        }
2247
        str += '</td>';
2 - 2248
 
6 - 2249
        str += '</tr>';
2250
    }
2 - 2251
 
6 - 2252
    return (str);
2 - 2253
}
2254
 
2255
function getUPSTracking(trackingNumber) {
6 - 2256
    var xhr = new XMLHttpRequest();
2 - 2257
 
6 - 2258
    var xml = '<?xml version="1.0"?>';
2259
    xml += '<AccessRequest xml:lang="en-US">';
2260
    xml += '<AccessLicenseNumber>' + configUPSAccessKey + '</AccessLicenseNumber>';
2261
    xml += '<UserId>' + configUPSUsername + '</UserId>';
2262
    xml += '<Password>' + configUPSPassword + '</Password>';
2263
    xml += '</AccessRequest>';
2264
    xml += '<?xml version="1.0"?>';
2265
    xml += '<TrackRequest xml:lang="en-US">';
2266
    xml += '<Request>';
2267
    xml += '<TransactionReference>';
2268
    xml += '<CustomerContext>' + 'MUNA Trading' + '</CustomerContext>';
2269
    xml += '</TransactionReference>';
2270
    xml += '<RequestAction>Track</RequestAction>';
2271
    xml += '<RequestOption>1</RequestOption>';
2272
    xml += '</Request>';
2273
    xml += '<TrackingNumber>' + trackingNumber + '</TrackingNumber>';
2274
    xml += '</TrackRequest>';
2 - 2275
 
6 - 2276
    xhr.onload = () => {
12 - 2277
        var jsonObj = XMLparse(xhr.responseXML, false);
2278
        var obj = jsonObj.TrackResponse;
2 - 2279
 
6 - 2280
        if (obj.Response.ResponseStatusDescription != 'Success') {
2281
            --trackingNumbersToProcess;
2282
            ++trackingNumbersProcessed;
2283
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2284
            return;
2285
        }
2 - 2286
 
6 - 2287
        trackingNumber = obj.Shipment.ShipmentIdentificationNumber;
2288
        summary = formatUPSTrackingLine(obj.Shipment.Package.Activity[0]);
2289
        detail = '';
2290
        footer = '';
2291
        deliveryDate = '';
2292
        duration = '';
2293
        lastUpdate = moment(obj.Shipment.Package.Activity[0].Status.Date, "YYYYMMDD").format('YYYY-MM-DD');
2294
        lastEvent = obj.Shipment.Package.Activity[0].Status.StatusType.Description;
2 - 2295
 
6 - 2296
        if (document.getElementById('DeliveryStatus' + trackingNumber) === null) {
2297
            --trackingNumbersToProcess;
2298
            ++trackingNumbersProcessed;
2299
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2300
            return;
2301
        }
2 - 2302
 
6 - 2303
        if (obj.Shipment.Package.Activity !== undefined && obj.Shipment.Package.Activity.length > 0) {
2304
            for (j = 0; j < obj.Shipment.Package.Activity.length; j++) {
2305
                detail += formatUPSTrackingLine(obj.Shipment.Package.Activity[j]);
2306
            }
2 - 2307
 
6 - 2308
            createDate = moment(obj.Shipment.PickupDate, "YYYYMMDD").format('YYYY-MM-DD');
2309
            footer = 'Enroute since ' + createDate + ' (' + moment().diff(createDate, 'days') + ' days)';
2 - 2310
 
6 - 2311
            if (obj.Shipment.Package.DeliveryIndicator == 'Y') {
2312
                deliveryDate = moment(obj.Shipment.Package.DeliveryDate, "YYYYMMDD").format('YYYY-MM-DD');
2313
                duration = moment(deliveryDate).diff(createDate, 'days');
2314
                document.getElementById('DeliveryStatus' + trackingNumber).style.color = "green";
2315
                footer = 'Delivered in ' + moment(deliveryDate).to(createDate, 'days');
2316
            } else if (moment().diff(lastUpdate, 'days') > 3) {
2317
                document.getElementById('DeliveryStatus' + trackingNumber).style.color = "red";
2318
            }
2319
        }
2 - 2320
 
14 - 2321
        if (document.getElementById('ShippedDate' + trackingNumber)) {
2322
            document.getElementById('ShippedDate' + trackingNumber).innerHTML = createDate;
2323
        }
6 - 2324
        document.getElementById('DeliveryStatus' + trackingNumber).innerHTML = lastEvent;
2325
        document.getElementById('DeliveryDays' + trackingNumber).innerHTML = duration;
2326
        document.getElementById('DeliveryDate' + trackingNumber).innerHTML = deliveryDate;
2 - 2327
 
6 - 2328
        str = document.getElementById(trackingNumber).innerHTML;
2329
        if (!str.startsWith('<button')) {
30 - 2330
            document.getElementById(trackingNumber).innerHTML = '<button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#mod' + trackingNumber + '">' + str + '</button>';
2 - 2331
 
30 - 2332
            str = '<div id="mod' + trackingNumber + '" class="modal">';
2333
            str += '<div class="modal-dialog modal-lg">';
2334
            str += '<div class="modal-content">';
2335
            str += '<div class="modal-header">';
2336
            str += '<h3>' + trackingNumber + ' (UPS ' + getCarrierService("UPS", trackingNumber, false) + ')</h3>';
2337
            str += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
2338
            str += '</div>';
2339
            str += '<div class="modal-body">';
2340
            str += '<table class="table border small">';
2341
            str += '<thead class="thead-dark">';
2342
            str += '<tr>';
2343
            str += '<th>DATE</th>';
2344
            str += '<th>TIME</th>';
2345
            str += '<th>STATUS</th>';
2346
            str += '<th>LOCATION</th>';
2347
            str += '</tr>';
2348
            str += '</thead>';
2349
            str += '<tbody>';
6 - 2350
            str += summary;
2351
            str += detail;
30 - 2352
            str += '</tbody>';
2353
            str += '</table>';
2354
            str += '</div>';
2355
            str += '<div class="modal-footer">';
2356
            str += '<p>' + document.getElementById('DeliveryAddress' + trackingNumber).innerHTML + ' - ' + footer + '</p>';
2357
            str += '</div>';
2358
            str += '</div>';
2359
            str += '</div>';
2360
            str += '</div>';
2 - 2361
 
6 - 2362
            document.getElementById("modals").innerHTML += str;
2363
        }
2 - 2364
 
6 - 2365
        --trackingNumbersToProcess;
2366
        ++trackingNumbersProcessed;
2367
        updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2368
    };
2 - 2369
 
6 - 2370
    xhr.open('POST', configProxyUrl, true);
2371
    xhr.setRequestHeader('Content-Type', 'text/xml');
97 - 2372
    xhr.setRequestHeader('Accept-Charset', 'UTF-8,*;q=0.5');
6 - 2373
    xhr.setRequestHeader('X-Proxy-URL', configUPSUrl);
2374
    xhr.send(xml);
2 - 2375
}
2376
 
2377
function formatUPSTrackingLine(t) {
6 - 2378
    var str = '';
2 - 2379
 
6 - 2380
    if (t !== undefined) {
2381
        str = '<tr>';
2 - 2382
 
6 - 2383
        str += '<td>' + moment(t.Date, "YYYYMMDD").format('YYYY-MM-DD') + '</td>';
2 - 2384
 
6 - 2385
        str += '<td>';
2386
        if (t.Time.length > 0) {
2387
            str += ' ' + moment(t.Time, "HHmmss").format('HH:mm');
2388
        }
2389
        str += '</td>';
2 - 2390
 
6 - 2391
        str += '<td>' + t.Status.StatusType.Description + '</td>';
2 - 2392
 
6 - 2393
        str += '<td>';
2394
        if (t.ActivityLocation.Address.City !== undefined) {
2395
            str += t.ActivityLocation.Address.City;
2396
            if (t.ActivityLocation.Address.StateProvinceCode !== undefined) {
2397
                str += ", " + t.ActivityLocation.Address.StateProvinceCode;
2398
            }
2399
        }
2400
        str += '</td>';
2 - 2401
 
6 - 2402
        str += '</tr>';
2403
    }
2 - 2404
 
6 - 2405
    return (str);
2 - 2406
}
2407
 
2408
 
2409
function connected() {
6 - 2410
    var x;
2 - 2411
 
6 - 2412
    eBayAuthTokenFlag = true;
30 - 2413
    if (!document.getElementById("connected").innerHTML.endsWith("(Connected)")) {
2414
        document.getElementById("connected").innerHTML += " (Connected)";
2415
    }
2 - 2416
 
6 - 2417
    x = document.getElementById("startButton");
30 - 2418
    x.className = x.className.replace(" btn-danger", " btn-primary");
2 - 2419
 
6 - 2420
    x = document.getElementById("login");
2421
    x.className = x.className.replace(" w3-show", "");
2 - 2422
 
6 - 2423
    x = document.getElementById("results");
2424
    x.innerHTML = "";
2425
    x.className = x.className.replace(" w3-show", "");
2 - 2426
}
2427
 
2428
    </script>
30 - 2429
    <script>includeHTML();</script>
2 - 2430
 
2431
</body>
2432
</html>