Subversion Repositories munaweb

Rev

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