Subversion Repositories munaweb

Rev

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