PageSourceSearch

https://gecs.galfar.com/SupplyChainPortal/views/invoiceUploadMain.js?3.4.2

js galfar.com collected 2026-10-02 16:30:02 UTC 108,521 bytes, 1,709 lines download raw bytes

1//FixVersion="3.3.0.1039"
2//FixVersion="3.3.1.1028"
3SupplierPortalMaterialize.InvoiceUploadMain = function (parseParams) {
4    //var parseParams = JSON.parse(params.title.substr(5, params.title.length));
5
6    var invoiceRefData = [];
7    var fileError = 0, ifValidFile, serialNo = [], countRow = 0, changeFileFlag = true, gridHeight, ifSetCallback = false;
8    var purchaseData = [], excelFileInstance, coRefValidate = [], divisionCurrencyLink, entityGrnDetails = [], uploadFlag, invoiceFile = {}, entityName, deliveryTktValidate = [], all_valid = true, colNum = [8], invoiceFileAttachment = [], orderRefDeliveryTkts = {}, delTicketData = {}, arrExcel = [], objDeliveryTktArr = {}, getOrderRefStatus = {}, ifError = false, orderRefValidate = [], error_count = 0, valid_entry = 0, row_id = 0, row_count = 0, entityFilter = parseParams.entity_id, is_clear = 0, all = [], ifInvoiceRef = [];
9    var responsiveTableOption = {
10        'columnDefs': [{ "targets": colNum, "visible": false }, { "bSortable": false, "aTargets": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] }],
11        'filter': false,
12        //"order": [[3, "desc"]],
13        responsive: false
14    };
15    var responsiveTableOption1 = {
16        'columnDefs': [{ "bSortable": false, "aTargets": [0, 1] }],
17        //'filter': true,
18        //"order": [[3, "desc"]],
19        responsive: true
20    };
21    // var customDataTable;
22    var monthsIndex = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
23    function bindInvoiceUploadMainHostActions() {
24        $('#txt_filter').off('.invoiceUploadMainHostActions').on('keyup.invoiceUploadMainHostActions', function (e) {
25            if (e.keyCode == 13) {
26                vmInvoiceUploadMain.searchFilter();
27            }
28        });
29
30        $(document).off('click.invoiceUploadMainHostActions', '#btnSearchInvoiceUploadMainFilter');
31        $(document).on('click.invoiceUploadMainHostActions', '#btnSearchInvoiceUploadMainFilter', function (e) {
32            e.preventDefault();
33            vmInvoiceUploadMain.searchFilter();
34        });
35        $(document).off('click.invoiceUploadMainHostActions', '#btnClearInvoiceUploadMainFilter');
36        $(document).on('click.invoiceUploadMainHostActions', '#btnClearInvoiceUploadMainFilter', function (e) {
37            e.preventDefault();
38            vmInvoiceUploadMain.clearFilter();
39        });
40        $(document).off('click.invoiceUploadMainHostActions', '.uploadButn');
41        $(document).on('click.invoiceUploadMainHostActions', '.uploadButn', function (e) {
42            e.preventDefault();
43            vmInvoiceUploadMain.uploadInvoice();
44        });
45        $(document).off('click.invoiceUploadMainHostActions', '#btnValidateInv');
46        $(document).on('click.invoiceUploadMainHostActions', '#btnValidateInv', function (e) {
47            e.preventDefault();
48            vmInvoiceUploadMain.validateInv();
49        });
50    }
51
52    function initializeInvoiceUploadMainScreen(e) {
53        vmInvoiceUploadMain._lastRenderEvent = e || vmInvoiceUploadMain._lastRenderEvent || {};
54        vmInvoiceUploadMain.viewRenderedLegacy(vmInvoiceUploadMain._lastRenderEvent);
55        bindInvoiceUploadMainHostActions();
56    }
57
58    var vmInvoiceUploadMain = {
59        name: "InvoiceUploadMain",
60        _lastRenderEvent: null,
61        viewRendered: function (e) {
62            if (SupplierPortalMaterialize.Shell && SupplierPortalMaterialize.Shell.shouldUseRegisteredScreen("InvoiceUploadMain")) {
63                initializeInvoiceUploadMainScreen(e);
64                return;
65            }
66            initializeInvoiceUploadMainScreen(e);
67        },
68        initializeCustomScreen: function (e) {
69            initializeInvoiceUploadMainScreen(e);
70        },
71        viewRenderedLegacy: function (e) {
72            initUserAccess(e, function () {
73                DynamicMenu('invoice', { childPage: true, childName: 'Upload Invoice Header', icon: 'icon-file-upload' });
74                if (typeof bindBreadcrumbs === "function") {
75                    bindBreadcrumbs('invoice', { childPage: true, childName: 'Upload Invoice Header', icon: 'icon-file-upload' });
76                }
77                $('#custom-breadcrumbs').show();
78                // $('#headerChipUpload').html('');
79                //$.each(applicableInfoAreasArray, function (i1, obj1) {
80                //    if (parseFloat(obj1.VIEW_ID) == 20) {
81                //        $('.getGRN').removeClass('dn');
82                //        return;
83                //    }
84                //})
85                $('.getGRN').removeClass('dn');
86                $.each(allLinkedUserActiveArray, function (i, item) {
87                    if (item.ENTITY_DIVISION_ID == entityFilter) {
88                        //$('#headerChipUpload').append('<div class="chip linkcursor waves-effect">' +
89                        //    '<div class="divCount">' + (item.DIVISION_NAME).slice(0, 1) + '</div>' + item.DIVISION_NAME + '</div>');
90                        //$($('#headerChipUpload').find('.chip')).addClass('secondary_back');
91                        entityName = objActiveEntityList[item.ENTITY_DIVISION_ID]["DISPLAY_DIVISION_NAME"];//item.DIVISION_NAME;
92                        return;
93                    }
94                });
95                $('.headerChipUpload').text(entityName);
96                vmInvoiceUploadMain.getEntityGrnDetail();
97                $('.tooltip').tooltipster({
98                    side: 'right',
99                });
100            });
101            initDateTimePicker();
102
103            $(".currencyFormatMainDiv").on("focusin", ".currencyFormat:not([readonly])", function () {
104                $(this).val(($(this).val()).replace(/\,/g, ''));
105            });
106            $(".currencyFormatMainDiv").on("focusout", ".currencyFormat:not([readonly])", function () {
107                $(this).val(($(this).val()).CurrencyFormat());
108            });
109
110            $('#txt_filter').keyup(function (e) {
111                if (e.keyCode == 13) {
112                    vmInvoiceUploadMain.searchFilter();
113                }
114            })
115            $('currencyFormatMainDiv getGRN, currencyFormatMainDiv addInvRow').off('click', '**');
116            $('.currencyFormatMainDiv').on('click', '.getGRN', function () {
117                vmInvoiceUploadMain.fetchGrnData();
118                $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
119            });
120            $('.currencyFormatMainDiv').on('click', '.addInvRow', function () {
121                vmInvoiceUploadMain.addHeaderRow();
122            });
123            $('currencyFormatMainDiv addMultipleFiles').off('change', '**');
124            $('.currencyFormatMainDiv').on("change", '.addMultipleFiles', vmInvoiceUploadMain.addMultipleFiles);
125
126            $('#tblInvoice1 tbody').on('keypress', '.getamount, .gettax, .getother', function (event) {
127                var ind = $(event.target).closest('tr').data('lineno');
128                //  Doc_ID = $(event.target).closest('tr').data('docid');
129                var $this = $(this);
130                if ((event.which != 46 || $this.val().indexOf('.') != -1) && ((event.which != 0 && event.which != 8) && (event.which < 48 || event.which > 57))) {
131                    event.preventDefault();
132                }
133                var text = $(this).val();
134                var result = arrExcel.filter(function (obj) {
135                    return ((obj.uniqueId) == parseFloat(ind));
136                })
137                var precision = result[0].amountPrecision ? result.amountPrecision : 5;
138                if ((event.which == 46) && (text.indexOf('.') == -1)) {
139                    setTimeout(function () {
140                        if ($this.val().substring($this.val().indexOf('.')).length > precision + 1) {
141                            $this.val($this.val().substring(0, $this.val().indexOf('.') + precision + 1));
142                        }
143                    }, 1);
144                }
145                if ((text.indexOf('.') != -1) &&
146                    (text.substring(text.indexOf('.')).length > precision) &&
147                    (event.which != 0 && event.which != 8) &&
148                    ($(this)[0].selectionStart >= text.length - precision)) {
149                    event.preventDefault();
150                }
151            });
152
153            $('#tblInvoice1 tbody').on('click', '.delInvRow', function (e) {
154                countRow--;
155                var index = $(this).closest('tr').data('lineno');
156                var arrindex = 'fileLine' + index;
157                var delId;
158                $.each(arrExcel, function (i, obj) {
159                    if (obj.uniqueId == index) delId = i;
160                })
161                arrExcel.splice(delId, 1);
162                if (invoiceFileAttachment[arrindex]) delete invoiceFileAttachment[arrindex];
163                //invoiceFileAttachment.splice(arrindex, 1);
164                var table = $('#tblInvoice1').DataTable();
165                table.row($(this).parents('tr')).remove().draw();
166                if (countRow == 0) {
167                    var UploadFileClone = $('#excelUpload');
168                    //$('#btnValidateInv').prop('disabled', true);
169                    $('#btnValidateInv').addClass('disabled');
170                    $('#btnValidateInv').css('pointer-events', 'none');
171                    arrExcel = [];
172                    invoiceFileAttachment = [];
173                    $('#excelName').val('');
174                    $('.fileAttach').addClass('disabled');
175                    $('.fileAttach').css('pointer-events', 'none');
176                    // UploadFileClone.replaceWith(UploadFileClone = UploadFileClone.clone(true));
177                    $('#excelUpload').val('');
178                    $('#excelUpload').attr('title', 'No file chosen');
179                    //$('.Details').find('.file-field').attr('title', 'No file chosen');
180                    $('.currencyFormatMainDiv').find('.dataTables_empty').text('No data available');
181                }
182            });
183            $('#tblInvoice1 tbody').on('change', '.getref, .getdate, .getorderref, .getdel_tkt, .getamount, .gettax, .getother, .fileupload1', function (e) {
184                var index = $(this).closest('tr').data('lineno');
185                var delId, precision;
186                $.each(arrExcel, function (i, obj) {
187                    if (obj.uniqueId == index) {
188                        delId = i;
189                        precision = obj.amountPrecision;
190                    }
191                })
192                precision = precision ? precision : 5;
193                if ($(e.currentTarget).hasClass('getref')) arrExcel[delId].InvoiceRef = e.target.value;
194                else if ($(e.currentTarget).hasClass('getdate')) {
195                    arrExcel[delId]['Date(dd-mmm-yyyy)'] = e.target.value;
196                    arrExcel[delId].dateErr = 'N';
197                }
198                else if ($(e.currentTarget).hasClass('getorderref')) arrExcel[delId].OrderRef = e.target.value;
199                else if ($(e.currentTarget).hasClass('getdel_tkt')) arrExcel[delId].DeliveryTkt = e.target.value;
200                else if ($(e.currentTarget).hasClass('getamount')) {
201                    var inputVal = e.target.value.replace(/\,/g, "");
202                    if (!parseFloat(inputVal)) {
203                        arrExcel[delId].TotalAmount = inputVal;
204                        $(e.currentTarget).val(inputVal);
205                    }
206                    else {
207                        arrExcel[delId].TotalAmount = inputVal;
208                        $(e.currentTarget).val(parseFloat(inputVal).toFixedExtend(precision));
209                    }
210                }
211                else if ($(e.currentTarget).hasClass('gettax')) {
212                    var inputVal = e.target.value.replace(/\,/g, "");
213                    if (!parseFloat(inputVal)) {
214                        arrExcel[delId].TaxAmount = inputVal;
215                        $(e.currentTarget).val(inputVal);
216                    }
217                    else {
218                        arrExcel[delId].TaxAmount = inputVal;
219                        $(e.currentTarget).val(parseFloat(inputVal).toFixedExtend(precision));
220                    }
221                }
222                else if ($(e.currentTarget).hasClass('getother')) {
223                    var inputVal = e.target.value.replace(/\,/g, "");
224                    if (!parseFloat(inputVal)) {
225                        arrExcel[delId].OtherCharges = inputVal;
226                        $(e.currentTarget).val(inputVal);
227                    }
228                    else {
229                        arrExcel[delId].OtherCharges = inputVal;
230                        $(e.currentTarget).val(parseFloat(inputVal).toFixedExtend(precision));
231                    }
232                }
233                else {
234                    var arrIndex = 'fileLine' + index;
235                    var rowIndex = $(this).closest('tr').index();
236                    var cloneUpload = $('#file_upload' + index + '');
237                    var FileName = e.target.value;
238                    if (!FileName) {
239                        if (invoiceFileAttachment[arrIndex] && invoiceFileAttachment[arrIndex] != undefined) {
240                            var name = invoiceFileAttachment[arrIndex].name;
241                            $('#filename' + index + '').val(name);
242                            $('#file_upload' + index + '').attr('title', name);
243                            return false;
244                        }
245                    }
246                    else {
247                        var ext = FileName.split('.').pop().toLowerCase();
248                        if (ext != 'pdf') {
249                            $('#filename' + index + '').val('');
250                            $('#file_upload' + index + '').attr('title', 'No file chosen');
251                            cloneUpload.replaceWith(cloneUpload = cloneUpload.clone(true));
252                            $('#file_upload' + index + '').val('');
253                            if ($('#fileErrorMsg' + index + '').length == 0) {
254                                $('#message' + index + '').append('<div class="errorTextMessage" id="fileErrorMsg' + index + '">Upload PDF file.</div>');
255                                // fileError++;
256                            }
257                            invoiceFileAttachment[arrIndex] = undefined;
258                        }
259                        else {
260                            if ($('#fileErrorMsg' + index + '').length > 0) {
261                                $('#fileErrorMsg' + index + '').remove();
262                                //fileError--;
263                            }
264                            invoiceFileAttachment[arrIndex] = $(this).closest('tr').find('.fileupload1')[0].files[0];
265                            $('#filename' + index + '').val(invoiceFileAttachment[arrIndex].name);
266                            $('#file_upload' + index + '').attr('title', invoiceFileAttachment[arrIndex].name);
267                        }
268                    }
269                    Materialize.updateTextFields();
270                    intialFilePickerDropify();
271                }
272            });
273
274            var cloneUploadFile = $('#excelUpload');
275            $('#excelUpload').change(function (e) {
276                $('#custom-loader').show();
277                ifValidFile = 0;
278                uploadFlag = 0;
279                arrExcel = [];
280                arrExcelDataCopy = [];
281                invoiceFileAttachment = [];
282                invoiceFile = {};
283                var FileName = e.target.value;
284                if (!FileName) {
285                    if (excelFileInstance) {
286                        $('#excelName').val(excelFileInstance);
287                        //$('.Details').find('.file-field').attr('title', excelFileInstance);
288                        $('#excelUpload').attr('title', excelFileInstance);
289                        $('#custom-loader').hide();
290                        return false;
291                    }
292                }
293                else {
294                    var ext = FileName.split('.').pop().toLowerCase();
295                    if (ext == 'xlsx' || ext == 'xls') {
296                        if (e.target.files) parseExcelToJsonUpload(e.target.files, function (jsonObj) {
297                            arrExcel = jsonObj;
298                            arrExcelDataCopy = jsonObj;
299                            if (jsonObj == undefined) ifValidFile = 0;
300                            else {
301                                if ('LineNo' in arrExcel[0] && 'Date(dd-mmm-yyyy)' in arrExcel[0] && 'InvoiceRef' in arrExcel[0] && 'OrderRef' in arrExcel[0] && 'AmountIncludingTax' in arrExcel[0] && 'DeliveryTkt' in arrExcel[0] && 'TaxAmount' in arrExcel[0] && 'OtherCharges' in arrExcel[0] && 'PDF filename' in arrExcel[0])
302                                    ifValidFile = 1;
303                            }
304                            if (ifValidFile == 0) {
305                                $('#excelName').val('');
306                                //changeFileFlag = false;
307                                $('#uploadExcelFile').find('.placeholder').show();
308                                arrExcel = [];
309                                cloneUploadFile.replaceWith(cloneUploadFile = cloneUploadFile.clone(true));
310                                $('#excelUpload').val('');
311                                $('#excelUpload').attr('title', 'No file chosen');
312                                //$('.Details').find('.file-field').attr('title', 'No file chosen');
313                                // $('#btnValidateInv').prop('disabled', true);
314                                $('#btnValidateInv').addClass('disabled');
315                                $('#btnValidateInv').css('pointer-events', 'n
315one');
316                                //$('#custom-loader').hide();
317                                displayToast('Upload valid Microsoft Excel Worksheet ', 'warning', defaultToastMessageDuration);
318                                vmInvoiceUploadMain.loadInvoiceTableData();
319                            }
320                            else {
321                                excelFileInstance = e.target.files[0].name;
322                                $('#uploadExcelFile').find('.placeholder').hide();
323                                $('#excelName').val(excelFileInstance);
324                                //$(".Details").find(".file-field").attr('title', excelFileInstance);
325                                //changeFileFlag = false;
326                                cloneUploadFile.replaceWith(cloneUploadFile = cloneUploadFile.clone(true));
327                                $('#excelUpload').val('');
328                                $('#excelUpload').attr('title', excelFileInstance);
329                                //$('#btnValidateInv').prop('disabled', false);
330                                $('#btnValidateInv').removeClass('disabled');
331                                $('#btnValidateInv').css('pointer-events', '');
332                                vmInvoiceUploadMain.validateInvoiceRef(function () {
333                                    if (ifError == false && fileError == 0) $('#tblInvoice1').closest('div').scrollLeft(0);
334                                    else $('#tblInvoice1').closest('div').scrollLeft($('#tblInvoice1 tbody').width());
335                                });
336                            }
337                        })
338                    }
339                    else {
340                        $('#excelName').val('');
341                        //changeFileFlag = false;
342                        $('#uploadExcelFile').find('.placeholder').show();
343                        arrExcel = [];
344                        cloneUploadFile.replaceWith(cloneUploadFile = cloneUploadFile.clone(true));
345                        $('#excelUpload').val('');
346                        $('#excelUpload').attr('title', 'No file chosen');
347                        //$('.Details').find('.file-field').attr('title', 'No file chosen');
348                        //$('#btnValidateInv').prop('disabled', true);
349                        $('#btnValidateInv').addClass('disabled');
350                        $('#btnValidateInv').css('pointer-events', 'none');
351                        vmInvoiceUploadMain.loadInvoiceTableData();
352                        //$('#custom-loader').hide();
353                        displayToast('Upload valid Microsoft Excel Worksheet ', 'warning', defaultToastMessageDuration);
354                    }
355                }
356            })
357
358            $(document).ready(function () {
359                var head = document.getElementsByTagName('head')[0];
360                var js = document.createElement("script");
361                js.src = "https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.4/purify.min.js";
362                var js1 = document.createElement("script");
363                js1.src = "https://cdnjs.cloudflare.com/ajax/libs/he/1.2.0/he.js";
364                head.insertBefore(js1, head.firstChild);
365                head.insertBefore(js, head.firstChild);
366                // Function to sanitize input
367                function fullyDecode(input) {
368                    let decodedInput;
369
370                    // Keep decoding until no more entities can be decoded
371                    do {
372                        decodedInput = input;
373                        input = he.decode(input); // Use he.decode as the main decoder
374                    } while (input !== decodedInput); // Repeat until no change occurs
375
376                    return input; // Return fully decoded string
377                }
378
379                function sanitizeInput(textInput) {
380                    //const input = textInput.value;
381                    let input = fullyDecode(textInput.value);
382                    let sanitizedInput = DOMPurify.sanitize(input, { SAFE_FOR_TEMPLATES: true });
383                    let encodedInput = he.encode(sanitizedInput, {
384                        useNamedReferences: true
385                    });
386                    let prevInput;
387                    do {
388                        prevInput = encodedInput;
389
390                        excludedSymbols.forEach(symbol => {
391                            const encodedSymbol = he.encode(symbol, { useNamedReferences: true });
392
393                            // Use replaceAll to replace encoded symbols with the original symbol
394                            encodedInput = encodedInput.replaceAll(encodedSymbol, symbol);
395                        });
396
397                        // Repeat the process until no more replacements are made
398                    } while (encodedInput !== prevInput);
399
400                    textInput.value = encodedInput;
401
402                }
403
404                $(document).on('blur', 'input[type="text"], textarea', function () {
405                    sanitizeInput(this);
406                });
407            });
408        },
409        validateInvoiceRef: function (callback) {
410            //$('#custom-loader').show();
411            invoiceRefData = [];
412            var invoiceRefString = [];
413            $.each(arrExcel, function (i, obj) {
414                if (obj.InvoiceRef.trim()) {
415                    if (obj.InvoiceRef.trim().length > 30) obj.InvoiceRefLenErr = 'Y';
416                    else {
417                        if (($.inArray(obj.InvoiceRef.trim(), invoiceRefString) == -1)) invoiceRefString.push(obj.InvoiceRef.trim());
418                    }
419                }
420            })
421            executeServiceCall("GetPoRefAgainstInvoiceNumber", {
422                sEntityDivisionId: entityFilter.toString(),
423                sEntityInvoiceNo: invoiceRefString.toString(),
424            }, function (successData) {
425                invoiceRefData = successData;
426                vmInvoiceUploadMain.sendOrderRef(callback);
427                //vmInvoiceUploadMain.loadInvoiceTableData(callback);
428            });
429        },
430        sendOrderRef: function (callback) {
431            var orderRefString = [];
432            var creditRefString = [];
433            $.each(arrExcel, function (i, obj) {
434                if (obj.OrderRef.trim()) {
435                    if (obj.OrderRef.trim().length > 30) obj.OrderRefLenErr = 'Y';
436                    else {
437                        if ($.inArray(obj.OrderRef.trim(), orderRefString) == -1) orderRefString.push(obj.OrderRef.trim());
438                    }
439                }
440            })
441            vmInvoiceUploadMain.getOrderRefData(callback, orderRefString.toString());
442        },
443        getOrderRefData: function (callback, orderRefString) {
444            orderRefValidate = [];
445            executeServiceCall("GetOrderDocRefExistence", {
446                sOrderDocRefString: orderRefString,
447                sEntityDivisionId: entityFilter.toString(),
448                sUserName: ENCRYPTED_USER, //USERNAME, //XE-74005
449            }, function (successData) {
450                orderRefValidate = successData;
451                vmInvoiceUploadMain.loadInvoiceTableData(callback);
452            })
453        },
454        loadPurchaseOrder: function () {
455            $('#custom-loader').show();
456            row_id = 0;
457            row_count = 0;
458            arrExcel = [];
459            purchaseData = [];
460            executeServiceCall("GetBasePurchaseOrderlist4Import", {
461                sUserName: ENCRYPTED_USER, //USERNAME, //XE-74005
462            }, function (successData) {
463                purchaseData = $.grep(successData, function (obj) {
464                    return obj.INVOICE_TO_ENTITY_DIVISION_ID == entityFilter
465                });
466                // purchaseData = successData
467                vmInvoiceUploadMain.loadInvoiceTableData();
468            })
469        },
470        getEntityGrnDetail: function () {
471            entityGrnDetails = [];
472            executeServiceCall("GetOpenGRNListForEntity", {
473                sEntityDivisionId: entityFilter.toString(),
474                sUserName: ENCRYPTED_USER, //USERNAME, //XE-74005
475            }, function (successData) {
476                entityGrnDetails = successData;
477                vmInvoiceUploadMain.loadDeliveryTktInfo();
478                $("#grnInfo1").find('.ui-dialog-titlebar-close').css('display', 'none');
479                vmInvoiceUploadMain.loadPurchaseOrder();
480            })
481        },
482        loadDeliveryTktInfo: function () {
483            //responsiveTableOption1.scrollHeight = $('#grnInfo1').height() - $('#grnTable').find('.datatable-header').height();
484            //responsiveTableOption1.scrollCollapse = true;
485            setDataTablesResponsive('#grnTable', function () {
486                $('#grnTable tbody').html('');
487                $.each(entityGrnDetails, function (i, obj) {
488                    $('#grnTable tbody').append('<tr class="grnRow" data-row="' + i + '">' +
489                        '<td style = "vertical-align: top;">' + obj.PO_DOC_REF + '</td> ' +
490                        '<td style = "vertical-align: top;">' + (obj.DELIVERY_NO ? obj.DELIVERY_NO : 'N/A') + '</td> ' +
491                        '</tr>');
492                });
493            }, responsiveTableOption1)
494        },
495        calculateDueDate: function (PAY_TERM_CODE, METHOD, CREDIT_PERIOD_DAYS, date) {
496            var dateArr = date.split(' ');
497            var day = parseFloat(dateArr[0]);
498            var month = monthsIndex.indexOf(dateArr[1]);
499            var year = parseFloat(dateArr[2]);
500            if (PAY_TERM_CODE != null && METHOD != null) {
501                if (METHOD == "N") {
502                    month = month + 1;
503                    var newDateInfo = new Date(year, month, 0);
504                    day = newDateInfo.getDate();
505                    month = newDateInfo.getMonth();
506                    year = newDateInfo.getFullYear();// day - 1;
507                }
508                dueDate = new Date(year, month, day + CREDIT_PERIOD_DAYS);
509                return dueDate;
510            }
511            else return 0;
512        },
513        addMultipleFiles: function (e) {
514            var multipleFileArr = e.target.files;
515            var FileName = e.target.value;
516            var count = 0;
517            if (!FileName) return;
518            else {
519                var fileNames = [];
520                $.each(multipleFileArr, function (i, obj) {
521                    if (obj.name.split('.').pop().toLowerCase() == 'pdf') {
522                        var fileNaming = obj.name.split('.');
523                        fileNaming.pop();
524                        fileNames.push(fileNaming.join('.').toUpperCase());
525                    }
526                })
527                $.each($('#tblInvoice1 tbody tr'), function (i2, obj2) {
528                    var index = 'fileLine' + $(obj2).data('lineno');
529                    var fileIndex = $(obj2).data('lineno');
530                    //$.each()
531                    if (invoiceFile[$(obj2).find('.getref').val().trim()] && $.inArray(invoiceFile[$(obj2).find('.getref').val().trim()].toUpperCase(), fileNames) != -1) {
532                        invoiceFileAttachment[index] = multipleFileArr[$.inArray(invoiceFile[$(obj2).find('.getref').val().trim()].toUpperCase(), fileNames)];
533                        $('#filename' + fileIndex).val(invoiceFileAttachment[index].name);
534                        $('#file_upload' + fileIndex).attr('title', invoiceFileAttachment[index].name);
535                        if ($('#fileErrorMsg' + fileIndex).length > 0) {
536                            $('#fileErrorMsg' + fileIndex).remove();
537                            // count--;
538                        }
539                    }
540                    else if ($(obj2).find('.getref').val().trim() && $.inArray($(obj2).find('.getref').val().trim().toUpperCase(), fileNames) != -1) {
541                        invoiceFileAttachment[index] = multipleFileArr[$.inArray($(obj2).find('.getref').val().trim().toUpperCase(), fileNames)];
542                        invoiceFile[$(obj2).find('.getref').val().trim()] = $(obj2).find('.getref').val().trim();
543                        $('#filename' + fileIndex).val(invoiceFileAttachment[index].name);
544                        $('#file_upload' + fileIndex).attr('title', invoiceFileAttachment[index].name);
545                        if ($('#fileErrorMsg' + fileIndex).length > 0) {
546                            $('#fileErrorMsg' + fileIndex).remove();
547                            // count--;
548                        }
549                    }
550                    else {
551                        // if (invoiceFileAttachment[index] == undefined) {
552                        invoiceFileAttachment[index] = undefined;
553                        $('#filename' + fileIndex).val('');
554                        $('#file_upload' + fileIndex).attr('title', 'No file chosen');
555                        if ($('#fileErrorMsg' + fileIndex).length == 0) $('#message' + fileIndex).append('<div class="errorTextMessage" id="fileErrorMsg' + fileIndex + '">Upload PDF file.</div>');
556                        // fileError++;
557                        count++;
558                        //}
559                    }
560                })
561            }
562            if (count > 0) {
563                displayToast('Files are not attached for invoice(s) due to invalid file selection', 'warning', defaultToastMessageDuration);
564                $('#tblInvoice1').closest('div').scrollLeft($('#tblInvoice1 tbody').width());
565                //$('.datatable-scroll-wrap').scrollLeft($('#tblInvoice1 tbody').width());
566            }
567            $('.addMultipleFiles').val('');
568            Materialize.updateTextFields();
569        },
570        addHeaderRow: function () {
571            countRow++;
572            var lineIndex = 0;
573            var uniqueId = 0;
574            $.each(arrExcel, function (i, obj) {
575                if (parseFloat(obj.LineNo) > lineIndex) lineIndex = parseFloat(obj.LineNo);
576                if (parseFloat(obj.uniqueId) > uniqueId) uniqueId = parseFloat(obj.uniqueId);
577            })
578            $('#btnValidateInv').removeClass('disabled');
579            $('#btnValidateInv').css('pointer-events', '');
580            var rowDataPO = {
581                'uniqueId': (uniqueId + 1),
582                'LineNo': (lineIndex + 1),
583                'InvoiceRef': '',
584                'Date(dd-mmm-yyyy)': '',
585                'OrderRef': '',
586                'DeliveryTkt': '',
587                'TotalAmount': '',
588                'TaxAmount': '',
589                'OtherCharges': '',
590                //'Type': 'INVOICE',
591                'rowAdd': 'Y',
592                'PDF filename': '',
593            };
594            arrExcel.push(rowDataPO);
595            //$('#custom-loader').show();
596            vmInvoiceUploadMain.InsertNewRow();
597        },
598        InsertNewRow: function () {
599            setDataTablesResponsive('#tblInvoice1', function () {
600                var i = arrExcel[arrExcel.length - 1].uniqueId;
601                var line = '<div id="line' + i + '" class="getLine currencyFormat" style="margin-top: 7px;">' + (parseFloat(arrExcel[arrExcel.length - 1].LineNo) ? (arrExcel[arrExcel.length - 1].LineNo) : (arrExcel[arrExcel.length - 1].LineNo ? arrExcel[arrExcel.length - 1].LineNo : '')) + '</div>';
602                var ref = '<input type="text" id="ref' + i + '" class="getref" maxlength="30">';
603                var date = '<input id="invoice_date' + i + '" class="datetimeinput getdate form-control" type="text">';
604                var order_ref = '<input type="text" id="order_ref' + i + '" class="getorderref" maxlength="30">';
605                var del_tkt = '<input type="text" id="del_tkt' + i + '" class="getdel_tkt" maxlength="500">';
606                var amount = '<input type="text" class="getamount currencyFormat tright" id="amount' + i + '" maxlength="35">';
607                var tax = '<input type="text" class="gettax currencyFormat tright" id="tax' + i + '" maxlength="35">';
608                var other = '<input type="text" class="getother currencyFormat tright" id="other' + i + '" maxlength="35">';
609                var file = '<div class="file-field input-field s12" style="margin-top: 0px;">' +
610                    '<div class="btn" style="width: 30px;">' +
611                    '<span>File</span>' +
612                    '<input type="file" class="fileupload1" id="file_upload' + i + '" accept="application/pdf">' +
613                    '</div>' +
614                    '<div class="file-path-wrapper">' +
615                    '<input class="file-path validate" id="filename' + i + '" name="filename' + i + '" style="padding-top: 4px;" type="text" required="required" placeholder="Upload PDF file *" data-error=".errorTxt9">' +
616                    //'<span class="placeholder" style="left: 93px;">Upload PDF file <span>*</span></span>' +
617                    '<div class="errorTxt9"></div>' +
618                    '</div>';
619                var currency = '<div class="getcurrency" style="margin-top: 7px;" id="currency' + i + '">
619' + (arrExcel[arrExcel.length - 1].currency ? arrExcel[arrExcel.length - 1].currency : '') + '</div>';
620                var project = '<div id="project' + i + '" class="getproject" style="margin-top: 7px;">' + (arrExcel[arrExcel.length - 1].project ? arrExcel[arrExcel.length - 1].project : '') + '</div>';
621                var msg1 = '<div id="message' + i + '" class="getmessage"></div>';
622
623
624                if (!gridHeight) {
625                    gridHeight = $('#layouts-horizontal').height() - ($('#header').height() + $('#horizontal-nav').height() +
626                        $('#headerChipUpload').height() + $('.Details').height() + $('.datatable-header').height() + $('.addValidationButns').height() + $('.page-footer').height() + $('.uploadButn').height() + 190);
627                    responsiveTableOption.scrollHeight = gridHeight;
628                    responsiveTableOption.scrollCollapse = true;
629                }
630                $('#tblInvoice1 tbody').append('<tr class="invoiceRow" data-row="' + (arrExcel.length - 1) + '" data-lineno="' + i + '">' +
631                    '<td style = "vertical-align: top;">' + line + '<span class="getPdfName dn"></span></td></td> ' +
632                    '<td style = "vertical-align: top;">' + ref + '</td> ' +
633                    '<td style = "vertical-align: top;">' + date + '</td>' +
634                    '<td style = "vertical-align: top;">' + order_ref + '<span class="dn"></td>' +
635                    '<td style = "vertical-align: top;">' + del_tkt + '</td>' +
636                    '<td style = "vertical-align: top;">' + amount + '<span class="dn"></span></td>' +
637                    '<td style = "vertical-align: top;">' + tax + '<span class="dn"></td>' +
638                    '<td style = "vertical-align: top;">' + other + '<span class="dn"></td>' +
639                    '<td style = "vertical-align: top;">' + currency + '</td>' +
640                    '<td style = "vertical-align: top;">' + file + '</td>' +
641                    // '<td style = "vertical-align: top;">' + currency + '</td>' +
642                    //'<td style = "vertical-align: top;">' + project + '</td>' +
643                    '<td style = "vertical-align: top;">' + msg1 + '</td>' +
644                    '<td><div class="delInvRow linkcursor fright tooltip" title="Delete row"><a><i class="icon-bin" style="padding-right: 0.1%;"></i></a></div></td>' +
645                    '</tr>');
646            }, responsiveTableOption);
647            var selectedRow = $('#tblInvoice1 tbody').find('tr:last');
648            initDateTimePicker($(selectedRow).find('.getdate'));
649            $(selectedRow).find('.getdate').val('');
650            $(selectedRow).find('.getref').focus();
651            $(window).scrollTop($('#main').height());
652            if ($('.fileAttach').hasClass('disabled')) {
653                $('.fileAttach').removeClass('disabled');
654                $('.fileAttach').css('pointer-events', '');
655            }
656            $('#tblInvoice1').DataTable().draw();
657        },
658        fetchGrnData: function () {
659            $("#grnInfo1").dialog({
660                //height: auto,
661                height: 500,
662                minheight: 500,
663                width: 400,
664                maxwidth: 500,
665                right: 0,
666                modal: false,
667                draggable: true,
668                resizable: false,
669                // overflow: auto,
670                //show: 'blind',
671                //hide: 'blind',              
672                dialogClass: 'ui-dialog',
673                open: function (event, ui) { $(".ui-dialog-titlebar-close").hide() },
674                create: function (e, ui) { $(".ui-front").css("z-index", "999"); },
675                position: { my: "right top", at: "right top", of: "#content" },
676                //buttons: {
677                //    "Close": function () {
678                //        $(this).dialog("close");
679                //    },
680                //}               
681                buttons: [
682                    {
683                        text: "Close",
684                        "class": 'waves-effect waves-green btn tright',
685                        "style": 'line-height: 15px',
686                        click: function () {
687                            $(this).dialog("close");
688                        }
689                    }
690                ]
691            });
692        },
693        closeModal: function () {
694            $('#grnInfo').closeModal();
695        },
696        validateInv: function () {
697            uploadFlag = 1;
698            fileError = 0;
699            purchaseData = [];
700            $('#custom-loader').show();
701            executeServiceCall("GetBasePurchaseOrderlist4Import", {
702                sUserName: ENCRYPTED_USER, //USERNAME, //XE-74005
703            }, function (successData) {
704                purchaseData = $.grep(successData, function (obj) {
705                    return obj.INVOICE_TO_ENTITY_DIVISION_ID == entityFilter
706                });
707                //purchaseData = successData
708                vmInvoiceUploadMain.validateInvData(function () {
709                    if (ifError == false && fileError == 0) {
710                        $('#tblInvoice1').closest('div').scrollLeft(0);
711                        //$('.datatable-scroll-wrap').scrollLeft(0);
712                        displayToast('Validation Successful.', 'success', defaultToastMessageDuration);
713                    }
714                    //else $('.datatable-scroll-wrap').scrollLeft($('#tblInvoice1 tbody').width());
715                    else $('#tblInvoice1').closest('div').scrollLeft($('#tblInvoice1 tbody').width());
716                });
717            })
718        },
719        checkInvData: function (callback) {
720            arrExcel = [];
721            $.each($('#tblInvoice1 tbody tr'), function (i, obj) {
722                //if ($(obj).find('.fileupload1').length > 0)
723                //    if ($(obj).find('.fileupload1')[0].files.length > 0) invoiceFileAttachment[i] = $(obj).find('.fileupload1')[0].files[0];
724                var rowDataPO = {
725                    'uniqueId': $(obj).data('lineno'),
726                    'LineNo': $(obj).find('.getLine').text(),
727                    'InvoiceRef': $(obj).find('.getref').val(),
728                    'Date(dd-mmm-yyyy)': $(obj).find('.getdate').val(),
729                    'OrderRef': $(obj).find('.getorderref').val(),
730                    'DeliveryTkt': $(obj).find('.getdel_tkt').val(),
731                    //'TotalAmount': $(obj).find('.getamount').val().replace(/\,/g, ''),
732                    'AmountIncludingTax': $(obj).find('.getamount').val().replace(/\,/g, ''),
733                    'TaxAmount': $(obj).find('.gettax').val().replace(/\,/g, ''),
734                    'OtherCharges': $(obj).find('.getother').val().replace(/\,/g, ''),
735                    'PDF filename': invoiceFile[$(obj).find('.getref').val()] ? invoiceFile[$(obj).find('.getref').val().trim()] : $(obj).find('.getref').val().trim(),
736                    //   'Type': $(obj).find('.gettype').text(),
737                };
738                arrExcel.push(rowDataPO);
739            });
740            vmInvoiceUploadMain.validateInvoiceRef(callback);
741        },
742        validateInvData: function (callback) {
743            if ($('#txt_filter').val()) {
744                ifSetCallback = true;
745                vmInvoiceUploadMain.clearFilter(function () {
746                    ifSetCallback = false;
747                    vmInvoiceUploadMain.checkInvData(callback);
748                })
749            }
750            else
751                vmInvoiceUploadMain.checkInvData(callback);
752        },
753        searchFilter: function () {
754            var filterText = $('#txt_filter').val();
755            $('#custom-loader').show();
756            setTimeout(function () {
757                vmInvoiceUploadMain.loadFilterData(filterText);
758            }, 30);
759        },
760        clearFilter: function (callback) {
761            $('#txt_filter').val('');
762            $('#custom-loader').show();
763            vmInvoiceUploadMain.loadFilterData(null, ifSetCallback ? callback : null);
764        },
765        loadFilterData: function (filterText, callback) {
766            var filterArr = arrExcel, ttlamt, txamt, othchrs;
767            if (filterText) {
768                filterArr = $.grep(filterArr, function (obj) {
769                    ttlamt = obj.TotalAmount ? (parseFloat(obj.TotalAmount) ? parseFloat(obj.TotalAmount).toFixedExtend(obj.amountPrecision ? obj.amountPrecision : 5) : obj.TotalAmount) : '';
770                    txamt = obj.TaxAmount ? (parseFloat(obj.TaxAmount) ? parseFloat(obj.TaxAmount).toFixedExtend(obj.amountPrecision ? obj.amountPrecision : 5) : obj.TaxAmount) : '';
771                    othchrs = obj.OtherCharges ? (parseFloat(obj.OtherCharges) ? parseFloat(obj.OtherCharges).toFixedExtend(obj.amountPrecision ? obj.amountPrecision : 5) : obj.OtherCharges) : '';
772                    if (invoiceFileAttachment['fileLine' + obj.uniqueId] && invoiceFileAttachment['fileLine' + obj.uniqueId].name.toUpperCase().indexOf(filterText.toUpperCase()) != -1) {
773                        return true;
774                    }
775                    else {
776                        return ((obj.LineNo ? obj.LineNo : '').toString().indexOf(filterText.toUpperCase()) != -1
777                            || (obj.InvoiceRef ? obj.InvoiceRef : '').toUpperCase().indexOf(filterText.toUpperCase()) != -1
778                            || ((obj['Date(dd-mmm-yyyy)']) ? getFormattedDateString(new Date(obj['Date(dd-mmm-yyyy)']), standardDateFormat) : '').toUpperCase().indexOf(filterText.toUpperCase()) != -1
779                            || (obj.OrderRef ? obj.OrderRef : '').toUpperCase().indexOf(filterText.toUpperCase()) != -1
780                            || (obj.DeliveryTkt ? obj.DeliveryTkt : '').toUpperCase().indexOf(filterText.toUpperCase()) != -1
781                            //|| (obj['PDF filename'] ? obj['PDF filename'] : '').toUpperCase().indexOf(filterText.toUpperCase()) != -1
782                            || (ttlamt).toUpperCase().indexOf(filterText.toUpperCase()) != -1
783                            || (txamt).toUpperCase().indexOf(filterText.toUpperCase()) != -1
784                            || (othchrs).toUpperCase().indexOf(filterText.toUpperCase()) != -1
785                            || ttlamt.CurrencyFormat().toUpperCase().indexOf(filterText.toUpperCase()) != -1
786                            || txamt.CurrencyFormat().toUpperCase().indexOf(filterText.toUpperCase()) != -1
787                            || othchrs.CurrencyFormat().toUpperCase().indexOf(filterText.toUpperCase()) != -1)
788                    }
789                });
790            }
791            setTimeout(function () {
792                vmInvoiceUploadMain.tableIndex(filterArr, callback);
793                $('#custom-loader').hide();
794            }, 25);
795        },
796        loadInvoiceTableData: function (callback) {
797            objDeliveryTktArr = {};
798            ifInvoiceRef = [];
799            orderRefDeliveryTkts = {};
800            //invoiceFile = {};
801            $.each(arrExcel, function (i, obj) {
802                obj.uniqueId = obj.uniqueId ? parseFloat(obj.uniqueId) : i + 1;
803                obj.LineNo = obj.LineNo ? parseFloat(obj.LineNo) : obj.LineNo;
804                obj.InvoiceRef = obj.InvoiceRef ? obj.InvoiceRef.trim() : obj.InvoiceRef;
805                obj['Date(dd-mmm-yyyy)'] = obj['Date(dd-mmm-yyyy)'] ? obj['Date(dd-mmm-yyyy)'].trim() : obj['Date(dd-mmm-yyyy)'];
806                obj.OrderRef = obj.OrderRef ? (obj.OrderRef.trim()).toUpperCase() : obj.OrderRef;
807                obj.DeliveryTkt = obj.DeliveryTkt ? obj.DeliveryTkt.trim() : obj.DeliveryTkt;
808                obj.TotalAmount = obj.AmountIncludingTax ? (obj.AmountIncludingTax.trim()).replace(/\,/g, '') : obj.AmountIncludingTax;
809                // if (obj.TotalAmount < 0) { obj.TotalAmount = obj.TotalAmount * -1; }
810                obj.TaxAmount = obj.TaxAmount ? (obj.TaxAmount.trim()).replace(/\,/g, '') : obj.TaxAmount;
811                //if (obj.TaxAmount < 0) { obj.TaxAmount = obj.TaxAmount * -1; }
812                obj.OtherCharges = obj.OtherCharges ? (obj.OtherCharges.trim()).replace(/\,/g, '') : obj.OtherCharges;
813                var filename = obj['PDF filename'].trim().split('.');
814                var pdfName;
815                if (filename.length > 0) {
816                    if (filename[filename.length - 1].toLowerCase() == 'pdf') {
817                        var pdfNameArr = (filename.pop(-1));
818                        pdfName = filename.join('.');
819                    }
820                    else pdfName = obj['PDF filename'].trim();
821                }
822                else pdfName = '';
823                obj.pdfName = pdfName;
824                if (obj.InvoiceRef && !invoiceFile[obj.InvoiceRef]) invoiceFile[obj.InvoiceRef] = obj.pdfName ? obj.pdfName : obj.InvoiceRef;
825                //  obj.Type = obj.Type ? (obj.Type.trim()).toUpperCase() : obj.Type;
826                var dateSplitBySpace = obj['Date(dd-mmm-yyyy)'].split(' ');
827                var dateSplitBySlash = obj['Date(dd-mmm-yyyy)'].split('/');
828                var dateSplitByHiphon = obj['Date(dd-mmm-yyyy)'].split('-');
829                var monthIndex, yearIndex, dateIndex;
830                if (dateSplitBySpace.length != 3) {
831                    if (dateSplitBySlash.length == 3) {
832                        if ($.inArray(dateSplitBySlash[1].toUpperCase(), ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']) == -1 || $.inArray(dateSplitBySlash[2].length, [2, 4]) == -1) {
833                            obj.dateErr = 'Y';
834                        }
835                        else {
836                            yearIndex = dateSplitBySlash[2];
837                            monthIndex = $.inArray(dateSplitBySlash[1].toUpperCase(), ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']) + 1;
838                            if (dateSplitBySlash[2].length == 2) yearIndex = (parseFloat(dateSplitBySlash[2]) + 2000).toString();
839                            obj['Date(dd-mmm-yyyy)'] = monthIndex + '/' + dateSplitBySlash[0] + '/' + yearIndex;
840                        }
841                    }
842                    else {
843                        if (dateSplitByHiphon.length == 3) {
844                            if ($.inArray(dateSplitByHiphon[1].toUpperCase(), ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']) == -1 || $.inArray(dateSplitByHiphon[2].length, [2, 4]) == -1) {
845                                obj.dateErr = 'Y';
846                            }
847                            else {
848                                yearIndex = dateSplitByHiphon[2];
849                                monthIndex = $.inArray(dateSplitByHiphon[1].toUpperCase(), ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']) + 1;
850                                if (dateSplitByHiphon[2].length == 2) yearIndex = (parseFloat(dateSplitByHiphon[2]) + 2000).toString();
851                                obj['Date(dd-mmm-yyyy)'] = monthIndex + '/' + dateSplitByHiphon[0] + '/' + yearIndex;
852                            }
853                        }
854                        else {
855                            obj.dateErr = 'Y';
856                        }
857                    }
858                }
859                else {
860                    if (!Date.parse(obj['Date(dd-mmm-yyyy)'])) {
861                        obj.dateErr = 'Y';
862                    }
863                }
864            });
865            var loadTableRow = function (rowIndex) {
866                var ifExist = 0;
867                if (rowIndex < arrExcel.length) {
868                    if (arrExcel[rowIndex].LineNo && ($.inArray(arrExcel[rowIndex].LineNo, serialNo) == -1)) serialNo.push(arrExcel[rowIndex].LineNo);
869                    else arrExcel[rowIndex].isSr = 'N';
870                    if ((arrExcel[rowIndex].InvoiceRef) && ($.inArray(arrExcel[rowIndex].InvoiceRef, ifInvoiceRef) == -1)) {
871                        ifInvoiceRef.push(arrExcel[rowIndex].InvoiceRef);
872                        arrExcel[rowIndex].ifInvRefErr = 'N';
873                    }
874                    else arrExcel[rowIndex].ifInvRefErr = 'Y';
875                    if (arrExcel[rowIndex].OrderRef) {
876                        var filteredPOData = [];
877                        var filteredPOData1 = purchaseData.filter(function (obj) {
878                            return (obj.BASE_PO_DOC_REF.toUpperCase() == arrExcel[rowIndex].OrderRef.toUpperCase());
879                        })
880                        if (filteredPOData1.length == 0) {
881                            var filteredPOData2 = purchaseData.filter(function (obj) {
882                                return (obj.PARENT_PO_DOC_REF && obj.PARENT_PO_DOC_REF.toUpperCase() == arrExcel[rowIndex].OrderRef.toUpperCase())
883                            })
884                            if (filteredPOData2.length == 0) ifExist = 1;
885                            else {
886                                //  arrExcel[rowIndex].docGuid = filteredPOData2[0].PARENT_PO_DOC_GUID;
887                                arrExcel[rowIndex].isParentRefUsed 
887= 'Y';
888                                filteredPOData.push(filteredPOData2[0]);
889                            }
890                            //$('#orderRef' + row + '').text(arrExcel[row].OrderRef);
891                        }
892                        else {
893                            filteredPOData.push(filteredPOData1[0]);
894                            //arrExcel[rowIndex].docGuid = filteredPOData[0].BASE_PO_DOC_GUID;
895                        }
896                        if (ifExist == 1) loadTableRow(rowIndex + 1);
897                        else {
898                            arrExcel[rowIndex].isValidDocRef = 'Y';
899                            arrExcel[rowIndex].ieCode = filteredPOData[0].IE_CODE;
900                            arrExcel[rowIndex].entityDivisionId = filteredPOData[0].ENTITY_DIVISION_ID;
901                            arrExcel[rowIndex].docGuid = filteredPOData[0].BASE_PO_DOC_GUID;
902                            arrExcel[rowIndex].grnRequirement = filteredPOData[0].GRN_REQUIREMENT;
903                            arrExcel[rowIndex].poType = filteredPOData[0].PO_TYPE_BASIS;
904                            arrExcel[rowIndex].implementVat = filteredPOData[0].IMPLEMENTS_VAT;
905                            arrExcel[rowIndex].category = filteredPOData[0].CATEGORY;
906                            arrExcel[rowIndex].isAutoGrn = filteredPOData[0].IS_AUTO_GRN;
907                            arrExcel[rowIndex].project = filteredPOData[0].IE_CODE + '-' + filteredPOData[0].IE_NAME;
908                            arrExcel[rowIndex].currency = filteredPOData[0].OPERATING_CURRENCY_CODE;
909                            arrExcel[rowIndex].countryCode = filteredPOData[0].EC_COUNTRY_CODE;
910                            arrExcel[rowIndex].amountPrecision = filteredPOData[0].AMOUNT_PRECISION;
911                            arrExcel[rowIndex].invoiceTypeCode = filteredPOData[0].INVOICE_TYPE_CODE;
912                            arrExcel[rowIndex].processCode = filteredPOData[0].BASE_PO_PROCESS_CODE;
913                            arrExcel[rowIndex].stepCode = filteredPOData[0].BASE_PO_STEP_CODE;
914                            arrExcel[rowIndex].ParentDocRef = filteredPOData[0].PARENT_PO_DOC_REF ? filteredPOData[0].PARENT_PO_DOC_REF : filteredPOData[0].BASE_PO_DOC_REF;
915                            arrExcel[rowIndex].callOff = filteredPOData[0].CALL_OFF;
916                            arrExcel[rowIndex].nature = filteredPOData[0].ALLOW_NON_CUST_PUR;
917                            if (arrExcel[rowIndex].callOff == 'E' && arrExcel[rowIndex].isParentRefUsed == 'Y') arrExcel[rowIndex].callOffError = 'Y';
918                            if (arrExcel[rowIndex].DeliveryTkt) arrExcel[rowIndex].DeliveryTkt = $.map((arrExcel[rowIndex].DeliveryTkt).split(','), function (val) { return val.trim(); }).join();
919                            //  if (!objDate[arrExcel[rowIndex].InvoiceRef] && arrExcel[rowIndex].InvoiceDate) objDate[arrExcel[rowIndex].InvoiceRef] = arrExcel[rowIndex].InvoiceDate;                            
920
921                            if (arrExcel[rowIndex].isAutoGrn == 'N' && (arrExcel[rowIndex].DeliveryTkt)) {
922                                //if ((arrExcel[rowIndex].DeliveryTkt)) {
923                                deliveryTktValidate = [];
924                                deliveryTktValidate = arrExcel[rowIndex].DeliveryTkt.split(',');
925                                for (var w = 0; w < deliveryTktValidate.length; w++) {
926                                    var tkt = $.trim(deliveryTktValidate[w]);
927                                    deliveryTktValidate[w] = tkt;
928                                }
929                                DeliveryTktValidation(0, rowIndex)
930                            }
931                            else loadTableRow(rowIndex + 1);
932                        }
933                    }
934                    else loadTableRow(rowIndex + 1);
935                }
936
937                else {
938                    //tableIndex(callback);
939                    vmInvoiceUploadMain.tableIndex(arrExcel, callback);
940                }
941            };
942
943            var DeliveryTktValidation = function (id, rowIndex) {
944                var tktKey = "ENTITY" + arrExcel[rowIndex].entityDivisionId + "IECODE" + arrExcel[rowIndex].ieCode + "ORDERREF" + arrExcel[rowIndex].OrderRef + "DELTKT" + deliveryTktValidate[id];
945                if (id < deliveryTktValidate.length) {
946                    //if (!objDeliveryTktArr[tktKey]) {...........................................Another call for Delivery Ticket validation
947                    //    executeServiceCall("GetDeliveryTicketExistence", {
948                    //        sOrderDocRef: (arrExcel[rowIndex].OrderRef).toString(),
949                    //        sEntityDivisionId: (arrExcel[rowIndex].entityDivisionId).toString(),
950                    //        sIeCode: arrExcel[rowIndex].ieCode,
951                    //        sDeliveryTicketNo: deliveryTktValidate[id],
952                    //    }, function (successData) {
953                    //        objDeliveryTktArr[tktKey] = successData;f
954                    //        DeliveryTktValidation(id + 1, rowIndex);
955                    //    })
956                    //}
957
958                    if (!objDeliveryTktArr[tktKey]) {
959                        executeServiceCall("GetPoRefAgainstDeliveryTicket", {
960                            //sOrderDocRef: (arrExcel[rowIndex].OrderRef).toString(),
961                            sEntityDivisionId: (arrExcel[rowIndex].entityDivisionId).toString(),
962                            //  sIeCode: arrExcel[rowIndex].ieCode,
963                            sDeliveryTicketNo: deliveryTktValidate[id],
964                        }, function (successData) {
965                            objDeliveryTktArr[tktKey] = successData;
966                            DeliveryTktValidation(id + 1, rowIndex);
967                        })
968                    }
969                    else DeliveryTktValidation(id + 1, rowIndex);
970                }
971                else loadTableRow(rowIndex + 1);
972            };
973            delTicketData = {};
974            serialNo = [];
975            // objRemainingRefTktLine = {};
976            loadTableRow(0);
977        },
978        tableIndex: function (arr, callback) {
979            sortJsonByMultipleKeys(arr,
980                [
981                    { "key": "uniqueId", "order": "asc" },
982                ],
983                function (finalSortArray) {
984                    arr = finalSortArray;
985                });
986            ifError = false;
987            fileError = 0;
988            var hideCurrencyColumn = true;
989            countRow = arr.length;
990            setDataTablesResponsive('#tblInvoice1', function () {
991                $('#tblInvoice1 tbody').html('');
992                $.each(arr, function (i2, obj) {
993                    var errorCount = 0;
994                    var i = obj.uniqueId;
995                    var line = '<div id="line' + i + '" class="getLine currencyFormat" style="margin-top: 7px;">' + (parseFloat(obj.LineNo) ? (obj.LineNo) : (obj.LineNo ? obj.LineNo : '')) + '</div>';
996                    var ref = '<input type="text" id="ref' + i + '" class="getref" maxlength="30">';
997                    var date = '<input id="invoice_date' + i + '" class="datetimeinput getdate form-control" type="text">';
998                    var order_ref = '<input type="text" id="order_ref' + i + '" class="getorderref" maxlength="30">';
999                    var del_tkt = '<input type="text" id="del_tkt' + i + '" class="getdel_tkt" maxlength="500">';
1000                    var amount = '<input type="text" class="getamount currencyFormat tright" id="amount' + i + '" maxlength="35">';
1001                    var tax = '<input type="text" class="gettax currencyFormat tright" id="tax' + i + '" maxlength="35">';
1002                    var other = '<input type="text" class="getother currencyFormat tright" id="other' + i + '" maxlength="35">';
1003                    var file = '<div class="file-field input-field s12" style="margin-top: 0px;">' +
1004                        '<div class="btn" style="width: 30px;">' +
1005                        '<span>File</span>' +
1006                        '<input type="file" class="fileupload1" id="file_upload' + i + '" accept="application/pdf">' +
1007                        '</div>' +
1008                        '<div class="file-path-wrapper">' +
1009                        '<input class="file-path validate" id="filename' + i + '" name="filename' + i + '" style="padding-top: 4px;" type="text" required="required" placeholder="Upload PDF file *" data-error=".errorTxt9">' +
1010                        //'<span class="placeholder" style="left: 93px;">Upload PDF file <span>*</span></span>' +
1011                        '<div class="errorTxt9"></div>' +
1012                        '</div>';
1013                    var currency = '<div class="getcurrency" style="margin-top: 7px;" id="currency' + i + '">' + (obj.currency ? obj.currency : '') + '</div>';
1014                    var project = '<div id="project' + i + '" class="getproject" style="margin-top: 7px;">' + (obj.project ? obj.project : '') + '</div>';
1015                    var msg1 = '<div id="message' + i + '" class="getmessage"></div>';
1016                    var message = '<div id="message' + i + '" class="getmessage"></div>';
1017
1018                    if (uploadFlag == 1) {
1019                        if (!invoiceFileAttachment['fileLine' + obj.uniqueId] || invoiceFileAttachment['fileLine' + obj.uniqueId] == undefined) {
1020                            if ($('#fileErrorMsg' + i + '').length == 0) {
1021                                message += '<div class="errorTextMessage" id="fileErrorMsg' + i + '">Upload PDF file.</div>';
1022                                fileError++;
1023                                errorCount++;
1024                            }
1025                        }
1026                    }
1027                    if (!obj.LineNo) {
1028                        message += '<div class="errorTextMessage"># is mandatory.</div>';
1029                        ifError = true;
1030                        errorCount++;
1031                    }
1032                    else {
1033                        if (!parseFloat(obj.LineNo)) {
1034                            message += '<div class="errorTextMessage">Invalid #.</div>';
1035                            ifError = true;
1036                            errorCount++;
1037                        }
1038                        else {
1039                            if (obj.isSr == 'N') {
1040                                message += '<div class="errorTextMessage"># is already assigned.</div>';
1041                                ifError = true;
1042                                errorCount++;
1043                            }
1044                        }
1045                    }
1046
1047                    if (!obj['Date(dd-mmm-yyyy)']) {
1048                        message += '<div class="errorTextMessage">Date is mandatory.</div>';
1049                        ifError = true;
1050                        errorCount++;
1051                    }
1052                    else {
1053                        if (obj.dateErr == 'Y') {
1054                            message += '<div class="errorTextMessage">Invalid Date format.</div>';
1055                            ifError = true;
1056                            errorCount++;
1057                        }
1058                        else {
1059                            if (!Date.parse(obj['Date(dd-mmm-yyyy)'])) {
1060                                message += '<div class="errorTextMessage">Invalid Date format.</div>';
1061                                ifError = true;
1062                                obj.dateErr = 'Y';
1063                                errorCount++;
1064                            }
1065                        }
1066                    }
1067                    if (!obj.InvoiceRef) { message += '<div class="errorTextMessage">Invoice Ref. # is mandatory.</div>'; ifError = true; errorCount++; }
1068                    else {
1069                        if (obj.InvoiceRef.length > 30) {
1070                            message += '<div class="errorTextMessage">Max. length limit for Invoice Ref. # is 30.</div>';
1071                            ifError = true;
1072                            errorCount++;
1073                        }
1074                        else {
1075                            if (obj.ifInvRefErr == 'Y') {
1076                                message += '<div class="errorTextMessage">Invoice Ref. # is already assigned.</div>';
1077                                ifError = true;
1078                                errorCount++;
1079                            }
1080                            else {
1081                                if (invoiceRefData.length > 0) {
1082                                    var invRefCheck = invoiceRefData.filter(function (val1) {
1083                                        return (obj.InvoiceRef == val1.INV_REF_NO && val1.ENTITY_DIVISION_ID == entityFilter)
1084                                    })
1085                                    if (invRefCheck.length > 0) {
1086                                        message += '<div class="errorTextMessage">Invoice Ref. # already exists for supplier ' + entityName + '.</div>';
1087                                        ifError = true;
1088                                        errorCount++;
1089                                    }
1090                                }
1091                            }
1092                        }
1093                    }
1094                    if (!obj.OrderRef) {
1095                        message += '<div class="errorTextMessage">PO/CO Ref. # is mandatory.</div>';
1096                        ifError = true;
1097                        errorCount++;
1098                    }
1099                    else {
1100                        if (obj.OrderRefLenErr) {
1101                            message += '<div class="errorTextMessage">Max. length limit for PO/CO Ref. # is 30.</div>';
1102                            ifError = true;
1103                            errorCount++;
1104                        }
1105                        else {
1106                            if (!obj.isValidDocRef) {
1107                                var checkOrderRefStatus = orderRefValidate.filter(function (obj) {
1108                                    return ((obj.ORDER_DOC_REF.toUpperCase()) == ((arr[i2].OrderRef).toString()));
1109                                })
1110                                if (checkOrderRefStatus.length > 0 /*&& checkOrderRefStatus[0].DOC_REF_EXISTS == 'Y'*/) {
1111                                    if (!obj.docid) {
1112                                        obj.docGuid = checkOrderRefStatus[0].ORDER_DOC_GUID;
1113                                        obj.currency = checkOrderRefStatus[0].D_CURRENCY_CODE;
1114                                        obj.ieCode = checkOrderRefStatus[0].IE_CODE;
1115                                        obj.processCode = checkOrderRefStatus[0].PROCESS_CODE;
1116                                        obj.invoiceTypeCode = checkOrderRefStatus[0].STEP_CODE;
1117                                    }
1118                                    
1119                                    /*if (checkOrderRefStatus[0].DOC_REF_EXISTS == 'Y') {
1120                                        message += '<div class="errorTextMessage">GRN is not prepared for this Order Reference.</div>';
1121                                    } else */if (checkOrderRefStatus[0].DOC_REF_EXISTS == 'C') {
1122                                        message += '<div class="errorTextMessage">Order is fulfilled.</div>';
1123                                        ifError = true;
1124                                        errorCount++;
1125                                    } else
1126                                        if (checkOrderRefStatus[0].DOC_REF_EXISTS == 'N') {
1127                                            message += '<div class="errorTextMessage">PO/CO Ref. # is not a valid Order Reference.</div>';
1128                                            ifError = true;
1129                                            errorCount++;
1130                                        }
1131
1132                                    //  message += '<div class="errorTextMessage">Ord/CO Ref. is fulfilled</div>';
1133                                    //message += '<div class="errorTextMessage">PO/CO Ref. # is fulfilled or Call off is not prepared for this Order Reference.</div>';
1134                                    //message += '<div class="errorTextMessage">PO/CO Ref. # is fulfilled or Call off is not prepared for this Order Reference or GRN is not prepared for this Order Reference.</div>';
1135                                    //ifError = true;
1136                                    //errorCount++;
1137                                }
1138                                else {
1139                                    message += '<div class="errorTextMessage">PO/CO Ref. # is not a valid Order Reference.</div>';
1140                                    ifError = true;
1141                                    errorCount++;
1142                                }
1143                            }
1144                            else {
1145                                //    //  if (obj.callOffError == 'Y') { message += '<div class="errorTextMessage">For this Ord/CO Ref., Call Off is enabled, hence enter Call Off Reference.</div>'; ifError = true; }......Uncomment this
1146                                if (hideCurrencyColumn == true) {
1147                                    if (!divisionCurrencyLink) divisionCurrencyLink = obj.currency;
1148                                    else {
1149                                        if (divisionCurrencyLink != obj.currency) {
1150                                            hideCurrencyColumn = false;
1151                                            colNum = [];
1152                                        }
1153                                    }
1154                                }
1155                            }
1156                        }
1157                    }
1158                    if (!obj.OrderRefLenErr && obj.isValidDocRef == 'Y') {// && !obj.callOffError) {
1159                        if (obj.DeliveryTkt) {
1160                            var invalidDelTkts = [];
1161                            var tktArr = $.map((obj.DeliveryTkt).split(','), function (val) { return val.trim(); });
1162                            for (var id = 0; id < tktArr.length; id++) {
1163                                var tktKey = "ENTITY" + obj.entityDivisionId + "IECODE" + obj.ieCode + "ORDERREF" + obj.OrderRef + "DELTKT" + tktArr[id];
1164                                if (objDeliveryTktArr[tktKey] && objDeliveryTktArr[tktKey].length > 0) {
1165                                    if (obj.OrderRef != obj.ParentDocRef.toUpperCase()) {
1166                                        if (objDeliveryTktArr[tktKey][0].BASE_PO_DOC_REF.toUpperCase() == obj.ParentDocRef.toUpperCase()) {
1167                                            if (obj.OrderRef != objDeliveryTktArr[tktKey][0].DOC_REF.toUpperCase()) {
1168                                                if ($.inArray(tktArr[id], invalidDelTkts) == -1) invalidDelTkts.push(tktArr[id]);
1169                                            }
1170                                        }
1171                                        else {
1172                                            if ($.inArray(tktArr[id], invalidDelTkts) == -1) invalidDelTkts.push(tktArr[id]);
1173                                        }
1174                                    }
1175                                    else {
1176                                        if (obj.OrderRef != objDeliveryTktArr[tktKey][0].BASE_PO_DOC_REF.toUpperCase()) {
1177                                            if ($.inArray(tktArr[id], invalidDelTkts) == -1) invalidDelTkts.push(tktArr[id]);
1178                                        }
1179                                    }
1180                                }
1181                                else {
1182                                    if ($.inArray(tktArr[id], invalidDelTkts) == -1) invalidDelTkts.push(tktArr[id]);
1183                                }
1184                            }
1185                            if (invalidDelTkts.length > 0) {
1186                                message += ('<div class="warningTextMessage">Invoice Processing may be delayed due to one or more missing Delivery Ticket(s): ' + invalidDelTkts.toString() + '.</div>');
1187                                errorCount++;
1188                            }
1189                        }
1190                        //else {.........................***Uncomment this after getting Multi Delivery Ticket flag. //17-11-2017
1191                        //    // Write validations here..
1192                        //    if (obj.multiDeliveryTkt == 'Y') {
1193                        //        message += '<div class="errorTextMessage">
1193One or more Delivery Tickets must be provided.</div>';
1194                        //        ifError = true;
1195                        //    }
1196                        //    else {
1197                        //        if (obj.isAutoGrn == 'Y') {
1198                        //            message += '<div class="warningTextMessage">Invoice Processing maybe delayed due to Delivery Tickets not being provided.</div>';
1199                        //          //  ifError = true;
1200                        //        }                                    
1201                        //    }
1202                        //}
1203                    }
1204                    if (!obj.TotalAmount) {
1205                        message += '<div class="errorTextMessage">Amount (incl. Tax) is mandatory.</div>';
1206                        ifError = true;
1207                        errorCount++;
1208                    }
1209                    else {
1210                        if (!parseFloat(obj.TotalAmount) && parseFloat(obj.TotalAmount) != 0) {
1211                            message += '<div class="errorTextMessage">Invalid Amount (incl. Tax).</div>';
1212                            ifError = true;
1213                            errorCount++;
1214                        }
1215                    }
1216                    // else {
1217                    if (obj.implementVat == 'Y') {
1218                        if (LINE_LEVEL_VAT == 'Y') {
1219                            if (!obj.TaxAmount) {
1220                                message += '<div class="errorTextMessage">Amount (incl. Tax) is mandatory.</div>';
1221                                ifError = true;
1222                                errorCount++;
1223                            }
1224                            else {
1225                                if (!parseFloat(obj.TaxAmount) && parseFloat(obj.TaxAmount) != 0) {
1226                                    message += '<div class="errorTextMessage">Invalid Tax Amount.</div>';
1227                                    ifError = true;
1228                                    errorCount++;
1229                                }
1230                            }
1231                        }
1232                        else {
1233                            if (obj.TaxAmount && !parseFloat(obj.TaxAmount) && parseFloat(obj.TaxAmount) != 0) {
1234                                message += '<div class="errorTextMessage">Invalid Tax Amount.</div>';
1235                                ifError = true;
1236                                errorCount++;
1237                            }
1238                        }
1239                    }
1240                    else {
1241                        if (obj.TaxAmount && !parseFloat(obj.TaxAmount) && parseFloat(obj.TaxAmount) != 0) {
1242                            message += '<div class="errorTextMessage">Invalid Tax Amount.</div>';
1243                            ifError = true;
1244                            errorCount++;
1245                        }
1246                    }
1247
1248                    if (obj.OtherCharges && parseFloat(obj.OtherCharges) != 0 && !parseFloat(obj.OtherCharges)) {
1249                        message += '<div class="errorTextMessage">Invalid Other Charges.</div>';
1250                        ifError = true;
1251                        errorCount++;
1252                    }
1253                    if (obj.TotalAmount < 0 || obj.TaxAmount < 0) {
1254                        message += '<div class="errorTextMessage">Negative Invoice Upload should be through Credit Note only.</div>';
1255                        ifError = true;
1256                        errorCount++;
1257                    }
1258                    if (obj.TotalAmount) {
1259                        if (!obj.TaxAmount || parseFloat(obj.TaxAmount) == 0 || parseFloat(obj.TaxAmount) || !obj.OtherCharges || parseFloat(obj.OtherCharges) == 0 || parseFloat(obj.OtherCharges)) {
1260                            if (parseFloat(obj.TotalAmount) < (parseFloat(obj.TaxAmount ? obj.TaxAmount : 0) + parseFloat(obj.OtherCharges ? obj.OtherCharges : 0))) {
1261                                message += '<div class="errorTextMessage">Amount (incl. Tax) should be greater than Tax Amount + Other Charges.</div>';
1262                                ifError = true;
1263                                errorCount++;
1264                            }
1265                        }
1266                    }
1267
1268                    if (errorCount == 0 && uploadFlag == 1) message = '<div style="color: green; font-size: 11px; padding-top:11px;">Success</div>';
1269                    if (!gridHeight) {
1270                        var gridHeight = $('#layouts-horizontal').height() - ($('#header').height() + $('#horizontal-nav').height() +
1271                            $('#headerChipUpload').height() + $('.Details').height() + $('.datatable-header').height() + $('.addValidationButns').height() + $('.page-footer').height() + $('.uploadButn').height() + 190);
1272                        responsiveTableOption.scrollHeight = gridHeight;
1273                        responsiveTableOption.scrollCollapse = true;
1274                    }
1275                    $('#tblInvoice1 tbody').append('<tr class="invoiceRow" data-row="' + i2 + '" data-lineno="' + obj.uniqueId + '">' +
1276                        '<td style = "vertical-align: top;">' + line + '<span class="getPdfName dn"></span></td></td> ' +
1277                        '<td style = "vertical-align: top;">' + ref + '</td> ' +
1278                        '<td style = "vertical-align: top;">' + date + '</td>' +
1279                        '<td style = "vertical-align: top;">' + order_ref + '<span class="dn"></td>' +
1280                        '<td style = "vertical-align: top;">' + del_tkt + '</td>' +
1281                        '<td style = "vertical-align: top;">' + amount + '<span class="dn"></span></td>' +
1282                        '<td style = "vertical-align: top;">' + tax + '<span class="dn"></td>' +
1283                        '<td style = "vertical-align: top;">' + other + '<span class="dn"></td>' +
1284                        '<td style = "vertical-align: top;">' + currency + '</td>' +
1285                        '<td style = "vertical-align: top;">' + file + '</td>' +
1286                        // '<td style = "vertical-align: top;">' + currency + '</td>' +
1287                        //'<td style = "vertical-align: top;">' + project + '</td>' +
1288                        '<td style = "vertical-align: top;">' + (obj.rowAdd == 'Y' ? msg1 : message) + '</td>' +
1289                        '<td><div class="delInvRow linkcursor fright tooltip" title="Delete row"><a><i class="icon-bin" style="padding-right: 0.1%;"></i></a></div></td>' +
1290                        '</tr>');
1291                    $('#tblInvoice1 tbody').find('tr[data-row="' + i2 + '"]').find('.warningTextMessage').
1292                        after($('#tblInvoice1 tbody').find('tr[data-row="' + i2 + '"]').find('.errorTextMessage'));
1293                    // if (!obj.rowAdd) {
1294                    if (invoiceFileAttachment['fileLine' + obj.uniqueId] != undefined) {
1295                        $('#filename' + obj.uniqueId + '').val(invoiceFileAttachment['fileLine' + obj.uniqueId].name);
1296                        $('#file_upload' + obj.uniqueId + '').attr('title', invoiceFileAttachment['fileLine' + obj.uniqueId].name);
1297                        //$('#tblInvoice1 tbody').find('tr[data-row="' + i + '"]').find('.file-field').attr('title', invoiceFileAttachment[obj.uniqueId].name);
1298                    }
1299                    //}
1300                });
1301            }, responsiveTableOption);
1302
1303            if (divisionCurrencyLink != undefined && hideCurrencyColumn == true) {
1304                $('.totalAmt').text('Amount (incl. Tax) (' + divisionCurrencyLink + ')');
1305                $('.taxAmt').text('Tax Amount (' + divisionCurrencyLink + ')');
1306                $('.otherAmt').text('Other Charges (' + divisionCurrencyLink + ')');
1307            }
1308            //$('.currencyFormatMainDiv').find('.datatable-header').append('<div class=" multipleButtons tright" style="padding-bottom: 3px;">' +
1309            //    '<a class="waves-effect waves-light secondary_back file-field btn-floating fileAttach tooltip" style="margin-right: 7px;" title="Upload PDF files"><i class="icon-attachment"></i><input type="file" multiple class="addMultipleFiles" title=" " accept="application/pdf"></a>' +
1310            //    '<a class="waves-effect waves-light secondary_back btn-floating getGRN tooltip" style="margin-right: 7px;" title="Delivery Tickets not invoiced"><i class="mdi-notification-event-note"></i></a>' +
1311            //    '<a class="waves-effect waves-light secondary_back btn-floating addInvRow tooltip" title="Add row"><i class="mdi-av-my-library-add"></i></a>');
1312
1313            $('.datatable-scroll-wrap').css('overflow-x', 'auto');
1314            if (countRow == 0) {
1315                $('.fileAttach').addClass('disabled');
1316                $('.fileAttach').css('pointer-events', 'none');
1317            }
1318            else {
1319                $('.fileAttach').removeClass('disabled');
1320                $('.fileAttach').css('pointer-events', '');
1321            }
1322            // intialDatePicker();
1323            //initDateTimePicker();
1324            Materialize.updateTextFields();
1325            $.each(arr, function (i, obj) {
1326                var amountPrecision = obj.amountPrecision ? obj.amountPrecision : 5;
1327                var selectedRow = $('#tblInvoice1 tbody').find('tr[data-lineno="' + obj.uniqueId + '"]');
1328                $(selectedRow).find('.getLine').text(obj.LineNo ? obj.LineNo : '');
1329                $(selectedRow).find('.getref').val(obj.InvoiceRef ? obj.InvoiceRef : '');
1330                if (Date.parse(obj['Date(dd-mmm-yyyy)']) && obj.dateErr != 'Y') initDateTimePicker($(selectedRow).find('.getdate'), { 'value': obj['Date(dd-mmm-yyyy)'] });
1331                else {
1332                    initDateTimePicker($(selectedRow).find('.getdate'));
1333                    $(selectedRow).find('.getdate').val('');
1334                }
1335
1336                var setAmount = (parseFloat(obj.TotalAmount) || parseFloat(obj.TotalAmount) == 0) ? (parseFloat((obj.TotalAmount).replace(/\,/g, '')).toFixedExtend(amountPrecision)).CurrencyFormat() : (obj.TotalAmount ? obj.TotalAmount : '');
1337                var setTax = (parseFloat(obj.TaxAmount) || parseFloat(obj.TaxAmount) == 0) ? (parseFloat((obj.TaxAmount).replace(/\,/g, '')).toFixedExtend(amountPrecision)).CurrencyFormat() : (obj.TaxAmount ? obj.TaxAmount : '');
1338                /* if (isNaN(obj.TotalAmount)) {
1339                     var setAmount = (parseFloat(obj.TotalAmount) || parseFloat(obj.TotalAmount) == 0) ? (parseFloat((obj.TotalAmount).replace(/\,/g, '')).toFixedExtend(amountPrecision ? amountPrecision: 0)).CurrencyFormat() : (obj.TotalAmount ? obj.TotalAmount : '');
1340                 } else {
1341                     var setAmount = (parseFloat(obj.TotalAmount) || parseFloat(obj.TotalAmount) == 0) ? parseFloat(obj.TotalAmount).toFixedExtend(obj.amountPrecision ? amountPrecision:0) : (obj.TotalAmount ? obj.TotalAmount : '');
1342                     setAmount = setAmount ? (setAmount.toString()).CurrencyFormat() : '';
1343                 }
1344 
1345                 if (isNaN(obj.TaxAmount)) {
1346                     var setTax = (parseFloat(obj.TaxAmount) || parseFloat(obj.TaxAmount) == 0) ? (parseFloat((obj.TaxAmount).replace(/\,/g, '')).toFixedExtend(amountPrecision ? amountPrecision:0)).CurrencyFormat() : (obj.TaxAmount ? obj.TaxAmount : '');
1347                 } else {
1348                     var setTax = (parseFloat(obj.TaxAmount) || parseFloat(obj.TaxAmount) == 0) ? parseFloat(obj.TaxAmount).toFixedExtend(obj.amountPrecision ? amountPrecision : 0) : (obj.TaxAmount ? obj.TaxAmount : '');
1349                     setTax = setTax ? (setTax.toString()).CurrencyFormat() : '';
1350                 }*/
1351
1352                var setOtherCharges = (parseFloat(obj.OtherCharges) || parseFloat(obj.OtherCharges) == 0) ? (parseFloat((obj.OtherCharges).replace(/\,/g, '')).toFixedExtend(amountPrecision)).CurrencyFormat() : (obj.OtherCharges ? obj.OtherCharges : '');
1353                $(selectedRow).find('.getorderref').val(obj.OrderRef ? obj.OrderRef : ''); // new Date(obj.InvoiceDate)
1354                $(selectedRow).find('.getdel_tkt').val(obj.DeliveryTkt ? obj.DeliveryTkt : ''); // new Date(obj.InvoiceDate)                    
1355                $(selectedRow).find('.getamount').val(setAmount); // new Date(obj.InvoiceDate)
1356                $(selectedRow).find('.gettax').val(setTax); // new Date(obj.InvoiceDate)
1357                $(selectedRow).find('.getother').val(setOtherCharges);
1358            });
1359            if (callback) callback();
1360            setTimeout(function () {
1361                $('#custom-loader').hide();
1362            }, 100);
1363        },
1364        verifyme: function () {
1365            swal({
1366                title: '',
1367                html: '<div><input type="checkbox" id="isDeclared" class="filled-in"><label for="isDeclared" id="lblDeclared" style="text-decoration: none; font-size: 16px; color: red;"> I hereby verify that uploaded files are valid tax invoices</label><div>' +
1368                    '<div class="showWarningMsg dn tleft"><span style="text-decoration: none; font-size: 10px; color: red; margin-left: 25px;"> * Declaration is mandatory</span></div>',
1369                type: "warning",
1370                showCancelButton: true,
1371                confirmButtonText: confirmButtonText,
1372                cancelButtonText: cancelButtonText,
1373                confirmButtonColor: confirmButtonColor,
1374                cancelButtonColor: cancelButtonColor,
1375                allowOutsideClick: false,
1376                animation: false,
1377                customClass: 'animated zoomIn',
1378            }).then(function (r) {
1379                if (r.value) {
1380                    if ($('#isDeclared').prop('checked') == false) {
1381                        $('.showWarningMsg').removeClass('dn');
1382                    }
1383                }
1384            });
1385        },
1386        closeModal: function () {
1387            $('.declaration').closeModal();
1388        },
1389        uploadInvoice: function () {
1390            $('#custom-loader').show();
1391            SupplyPortalOnlineDB.stateManager.reset();
1392            var getAllRowsValue = function (x) {
1393                var returnObject = {};
1394                //     var type1 = (arrExcel[x].Type);
1395                returnObject.ref = arrExcel[x].InvoiceRef;//$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getref')[0].innerHTML;
1396                returnObject.date = getFormattedDateString(new Date(arrExcel[x]['Date(dd-mmm-yyyy)']), standardDateFormat); //$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getdate')[0].innerHTML;//Order_Ref	DeliveryTkt	Total_Amount	Tax	Other_Charges	Type
1397                returnObject.order_ref = arrExcel[x].OrderRef;// $($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getorderref')[0].innerHTML;
1398                returnObject.getdel_tkt = (arrExcel[x].DeliveryTkt ? $.map((arrExcel[x].DeliveryTkt).split(','), function (val) { return val.trim(); }).join() : null); //: null; //$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getdel_tkt')[0].innerHTML.replace(/\' '/g, '');
1399                returnObject.amountPrecision = arrExcel[x].amountPrecision ? arrExcel[x].amountPrecision : 5;   //Modified (ForNull-5) XE-57267     //In following lines (arrExcel[x]->returnObject).amountPrecision
1400                returnObject.amount = (arrExcel[x].TotalAmount) ? parseFloat((arrExcel[x].TotalAmount).replace(/\,/g, '')).toFixedExtend(returnObject.amountPrecision) : 0; //$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getamount')[0].innerHTML.replace(/\,/g, '');
1401                returnObject.tax = (arrExcel[x].TaxAmount) ? parseFloat((arrExcel[x].TaxAmount).replace(/\,/g, '')).toFixedExtend(returnObject.amountPrecision) : 0;//$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.gettax')[0].innerHTML.replace(/\,/g, '');
1402                returnObject.other = (arrExcel[x].OtherCharges) ? parseFloat((arrExcel[x].OtherCharges).replace(/\,/g, '')).toFixedExtend(returnObject.amountPrecision) : '0'; //$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getother')[0].innerHTML.replace(/\,/g, '');
1403                //var type1 = (arrExcel[x].Type).toUpperCase(); //$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.gettype')[0].innerHTML.toUpperCase();
1404                // if (type1 == 'INVOICE') returnObject.type = 'INV';
1405                //  else if (type1 == 'CREDIT NOTE') returnObject.type = 'CRN';
1406                returnObject.type = 'INV';
1407                returnObject.currency = (arrExcel[x].currency);// : null; //$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getcurrency').text();
1408                returnObject.project = (arrExcel[x].project);// : null; //$($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getproject').text();
1409                //    returnObject.message = $($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.getmessage')[0].innerHTML;
1410                returnObject.FileAttached = invoiceFileAttachment['fileLine' + arrExcel[x].uniqueId]; // $($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.fileupload1').length > 0 ? $($('#tblInvoice1 tbody tr.invoiceRow')[x]).find('.fileupload1')[0].files[0] : '';
1411                //  returnObject.getdel_tkt = $.map(returnObject.getdel_tkt.split(','), function (v) { return v.trim(); }).join();
1412                returnObject.FileName = returnObject.FileAttached ? (returnObject.FileAttached).name : '';
1413                //var result = purchaseData.filter(function (obj) {
1414                //    return (obj.BASE_PO_DOC_REF == returnObject.order_ref);
1415                //})
1416                returnObject.autoGRN = arrExcel[x].isAutoGrn;// : null;//result[0].IS_AUTO_GRN;
1417                returnObject.docid = arrExcel[x].docGuid;// : null; //result[0].BASE_PO_DOC_GUID;
1418                returnObject.ENTITY_DIVISION_ID = arrExcel[x].entityDivisionId;// : null;
1419                // returnObject.implementCis = arrExcel[x].entityDivisionId; //result[0].IMPLEMENTS_CIS;
1420                returnObject.implementVat = arrExcel[x].implementVat;// : null; //result[0].IMPLEMENTS_VAT;
1421                returnObject.CATEGORY = arrExcel[x].category;// : null; //result[0].CATEGORY;
1422                returnObject.country_code = arrExcel[x].countryCode; //result[0].EC_COUNTRY_CODE;
1423                //  returnObject.amount_pre = result[0].AMOUNT_PRECISION;
1424                returnObject.INVOICE_TYPE_CODE = arrExcel[x].invoiceTypeCode;// : null; //result[0].INVOICE_TYPE_CODE;
1425                returnObject.iecode = arrExcel[x].ieCode; //result[0].IE_CODE;
1426                returnObject.PO_DOC_REF = arrExcel[x].OrderRef;// : null; //result[0].BASE_PO_DOC_REF;
1427                returnObject.PROCESS_CODE = arrExcel[x].processCode;// : null; //result[0].BASE_PO_PROCESS_CODE;
1428                returnObject.STEP_CODE = arrExcel[x].stepCode;// : null; //result[0].BASE_PO_STEP_CODE;
1429                returnObject.nature = arrExcel[x].nature;
1430                //   if (type1 == 'INVOICE') {
1431                var calc = [];//, PAY_TERM_CODE, ENTITY_INV_DUE_DATE, CREDIT_PERIOD_DAYS, CUSTODIAN_IE_CODE, METHOD
1432                executeServiceCall("GetInvoiceDueDateInfo", {
1433                    sProcessCode: (returnObject.PROCESS_CODE).toString(),
1434                    sStepCode: (returnObject.STEP_CODE).toString(),
1435                    sBasePOdocGuid: (returnObject.docid).toString(),
1436                }, function (successData) {
1437                    calc = successData;
1438                    returnObject.PAY_TERM_CODE = calc[0].PAY_TERM_CODE;
1439                    returnObject.CREDIT_PERIOD_DAYS = parseFloat(calc[0].CREDIT_PERIOD_DAYS);
1440                    returnObject.CUSTODIAN_IE_CODE = calc[0].CUSTODIAN_IE_CODE;
1441                    returnObject.METHOD = calc[0].METHOD;
1442                    returnObject.ENTITY_INV_DUE_DATE = vmInvoiceUploadMain.calculateDueDate(returnObject.PAY_TERM_CODE, returnObject.METHOD, returnObject.CREDIT_PERIOD_DAYS, returnObject.date);
1443                    getBaseStringFromFile(x, returnObject);
1444                });
1445                // }
1446                //  else getBaseStringFromFile(x, returnObject);
1447            };
1448
1449            var getBaseStringFromFile = function (x, returnObject) {
1450                returnObject.index = x;
1451                if (returnObject.FileAttached)
1452                    returnObject.FileAttached.convertToBase64(returnObject, function (returnObject, stringNew) {
1453                        returnObject.stringNew = stringNew;
1454                        execAfterFileString(returnObject);
1455                    });
1456                else {
1457                    returnObject.stringNew = '';
1458                    execAfterFileString(returnObject);
1459                }
1460            }
1461            var execAfterFileString = function (returnObject) {
1462                // if (returnObject.type == 'INV') {
1463                // $('#custom-loader').show();
1464                var INVOICE_HDR = {
1465                    USER_SESSION_GUID: USER_SESSION_GUID,
1466                    PROCESS_CODE: returnObject.PROCESS_CODE,
1467                    STEP_CODE: returnObject.INVOICE_TYPE_CODE,
1468                    DOC_GUID: (returnObject.index + 1) * -1,
1469                    IE_CODE: returnObject.iecode,
1470                    ENTITY_DIVISION_ID: entityFilter, //returnObject.ENTITY_DIVISION_ID,
1471                    ENTITY_INV_NO: returnObject.ref,
1472                    ENTITY_INV_DATE: returnObject.date ? localToServerTime(setOnlyDate(returnObject.date)) : null,
1473                    D_CURRENCY_CODE: returnObject.currency,
1474                    CTRL_GROSS_AMT: parseFloat((parseFloat(returnObject.amount) - parseFloat(returnObject.tax)).toFixedExtend(returnObject.amountPrecision)),// - parseFloat(returnObject.other)).toFixed(returnObject.amountPrecision)),
1475                    CTRL_VAT_AMOUNT: (returnObject.implementVat == 'Y') ? parseFloat(returnObject.tax) : 0,
1476                    CTRL_CIS_AMOUNT: 0,
1477                    LINE_SUM_AMOUNT: parseFloat((parseFloat(returnObject.amount) - parseFloat(returnObject.tax) - parseFloat(returnObject.other)).toFixedExtend(returnObject.amountPrecision)),
1478                    DOC_VALUE: parseFloat(returnObject.amount),
1479                    PO_DOC_GUID: returnObject.docid,
1480                    PO_DOC_REF: returnObject.PO_DOC_REF,
1481                    ENTITY_INV_DUE_DATE: null,//(returnObject.ENTITY_INV_DUE_DATE != 0) ? localToServerTime(setOnlyDate(returnObject.ENTITY_INV_DUE_DATE)) : null,
1482                    FILENAME: returnObject.FileName,
1483                    INVOICE_ATTACHMENT: returnObject.stringNew,
1484                    CUSTODIAN_IE_CODE: returnObject.nature == 'Y' ? (returnObject.CUSTODIAN_IE_CODE ? returnObject.CUSTODIAN_IE_CODE : returnObject.iecode) : null,
1485                    PAY_TERM_CODE: null,//returnObject.PAY_TERM_CODE ? returnObject.PAY_TERM_CODE : null,
1486                    EC_COUNTRY_CODE: returnObject.country_code,
1487                    SUNDRY_CONTRA_AMOUNT: parseFloat(returnObject.other),
1488                    TAX_TREATMENT_STATUS: null,
1489                    DELIVERY_TKT_REF: (returnObject.autoGRN == 'N') ? returnObject.getdel_tkt : null,
1490                    TYPE: (returnObject.type),// ? returnObject.type : null,
1491                };
1492                SupplyPortalOnlineDB.SCP_ISA_INVOICE_HDR.add(INVOICE_HDR);
1493                //    }
1494                //else {
1495                //    var CREDIT_NOTE = {
1496                //        USER_SESSION_GUID: USER_SESSION_GUID,
1497                //        DEST_PROCESS_CODE: 'ACCOUNTSPAYABLE',
1498                //        DEST_STEP_CODE: 'SUNDRYCONTRA-PROCUREMENT',
1499                //        LINE_GUID: (returnObject.index + 1) * -1,
1500                //        IE_CODE: returnObject.iecode,
1501                //        FILE_NAME: returnObject.FileName,
1502                //        CREDIT_NOTE_ATTACHMENT: returnObject.stringNew,
1503                //        ENTITY_DIVISION_ID: entityFilter,
1504                //        CREDIT_NOTE_NUMBER: returnObject.ref,
1505                //        CREDIT_NOTE_DATE: returnObject.date ? localToServerTime(setOnlyDate(returnObject.date)) : null,
1506                //        CREDIT_NOTE_AMOUNT: parseFloat(returnObject.amount),
1507                //        CREDIT_NOTE_TAX: parseFloat(returnObject.tax),
1508                //        INVOICE_NUMBER: returnObject.invoiceRef,
1509                //
1510                //    };
1511                //    SupplyPortalOnlineDB.SCP_ISA_INVOICE_CREDIT_NOTE.add(CREDIT_NOTE);
1512                //}
1513                var x = returnObject.index + 1;
1514                if (x < $('#tblInvoice1 tbody tr.invoiceRow').length) getAllRowsValue(x);
1515                else {
1516                    var promise = SupplyPortalOnlineDB.saveChanges();
1517                    promise.then(function (success) {
1518
1519                        executeServiceCall("UploadInvoiceHeader", {
1520                            sUserSessionGUID: USER_SESSION_GUID,
1521                        }, function (success) {
1522                            $('#custom-loader').hide();
1523                            displayToast('Saved Successfully', 'success', defaultToastMessageDuration);
1524                            // $('#selectentitylist').val(selectedentity);
1525                            arrExcel = [];
1526                            arrExcelDataCopy = [];
1527                            globalCountChange = true;
1528                            window.clearTimeout(invoiceTimeOut);
1529                            retrieveInvoiceArr = null;
1530                            vmInvoiceUploadMain.loadPurchaseOrder();
1531                            vmInvoiceUploadMain.clearDetails();
1532                            //   $('.mytable_main').find('#task_main_header').prop('')                           
1533                            //  vmInvoiceUpload.loadTable();
1534                        }, function (err) {
1535                            $('#custom-loader').hide();
1536                            displayToast(err, 'danger', defaultToastMessageDuration);
1537                        });
1538                    }, function (err) {
1539                        $('#custom-loader').hide();
1540                        if (err.message) {
1541                            if (err.message == "The page was not displayed because the request entity is too large.") {
1542                                displayToast("The cumulative size of all attachments exceeds the allowable limit on the Server. To solve this problem, please reduce the number of invoices uploaded at a time.", 'danger', defaultToastMessageDuration);
1543                            } else {
1544                                /*var localMessage = JSON.parse(err.message);   //Console Error on Json Parse XE-57267
1545                                if (localMessage.ExceptionMessage && localMessage.ExceptionMessage == "Maximum request length exceeded.") {
1546                                    displayToast("The cumulative size of all attachments exceeds the allowable limit on the Server. To solve this problem, please reduce the number of invoices uploaded at a time.", 'danger', defaultToastMessageDuration);
1547                                }*/
1548                                var localMessage = JSON.stringify(err);
1549                                if (localMessage && localMessage.indexOf("Maximum request length exceeded.") > -1) {
1550                                    displayToast("The cumulative size of all attachments exceeds the allowable limit on the Server. To solve this problem, please reduce the number of invoices uploaded at a time.", 'danger', defaultToastMessageDuration);
1551                                } else {
1552                                    displayToast(err, 'danger', defaultToastMessageDuration);
1553                                }
1554                            }
1555                        }
1556
1557                    });
1558                }
1559            };
1560            uploadFlag = 1;
1561            if (arrExcel.length == 0) {
1562                $('#custom-loader').hide();
1563                displayToast('Please upload Invoice excel file.', 'w
1563arning', defaultToastMessageDuration);
1564            }
1565            else {
1566                //if (countRow == 0) {
1567                //    displayToast('Datatable is empty.', 'warning', defaultToastMessageDuration);
1568                //}
1569                // else {
1570                vmInvoiceUploadMain.validateInvData(function () {
1571                    if (ifError == true || fileError > 0) displayToast('There seem to be errors in your upload. ', 'warning', defaultToastMessageDuration);
1572                    else {
1573                        swal({
1574                            title: 'Declaration',
1575                            html: '<div><input type="checkbox" id="isDeclared" class="filled-in"><label for="isDeclared" id="lblDeclared" style="text-decoration: none; font-size: 16px; color: red;"> I hereby verify that uploaded files are valid tax invoices</label><div>',
1576                            type: "warning",
1577                            showCancelButton: true,
1578                            confirmButtonText: confirmButtonText,
1579                            cancelButtonText: cancelButtonText,
1580                            confirmButtonColor: confirmButtonColor,
1581                            cancelButtonColor: cancelButtonColor,
1582                            allowOutsideClick: false,
1583                            animation: false,
1584                            customClass: 'animated zoomIn',
1585                            preConfirm: function (ev) {
1586                                if ($('#isDeclared').is(":checked")) {
1587                                    return true;
1588                                }
1589                                else {
1590                                    //swal.showValidationError('Please check and confirm.');
1591                                    return false;
1592                                }
1593                            },
1594                        }).then(function (r) {
1595                            if (r.value) {
1596                                $('#custom-loader').show();
1597                                getAllRowsValue(0);
1598                            }
1599                        });
1600                    }
1601                });
1602                //if (ifError == false) {
1603                //    getAllRowsValue(0);
1604                //    invoiceFileAttachment = {};
1605                //}
1606                //else displayToast('There seem to be errors in your upload. ', 'warning', defaultToastMessageDuration);
1607                //                }
1608            }
1609        },
1610        clearDetails: function () {
1611            $('#btnValidateInv').addClass('disabled');
1612            $('#btnValidateInv').css('pointer-events', 'none');
1613            invoiceFileAttachment = [];
1614            $('#uploadExcelFile').html('');
1615            $('#uploadExcelFile').append('<div class="btn" style="margin: 0px 0px !important;">' +
1616                '<span>File</span>' +
1617                '<input type="file" id="excelUpload" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">' +
1618                '</div>' +
1619                '<div class="file-path-wrapper">' +
1620                '<input class="file-path validate" id="excelName" name="excelName" type="text" placeholder="Upload Microsoft Excel Worksheet">' +
1621                //'<span class="placeholder" style="left:90px;">Upload Microsoft Excel Worksheet</span>' +
1622                '</div>');
1623            var cloneUploadFile = $('#excelUpload');
1624            $('#excelUpload').change(function (e) {
1625                $('#custom-loader').show();
1626                ifValidFile = 0;
1627                uploadFlag = 0;
1628                arrExcel = [];
1629                arrExcelDataCopy = [];
1630                invoiceFile = {};
1631                invoiceFileAttachment = [];
1632                var FileName = e.target.value;
1633                if (!FileName) {
1634                    if (excelFileInstance) {
1635                        $('#excelName').val(excelFileInstance);
1636                        //$('.Details').find('.file-field').attr('title', excelFileInstance);
1637                        $('#excelUpload').attr('title', excelFileInstance);
1638                        $('#custom-loader').hide();
1639                        return false;
1640                    }
1641                }
1642                else {
1643                    var ext = FileName.split('.').pop().toLowerCase();
1644                    if (ext == 'xlsx' ) { // removed xls for vapt
1645                        if (e.target.files) parseExcelToJsonUpload(e.target.files, function (jsonObj) {
1646                            arrExcel = jsonObj;
1647                            arrExcelDataCopy = jsonObj;
1648                            if (jsonObj == undefined) ifValidFile = 0;
1649                            else {
1650                                if ('LineNo' in arrExcel[0] && 'Date(dd-mmm-yyyy)' in arrExcel[0] && 'InvoiceRef' in arrExcel[0] && 'OrderRef' in arrExcel[0] && 'TotalAmount' in arrExcel[0] && 'DeliveryTkt' in arrExcel[0] && 'TaxAmount' in arrExcel[0] && 'OtherCharges' in arrExcel[0] && 'PDF filename' in arrExcel[0])
1651                                    ifValidFile = 1;
1652                            }
1653                            if (ifValidFile == 0) {
1654                                $('#excelName').val('');
1655                                //changeFileFlag = false;
1656                                $('#uploadExcelFile').find('.placeholder').show();
1657                                arrExcel = [];
1658                                cloneUploadFile.replaceWith(cloneUploadFile = cloneUploadFile.clone(true));
1659                                $('#excelUpload').val('');
1660                                $('#excelUpload').attr('title', 'No file chosen');
1661                                //$('.Details').find('.file-field').attr('title', 'No file chosen');
1662                                //$('#btnValidateInv').prop('disabled', true);
1663                                $('#btnValidateInv').addClass('disabled');
1664                                $('#btnValidateInv').css('pointer-events', 'none');
1665                                //$('#custom-loader').hide();
1666                                vmInvoiceUploadMain.loadInvoiceTableData();
1667                                displayToast('Upload valid Microsoft Excel Worksheet ', 'warning', defaultToastMessageDuration);
1668                            }
1669                            else {
1670                                excelFileInstance = e.target.files[0].name;
1671                                $('#excelName').val(excelFileInstance);
1672                                //$(".Details").find(".file-field").attr('title', excelFileInstance);
1673                                //changeFileFlag = false;
1674                                $('#uploadExcelFile').find('.placeholder').hide();
1675                                cloneUploadFile.replaceWith(cloneUploadFile = cloneUploadFile.clone(true));
1676                                $('#excelUpload').val('');
1677                                $('#excelUpload').attr('title', excelFileInstance);
1678                                //$('#btnValidateInv').prop('disabled', false);
1679                                $('#btnValidateInv').removeClass('disabled');
1680                                $('#btnValidateInv').css('pointer-events', '');
1681                                vmInvoiceUploadMain.validateInvoiceRef(function () {
1682                                    if (ifError == false && fileError == 0) $('#tblInvoice1').closest('div').scrollLeft(0);
1683                                    else $('#tblInvoice1').closest('div').scrollLeft($('#tblInvoice1 tbody').width());
1684                                });
1685                            }
1686                        })
1687                    }
1688                    else {
1689                        $('#excelName').val('');
1690                        //changeFileFlag = false;
1691                        $('#uploadExcelFile').find('.placeholder').show();
1692                        arrExcel = [];
1693                        cloneUploadFile.replaceWith(cloneUploadFile = cloneUploadFile.clone(true));
1694                        $('#excelUpload').val('');
1695                        $('#excelUpload').attr('title', 'No file chosen');
1696                        //$('.Details').find('.file-field').attr('title', 'No file chosen');
1697                        //$('#custom-loader').hide();
1698                        //$('#btnValidateInv').prop('disabled', true);
1699                        $('#btnValidateInv').addClass('disabled');
1700                        $('#btnValidateInv').css('pointer-events', 'n
1700one');
1701                        vmInvoiceUploadMain.loadInvoiceTableData();
1702                        displayToast('Upload valid Microsoft Excel Worksheet ', 'warning', defaultToastMessageDuration);
1703                    }
1704                }
1705            })
1706        },
1707    }
1708    return vmInvoiceUploadMain;
1709};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.