Subversion Repositories munaweb

Rev

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

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