Subversion Repositories munaweb

Rev

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