Subversion Repositories munaweb

Rev

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