Subversion Repositories munaweb

Rev

Rev 158 | 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()));
198 - 896
        html.push(tableCell(emailAddress != 'Invalid Request' && emailAddress !== undefined ? emailAddress : ""));
6 - 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');
198 - 1254
    xw.writeElementString('IncludeNettedEntries', 'true');
2 - 1255
 
6 - 1256
    xw.writeStartElement('Pagination');
1257
    xw.writeElementString('EntriesPerPage', configXmlRequestEntriesPerPage);
1258
    xw.writeElementString('PageNumber', pageNumber.toString());
1259
    xw.writeEndElement(); /* Pagination */
2 - 1260
 
6 - 1261
    xw.writeElementString('ErrorLanguage', 'en_US');
1262
    xw.writeElementString('Version', configeBayTradingVersion);
1263
    xw.writeElementString('WarningLevel', configWarningLevel);
2 - 1264
 
6 - 1265
    xw.writeEndElement(); /* GetAccountRequest */
1266
    xw.writeEndDocument();
2 - 1267
 
6 - 1268
    xhr.open('POST', configProxyUrl, true);
1269
    xhr.setRequestHeader('Content-Type', 'text/xml');
1270
    xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
1271
    xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
1272
    xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'GetAccount');
1273
    xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
1274
    xhr.setRequestHeader('X-EBAY-API-DEV-NAME', '');
1275
    xhr.setRequestHeader('X-EBAY-API-CERT-NAME', '');
1276
    xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
2 - 1277
 
6 - 1278
    xml = xw.flush();
1279
    xw.close();
2 - 1280
 
6 - 1281
    xhr.onload = () => {
12 - 1282
        var jsonObj = XMLparse(xhr.responseXML, false);
1283
        var obj = jsonObj.GetAccountResponse;
6 - 1284
        var returnCode = obj.Ack;
19 - 1285
        var str;
2 - 1286
 
6 - 1287
        var x = document.getElementById("results");
1288
        if (x.className.indexOf("w3-show") == -1) {
1289
            x.className += " w3-show";
1290
        }
2 - 1291
 
6 - 1292
        if (obj.Message) {
1293
            x.innerHTML += "<p>" + obj.Message + "</p>";
1294
        }
2 - 1295
 
6 - 1296
        if (returnCode == 'Success' || (returnCode == 'Warning' && obj.Errors.ErrorCode == '21917182')) {
1297
            createFeeTable(obj, pageNumber);
2 - 1298
 
12 - 1299
            x.innerHTML += '<p><strong>' + returnCode + ' (Fees/Credits ' + pageNumber + ' / ' + obj.PaginationResult.TotalNumberOfPages + ')</strong></p>';
2 - 1300
 
6 - 1301
            if (obj.HasMoreEntries == 'true') {
1302
                ++pagesToProcess;
1303
                ++maxPagesToProcess;
1304
                updateProgressBar(maxPagesToProcess, pagesProcessed);
1305
                retrieveFees(pageNumber + 1);
1306
            }
2 - 1307
 
6 - 1308
            document.getElementById("logging").innerHTML = html.join('');
2 - 1309
 
6 - 1310
            --pagesToProcess;
1311
            ++pagesProcessed;
1312
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1313
        } else {
1314
            x.className += " process-errors";
19 - 1315
            str = "<p><strong>" + returnCode + ":</strong></p>";
2 - 1316
 
6 - 1317
            var errors = getJsonArray(obj.Errors);
19 - 1318
            str += "<p>";
6 - 1319
            for (i = 0; i < errors.length; i++) {
19 - 1320
                str += errors[i].SeverityCode + " (" + errors[i].ErrorCode + "): " + escapeHtml(errors[i].LongMessage) + "<br/>";
6 - 1321
                if (errors[i].LongMessage.includes('Auth')) {
1322
                    authErrorFlag = true;
1323
                }
1324
            }
19 - 1325
            str += "</p>";
2 - 1326
 
19 - 1327
            x.innerHTML += str;
1328
 
6 - 1329
            if (authErrorFlag === true) {
1330
                eBayAuthTokenFlag = false;
1331
                x = document.getElementById("login");
1332
                if (x.className.indexOf("w3-show") == -1) {
1333
                    x.className += " w3-show";
1334
                }
1335
            }
2 - 1336
 
6 - 1337
            --pagesToProcess;
1338
            ++pagesProcessed;
1339
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1340
        }
1341
    };
2 - 1342
 
6 - 1343
    xhr.send(xml);
2 - 1344
 
6 - 1345
    function checkpagesToProcess() {
1346
        if (pagesToProcess > 0) {
1347
            window.setTimeout(checkpagesToProcess, 100); // wait 100 milliseconds
1348
        } else {
158 - 1349
            sortTable("feeTable", true);
6 - 1350
            x = document.getElementById("results");
1351
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
2 - 1352
 
6 - 1353
            endProgressBar();
1354
 
1355
            var y = document.getElementById("dlFeeListButton");
1356
            if (y.className.indexOf("w3-show") == -1) {
1357
                y.className += " w3-show";
1358
            }
1359
 
1360
            if (!x.className.includes("process-errors")) {
1361
                setTimeout(function() {
1362
                    x.className = x.className.replace(" w3-show", "");
1363
                }, 3000);
1364
            }
1365
        }
1366
    }
1367
 
1368
    if (pageNumber == 1) {
1369
        checkpagesToProcess();
1370
    }
2 - 1371
}
1372
 
1373
function createFeeTable(obj, pageNumber) {
6 - 1374
    var i;
2 - 1375
 
6 - 1376
    if (pageNumber == 1) {
1377
        totalAmount = 0;
2 - 1378
 
6 - 1379
        document.getElementById("logging").innerHTML = '';
1380
        html = [];
30 - 1381
        html.push('<div class="border table-responsive">');
6 - 1382
        html.push('<h3>Fees and Credits List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
30 - 1383
    	html.push('<table id="feeTable" class="table table-hover table-striped table-bordered small">');
1384
        html.push('<thead class="thead-dark">');
6 - 1385
        html.push('<tr>');
2 - 1386
 
158 - 1387
        html.push(tableHeader('Date'));
1388
        html.push(tableHeader('Reference Id'));
6 - 1389
        html.push(tableHeader('Title'));
158 - 1390
        html.push(tableHeader('Item Id'));
6 - 1391
        html.push(tableHeader('Fee Type'));
158 - 1392
        html.push(tableHeader(''));
1393
        html.push(tableHeader(''));
1394
        html.push(tableHeader(''));
1395
        html.push(tableHeader(''));
1396
        html.push(tableHeader(''));
6 - 1397
        html.push(tableHeader('Amount'));
2 - 1398
 
6 - 1399
        html.push('</tr>');
1400
        html.push('</thead>');
1401
        html.push('<tbody>');
1402
    }
2 - 1403
 
12 - 1404
    for (i = 0; i < obj.AccountEntries.AccountEntry.length; i++) {
1405
        var AccountEntry = obj.AccountEntries.AccountEntry[i];
198 - 1406
/*        if ((!AccountEntry.Description.includes('Payment') && !AccountEntry.Description.includes('Final Value Fee') && AccountEntry.GrossDetailAmount.text != '0.0' && AccountEntry.NetDetailAmount.text != '0.0') ||
12 - 1407
            (AccountEntry.Description.includes('Final Value Fee') && AccountEntry.NetDetailAmount.text.substr(0, 1) == '-')) {
198 - 1408
*/
1409
            if (!(AccountEntry.Description == 'Payment' && AccountEntry.RefNumber == 0)) {
6 - 1410
            html.push('<tr>');
2 - 1411
 
158 - 1412
            html.push(tableCellDate(AccountEntry.Date));
1413
            html.push(tableCell(AccountEntry.RefNumber));
1414
            html.push(tableCell(AccountEntry.Title));
12 - 1415
            html.push(tableCell(AccountEntry.ItemID));
1416
            html.push(tableCell(AccountEntry.Description));
158 - 1417
            html.push(tableHeader(''));
1418
            html.push(tableHeader(''));
1419
            html.push(tableHeader(''));
1420
            html.push(tableHeader(''));
1421
            html.push(tableHeader(''));
12 - 1422
            html.push(tableCell('$' + parseFloat(AccountEntry.GrossDetailAmount.text).toFixed(2)));
1423
            totalAmount += parseFloat(AccountEntry.GrossDetailAmount.text);
2 - 1424
 
6 - 1425
            html.push('</tr>');
1426
        }
1427
    }
2 - 1428
 
6 - 1429
    if (obj.HasMoreEntries != 'true') {
1430
        html.push('</tbody>');
1431
        html.push('<tfoot>');
1432
        html.push('<tr>');
1433
        html.push(tableCell('<strong>Totals</strong>'));
1434
        html.push(tableCell(''));
1435
        html.push(tableCell(''));
1436
        html.push(tableCell(''));
158 - 1437
        html.push(tableCell(''));
1438
        html.push(tableCell(''));
1439
        html.push(tableCell(''));
1440
        html.push(tableCell(''));
1441
        html.push(tableCell(''));
1442
        html.push(tableCell(''));
6 - 1443
        html.push(tableCell('<strong>$' + totalAmount.toFixed(2) + '</strong>'));
1444
        html.push('</tr>');
1445
        html.push('</tfoot>');
1446
        html.push('</table>');
30 - 1447
        html.push('</div>');
6 - 1448
    }
2 - 1449
}
1450
 
1451
 
1452
function tableCellDate(utcDate) {
6 - 1453
    var localDate = new Date(utcDate);
1454
    return ('<td>' + localDate.yyyymmdd() + '</td>');
2 - 1455
}
1456
 
1457
function tableCellSKU(str, title) {
6 - 1458
    if (str === undefined) {
1459
        str = '';
1460
    }
2 - 1461
 
6 - 1462
    if (str.indexOf(" - ") > 0) {
1463
        str = str.substr(0, str.indexOf(" - "));
1464
    }
2 - 1465
 
139 - 1466
    if (str.startsWith("Batch") && !isNaN(str.substr(6))) {
6 - 1467
        var batchNo = Number(str.substr(6));
1468
        str = "Batch " + pad(batchNo, 2);
1469
    }
2 - 1470
 
6 - 1471
    if (title.includes('(DVD') || title.includes('(HD') || title.includes('(Blu')) {
1472
        str = 'DVD ' + str;
1473
    } else if (title.includes('(CD')) {
1474
        str = 'CD ' + str;
1475
    } else if (title.includes('Hardcover') || title.includes('Paperback')) {
1476
        str = 'Book ' + str;
1477
    }
2 - 1478
 
6 - 1479
    return ('<td>' + str + '</td>');
2 - 1480
}
1481
 
17 - 1482
function retrieveCancelReturn(pageNumber) {
1483
    if (eBayAuthTokenFlag === false) {
1484
        return;
1485
    }
1486
 
1487
    var valueStartDate = document.getElementById('startDate').value + "T00:00:00.000Z";
1488
    var valueEndDate = document.getElementById('endDate').value + "T23:59:59.999Z";
1489
 
1490
    url = configeBayPostOrder + "/return/search?";
1491
    url += "creation_date_range_from=" + valueStartDate;
1492
    url += "&creation_date_range_to=" + valueEndDate;
1493
    url += "&return_state=CLOSED";
1494
 
1495
    var xhttp = new XMLHttpRequest();
1496
 
1497
    xhttp.onreadystatechange = function() {
147 - 1498
        if (this.readyState == 4 && this.status == 200) {
17 - 1499
            var obj = JSON.parse(this.responseText);
30 - 1500
 
17 - 1501
            createCancelReturnTable(obj, pageNumber, true);
1502
 
1503
            if (obj.paginationOutput.totalPages > pageNumber) {
1504
                ++pagesToProcess;
1505
                ++maxPagesToProcess;
1506
                updateProgressBar(maxPagesToProcess, pagesProcessed);
1507
                retrieveCancelReturn(pageNumber + 1);
1508
            }
1509
 
1510
            document.getElementById("logging").innerHTML = html.join('');
1511
 
1512
            --pagesToProcess;
1513
            ++pagesProcessed;
1514
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1515
        }
1516
    };
1517
 
1518
    xhttp.open("GET", configProxyUrl, true);
1519
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
1520
    xhttp.setRequestHeader("X-Authorization", "TOKEN " + eBayAuthToken);
1521
    xhttp.setRequestHeader("Content-Type", "application/json");
1522
    xhttp.setRequestHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
1523
    xhttp.send();
1524
 
1525
    function checkpagesToProcess() {
1526
        if (pagesToProcess > 0) {
1527
            window.setTimeout(checkpagesToProcess, 100); // wait 100 milliseconds
1528
        } else {
1529
            endProgressBar();
1530
 
1531
            pagesToProcess = 1;
1532
            maxPagesToProcess = 1;
1533
            pagesProcessed = 0;
1534
            initProgressBar("Retrieving Cancellations...");
1535
 
1536
            retrieveCancel(1);
1537
        }
1538
    }
1539
 
1540
    if (pageNumber == 1) {
1541
        checkpagesToProcess();
1542
    }
1543
}
1544
 
1545
function retrieveCancel(pageNumber) {
1546
    if (eBayAuthTokenFlag === false) {
1547
        return;
1548
    }
1549
 
1550
    var valueStartDate = document.getElementById('startDate').value + "T00:00:00.000Z";
1551
    var valueEndDate = document.getElementById('endDate').value + "T23:59:59.999Z";
1552
 
1553
    url = configeBayPostOrder + "/cancellation/search?";
1554
    url += "creation_date_range_from=" + valueStartDate;
1555
    url += "&creation_date_range_to=" + valueEndDate;
1556
    url += "&return_state=CLOSED";
1557
 
1558
    var xhttp = new XMLHttpRequest();
1559
 
1560
    xhttp.onreadystatechange = function() {
147 - 1561
        if (this.readyState == 4 && this.status == 200) {
17 - 1562
            var obj = JSON.parse(this.responseText);
30 - 1563
 
17 - 1564
            createCancelReturnTable(obj, pageNumber, false);
1565
 
1566
            if (obj.paginationOutput.totalPages > pageNumber) {
1567
                ++pagesToProcess;
1568
                ++maxPagesToProcess;
1569
                updateProgressBar(maxPagesToProcess, pagesProcessed);
1570
                retrieveCancel(pageNumber + 1);
1571
            }
1572
 
1573
            document.getElementById("logging").innerHTML = html.join('');
1574
 
1575
            --pagesToProcess;
1576
            ++pagesProcessed;
1577
            updateProgressBar(maxPagesToProcess, pagesProcessed);
1578
        }
1579
    };
1580
 
1581
    xhttp.open("GET", configProxyUrl, true);
1582
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
1583
    xhttp.setRequestHeader("X-Authorization", "TOKEN " + eBayAuthToken);
1584
    xhttp.setRequestHeader("Content-Type", "application/json");
1585
    xhttp.setRequestHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
1586
    xhttp.send();
1587
 
1588
    function checkpagesToProcess() {
1589
        if (pagesToProcess > 0) {
1590
            window.setTimeout(checkpagesToProcess, 100); // wait 100 milliseconds
1591
        } else {
158 - 1592
            sortTable("cancelReturnTable", true);
17 - 1593
            x = document.getElementById("results");
1594
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1595
 
1596
            endProgressBar();
1597
 
1598
            var y = document.getElementById("dlCancelReturnListButton");
1599
            if (y.className.indexOf("w3-show") == -1) {
1600
                y.className += " w3-show";
1601
            }
1602
 
1603
            if (!x.className.includes("process-errors")) {
1604
                setTimeout(function() {
1605
                    x.className = x.className.replace(" w3-show", "");
1606
                }, 3000);
1607
            }
1608
        }
1609
    }
1610
 
1611
    if (pageNumber == 1) {
1612
        checkpagesToProcess();
1613
    }
1614
}
1615
function createCancelReturnTable(obj, pageNumber, flag) {
1616
    var i;
1617
 
1618
    if (pageNumber == 1 && flag) {
1619
        totalAmount = 0;
1620
 
1621
        document.getElementById("logging").innerHTML = '';
1622
        html = [];
1623
 
30 - 1624
        html.push('<div class="border table-responsive">');
17 - 1625
        html.push('<h3>Cancellations and Returns List from ' + document.getElementById("startDate").value + ' to ' + document.getElementById("endDate").value + '</h3>');
30 - 1626
    	html.push('<table id="cancelReturnTable" class="table table-hover table-striped table-bordered small">');
1627
        html.push('<thead class="thead-dark">');
17 - 1628
        html.push('<tr>');
1629
 
158 - 1630
        html.push(tableHeader('Date'));
1631
        html.push(tableHeader('Order Id'));
1632
        html.push(tableHeader('Title'));
17 - 1633
        html.push(tableHeader('Item ID'));
1634
        html.push(tableHeader('Reason'));
1635
        html.push(tableHeader('Status'));
158 - 1636
        html.push(tableHeader(''));
1637
        html.push(tableHeader(''));
17 - 1638
        html.push(tableHeader('Amount'));
1639
 
1640
        html.push('</tr>');
1641
        html.push('</thead>');
1642
        html.push('<tbody>');
1643
    }
1644
 
1645
    if (flag) {
1646
        for (i = 0; obj.members !== undefined && i < obj.members.length; i++) {
1647
            var returnEntry = obj.members[i];
1648
            html.push('<tr>');
1649
 
158 - 1650
            html.push(tableCellDate(returnEntry.creationInfo.creationDate.value.substr(0,10)));
1651
            html.push(tableCell(returnEntry.orderId));
1652
            html.push(tableCell(returnEntry.creationInfo.item.itemTitle));
17 - 1653
            html.push(tableCell(returnEntry.creationInfo.item.itemId));
158 - 1654
            html.push(tableCell(returnEntry.creationInfo.reason));
17 - 1655
            html.push(tableCell(returnEntry.status));
158 - 1656
            html.push(tableCell(''));
1657
            html.push(tableCell(''));
1658
            if (returnEntry.sellerTotalRefund.actualRefundAmount !== undefined) {
1659
                html.push(tableCell('$' + parseFloat(returnEntry.sellerTotalRefund.actualRefundAmount.value).toFixed(2)));
1660
                totalAmount += parseFloat(returnEntry.sellerTotalRefund.actualRefundAmount.value);
1661
            } else{
1662
                html.push(tableCell('$' + parseFloat(returnEntry.sellerTotalRefund.estimatedRefundAmount.value).toFixed(2)));
1663
                totalAmount += parseFloat(returnEntry.sellerTotalRefund.estimatedRefundAmount.value);
1664
            }
17 - 1665
 
1666
            html.push('</tr>');
1667
        }
1668
    } else{
1669
        for (i = 0; obj.cancellations !== undefined && i < obj.cancellations.length; i++) {
1670
            var cancelEntry = obj.cancellations[i];
30 - 1671
 
17 - 1672
            if (cancelEntry.cancelStatus == 'CANCEL_CLOSED_WITH_REFUND') {
1673
                html.push('<tr>');
1674
 
1675
                html.push(tableCellDate(cancelEntry.cancelCloseDate.value.substr(0,10)));
158 - 1676
                html.push(tableCell(cancelEntry.legacyOrderId));
1677
                html.push(tableCell(cancelEntry.lineItems[0].itemTitle));
1678
                html.push(tableCell(cancelEntry.lineItems[0].itemId));
17 - 1679
                html.push(tableCell(cancelEntry.requestorType + ' / ' + cancelEntry.cancelCloseReason));
1680
                html.push(tableCell(cancelEntry.cancelStatus));
158 - 1681
                html.push(tableCell(''));
1682
                html.push(tableCell(''));
17 - 1683
                html.push(tableCell('$' + parseFloat(cancelEntry.requestRefundAmount.value).toFixed(2)));
1684
                totalAmount += parseFloat(cancelEntry.requestRefundAmount.value);
1685
 
1686
                html.push('</tr>');
1687
            }
1688
        }
1689
    }
1690
 
1691
    if (!flag) {
1692
        if (obj.HasMoreEntries != 'true') {
1693
            html.push('</tbody>');
1694
            html.push('<tfoot>');
1695
            html.push('<tr>');
1696
            html.push(tableCell('<strong>Totals</strong>'));
1697
            html.push(tableCell(''));
1698
            html.push(tableCell(''));
1699
            html.push(tableCell(''));
158 - 1700
            html.push(tableCell(''));
1701
            html.push(tableCell(''));
1702
            html.push(tableCell(''));
1703
            html.push(tableCell(''));
17 - 1704
            html.push(tableCell('<strong>$' + totalAmount.toFixed(2) + '</strong>'));
1705
            html.push('</tr>');
1706
            html.push('</tfoot>');
1707
            html.push('</table>');
30 - 1708
            html.push('</div>');
17 - 1709
        }
1710
    }
1711
}
1712
 
139 - 1713
function sortTable(tableName, stringSortFlag = false){
1714
    var tbl = document.getElementById(tableName).tBodies[0];
1715
    var sortnr;
1716
    var store = [];
1717
    for (var i = 0, len = tbl.rows.length; i < len; i++) {
1718
        var row = tbl.rows[i];
1719
        if (stringSortFlag) {
1720
            sortnr = row.cells[0].textContent || row.cells[0].innerText;
1721
            store.push([sortnr, row]);
1722
        } else {
1723
            sortnr = parseInt(row.cells[0].textContent || row.cells[0].innerText);
1724
            if(!isNaN(sortnr)) store.push([sortnr, row]);
6 - 1725
        }
139 - 1726
    }
1727
    store.sort(function(x,y){
1728
        if (stringSortFlag) {
1729
            return x[0] > y[0];
1730
        } else {
1731
            return x[0] - y[0];
6 - 1732
        }
139 - 1733
    });
1734
    for(var i=0, len=store.length; i<len; i++){
1735
        tbl.appendChild(store[i][1]);
6 - 1736
    }
139 - 1737
    store = null;
2 - 1738
}
1739
 
1740
function printData() {
6 - 1741
    var printContent = document.getElementById("printTable");
2 - 1742
 
6 - 1743
    var num;
1744
    var cssReference = [];
1745
    var uniqueName = new Date();
2 - 1746
 
6 - 1747
    var windowName = 'Print' + uniqueName.getTime();
1748
    var printWindow = window.open(num, windowName, 'left=50000,top=50000,width=0,height=0');
1749
    cssReference[0] = printWindow.document.createElement("link");
30 - 1750
    cssReference[0].href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css";
6 - 1751
    cssReference[0].rel = "stylesheet";
1752
    cssReference[0].type = "text/css";
1753
    cssReference[1] = printWindow.document.createElement("link");
1754
    cssReference[1].href = "css/style.css";
1755
    cssReference[1].rel = "stylesheet";
1756
    cssReference[1].type = "text/css";
2 - 1757
 
34 - 1758
    printWindow.document.write(printContent.outerHTML.replace("table-bordered", "").replace("table-striped", "").replace("table-hover", ""));
6 - 1759
    printWindow.document.getElementsByTagName('head')[0].appendChild(cssReference[0]);
1760
    printWindow.document.getElementsByTagName('head')[0].appendChild(cssReference[1]);
2 - 1761
 
6 - 1762
    printWindow.document.close();
1763
    printWindow.focus();
1764
    printWindow.print();
1765
    printWindow.close();
2 - 1766
}
1767
 
1768
function printSummary() {
134 - 1769
    var profit = grossSales + shippingRcvd - shippingCost - eBayFees - PayPalFees;
2 - 1770
 
30 - 1771
    document.getElementById("summary").innerHTML = '<h2>Profit: ' + profit.toFixed(2) + '</h3>';
2 - 1772
}
1773
 
1774
function findThumbNails() {
6 - 1775
    var i;
1776
    var x = document.getElementById("shippingTable");
2 - 1777
 
6 - 1778
    thumbnailsToProcess = 0;
1779
    thumbnailsProcessed = 0;
1780
    maxThumbnailsToProcess = 0;
1781
    initProgressBar("");
2 - 1782
 
6 - 1783
    for (i = 1; i < (x.rows.length - 1); i++) {
1784
        if (x.rows[i].cells[7].innerHTML == 'eBay' && x.rows[i].cells[2] !== undefined && x.rows[i].cells[2].innerHTML.length < 1) {
1785
            ++thumbnailsToProcess;
1786
            ++maxThumbnailsToProcess;
1787
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1788
            getThumbNail(x.rows[i].cells[4].innerHTML);
1789
        } else if (x.rows[i].cells[7].innerHTML == 'Shopify' && x.rows[i].cells[2] !== undefined && x.rows[i].cells[2].innerHTML.length > 0) {
1790
            ++thumbnailsToProcess;
1791
            ++maxThumbnailsToProcess;
1792
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1793
            getShopifyThumbNail(x.rows[i].cells[2].innerHTML);
1794
        }
1795
    }
2 - 1796
 
6 - 1797
    function checkthumbnailsToProcess() {
1798
        if (thumbnailsToProcess > 0) {
1799
            window.setTimeout(checkthumbnailsToProcess, 100); // wait 100 milliseconds
1800
        } else {
1801
            endProgressBar();
1802
            x = document.getElementById("results");
1803
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1804
            if (!x.className.includes("process-errors")) {
1805
                setTimeout(function() {
1806
                    x.className = x.className.replace(" w3-show", "");
1807
                }, 3000);
1808
            }
1809
        }
1810
    }
2 - 1811
 
6 - 1812
    checkthumbnailsToProcess();
2 - 1813
}
1814
 
1815
function getThumbNail(itemId) {
6 - 1816
    // Construct the getSingleItem request
1817
    url = configeBayShopping + "?";
1818
    url += "callname=GetSingleItem";
1819
    url += "&responseencoding=JSON";
1820
    url += "&appid=" + configAppid;
1821
    url += "&version=" + configeBayShoppingVersion;
1822
    url += "&ItemID=";
1823
    url += itemId;
2 - 1824
 
6 - 1825
    var xhttp = new XMLHttpRequest();
2 - 1826
 
6 - 1827
    xhttp.onreadystatechange = function() {
147 - 1828
        if (this.readyState == 4 && this.status == 200) {
148 - 1829
            if (this.responseText) {
1830
                _cb_getThumbNail(JSON.parse(this.responseText));
1831
            } else {
1832
                getThumbNail(itemId);
1833
            }
6 - 1834
        }
1835
    };
2 - 1836
 
6 - 1837
    xhttp.open("GET", configProxyUrl, true);
1838
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
1839
    xhttp.send();
2 - 1840
}
1841
 
1842
function _cb_getThumbNail(root) {
6 - 1843
    var ack = root.Ack;
2 - 1844
 
6 - 1845
    if (ack == 'Failure' || ack == 'PartialFailure') {
1846
        return;
1847
    }
2 - 1848
 
6 - 1849
    var JsonObj = typeof root.Item != 'object' ? JSON.parse(root.Item) : root.Item;
1850
    var ItemID = JsonObj.ItemID;
1851
    var PictureURL = getJsonArray(JsonObj.PictureURL);
2 - 1852
 
6 - 1853
    document.getElementById('PictureURL' + ItemID).innerHTML = '<img src="' + PictureURL[0] + '" style="max-height:100px">';
1854
    --thumbnailsToProcess;
1855
    ++thumbnailsProcessed;
1856
    updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
2 - 1857
}
1858
 
1859
function getShopifyThumbNail(productId) {
6 - 1860
    var xhttp = new XMLHttpRequest();
1861
    xhttp.onreadystatechange = function() {
1862
        if (this.readyState == 4 && this.status == 200) {
1863
            //window.alert(this.responseText);
1864
            var json = JSON.parse(this.responseText);
1865
            if (json.product !== undefined) {
1866
                document.getElementById('PictureURL' + productId).innerHTML = '<img src="' + json.product.image.src + '" style="max-height:100px">';
1867
            }
1868
            --thumbnailsToProcess;
1869
            ++thumbnailsProcessed;
1870
            updateProgressBar(maxThumbnailsToProcess, thumbnailsProcessed);
1871
        }
1872
    };
2 - 1873
 
6 - 1874
    xhttp.open("GET", configProxyUrl, true);
1875
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + 'products/' + productId + '.json?fields=image'));
1876
    xhttp.send();
2 - 1877
}
1878
 
1879
function findShippingCosts() {
6 - 1880
    var i;
1881
    var x;
2 - 1882
 
6 - 1883
    shippingsToProcess = 0;
1884
    shippingsProcessed = 0;
1885
    maxShippingsToProcess = 0;
1886
    initProgressBar("Retrieving Shipping Costs...");
2 - 1887
 
6 - 1888
    if (getRadioValue('rptType') == 'trackingList') {
1889
        x = document.getElementById("trackingTable");
1890
    } else {
1891
        x = document.getElementById("orderTable");
1892
    }
2 - 1893
 
6 - 1894
    for (i = (x.rows.length - 1); i > 0; i--) {
1895
        if (getRadioValue('rptType') == 'trackingList') {
1896
            if (x.rows[i].cells[3] !== undefined && x.rows[i].cells[3].innerHTML.length < 1) {
1897
                if (x.rows[i].cells[7] !== undefined && x.rows[i].cells[7].innerHTML.length < 1) {
1898
                    document.getElementById("trackingTable").deleteRow(i);
1899
                } else {
1900
                    ++shippingsToProcess;
1901
                    ++maxShippingsToProcess;
1902
                    updateProgressBar(maxShippingsToProcess, shippingsProcessed);
1903
                    getShippingCost(x.rows[i].cells[2].innerHTML);
1904
                }
1905
            }
1906
        } else {
158 - 1907
            if (x.rows[i].cells[4].innerHTML == 'eBay' && x.rows[i].cells[9] !== undefined && x.rows[i].cells[9].innerHTML.length < 1) {
6 - 1908
                ++shippingsToProcess;
1909
                ++maxShippingsToProcess;
1910
                updateProgressBar(maxShippingsToProcess, shippingsProcessed);
158 - 1911
                getShippingCost(x.rows[i].cells[1].innerHTML);
1912
            } else if (x.rows[i].cells[4].innerHTML == 'Shopify') {
6 - 1913
                ++shippingsToProcess;
1914
                ++maxShippingsToProcess;
1915
                updateProgressBar(maxShippingsToProcess, shippingsProcessed);
158 - 1916
                getPaymentTransaction(x.rows[i].cells[1].innerHTML);
6 - 1917
            }
1918
        }
1919
    }
2 - 1920
 
6 - 1921
    function checkshippingsToProcess() {
1922
        if (shippingsToProcess > 0) {
1923
            window.setTimeout(checkshippingsToProcess, 100); // wait 100 milliseconds
1924
        } else {
1925
            endProgressBar();
1926
            x = document.getElementById("results");
1927
            if (getRadioValue('rptType') != 'trackingList') {
1928
                document.getElementById("ShippingTotal").innerHTML = '<strong>$' + shippingCost.toFixed(2) + '</strong>';
1929
                x.innerHTML += '<p><strong>Report Finished!</strong></p>';
1930
                if (!x.className.includes("process-errors")) {
1931
                    setTimeout(function() {
1932
                        x.className = x.className.replace(" w3-show", "");
1933
                    }, 3000);
1934
                }
1935
            } else {
1936
                x.innerHTML += '<p><strong>Retrieving Carrier Tracking...</strong></p>';
1937
                getTrackingDetails();
1938
            }
1939
        }
1940
    }
1941
 
1942
    checkshippingsToProcess();
2 - 1943
}
1944
 
1945
function getShippingCost(OrderId) {
6 - 1946
    var i;
1947
    var xml;
1948
    var correlationId;
1949
    var shippingCostStr;
1950
    var deliveryStatus;
1951
    var authErrorFlag = false;
2 - 1952
 
6 - 1953
    var xw = new XMLWriter('UTF-8', '1.0');
1954
    var xhr = new XMLHttpRequest();
2 - 1955
 
6 - 1956
    xw.writeStartDocument();
1957
    xw.writeStartElement("GetSellingManagerSaleRecordRequest");
1958
    xw.writeAttributeString('xmlns', 'urn:ebay:apis:eBLBaseComponents');
2 - 1959
 
6 - 1960
    xw.writeStartElement('RequesterCredentials');
1961
    xw.writeElementString('eBayAuthToken', eBayAuthToken);
1962
    xw.writeEndElement(); /* RequesterCredentials */
2 - 1963
 
6 - 1964
    xw.writeElementString('OrderID', OrderId);
1965
    xw.writeElementString('MessageID', OrderId);
2 - 1966
 
6 - 1967
    xw.writeElementString('ErrorLanguage', 'en_US');
1968
    xw.writeElementString('Version', configeBayTradingVersion);
1969
    xw.writeElementString('WarningLevel', configWarningLevel);
2 - 1970
 
6 - 1971
    xw.writeEndElement(); /* GetSellingManagerSaleRecordRequest */
1972
    xw.writeEndDocument();
2 - 1973
 
6 - 1974
    xhr.open('POST', configProxyUrl, true);
1975
    xhr.setRequestHeader('Content-Type', 'text/xml');
1976
    xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
1977
    xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
1978
    xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'GetSellingManagerSaleRecord');
1979
    xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
1980
    xhr.setRequestHeader('X-EBAY-API-DEV-NAME', '');
1981
    xhr.setRequestHeader('X-EBAY-API-CERT-NAME', '');
1982
    xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
2 - 1983
 
6 - 1984
    xml = xw.flush();
1985
    xw.close();
2 - 1986
 
6 - 1987
    xhr.onload = () => {
12 - 1988
        var jsonObj = XMLparse(xhr.responseXML, false);
1989
        var obj = jsonObj.GetSellingManagerSaleRecordResponse;
6 - 1990
        var returnCode = obj.Ack;
19 - 1991
        var str;
2 - 1992
 
6 - 1993
        var x = document.getElementById("results");
1994
        if (x.className.indexOf("w3-show") == -1) {
1995
            x.className += " w3-show";
1996
        }
2 - 1997
 
6 - 1998
        if (obj.Message) {
1999
            x.innerHTML += "<p>" + obj.Message + "</p>";
2000
        }
2 - 2001
 
6 - 2002
        if (returnCode == 'Success' || (returnCode == 'Warning' && obj.Errors.ErrorCode == '21917182')) {
2003
            correlationId = obj.CorrelationID;
2004
            deliveryStatus = '';
2005
            shippingCostStr = '';
2 - 2006
 
6 - 2007
            if (obj.SellingManagerSoldOrder.ActualShippingCost !== undefined &&
2008
                obj.SellingManagerSoldOrder.ActualShippingCost.text != '0.0' &&
2009
                document.getElementById('ShippingCost' + correlationId).innerHTML.length < 1) {
2010
                shippingCostStr = '$' + parseFloat(obj.SellingManagerSoldOrder.ActualShippingCost.text).toFixed(2);
2011
                shippingCost += parseFloat(obj.SellingManagerSoldOrder.ActualShippingCost.text);
2012
                document.getElementById('ShippingCost' + correlationId).innerHTML = shippingCostStr;
2013
                if (getRadioValue('rptType') == 'orderList') {
2014
                    printSummary();
2015
                }
2016
            }
2 - 2017
 
6 - 2018
            if (getRadioValue('rptType') != 'trackingList') {
2019
                var soldTransactions = getJsonArray(obj.SellingManagerSoldOrder.SellingManagerSoldTransaction);
2020
                for (i = 0; i < soldTransactions.length; i++) {
97 - 2021
                    if (soldTransactions[i].Shipment !== undefined && soldTransactions[i].Shipment.DeliveryStatus !== undefined) {
6 - 2022
                        deliveryStatus += (i > 0 ? '<br/>' : '') + soldTransactions[i].Shipment.DeliveryStatus;
2023
                    }
2024
                }
2025
                document.getElementById('Delivery' + correlationId).innerHTML = deliveryStatus;
2026
            }
2027
        } else {
2028
            x.className += " process-errors";
19 - 2029
            str = "<p><strong>" + returnCode + ":</strong></p>";
2 - 2030
 
6 - 2031
            var errors = getJsonArray(obj.Errors);
19 - 2032
            str += "<p>";
6 - 2033
            for (i = 0; i < errors.length; i++) {
19 - 2034
                str += errors[i].SeverityCode + " (" + errors[i].ErrorCode + "): " + escapeHtml(errors[i].LongMessage) + "<br/>";
6 - 2035
                if (errors[i].LongMessage.includes('Auth')) {
2036
                    authErrorFlag = true;
2037
                }
2038
            }
19 - 2039
            str += "</p>";
2 - 2040
 
19 - 2041
            x.innerHTML += str;
2042
 
6 - 2043
            if (authErrorFlag === true) {
2044
                eBayAuthTokenFlag = false;
2045
                x = document.getElementById("login");
2046
                if (x.className.indexOf("w3-show") == -1) {
2047
                    x.className += " w3-show";
2048
                }
2049
            }
2050
        }
2 - 2051
 
6 - 2052
        --shippingsToProcess;
2053
        ++shippingsProcessed;
2054
        updateProgressBar(maxShippingsToProcess, shippingsProcessed);
2055
    };
2 - 2056
 
6 - 2057
    xhr.send(xml);
2 - 2058
}
2059
 
2060
function getPaymentTransaction(fullId) {
6 - 2061
    var id = fullId.substr(0, fullId.indexOf(' '));
2062
    var i;
2063
    var transFee = 0.00;
2064
    var transFeeStr = '';
2065
    var transDate = '';
2066
    var transId = '';
2 - 2067
 
6 - 2068
    var xhttp = new XMLHttpRequest();
2069
    xhttp.onreadystatechange = function() {
2070
        if (this.readyState == 4 && this.status == 200) {
2071
            //window.alert(this.responseText);
2072
            var json = JSON.parse(this.responseText);
10 - 2073
            var transactions = getJsonArray(json.transactions);
2074
            for (i = 0; i < transactions.length; i++) {
2075
                transDate = getJsonValue(transactions[i].created_at).substr(0, 10);
2076
                document.getElementById('PaidDate' + id).innerHTML = transDate;
2 - 2077
 
10 - 2078
                var gateway = getJsonValue(transactions[i].gateway);
2079
                if (gateway == 'shopify_payments') {
2080
                    transId = getJsonValue(transactions[i].id);
2081
                    transFee = Number(getJsonValue(transactions[i].receipt.fee_amount)) / 100;
2082
                } else if (gateway == 'paypal') {
2083
                    transId = getJsonValue(transactions[i].authorization);
2084
                    transFee = Number(getJsonValue(transactions[i].receipt.fee_amount));
2085
                } else if (gateway == 'manual') {
2086
                    transId = getJsonValue(json.transactions[i].id);
2087
                }
2 - 2088
 
10 - 2089
                document.getElementById('TransactionId' + id).innerHTML = transId;
2 - 2090
 
10 - 2091
                transFeeStr = '$' + parseFloat(transFee).toFixed(2);
2092
                PayPalFees += transFee;
2093
                document.getElementById('Fee' + id).innerHTML = transFeeStr;
6 - 2094
            }
2 - 2095
 
6 - 2096
            --shippingsToProcess;
2097
            ++shippingsProcessed;
2098
            updateProgressBar(maxShippingsToProcess, shippingsProcessed);
2099
        }
2100
    };
2 - 2101
 
6 - 2102
    xhttp.open("GET", configProxyUrl, true);
2103
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(configShopifyUrl + configShopifyTransactionsUrl1 + id + configShopifyTransactionsUrl2));
2104
    xhttp.send();
2 - 2105
}
2106
 
2107
function getTrackingDetails() {
6 - 2108
    var i;
2109
    var x;
2 - 2110
 
6 - 2111
    trackingNumbersToProcess = 0;
2112
    trackingNumbersProcessed = 0;
2113
    maxTrackingNumbersToProcess = 0;
2114
    initProgressBar("Retrieving Carrier Tracking...");
2 - 2115
 
6 - 2116
    for (i = 0; i < trackingList.length; i++) {
2117
        ++trackingNumbersToProcess;
2118
        ++maxTrackingNumbersToProcess;
2119
        if (trackingList[i].substr(0, 2) == '1Z') {
2120
            getUPSTracking(trackingList[i]);
2121
        } else {
2122
            getUSPSTracking(trackingList[i]);
2123
        }
2124
    }
2 - 2125
 
6 - 2126
    function checkTrackingsToProcess() {
2127
        if (trackingNumbersToProcess > 0) {
2128
            window.setTimeout(checkTrackingsToProcess, 100); // wait 100 milliseconds
2129
        } else {
2130
            endProgressBar();
2131
            x = document.getElementById("results");
2132
            x.innerHTML += '<p><strong>Report Finished!</strong></p>';
2133
            if (!x.className.includes("process-errors")) {
2134
                setTimeout(function() {
2135
                    x.className = x.className.replace(" w3-show", "");
2136
                }, 3000);
2137
            }
2138
        }
2139
    }
2 - 2140
 
6 - 2141
    checkTrackingsToProcess();
2 - 2142
}
2143
 
2144
function getUSPSTracking(searchNumber) {
6 - 2145
    var j;
2146
    var str;
2147
    var url;
2148
    var trackingNumber;
2149
    var summary;
2150
    var detail;
2151
    var deliveryDate;
2152
    var createDate;
2153
    var duration;
2154
    var lastUpdate;
2155
    var lastEvent;
2156
    var footer;
2 - 2157
 
6 - 2158
    var xhttp = new XMLHttpRequest();
2159
    xhttp.onreadystatechange = function() {
2160
        if (this.readyState == 4 && this.status == 200) {
12 - 2161
            var obj = XMLparse(this.responseXML, false);
2 - 2162
 
12 - 2163
            if (obj.TrackResponse.TrackInfo.TrackSummary === undefined) {
6 - 2164
                --trackingNumbersToProcess;
2165
                ++trackingNumbersProcessed;
2166
                updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2167
                return;
2168
            }
2 - 2169
 
12 - 2170
            var trackingInfo = obj.TrackResponse.TrackInfo;
2171
 
2172
            trackingNumber = trackingInfo.ID;
2173
            summary = formatUSPSTrackingLine(trackingInfo.TrackSummary);
6 - 2174
            detail = '';
2175
            footer = '';
2176
            deliveryDate = '';
2177
            duration = '';
2178
            lastUpdate = summary.substr(8, 10);
12 - 2179
            lastEvent = trackingInfo.TrackSummary.Event;
2 - 2180
 
6 - 2181
            if (document.getElementById('DeliveryStatus' + trackingNumber) === null) {
2182
                --trackingNumbersToProcess;
2183
                ++trackingNumbersProcessed;
2184
                updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2185
                return;
2186
            }
2 - 2187
 
12 - 2188
            if (trackingInfo.TrackDetail !== undefined && trackingInfo.TrackDetail.length > 0) {
2189
                for (j = 0; j < trackingInfo.TrackDetail.length; j++) {
2190
                    detail += formatUSPSTrackingLine(trackingInfo.TrackDetail[j]);
6 - 2191
                }
2 - 2192
 
12 - 2193
                createDate = moment(trackingInfo.TrackDetail[(trackingInfo.TrackDetail.length - 1)].EventDate, "MMMM DD, YYYY").format('YYYY-MM-DD');
6 - 2194
                footer = 'Enroute since ' + createDate + ' (' + moment().diff(createDate, 'days') + ' days)';
2 - 2195
 
6 - 2196
                if (summary.includes("Delivered")) {
2197
                    deliveryDate = summary.substr(8, 10);
2198
                    duration = moment(deliveryDate).diff(createDate, 'days');
2199
                    document.getElementById('DeliveryStatus' + trackingNumber).style.color = "green";
2200
                    footer = 'Delivered in ' + moment(deliveryDate).to(createDate, 'days');
2201
                } else if (moment().diff(lastUpdate, 'days') > 3) {
2202
                    document.getElementById('DeliveryStatus' + trackingNumber).style.color = "red";
2203
                }
2204
            }
2 - 2205
 
6 - 2206
            document.getElementById('DeliveryStatus' + trackingNumber).innerHTML = lastEvent;
2207
            document.getElementById('DeliveryDays' + trackingNumber).innerHTML = duration;
2208
            document.getElementById('DeliveryDate' + trackingNumber).innerHTML = deliveryDate;
2 - 2209
 
6 - 2210
            str = document.getElementById(trackingNumber).innerHTML;
2211
            if (!str.startsWith('<button')) {
30 - 2212
                document.getElementById(trackingNumber).innerHTML = '<button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#mod' + trackingNumber + '">' + str + '</button>';
2 - 2213
 
30 - 2214
                str = '<div id="mod' + trackingNumber + '" class="modal">';
2215
                str += '<div class="modal-dialog modal-lg">';
2216
                str += '<div class="modal-content">';
2217
                str += '<div class="modal-header">';
2218
                str += '<h3>' + trackingNumber + ' (USPS ' + getCarrierService("USPS", trackingNumber, false) + ')</h3>';
2219
                str += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
2220
                str += '</div>';
2221
                str += '<div class="modal-body">';
2222
                str += '<table class="table border small">';
2223
                str += '<thead class="thead-dark">';
2224
                str += '<tr>';
2225
                str += '<th>DATE</th>';
2226
                str += '<th>TIME</th>';
2227
                str += '<th>STATUS</th>';
2228
                str += '<th>LOCATION</th>';
2229
                str += '</tr>';
2230
                str += '</thead>';
2231
                str += '<tbody>';
6 - 2232
                str += summary;
2233
                str += detail;
30 - 2234
                str += '</tbody>';
2235
                str += '</table>';
2236
                str += '</div>';
2237
                str += '<div class="modal-footer">';
2238
                str += '<p>' + document.getElementById('DeliveryAddress' + trackingNumber).innerHTML + ' - ' + footer + '</p>';
2239
                str += '</div>';
2240
                str += '</div>';
2241
                str += '</div>';
2242
                str += '</div>';
2 - 2243
 
6 - 2244
                document.getElementById("modals").innerHTML += str;
2245
            }
2 - 2246
 
6 - 2247
            --trackingNumbersToProcess;
2248
            ++trackingNumbersProcessed;
2249
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2250
        }
2251
    };
2 - 2252
 
6 - 2253
    url = configUSPSUrl + '?API=TrackV2&XML=';
2254
    url += '<TrackFieldRequest USERID="';
2255
    url += configUSPSUserId;
2256
    url += '">';
2257
    url += '<TrackID ID="' + searchNumber + '"></TrackID>';
2258
    url += '</TrackFieldRequest>';
2259
    url = url.replace(/ /g, '%20');
2 - 2260
 
6 - 2261
    xhttp.open("GET", configProxyUrl, true);
2262
    xhttp.setRequestHeader("X-Proxy-Url", encodeURI(url));
2263
    xhttp.send();
2 - 2264
}
2265
 
2266
function formatUSPSTrackingLine(t) {
6 - 2267
    var str = '';
2 - 2268
 
6 - 2269
    if (t !== undefined) {
2270
        str = '<tr>';
2 - 2271
 
6 - 2272
        str += '<td>' + moment(t.EventDate, "MMMM DD, YYYY").format('YYYY-MM-DD') + '</td>';
2 - 2273
 
6 - 2274
        str += '<td>';
2275
        if (t.EventTime.length > 0) {
2276
            str += ' ' + moment(t.EventTime, "hh:mm a").format('HH:mm');
2277
        }
2278
        str += '</td>';
2 - 2279
 
6 - 2280
        str += '<td>' + t.Event + '</td>';
2 - 2281
 
6 - 2282
        str += '<td>';
2283
        if (t.EventCity.length > 0) {
2284
            str += t.EventCity;
2285
            if (t.EventState.length > 0) {
2286
                str += ", " + t.EventState + ' ' + t.EventZIPCode;
2287
            }
2288
        }
2289
        str += '</td>';
2 - 2290
 
6 - 2291
        str += '</tr>';
2292
    }
2 - 2293
 
6 - 2294
    return (str);
2 - 2295
}
2296
 
2297
function getUPSTracking(trackingNumber) {
6 - 2298
    var xhr = new XMLHttpRequest();
2 - 2299
 
6 - 2300
    var xml = '<?xml version="1.0"?>';
2301
    xml += '<AccessRequest xml:lang="en-US">';
2302
    xml += '<AccessLicenseNumber>' + configUPSAccessKey + '</AccessLicenseNumber>';
2303
    xml += '<UserId>' + configUPSUsername + '</UserId>';
2304
    xml += '<Password>' + configUPSPassword + '</Password>';
2305
    xml += '</AccessRequest>';
2306
    xml += '<?xml version="1.0"?>';
2307
    xml += '<TrackRequest xml:lang="en-US">';
2308
    xml += '<Request>';
2309
    xml += '<TransactionReference>';
2310
    xml += '<CustomerContext>' + 'MUNA Trading' + '</CustomerContext>';
2311
    xml += '</TransactionReference>';
2312
    xml += '<RequestAction>Track</RequestAction>';
2313
    xml += '<RequestOption>1</RequestOption>';
2314
    xml += '</Request>';
2315
    xml += '<TrackingNumber>' + trackingNumber + '</TrackingNumber>';
2316
    xml += '</TrackRequest>';
2 - 2317
 
6 - 2318
    xhr.onload = () => {
12 - 2319
        var jsonObj = XMLparse(xhr.responseXML, false);
2320
        var obj = jsonObj.TrackResponse;
2 - 2321
 
6 - 2322
        if (obj.Response.ResponseStatusDescription != 'Success') {
2323
            --trackingNumbersToProcess;
2324
            ++trackingNumbersProcessed;
2325
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2326
            return;
2327
        }
2 - 2328
 
6 - 2329
        trackingNumber = obj.Shipment.ShipmentIdentificationNumber;
2330
        summary = formatUPSTrackingLine(obj.Shipment.Package.Activity[0]);
2331
        detail = '';
2332
        footer = '';
2333
        deliveryDate = '';
2334
        duration = '';
2335
        lastUpdate = moment(obj.Shipment.Package.Activity[0].Status.Date, "YYYYMMDD").format('YYYY-MM-DD');
2336
        lastEvent = obj.Shipment.Package.Activity[0].Status.StatusType.Description;
2 - 2337
 
6 - 2338
        if (document.getElementById('DeliveryStatus' + trackingNumber) === null) {
2339
            --trackingNumbersToProcess;
2340
            ++trackingNumbersProcessed;
2341
            updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2342
            return;
2343
        }
2 - 2344
 
6 - 2345
        if (obj.Shipment.Package.Activity !== undefined && obj.Shipment.Package.Activity.length > 0) {
2346
            for (j = 0; j < obj.Shipment.Package.Activity.length; j++) {
2347
                detail += formatUPSTrackingLine(obj.Shipment.Package.Activity[j]);
2348
            }
2 - 2349
 
6 - 2350
            createDate = moment(obj.Shipment.PickupDate, "YYYYMMDD").format('YYYY-MM-DD');
2351
            footer = 'Enroute since ' + createDate + ' (' + moment().diff(createDate, 'days') + ' days)';
2 - 2352
 
6 - 2353
            if (obj.Shipment.Package.DeliveryIndicator == 'Y') {
2354
                deliveryDate = moment(obj.Shipment.Package.DeliveryDate, "YYYYMMDD").format('YYYY-MM-DD');
2355
                duration = moment(deliveryDate).diff(createDate, 'days');
2356
                document.getElementById('DeliveryStatus' + trackingNumber).style.color = "green";
2357
                footer = 'Delivered in ' + moment(deliveryDate).to(createDate, 'days');
2358
            } else if (moment().diff(lastUpdate, 'days') > 3) {
2359
                document.getElementById('DeliveryStatus' + trackingNumber).style.color = "red";
2360
            }
2361
        }
2 - 2362
 
14 - 2363
        if (document.getElementById('ShippedDate' + trackingNumber)) {
2364
            document.getElementById('ShippedDate' + trackingNumber).innerHTML = createDate;
2365
        }
6 - 2366
        document.getElementById('DeliveryStatus' + trackingNumber).innerHTML = lastEvent;
2367
        document.getElementById('DeliveryDays' + trackingNumber).innerHTML = duration;
2368
        document.getElementById('DeliveryDate' + trackingNumber).innerHTML = deliveryDate;
2 - 2369
 
6 - 2370
        str = document.getElementById(trackingNumber).innerHTML;
2371
        if (!str.startsWith('<button')) {
30 - 2372
            document.getElementById(trackingNumber).innerHTML = '<button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#mod' + trackingNumber + '">' + str + '</button>';
2 - 2373
 
30 - 2374
            str = '<div id="mod' + trackingNumber + '" class="modal">';
2375
            str += '<div class="modal-dialog modal-lg">';
2376
            str += '<div class="modal-content">';
2377
            str += '<div class="modal-header">';
2378
            str += '<h3>' + trackingNumber + ' (UPS ' + getCarrierService("UPS", trackingNumber, false) + ')</h3>';
2379
            str += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
2380
            str += '</div>';
2381
            str += '<div class="modal-body">';
2382
            str += '<table class="table border small">';
2383
            str += '<thead class="thead-dark">';
2384
            str += '<tr>';
2385
            str += '<th>DATE</th>';
2386
            str += '<th>TIME</th>';
2387
            str += '<th>STATUS</th>';
2388
            str += '<th>LOCATION</th>';
2389
            str += '</tr>';
2390
            str += '</thead>';
2391
            str += '<tbody>';
6 - 2392
            str += summary;
2393
            str += detail;
30 - 2394
            str += '</tbody>';
2395
            str += '</table>';
2396
            str += '</div>';
2397
            str += '<div class="modal-footer">';
2398
            str += '<p>' + document.getElementById('DeliveryAddress' + trackingNumber).innerHTML + ' - ' + footer + '</p>';
2399
            str += '</div>';
2400
            str += '</div>';
2401
            str += '</div>';
2402
            str += '</div>';
2 - 2403
 
6 - 2404
            document.getElementById("modals").innerHTML += str;
2405
        }
2 - 2406
 
6 - 2407
        --trackingNumbersToProcess;
2408
        ++trackingNumbersProcessed;
2409
        updateProgressBar(maxTrackingNumbersToProcess, trackingNumbersProcessed);
2410
    };
2 - 2411
 
6 - 2412
    xhr.open('POST', configProxyUrl, true);
2413
    xhr.setRequestHeader('Content-Type', 'text/xml');
97 - 2414
    xhr.setRequestHeader('Accept-Charset', 'UTF-8,*;q=0.5');
6 - 2415
    xhr.setRequestHeader('X-Proxy-URL', configUPSUrl);
2416
    xhr.send(xml);
2 - 2417
}
2418
 
2419
function formatUPSTrackingLine(t) {
6 - 2420
    var str = '';
2 - 2421
 
6 - 2422
    if (t !== undefined) {
2423
        str = '<tr>';
2 - 2424
 
6 - 2425
        str += '<td>' + moment(t.Date, "YYYYMMDD").format('YYYY-MM-DD') + '</td>';
2 - 2426
 
6 - 2427
        str += '<td>';
2428
        if (t.Time.length > 0) {
2429
            str += ' ' + moment(t.Time, "HHmmss").format('HH:mm');
2430
        }
2431
        str += '</td>';
2 - 2432
 
6 - 2433
        str += '<td>' + t.Status.StatusType.Description + '</td>';
2 - 2434
 
6 - 2435
        str += '<td>';
2436
        if (t.ActivityLocation.Address.City !== undefined) {
2437
            str += t.ActivityLocation.Address.City;
2438
            if (t.ActivityLocation.Address.StateProvinceCode !== undefined) {
2439
                str += ", " + t.ActivityLocation.Address.StateProvinceCode;
2440
            }
2441
        }
2442
        str += '</td>';
2 - 2443
 
6 - 2444
        str += '</tr>';
2445
    }
2 - 2446
 
6 - 2447
    return (str);
2 - 2448
}
2449
 
2450
 
2451
function connected() {
6 - 2452
    var x;
2 - 2453
 
6 - 2454
    eBayAuthTokenFlag = true;
30 - 2455
    if (!document.getElementById("connected").innerHTML.endsWith("(Connected)")) {
2456
        document.getElementById("connected").innerHTML += " (Connected)";
2457
    }
2 - 2458
 
6 - 2459
    x = document.getElementById("startButton");
30 - 2460
    x.className = x.className.replace(" btn-danger", " btn-primary");
2 - 2461
 
6 - 2462
    x = document.getElementById("login");
2463
    x.className = x.className.replace(" w3-show", "");
2 - 2464
 
6 - 2465
    x = document.getElementById("results");
2466
    x.innerHTML = "";
2467
    x.className = x.className.replace(" w3-show", "");
2 - 2468
}
2469
 
2470
    </script>
30 - 2471
    <script>includeHTML();</script>
2 - 2472
 
2473
</body>
2474
</html>