Subversion Repositories munaweb

Rev

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