Subversion Repositories munaweb

Rev

Rev 148 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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