Subversion Repositories munaweb

Rev

Rev 97 | Rev 139 | 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') {
266
                    sortTable("customerTable", 1);
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
 
445
                sortTable("orderTable", 1);
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
 
6 - 542
    sortTable("orderTable", 1);
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
 
6 - 561
            sortTable("shippingTable", 1);
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('');
616
            sortTable("trackingTable", 1);
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 {
1352
            sortTable("feeTable", 1);
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
 
6 - 1449
    if (str.startsWith("Batch")) {
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 {
1575
            sortTable("cancelReturnTable", 1);
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
 
2 - 1675
function sortTable(tableName, column) {
6 - 1676
    var table, rows, switching, i, x, y, shouldSwitch;
1677
    --column; // column parameter starts with 1
1678
    table = document.getElementById(tableName);
1679
    switching = true;
1680
    /*Make a loop that will continue until
1681
    no switching has been done:*/
1682
    while (switching) {
1683
        //start by saying: no switching is done:
1684
        switching = false;
1685
        rows = table.getElementsByTagName("TR");
1686
        /*Loop through all table rows (except the
1687
        first, which contains table headers, and the last
1688
        which contains the table footers):*/
1689
        for (i = 1; i < (rows.length - 2); i++) {
1690
            //start by saying there should be no switching:
1691
            shouldSwitch = false;
1692
            /*Get the two elements you want to compare,
1693
            one from current row and one from the next:*/
1694
            x = rows[i].getElementsByTagName("TD")[column];
1695
            y = rows[i + 1].getElementsByTagName("TD")[column];
1696
            //check if the two rows should switch place:
1697
            if (x !== undefined && x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
1698
                //if so, mark as a switch and break the loop:
1699
                shouldSwitch = true;
1700
                break;
1701
            }
1702
        }
1703
        if (shouldSwitch) {
1704
            /*If a switch has been marked, make the switch
1705
            and mark that a switch has been done:*/
1706
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
1707
            switching = true;
1708
        }
1709
    }
2 - 1710
}
1711
 
1712
function printData() {
6 - 1713
    var printContent = document.getElementById("printTable");
2 - 1714
 
6 - 1715
    var num;
1716
    var cssReference = [];
1717
    var uniqueName = new Date();
2 - 1718
 
6 - 1719
    var windowName = 'Print' + uniqueName.getTime();
1720
    var printWindow = window.open(num, windowName, 'left=50000,top=50000,width=0,height=0');
1721
    cssReference[0] = printWindow.document.createElement("link");
30 - 1722
    cssReference[0].href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css";
6 - 1723
    cssReference[0].rel = "stylesheet";
1724
    cssReference[0].type = "text/css";
1725
    cssReference[1] = printWindow.document.createElement("link");
1726
    cssReference[1].href = "css/style.css";
1727
    cssReference[1].rel = "stylesheet";
1728
    cssReference[1].type = "text/css";
2 - 1729
 
34 - 1730
    printWindow.document.write(printContent.outerHTML.replace("table-bordered", "").replace("table-striped", "").replace("table-hover", ""));
6 - 1731
    printWindow.document.getElementsByTagName('head')[0].appendChild(cssReference[0]);
1732
    printWindow.document.getElementsByTagName('head')[0].appendChild(cssReference[1]);
2 - 1733
 
6 - 1734
    printWindow.document.close();
1735
    printWindow.focus();
1736
    printWindow.print();
1737
    printWindow.close();
2 - 1738
}
1739
 
1740
function printSummary() {
134 - 1741
    var profit = grossSales + shippingRcvd - shippingCost - eBayFees - PayPalFees;
2 - 1742
 
30 - 1743
    document.getElementById("summary").innerHTML = '<h2>Profit: ' + profit.toFixed(2) + '</h3>';
2 - 1744
}
1745
 
1746
function findThumbNails() {
6 - 1747
    var i;
1748
    var x = document.getElementById("shippingTable");
2 - 1749
 
6 - 1750
    thumbnailsToProcess = 0;
1751
    thumbnailsProcessed = 0;
1752
    maxThumbnailsToProcess = 0;
1753
    initProgressBar("");
2 - 1754
 
6 - 1755
    for (i = 1; i < (x.rows.length - 1); i++) {
1756
        if (x.rows[i].cells[7].innerHTML == 'eBay' && x.rows[i].cells[2] !== undefined && x.rows[i].cells[2].innerHTML.length < 1) {
1757
            ++thumbnailsToProcess;
1758
            ++maxThumbnailsToProcess;
1759
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1760
            getThumbNail(x.rows[i].cells[4].innerHTML);
1761
        } else if (x.rows[i].cells[7].innerHTML == 'Shopify' && x.rows[i].cells[2] !== undefined && x.rows[i].cells[2].innerHTML.length > 0) {
1762
            ++thumbnailsToProcess;
1763
            ++maxThumbnailsToProcess;
1764
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1765
            getShopifyThumbNail(x.rows[i].cells[2].innerHTML);
1766
        }
1767
    }
2 - 1768
 
6 - 1769
    function checkthumbnailsToProcess() {
1770
        if (thumbnailsToProcess > 0) {
1771
            window.setTimeout(checkthumbnailsToProcess, 100); // wait 100 milliseconds
1772
        } else {
1773
            endProgressBar();
1774
            x = document.getElementById("results");
1775
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1776
            if (!x.className.includes("process-errors")) {
1777
                setTimeout(function() {
1778
                    x.className = x.className.replace(" w3-show", "");
1779
                }, 3000);
1780
            }
1781
        }
1782
    }
2 - 1783
 
6 - 1784
    checkthumbnailsToProcess();
2 - 1785
}
1786
 
1787
function getThumbNail(itemId) {
6 - 1788
    // Construct the getSingleItem request
1789
    url = configeBayShopping + "?";
1790
    url += "callname=GetSingleItem";
1791
    url += "&responseencoding=JSON";
1792
    url += "&appid=" + configAppid;
1793
    url += "&version=" + configeBayShoppingVersion;
1794
    url += "&ItemID=";
1795
    url += itemId;
2 - 1796
 
6 - 1797
    var xhttp = new XMLHttpRequest();
2 - 1798
 
6 - 1799
    xhttp.onreadystatechange = function() {
1800
        if (this.readyState == 4) {
1801
            _cb_getThumbNail(JSON.parse(this.responseText));
1802
        }
1803
    };
2 - 1804
 
6 - 1805
    xhttp.open("GET", configProxyUrl, true);
1806
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
1807
    xhttp.send();
2 - 1808
}
1809
 
1810
function _cb_getThumbNail(root) {
6 - 1811
    var ack = root.Ack;
2 - 1812
 
6 - 1813
    if (ack == 'Failure' || ack == 'PartialFailure') {
1814
        return;
1815
    }
2 - 1816
 
6 - 1817
    var JsonObj = typeof root.Item != 'object' ? JSON.parse(root.Item) : root.Item;
1818
    var ItemID = JsonObj.ItemID;
1819
    var PictureURL = getJsonArray(JsonObj.PictureURL);
2 - 1820
 
6 - 1821
    document.getElementById('PictureURL' + ItemID).innerHTML = '<img src="' + PictureURL[0] + '" style="max-height:100px">';
1822
    --thumbnailsToProcess;
1823
    ++thumbnailsProcessed;
1824
    updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
2 - 1825
}
1826
 
1827
function getShopifyThumbNail(productId) {
6 - 1828
    var xhttp = new XMLHttpRequest();
1829
    xhttp.onreadystatechange = function() {
1830
        if (this.readyState == 4 && this.status == 200) {
1831
            //window.alert(this.responseText);
1832
            var json = JSON.parse(this.responseText);
1833
            if (json.product !== undefined) {
1834
                document.getElementById('PictureURL' + productId).innerHTML = '<img src="' + json.product.image.src + '" style="max-height:100px">';
1835
            }
1836
            --thumbnailsToProcess;
1837
            ++thumbnailsProcessed;
1838
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1839
        }
1840
    };
2 - 1841
 
6 - 1842
    xhttp.open("GET", configProxyUrl, true);
1843
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + 'products/' + productId + '.json?fields=image'));
1844
    xhttp.send();
2 - 1845
}
1846
 
1847
function findShippingCosts() {
6 - 1848
    var i;
1849
    var x;
2 - 1850
 
6 - 1851
    shippingsToProcess = 0;
1852
    shippingsProcessed = 0;
1853
    maxShippingsToProcess = 0;
1854
    initProgressBar("Retrieving Shipping Costs...");
2 - 1855
 
6 - 1856
    if (getRadioValue('rptType') == 'trackingList') {
1857
        x = document.getElementById("trackingTable");
1858
    } else {
1859
        x = document.getElementById("orderTable");
1860
    }
2 - 1861
 
6 - 1862
    for (i = (x.rows.length - 1); i > 0; i--) {
1863
        if (getRadioValue('rptType') == 'trackingList') {
1864
            if (x.rows[i].cells[3] !== undefined && x.rows[i].cells[3].innerHTML.length < 1) {
1865
                if (x.rows[i].cells[7] !== undefined && x.rows[i].cells[7].innerHTML.length < 1) {
1866
                    document.getElementById("trackingTable").deleteRow(i);
1867
                } else {
1868
                    ++shippingsToProcess;
1869
                    ++maxShippingsToProcess;
1870
                    updateProgressBar(maxShippingsToProcess, shippingsProcessed);
1871
                    getShippingCost(x.rows[i].cells[2].innerHTML);
1872
                }
1873
            }
1874
        } else {
1875
            if (x.rows[i].cells[5].innerHTML == 'eBay' && x.rows[i].cells[9] !== undefined && x.rows[i].cells[9].innerHTML.length < 1) {
1876
                ++shippingsToProcess;
1877
                ++maxShippingsToProcess;
1878
                updateProgressBar(maxShippingsToProcess, shippingsProcessed);
1879
                getShippingCost(x.rows[i].cells[2].innerHTML);
1880
            } else if (x.rows[i].cells[5].innerHTML == 'Shopify') {
1881
                ++shippingsToProcess;
1882
                ++maxShippingsToProcess;
1883
                updateProgressBar(maxShippingsToProcess, shippingsProcessed);
1884
                getPaymentTransaction(x.rows[i].cells[2].innerHTML);
1885
            }
1886
        }
1887
    }
2 - 1888
 
6 - 1889
    function checkshippingsToProcess() {
1890
        if (shippingsToProcess > 0) {
1891
            window.setTimeout(checkshippingsToProcess, 100); // wait 100 milliseconds
1892
        } else {
1893
            endProgressBar();
1894
            x = document.getElementById("results");
1895
            if (getRadioValue('rptType') != 'trackingList') {
1896
                document.getElementById("ShippingTotal").innerHTML = '<strong>$' + shippingCost.toFixed(2) + '</strong>';
1897
                x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1898
                if (!x.className.includes("process-errors")) {
1899
                    setTimeout(function() {
1900
                        x.className = x.className.replace(" w3-show", "");
1901
                    }, 3000);
1902
                }
1903
            } else {
1904
                x.innerHTML += '<p><strong>Retrieving Carrier Tracking...</strong></p>';
1905
                getTrackingDetails();
1906
            }
1907
        }
1908
    }
1909
 
1910
    checkshippingsToProcess();
2 - 1911
}
1912
 
1913
function getShippingCost(OrderId) {
6 - 1914
    var i;
1915
    var xml;
1916
    var correlationId;
1917
    var shippingCostStr;
1918
    var deliveryStatus;
1919
    var authErrorFlag = false;
2 - 1920
 
6 - 1921
    var xw = new XMLWriter('UTF-8', '1.0');
1922
    var xhr = new XMLHttpRequest();
2 - 1923
 
6 - 1924
    xw.writeStartDocument();
1925
    xw.writeStartElement("GetSellingManagerSaleRecordRequest");
1926
    xw.writeAttributeString('xmlns', 'urn:ebay:apis:eBLBaseComponents');
2 - 1927
 
6 - 1928
    xw.writeStartElement('RequesterCredentials');
1929
    xw.writeElementString('eBayAuthToken', eBayAuthToken);
1930
    xw.writeEndElement(); /* RequesterCredentials */
2 - 1931
 
6 - 1932
    xw.writeElementString('OrderID', OrderId);
1933
    xw.writeElementString('MessageID', OrderId);
2 - 1934
 
6 - 1935
    xw.writeElementString('ErrorLanguage', 'en_US');
1936
    xw.writeElementString('Version', configeBayTradingVersion);
1937
    xw.writeElementString('WarningLevel', configWarningLevel);
2 - 1938
 
6 - 1939
    xw.writeEndElement(); /* GetSellingManagerSaleRecordRequest */
1940
    xw.writeEndDocument();
2 - 1941
 
6 - 1942
    xhr.open('POST', configProxyUrl, true);
1943
    xhr.setRequestHeader('Content-Type', 'text/xml');
1944
    xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
1945
    xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
1946
    xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'GetSellingManagerSaleRecord');
1947
    xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
1948
    xhr.setRequestHeader('X-EBAY-API-DEV-NAME', '');
1949
    xhr.setRequestHeader('X-EBAY-API-CERT-NAME', '');
1950
    xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
2 - 1951
 
6 - 1952
    xml = xw.flush();
1953
    xw.close();
2 - 1954
 
6 - 1955
    xhr.onload = () => {
12 - 1956
        var jsonObj = XMLparse(xhr.responseXML, false);
1957
        var obj = jsonObj.GetSellingManagerSaleRecordResponse;
6 - 1958
        var returnCode = obj.Ack;
19 - 1959
        var str;
2 - 1960
 
6 - 1961
        var x = document.getElementById("results");
1962
        if (x.className.indexOf("w3-show") == -1) {
1963
            x.className += " w3-show";
1964
        }
2 - 1965
 
6 - 1966
        if (obj.Message) {
1967
            x.innerHTML += "<p>" + obj.Message + "</p>";
1968
        }
2 - 1969
 
6 - 1970
        if (returnCode == 'Success' || (returnCode == 'Warning' && obj.Errors.ErrorCode == '21917182')) {
1971
            correlationId = obj.CorrelationID;
1972
            deliveryStatus = '';
1973
            shippingCostStr = '';
2 - 1974
 
6 - 1975
            if (obj.SellingManagerSoldOrder.ActualShippingCost !== undefined &&
1976
                obj.SellingManagerSoldOrder.ActualShippingCost.text != '0.0' &&
1977
                document.getElementById('ShippingCost' + correlationId).innerHTML.length < 1) {
1978
                shippingCostStr = '$' + parseFloat(obj.SellingManagerSoldOrder.ActualShippingCost.text).toFixed(2);
1979
                shippingCost += parseFloat(obj.SellingManagerSoldOrder.ActualShippingCost.text);
1980
                document.getElementById('ShippingCost' + correlationId).innerHTML = shippingCostStr;
1981
                if (getRadioValue('rptType') == 'orderList') {
1982
                    printSummary();
1983
                }
1984
            }
2 - 1985
 
6 - 1986
            if (getRadioValue('rptType') != 'trackingList') {
1987
                var soldTransactions = getJsonArray(obj.SellingManagerSoldOrder.SellingManagerSoldTransaction);
1988
                for (i = 0; i < soldTransactions.length; i++) {
97 - 1989
                    if (soldTransactions[i].Shipment !== undefined && soldTransactions[i].Shipment.DeliveryStatus !== undefined) {
6 - 1990
                        deliveryStatus += (i > 0 ? '<br/>' : '') + soldTransactions[i].Shipment.DeliveryStatus;
1991
                    }
1992
                }
1993
                document.getElementById('Delivery' + correlationId).innerHTML = deliveryStatus;
1994
            }
1995
        } else {
1996
            x.className += " process-errors";
19 - 1997
            str = "<p><strong>" + returnCode + ":</strong></p>";
2 - 1998
 
6 - 1999
            var errors = getJsonArray(obj.Errors);
19 - 2000
            str += "<p>";
6 - 2001
            for (i = 0; i < errors.length; i++) {
19 - 2002
                str += errors[i].SeverityCode + " (" + errors[i].ErrorCode + "): " + escapeHtml(errors[i].LongMessage) + "<br/>";
6 - 2003
                if (errors[i].LongMessage.includes('Auth')) {
2004
                    authErrorFlag = true;
2005
                }
2006
            }
19 - 2007
            str += "</p>";
2 - 2008
 
19 - 2009
            x.innerHTML += str;
2010
 
6 - 2011
            if (authErrorFlag === true) {
2012
                eBayAuthTokenFlag = false;
2013
                x = document.getElementById("login");
2014
                if (x.className.indexOf("w3-show") == -1) {
2015
                    x.className += " w3-show";
2016
                }
2017
            }
2018
        }
2 - 2019
 
6 - 2020
        --shippingsToProcess;
2021
        ++shippingsProcessed;
2022
        updateProgressBar(maxShippingsToProcess, shippingsProcessed);
2023
    };
2 - 2024
 
6 - 2025
    xhr.send(xml);
2 - 2026
}
2027
 
2028
function getPaymentTransaction(fullId) {
6 - 2029
    var id = fullId.substr(0, fullId.indexOf(' '));
2030
    var i;
2031
    var transFee = 0.00;
2032
    var transFeeStr = '';
2033
    var transDate = '';
2034
    var transId = '';
2 - 2035
 
6 - 2036
    var xhttp = new XMLHttpRequest();
2037
    xhttp.onreadystatechange = function() {
2038
        if (this.readyState == 4 && this.status == 200) {
2039
            //window.alert(this.responseText);
2040
            var json = JSON.parse(this.responseText);
10 - 2041
            var transactions = getJsonArray(json.transactions);
2042
            for (i = 0; i < transactions.length; i++) {
2043
                transDate = getJsonValue(transactions[i].created_at).substr(0, 10);
2044
                document.getElementById('PaidDate' + id).innerHTML = transDate;
2 - 2045
 
10 - 2046
                var gateway = getJsonValue(transactions[i].gateway);
2047
                if (gateway == 'shopify_payments') {
2048
                    transId = getJsonValue(transactions[i].id);
2049
                    transFee = Number(getJsonValue(transactions[i].receipt.fee_amount)) / 100;
2050
                } else if (gateway == 'paypal') {
2051
                    transId = getJsonValue(transactions[i].authorization);
2052
                    transFee = Number(getJsonValue(transactions[i].receipt.fee_amount));
2053
                } else if (gateway == 'manual') {
2054
                    transId = getJsonValue(json.transactions[i].id);
2055
                }
2 - 2056
 
10 - 2057
                document.getElementById('TransactionId' + id).innerHTML = transId;
2 - 2058
 
10 - 2059
                transFeeStr = '$' + parseFloat(transFee).toFixed(2);
2060
                PayPalFees += transFee;
2061
                document.getElementById('Fee' + id).innerHTML = transFeeStr;
6 - 2062
            }
2 - 2063
 
6 - 2064
            --shippingsToProcess;
2065
            ++shippingsProcessed;
2066
            updateProgressBar(maxShippingsToProcess, shippingsProcessed);
2067
        }
2068
    };
2 - 2069
 
6 - 2070
    xhttp.open("GET", configProxyUrl, true);
2071
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + configShopifyTransactionsUrl1 + id + configShopifyTransactionsUrl2));
2072
    xhttp.send();
2 - 2073
}
2074
 
2075
function getTrackingDetails() {
6 - 2076
    var i;
2077
    var x;
2 - 2078
 
6 - 2079
    trackingNumbersToProcess = 0;
2080
    trackingNumbersProcessed = 0;
2081
    maxTrackingNumbersToProcess = 0;
2082
    initProgressBar("Retrieving Carrier Tracking...");
2 - 2083
 
6 - 2084
    for (i = 0; i < trackingList.length; i++) {
2085
        ++trackingNumbersToProcess;
2086
        ++maxTrackingNumbersToProcess;
2087
        if (trackingList[i].substr(0, 2) == '1Z') {
2088
            getUPSTracking(trackingList[i]);
2089
        } else {
2090
            getUSPSTracking(trackingList[i]);
2091
        }
2092
    }
2 - 2093
 
6 - 2094
    function checkTrackingsToProcess() {
2095
        if (trackingNumbersToProcess > 0) {
2096
            window.setTimeout(checkTrackingsToProcess, 100); // wait 100 milliseconds
2097
        } else {
2098
            endProgressBar();
2099
            x = document.getElementById("results");
2100
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
2101
            if (!x.className.includes("process-errors")) {
2102
                setTimeout(function() {
2103
                    x.className = x.className.replace(" w3-show", "");
2104
                }, 3000);
2105
            }
2106
        }
2107
    }
2 - 2108
 
6 - 2109
    checkTrackingsToProcess();
2 - 2110
}
2111
 
2112
function getUSPSTracking(searchNumber) {
6 - 2113
    var j;
2114
    var str;
2115
    var url;
2116
    var trackingNumber;
2117
    var summary;
2118
    var detail;
2119
    var deliveryDate;
2120
    var createDate;
2121
    var duration;
2122
    var lastUpdate;
2123
    var lastEvent;
2124
    var footer;
2 - 2125
 
6 - 2126
    var xhttp = new XMLHttpRequest();
2127
    xhttp.onreadystatechange = function() {
2128
        if (this.readyState == 4 && this.status == 200) {
12 - 2129
            var obj = XMLparse(this.responseXML, false);
2 - 2130
 
12 - 2131
            if (obj.TrackResponse.TrackInfo.TrackSummary === undefined) {
6 - 2132
                --trackingNumbersToProcess;
2133
                ++trackingNumbersProcessed;
2134
                updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2135
                return;
2136
            }
2 - 2137
 
12 - 2138
            var trackingInfo = obj.TrackResponse.TrackInfo;
2139
 
2140
            trackingNumber = trackingInfo.ID;
2141
            summary = formatUSPSTrackingLine(trackingInfo.TrackSummary);
6 - 2142
            detail = '';
2143
            footer = '';
2144
            deliveryDate = '';
2145
            duration = '';
2146
            lastUpdate = summary.substr(8, 10);
12 - 2147
            lastEvent = trackingInfo.TrackSummary.Event;
2 - 2148
 
6 - 2149
            if (document.getElementById('DeliveryStatus' + trackingNumber) === null) {
2150
                --trackingNumbersToProcess;
2151
                ++trackingNumbersProcessed;
2152
                updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2153
                return;
2154
            }
2 - 2155
 
12 - 2156
            if (trackingInfo.TrackDetail !== undefined && trackingInfo.TrackDetail.length > 0) {
2157
                for (j = 0; j < trackingInfo.TrackDetail.length; j++) {
2158
                    detail += formatUSPSTrackingLine(trackingInfo.TrackDetail[j]);
6 - 2159
                }
2 - 2160
 
12 - 2161
                createDate = moment(trackingInfo.TrackDetail[(trackingInfo.TrackDetail.length - 1)].EventDate, "MMMM DD, YYYY").format('YYYY-MM-DD');
6 - 2162
                footer = 'Enroute since ' + createDate + ' (' + moment().diff(createDate, 'days') + ' days)';
2 - 2163
 
6 - 2164
                if (summary.includes("Delivered")) {
2165
                    deliveryDate = summary.substr(8, 10);
2166
                    duration = moment(deliveryDate).diff(createDate, 'days');
2167
                    document.getElementById('DeliveryStatus' + trackingNumber).style.color = "green";
2168
                    footer = 'Delivered in ' + moment(deliveryDate).to(createDate, 'days');
2169
                } else if (moment().diff(lastUpdate, 'days') > 3) {
2170
                    document.getElementById('DeliveryStatus' + trackingNumber).style.color = "red";
2171
                }
2172
            }
2 - 2173
 
6 - 2174
            document.getElementById('DeliveryStatus' + trackingNumber).innerHTML = lastEvent;
2175
            document.getElementById('DeliveryDays' + trackingNumber).innerHTML = duration;
2176
            document.getElementById('DeliveryDate' + trackingNumber).innerHTML = deliveryDate;
2 - 2177
 
6 - 2178
            str = document.getElementById(trackingNumber).innerHTML;
2179
            if (!str.startsWith('<button')) {
30 - 2180
                document.getElementById(trackingNumber).innerHTML = '<button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#mod' + trackingNumber + '">' + str + '</button>';
2 - 2181
 
30 - 2182
                str = '<div id="mod' + trackingNumber + '" class="modal">';
2183
                str += '<div class="modal-dialog modal-lg">';
2184
                str += '<div class="modal-content">';
2185
                str += '<div class="modal-header">';
2186
                str += '<h3>' + trackingNumber + ' (USPS ' + getCarrierService("USPS", trackingNumber, false) + ')</h3>';
2187
                str += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
2188
                str += '</div>';
2189
                str += '<div class="modal-body">';
2190
                str += '<table class="table border small">';
2191
                str += '<thead class="thead-dark">';
2192
                str += '<tr>';
2193
                str += '<th>DATE</th>';
2194
                str += '<th>TIME</th>';
2195
                str += '<th>STATUS</th>';
2196
                str += '<th>LOCATION</th>';
2197
                str += '</tr>';
2198
                str += '</thead>';
2199
                str += '<tbody>';
6 - 2200
                str += summary;
2201
                str += detail;
30 - 2202
                str += '</tbody>';
2203
                str += '</table>';
2204
                str += '</div>';
2205
                str += '<div class="modal-footer">';
2206
                str += '<p>' + document.getElementById('DeliveryAddress' + trackingNumber).innerHTML + ' - ' + footer + '</p>';
2207
                str += '</div>';
2208
                str += '</div>';
2209
                str += '</div>';
2210
                str += '</div>';
2 - 2211
 
6 - 2212
                document.getElementById("modals").innerHTML += str;
2213
            }
2 - 2214
 
6 - 2215
            --trackingNumbersToProcess;
2216
            ++trackingNumbersProcessed;
2217
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2218
        }
2219
    };
2 - 2220
 
6 - 2221
    url = configUSPSUrl + '?API=TrackV2&XML=';
2222
    url += '<TrackFieldRequest USERID="';
2223
    url += configUSPSUserId;
2224
    url += '">';
2225
    url += '<TrackID ID="' + searchNumber + '"></TrackID>';
2226
    url += '</TrackFieldRequest>';
2227
    url = url.replace(/ /g, '%20');
2 - 2228
 
6 - 2229
    xhttp.open("GET", configProxyUrl, true);
2230
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
2231
    xhttp.send();
2 - 2232
}
2233
 
2234
function formatUSPSTrackingLine(t) {
6 - 2235
    var str = '';
2 - 2236
 
6 - 2237
    if (t !== undefined) {
2238
        str = '<tr>';
2 - 2239
 
6 - 2240
        str += '<td>' + moment(t.EventDate, "MMMM DD, YYYY").format('YYYY-MM-DD') + '</td>';
2 - 2241
 
6 - 2242
        str += '<td>';
2243
        if (t.EventTime.length > 0) {
2244
            str += ' ' + moment(t.EventTime, "hh:mm a").format('HH:mm');
2245
        }
2246
        str += '</td>';
2 - 2247
 
6 - 2248
        str += '<td>' + t.Event + '</td>';
2 - 2249
 
6 - 2250
        str += '<td>';
2251
        if (t.EventCity.length > 0) {
2252
            str += t.EventCity;
2253
            if (t.EventState.length > 0) {
2254
                str += ", " + t.EventState + ' ' + t.EventZIPCode;
2255
            }
2256
        }
2257
        str += '</td>';
2 - 2258
 
6 - 2259
        str += '</tr>';
2260
    }
2 - 2261
 
6 - 2262
    return (str);
2 - 2263
}
2264
 
2265
function getUPSTracking(trackingNumber) {
6 - 2266
    var xhr = new XMLHttpRequest();
2 - 2267
 
6 - 2268
    var xml = '<?xml version="1.0"?>';
2269
    xml += '<AccessRequest xml:lang="en-US">';
2270
    xml += '<AccessLicenseNumber>' + configUPSAccessKey + '</AccessLicenseNumber>';
2271
    xml += '<UserId>' + configUPSUsername + '</UserId>';
2272
    xml += '<Password>' + configUPSPassword + '</Password>';
2273
    xml += '</AccessRequest>';
2274
    xml += '<?xml version="1.0"?>';
2275
    xml += '<TrackRequest xml:lang="en-US">';
2276
    xml += '<Request>';
2277
    xml += '<TransactionReference>';
2278
    xml += '<CustomerContext>' + 'MUNA Trading' + '</CustomerContext>';
2279
    xml += '</TransactionReference>';
2280
    xml += '<RequestAction>Track</RequestAction>';
2281
    xml += '<RequestOption>1</RequestOption>';
2282
    xml += '</Request>';
2283
    xml += '<TrackingNumber>' + trackingNumber + '</TrackingNumber>';
2284
    xml += '</TrackRequest>';
2 - 2285
 
6 - 2286
    xhr.onload = () => {
12 - 2287
        var jsonObj = XMLparse(xhr.responseXML, false);
2288
        var obj = jsonObj.TrackResponse;
2 - 2289
 
6 - 2290
        if (obj.Response.ResponseStatusDescription != 'Success') {
2291
            --trackingNumbersToProcess;
2292
            ++trackingNumbersProcessed;
2293
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2294
            return;
2295
        }
2 - 2296
 
6 - 2297
        trackingNumber = obj.Shipment.ShipmentIdentificationNumber;
2298
        summary = formatUPSTrackingLine(obj.Shipment.Package.Activity[0]);
2299
        detail = '';
2300
        footer = '';
2301
        deliveryDate = '';
2302
        duration = '';
2303
        lastUpdate = moment(obj.Shipment.Package.Activity[0].Status.Date, "YYYYMMDD").format('YYYY-MM-DD');
2304
        lastEvent = obj.Shipment.Package.Activity[0].Status.StatusType.Description;
2 - 2305
 
6 - 2306
        if (document.getElementById('DeliveryStatus' + trackingNumber) === null) {
2307
            --trackingNumbersToProcess;
2308
            ++trackingNumbersProcessed;
2309
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2310
            return;
2311
        }
2 - 2312
 
6 - 2313
        if (obj.Shipment.Package.Activity !== undefined && obj.Shipment.Package.Activity.length > 0) {
2314
            for (j = 0; j < obj.Shipment.Package.Activity.length; j++) {
2315
                detail += formatUPSTrackingLine(obj.Shipment.Package.Activity[j]);
2316
            }
2 - 2317
 
6 - 2318
            createDate = moment(obj.Shipment.PickupDate, "YYYYMMDD").format('YYYY-MM-DD');
2319
            footer = 'Enroute since ' + createDate + ' (' + moment().diff(createDate, 'days') + ' days)';
2 - 2320
 
6 - 2321
            if (obj.Shipment.Package.DeliveryIndicator == 'Y') {
2322
                deliveryDate = moment(obj.Shipment.Package.DeliveryDate, "YYYYMMDD").format('YYYY-MM-DD');
2323
                duration = moment(deliveryDate).diff(createDate, 'days');
2324
                document.getElementById('DeliveryStatus' + trackingNumber).style.color = "green";
2325
                footer = 'Delivered in ' + moment(deliveryDate).to(createDate, 'days');
2326
            } else if (moment().diff(lastUpdate, 'days') > 3) {
2327
                document.getElementById('DeliveryStatus' + trackingNumber).style.color = "red";
2328
            }
2329
        }
2 - 2330
 
14 - 2331
        if (document.getElementById('ShippedDate' + trackingNumber)) {
2332
            document.getElementById('ShippedDate' + trackingNumber).innerHTML = createDate;
2333
        }
6 - 2334
        document.getElementById('DeliveryStatus' + trackingNumber).innerHTML = lastEvent;
2335
        document.getElementById('DeliveryDays' + trackingNumber).innerHTML = duration;
2336
        document.getElementById('DeliveryDate' + trackingNumber).innerHTML = deliveryDate;
2 - 2337
 
6 - 2338
        str = document.getElementById(trackingNumber).innerHTML;
2339
        if (!str.startsWith('<button')) {
30 - 2340
            document.getElementById(trackingNumber).innerHTML = '<button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#mod' + trackingNumber + '">' + str + '</button>';
2 - 2341
 
30 - 2342
            str = '<div id="mod' + trackingNumber + '" class="modal">';
2343
            str += '<div class="modal-dialog modal-lg">';
2344
            str += '<div class="modal-content">';
2345
            str += '<div class="modal-header">';
2346
            str += '<h3>' + trackingNumber + ' (UPS ' + getCarrierService("UPS", trackingNumber, false) + ')</h3>';
2347
            str += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
2348
            str += '</div>';
2349
            str += '<div class="modal-body">';
2350
            str += '<table class="table border small">';
2351
            str += '<thead class="thead-dark">';
2352
            str += '<tr>';
2353
            str += '<th>DATE</th>';
2354
            str += '<th>TIME</th>';
2355
            str += '<th>STATUS</th>';
2356
            str += '<th>LOCATION</th>';
2357
            str += '</tr>';
2358
            str += '</thead>';
2359
            str += '<tbody>';
6 - 2360
            str += summary;
2361
            str += detail;
30 - 2362
            str += '</tbody>';
2363
            str += '</table>';
2364
            str += '</div>';
2365
            str += '<div class="modal-footer">';
2366
            str += '<p>' + document.getElementById('DeliveryAddress' + trackingNumber).innerHTML + ' - ' + footer + '</p>';
2367
            str += '</div>';
2368
            str += '</div>';
2369
            str += '</div>';
2370
            str += '</div>';
2 - 2371
 
6 - 2372
            document.getElementById("modals").innerHTML += str;
2373
        }
2 - 2374
 
6 - 2375
        --trackingNumbersToProcess;
2376
        ++trackingNumbersProcessed;
2377
        updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2378
    };
2 - 2379
 
6 - 2380
    xhr.open('POST', configProxyUrl, true);
2381
    xhr.setRequestHeader('Content-Type', 'text/xml');
97 - 2382
    xhr.setRequestHeader('Accept-Charset', 'UTF-8,*;q=0.5');
6 - 2383
    xhr.setRequestHeader('X-Proxy-URL', configUPSUrl);
2384
    xhr.send(xml);
2 - 2385
}
2386
 
2387
function formatUPSTrackingLine(t) {
6 - 2388
    var str = '';
2 - 2389
 
6 - 2390
    if (t !== undefined) {
2391
        str = '<tr>';
2 - 2392
 
6 - 2393
        str += '<td>' + moment(t.Date, "YYYYMMDD").format('YYYY-MM-DD') + '</td>';
2 - 2394
 
6 - 2395
        str += '<td>';
2396
        if (t.Time.length > 0) {
2397
            str += ' ' + moment(t.Time, "HHmmss").format('HH:mm');
2398
        }
2399
        str += '</td>';
2 - 2400
 
6 - 2401
        str += '<td>' + t.Status.StatusType.Description + '</td>';
2 - 2402
 
6 - 2403
        str += '<td>';
2404
        if (t.ActivityLocation.Address.City !== undefined) {
2405
            str += t.ActivityLocation.Address.City;
2406
            if (t.ActivityLocation.Address.StateProvinceCode !== undefined) {
2407
                str += ", " + t.ActivityLocation.Address.StateProvinceCode;
2408
            }
2409
        }
2410
        str += '</td>';
2 - 2411
 
6 - 2412
        str += '</tr>';
2413
    }
2 - 2414
 
6 - 2415
    return (str);
2 - 2416
}
2417
 
2418
 
2419
function connected() {
6 - 2420
    var x;
2 - 2421
 
6 - 2422
    eBayAuthTokenFlag = true;
30 - 2423
    if (!document.getElementById("connected").innerHTML.endsWith("(Connected)")) {
2424
        document.getElementById("connected").innerHTML += " (Connected)";
2425
    }
2 - 2426
 
6 - 2427
    x = document.getElementById("startButton");
30 - 2428
    x.className = x.className.replace(" btn-danger", " btn-primary");
2 - 2429
 
6 - 2430
    x = document.getElementById("login");
2431
    x.className = x.className.replace(" w3-show", "");
2 - 2432
 
6 - 2433
    x = document.getElementById("results");
2434
    x.innerHTML = "";
2435
    x.className = x.className.replace(" w3-show", "");
2 - 2436
}
2437
 
2438
    </script>
30 - 2439
    <script>includeHTML();</script>
2 - 2440
 
2441
</body>
2442
</html>