Subversion Repositories munaweb

Rev

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