function locale(num, disabled) { if (!disabled) { return num; } var backup = num; if (typeof num !== 'number') { num = Number(num); } if (isNaN(num)) { return backup; } var s = num.toFixed(2); var array = s.split('.'); var integer = array[0].split('').reverse().join('').replace(/(\d{3})+?/g, function (s) { return s + ',' }).split('').reverse().join(''); if (integer[0] == ',') { integer = integer.substring(1); } return integer + '.' + array[1]; } function OnExpendInTab(e) { var t = $(e); var tid = t.attr("target"); if (t.hasClass("iconchevrondown")) { t.removeClass("iconchevrondown").addClass("iconchevronright"); $("#" + tid).hide(); } else { t.removeClass("iconchevronright").addClass("iconchevrondown"); $("#" + tid).show(); } } /*************************Inspections********************************/ if (typeof ($woinspection) !== "function") { $woinspection = function (option) { this.option = option || {}; var _this = this; var inspectionDiv = null; this.changewo = function (woid, aid) { //if (woid !== option.workorderid) { this.option.workorderid = woid; if (aid) this.option.machineid = aid; inspectionDiv && inspectionDiv.empty(); getWOInspectItems(); //} } this.close = function () { } this.changeasset = function (aid) { this.option.machineid = aid; } this.createInspectionDiv = function (p_div) { inspectionDiv = $('
'); p_div.append(inspectionDiv); p_div.applyFleetLanguageText(true); } this.createInspectionDiv(this.option.parent); if (!this.option.inwidget) { inspectionDiv.addClass('overflow', 'auto'); window.onresize = resizeContent; resizeContent(); } function resizeContent() { inspectionDiv && inspectionDiv.css('height', $(window).height() - inspectionDiv.offset().top - 4); } var assetworkorders; var inloading = false; function getWOInspectItems() { inspectionDiv.empty(); assetworkorders = []; if (!_this.option.workorderid || _this.option.workorderid == "") return; if (inloading) return; inloading = true; if (typeof _this.option.showloading == 'function') _this.option.showloading(true); worequest("GetWOInspectItems", JSON.stringify([_this.option.workorderid, _this.option.machineid]), function (data) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data.WorkOrderID != _this.option.workorderid) { getWOInspectItems(); return; } data = data.Data; if (data && data.length > 0) { assetworkorders = data[0].WorkOrders; ShowWOInspects(data); } else { inspectionDiv.empty(); inspectionDiv.append($('
').text(GetTextByKey("P_WO_NOINSPECTION", 'No Inspection'))); } resizeContent(); }, function (err) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); }); } function ShowWOInspects(inspects) { var div = inspectionDiv; div.empty(); for (var i = 0; i < inspects.length; i++) { var ipt = inspects[i]; var targetid = "tbinspect_" + i; var div_title = $('
'); var spimg = $('').data('iptid', ipt.Id).click(function () { var t = $(this); var tid = t.attr("target"); if (t.hasClass("iconchevrondown")) { t.removeClass("iconchevrondown").addClass("iconchevronright"); $("#" + tid).hide(); } else { t.removeClass("iconchevronright").addClass("iconchevrondown"); $("#" + tid).show(); var iptid = t.data("iptid"); var iframe = $("#iframe_" + iptid); if (iframe.data("load") == 0) { iframe.attr('src', '../Inspection/ReportForWorkOrder.aspx?rid=' + iptid); iframe.data("load", 1); } } }); div_title.append(spimg); if (canExport) { spimg = $(''); spimg.attr('title', GetTextByKey('P_IPT_DOWNLOAD', 'Download')).on('click', ipt, function (e) { window.open("../Inspection/Inspection.aspx?rt=f&t=1&id=" + e.data.Id + "&team=0", '_blank'); }); div_title.append(spimg); spimg = $(''); spimg.attr('title', GetTextByKey('P_IPT_PRINT', 'Print')).on('click', ipt, function (e) { if (navigator.userAgent.indexOf('Firefox') >= 0 || navigator.userAgent.indexOf('Opera') >= 0) { window.open("../Inspection/Inspection.aspx?rt=f&t=2&id=" + e.data.Id + "&team=0", '_blank'); return; } $("#ifdiv").attr('src', "../Inspection/Inspection.aspx?rt=f&t=2&id=" + e.data.Id + "&team=0"); if (!$("#ifdiv").data('inited')) { $("#ifdiv").on('load', function () { onifload(); }); $("#ifdiv").data('inited', 1); } }); } div_title.append(spimg); if (!WOReadOnly) { spimg = $(''); if (ipt.VisibleToCustomer) spimg.data('checked', true).removeClass('iconnotview').addClass('iconview').attr('title', GetTextByKey('P_WO_CUSTOMERVISIBLE', 'Customer Visible')); else spimg.data('checked', false).removeClass('iconview').addClass('iconnotview').attr('title', GetTextByKey('P_WO_NOTCUSTOMERVISIBLE', 'Not Customer Visible')); div_title.append(spimg); spimg.data('checked', ipt.VisibleToCustomer).on('click', ipt, function (e) { var t = $(e.target); if (t.data('checked') == true) t.data('checked', false).removeClass('iconview').addClass('iconnotview').attr('title', GetTextByKey('P_WO_NOTCUSTOMERVISIBLE', 'Not Customer Visible')); else t.data('checked', true).removeClass('iconnotview').addClass('iconview').attr('title', GetTextByKey('P_WO_CUSTOMERVISIBLE', 'Customer Visible')); updateInspectVisibleToCustomer(e.data.Id, t.data('checked')); }); } var span = $('').text(ipt.TemplateName); div_title.append(span); span = $('').text(ipt.CommitTimeLocalStr + ' by ' + ipt.CommitedByUserName); div_title.append(span); div_title.append(span); if (AllowReassignWorkorders) { span = $('').text(GetTextByKey('P_WO_WO_COLON', 'WO:')); div_title.append(span); var div_editableselect = $(''); div_editableselect .attr({ 'inspection-id': ipt.Id, 'old-wo-id': ipt.WorkOrderId }) .dropdown(assetworkorders || [], { input: false, valueKey: 'Id', textKey: 'WorkOrderNumber', //selected: ipt.WorkOrderNumber }).on('select', function (_e, wo) { var et = $(_e.target); if (wo && wo.Id != et.attr('old-wo-id')) { var msg1 = GetTextByKey('P_WO_AREYOUSURETHATYOUWANTTOPROCEED', 'Are you sure that you want to proceed ?'); var msg = GetTextByKey('P_WO_YOUAREREASSIGNINGTHISWORKORDER', 'You are reassigning this work order. ') + "
" + msg1; if (wo.Completed) msg = GetTextByKey('P_WO_YOUAREREASSIGNINGTHISWORKORDERTOACLOSEDWORKORDER', 'You are reassigning this Work Order to a CLOSED Work Order.') + "
" + msg1; showConfirm(msg, GetTextByKey("P_WO_WORKORDERASSIGNMENT", 'Work Order Assignment'), function () { updateInspectionWorkOrder(et.attr('inspection-id'), wo.Id); }, function () { et.dropdownVal(et.attr('old-wo-id')); }); } }); div_editableselect.dropdownVal(ipt.WorkOrderId); div_title.append(div_editableselect); } div_title.append('
'); div.append(div_title); var tab = $(''); tr = $(""); td = $(''); var iframe = $('').attr("id", "iframe_" + ipt.Id).data("load", 0); td.append(iframe); tr.append(td); tab.append(tr); div.append(tab); } } function onifload() { var iframe = document.getElementById('ifdiv'); iframe.contentWindow.focus(); iframe.contentWindow.print(); } function updateInspectionWorkOrder(id, woid) { var p = JSON.stringify([id, woid, _this.option.workorderid]); worequest("UpdateInspectionWorkOrder", htmlencode(p), function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_WORKORDERASSIGNMENT", 'Work Order Assignment')); return; } getWOInspectItems(); }, function (err) { }); } function updateInspectVisibleToCustomer(id, chk) { var item = [id, chk]; var param = JSON.stringify(item); param = htmlencode(param); worequest('UpdateInspectionVisibleToCustomer', param, function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_AVAILABLETOCUSTOMER", 'Available to Customer')); } }, function (err) { }); } } } /*************************End Inspections********************************/ /*****************************************Begin Estimate*********************************************/ if (typeof ($woestimate) !== "function") { $woestimate = function (option) { this.option = option || {}; var _this = this; var EstimateStatus = { Draft: 0, Pending: 1, Cancelled: 2, Declined: 3, Approved: 4, Void: 5, None: 100, }; var estimatedata = []; var publishestid = 0; var publishestattach = null; var addestfiledatas = []; var cur_uploaddata; var cur_uploadestid = 0; var btn_woestattasave = null; this.changewo = function (woid) { //if (woid !== option.workorderid) { var keepui = this.option.workorderid === woid; this.option.workorderid = woid; //hideEstimatePopup(); //hidePublishEstimatePopup(); //hideWOEstAttachmentPopup(); getEstimates(keepui); //} } this.close = function () { estimateDialog?.remove(); estimatePublishMask?.remove(); estimatePublishDialog?.remove(); estimateAttachmentDialog?.remove(); } this.setwodata = function (wodata) { this.option.workorderdata = wodata; } this.updatecontact = function (contacts) { this.option.customercontacts = contacts if (this.option.customercontacts) { var names = ""; for (var i = 0; i < this.option.customercontacts.length; i++) { var c = this.option.customercontacts[i]; if (c.OptOut || c.OptOut_BC) continue; var mp = $.trim(c.MobilePhone); var email = $.trim(c.Email); if ((c.ContactPreference == "0" && (checkPhoneNumber(mp)) || (c.ContactPreference == "1" && isEmail(email)))) { if (names == "") names = c.Name; else names += ";" + c.Name; } } $('#dialog_est_phonenum').val(names); } else { $('#dialog_est_phonenum').val(""); } } this.createEstimate = function (p_div) { p_div.addClass('tab_estimates'); var div = $('
'); p_div.append(div); var span_add = $('Add Estimate'); span_add.click(OnAddEstimate); div.append(span_add); p_div.applyFleetLanguageText(true); } this.createEstimate(this.option.parent); var estimateDialog = createEstimateDialog(); var estimatePublishMask = $('
').hide(); $(document.body).append(estimatePublishMask); var estimatePublishDialog = createPublishEstimateDialog(); var estimateAttachmentDialog = createEstimateAttachmentDialog(); function createEstimateDialog() { var dialog = $(''); dialog.on('drop', function (ev) { dropAddEstimateAttachment(ev.originalEvent); }).on('dragover', function (ev) { dragOverAddEstimateAttachment(ev.originalEvent); }).on('paste', function (ev) { cutAddEstimateAttachment(ev.originalEvent); }); dialog.append('
Add Estimate
'); var tb = $('
'); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('Estimate #:').appendTo(tr); td = $('').appendTo(tr); var dialog_est_number = $('').appendTo(td); td = $('Estimate Status:').appendTo(tr); td = $('').appendTo(tr); var dialog_est_status = $('Draft').appendTo(td); tr = $('').appendTo(tb); td = $('Estimate Total Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_est_totalcosts = $('').appendTo(td); var icon = $('').appendTo(td); icon.on('click', function () { getEstimateTotalCost(''); }); td = $('Other Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_est_othercost = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Parts Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_est_partscost = $('').appendTo(td); td = $('Travel Time Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_est_traveltimecost = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Labor Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_est_laborcost = $('').appendTo(td); td = $('Labor Hours:').appendTo(tr); td = $('').appendTo(tr); var dialog_est_timetocomplete = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Taxes ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_est_taxes = $('').appendTo(td); td = $('PO Required:').appendTo(tr); td = $('').appendTo(tr); var dialog_est_porequired = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Customer Issues:').appendTo(tr); td = $('').appendTo(tr); var dialog_est_custissues = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Technician Notes:').appendTo(tr); td = $('').appendTo(tr); var dialog_est_technotes = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Attachments:').appendTo(tr); td = $('').appendTo(tr); var spanAtta = $('Add File').appendTo(td); spanAtta.on('click', function () { openWOEstAttachmentDialog(''); }) tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); var tb_att = $(''); td.append(tb_att); var tr_att = $(''); tb_att.append(tr_att); var td_att = $(''); tr_att.append(td_att); div_att = $('
'); td_att.append(div_att); tb_att = $('
'); div_att.append(tb_att); var func = $('
'); dialog.append(func); func.append(''); var btnpub = $(''); btnpub.on('click', function () { openPublishDialog(-1); }); func.append(btnpub); var btnok = $(''); btnok.on('click', function () { onSaveWorkOrderEstimate(''); }); func.append(btnok); func.append('
'); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { showmaskbg(false); }); dialog.applyFleetLanguageText(true); return dialog; } function createPublishEstimateDialog() { var dialog = $(''); dialog.append('
Publish Estimate
'); var tb = $('
'); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('').appendTo(tr); var dialog_est_chksendtextmsg = $('').appendTo(td); dialog_est_chksendtextmsg.change(function () { var checked = $('#dialog_est_chksendtextmsg').prop('checked'); $('#dialog_est_phonenum').prop('disabled', !checked); $('#dialog_est_chkIncludeStatusLink').prop('disabled', !checked); $('#dialog_est_textmsg').prop('disabled', !checked); }); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); $('
').appendTo(td); td = $('').appendTo(tr); var dialog_est_phonenum = $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); var dialog_est_chkIncludeStatusLink = $('').appendTo(td); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); $('').on('click', function () { if (this.disabled) { return; } var attachmentName = document.querySelector('#dialog_est_spanAttachmentName'); if (!this.checked) { publishestattach = null; attachmentName.style.display = 'none'; return; } var source; if (publishestid <= 0) { source = addestfiledatas.map(function (att) { return { file: att.File, name: att.Notes || att.File.name, enabled: /^image\//.test(att.File.type) || att.File.size <= 2 * 1024 * 1024 }; }); } else { source = estimatedata.find(e => e.Id === publishestid)?.Attachments?.map(function (att) { return { id: att.AttachmentId, name: att.Notes || att.FileName, enabled: true }; }); } var items = source.filter(function (s) { return s.enabled }); if (items.length === 1) { publishestattach = items[0]; attachmentName.innerText = publishestattach.name; attachmentName.style.display = 'block'; return; } publishestattach = null; var ui = window['lib-ui']; var container = ui.createElement('div'); container.style.width = '440px'; container.style.height = '300px'; var grid = new ui.Grid(container); grid.columns = [ { key: 'selected', type: ui.Grid.ColumnTypes.Checkbox, enabled: 'enabled', sortable: false, orderable: false, resizable: false, onchanged: function (item) { for (var it of this.source) { if (it !== item) { it.selected = false; } } this.refresh(); } }, { key: 'name', caption: GetTextByKey('P_WO_NAME', 'Name'), width: 340, orderable: false } ]; grid.init(); var popup = new ui.Popup({ title: GetTextByKey('P_WO_SELECTATTACHMENT', 'Select Attachment'), content: container, resolve: function () { var attachmentName = document.querySelector('#dialog_est_spanAttachmentName'); if (publishestattach == null) { document.querySelector('#dialog_est_chkSendAttachment').checked = false; attachmentName.style.display = 'none'; } else { attachmentName.innerText = publishestattach.name; attachmentName.style.display = 'block'; } }, buttons: [ { text: GetTextByKey('P_WO_ATTACH', 'Attach'), trigger: function () { var item = grid.source.filter(function (i) { return i.selected })[0]; if (item != null) { publishestattach = item; } } }, { text: GetTextByKey('P_WO_CANCEL', 'Cancel') } ] }); popup.show(dialog[0]).then(function () { grid.source = source }); }).appendTo(td); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('Message:').appendTo(tr); td = $('').appendTo(tr); var dialog_est_variables = $('').appendTo(td); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); dialog_est_variables.append(''); var dialog_est_insertfield = $('
').appendTo(td); dialog_est_insertfield.on('click', function () { insertestfield(); }); var dialog_est_textmsg = $('').appendTo(td); var func = $('
'); dialog.append(func); func.append(''); btn_publish = $(''); btn_publish.on('click', function () { onPublishEstimate(); }); func.append(btn_publish); func.append('
'); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { hidePublishEstimatePopup(); }); dialog.applyFleetLanguageText(true); return dialog; } function createEstimateAttachmentDialog() { var dialog = $(''); dialog.append('
Add Attachment
'); var tb = $('
'); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('Caption:').appendTo(tr); td = $('').appendTo(tr); var dialog_estatt_notes = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Attachments:').appendTo(tr); td = $('').appendTo(tr); var dialog_woestatt_uploadattfile = $('').appendTo(td); dialog_woestatt_uploadattfile.on('click', function () { UpLoadEstimateAttachment(); }); tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); var tb_att = $(''); td.append(tb_att); var tr_att = $(''); tb_att.append(tr_att); var td_att = $(''); tr_att.append(td_att); div_att = $('
'); td_att.append(div_att); tb_att = $('
'); div_att.append(tb_att); var func = $('
'); dialog.append(func); func.append(''); btn_woestattasave = $(''); btn_woestattasave.on('click', function () { onSaveWOEstAttachment(); }); func.append(btn_woestattasave); func.append('
'); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { hideWOEstAttachmentPopup(); }); dialog.applyFleetLanguageText(true); return dialog; } function insertestfield() { var field = $("#dialog_est_variables").find("option:selected").text(); $("#dialog_est_textmsg").focus(); document.execCommand('insertText', false, field); } function showEstimatePopup() { showmaskbg(true); estimateDialog.css({ 'top': (document.documentElement.clientHeight - estimateDialog.height()) / 3, 'left': (document.documentElement.clientWidth - estimateDialog.width()) / 2 }).showDialogfixed(); } function hideEstimatePopup() { showmaskbg(false); estimateDialog.hide(); } var inloading = false; function getEstimates(keepui) { if (!keepui) { _this.option.parent.find('.estimates_div').remove(); _this.option.parent.find('.estimates_table').remove(); } if (!_this.option.workorderid || _this.option.workorderid == "") return; if (inloading) return; inloading = true; if (typeof _this.option.showloading == 'function') _this.option.showloading(true); worequest("GetWorkOrderEstimates", _this.option.workorderid, function (data) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data.WorkOrderID != _this.option.workorderid) { getEstimates(false); return; } data = data.Data; _this.option.parent.find('.estimates_div').remove(); _this.option.parent.find('.estimates_table').remove(); if (data) { if (data && data.length > 0) { estimatedata = data; if (AllowCustomer) $('#dialog_estimatestatus').text(_this.getEstimateStatus(data[data.length - 1].Status)); for (var i = 0; i < data.length; i++) { showEstimate(data[i]); } } else { if (AllowCustomer) $('#dialog_estimatestatus').text(_this.getEstimateStatus(100)) } } }, function (err) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); }); } function dragOverEstimateAttachment(ev, estid) { ev.preventDefault(); ev.dataTransfer.dropEffect = 'link'; } function dropEstimateAttachment(ev, estid) { ev.preventDefault(); ev.stopPropagation(); var df = ev.dataTransfer; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } var estimate = $('#tabestimate' + estid).data('estimate'); if (!estimate) return; if (estimate.Status !== 0) return; if (files.length > 0) SaveEstimateAttachmentFiles(files, estid); } function cutEstimateAttachment(ev, estid) { ev.stopPropagation(); var df = ev.clipboardData; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } var estimate = $('#tabestimate' + estid).data('estimate'); if (!estimate) return; if (estimate.Status !== 0) return; if (files.length > 0) SaveEstimateAttachmentFiles(files, estid); } function showEstimate(estimate) { var estid = estimate.Id; var statustext = _this.getEstimateStatus(estimate.Status); var div_estimates = _this.option.parent; var div_title = $('
'); div_title.on('drop', estid, function (ev) { dropEstimateAttachment(ev.originalEvent, ev.data); }).on('dragover', estid, function (ev) { dragOverEstimateAttachment(ev.originalEvent, ev.data); }).on('paste', estid, function (ev) { cutEstimateAttachment(ev.originalEvent, ev.data); }); div_title.append(''); div_title.append('' + estimate.EstimateNumber + ''); div_title.append('' + statustext + ''); if (!WOReadOnly && (estimate.Status == 0 || estimate.Status === 1)) { var s_del = $(''); s_del.on('click', estid, function (e) { OnDeleteEstimate(e.data); }); div_title.append(s_del); } div_title.append('
'); div_estimates.append(div_title); var table = $('
').data('estimate', estimate).hide(); table.on('drop', estid, function (ev) { dropEstimateAttachment(ev.originalEvent, ev.data); }).on('dragover', estid, function (ev) { dragOverEstimateAttachment(ev.originalEvent, ev.data); }).on('paste', estid, function (ev) { cutEstimateAttachment(ev.originalEvent, ev.data); }); div_estimates.append(table); var tr = $(''); table.append(tr); var td = $('').text(GetTextByKey('P_WO_ESTIMATENUMBER_COLON', 'Estimate #:')); tr.append(td); td = $(''); tr.append(td); var ipt = $('').val(estimate.EstimateNumber).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_ESTIMATESTATUS_COLON', 'Estimate Status:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').text(statustext); td.append(ipt); if ([3, 4, 5].indexOf(estimate.Status) >= 0) { td = $(''); if (estimate.Status == 3) { td.text(GetTextByKey('P_WO_REJECTEDBY_COLON', 'Rejected By:')); } else if (estimate.Status == 4 || estimate.Status == 5) { td.text(GetTextByKey('P_WO_APPROVEDBY_COLON', 'Approved By:')); } tr.append(td); td = $(''); tr.append(td); var byph = ""; if (estimate.ResponsePhoneStr !== "") byph = " (" + estimate.ResponsePhoneStr + ")"; ipt = $('').text(estimate.ResponseName + byph); td.append(ipt); } else { tr.append(''); } var disabled = estimate.Status === EstimateStatus.Pending || estimate.Status === EstimateStatus.Declined || estimate.Status === EstimateStatus.Approved || estimate.Status === EstimateStatus.Void; tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_ESTIMATETOTALCOST_COLON', 'Estimate Total Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(estimate.TotalCost, disabled)); td.append(ipt); var btntotal = $("").click(estid, function (e) { getEstimateTotalCost(e.data); }).attr("title", GetTextByKey('P_WO_CALCULATINGTOTALS', 'Calculating Totals')); td.append(btntotal); td = $('').text(GetTextByKey('P_WO_OTHERCOST_COLON', 'Other Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(estimate.OtherCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); if ([3, 4, 5].indexOf(estimate.Status) >= 0) { td = $(''); if (estimate.Status == 3) { td.text(GetTextByKey('P_WO_REJECTEDTIME_COLON', 'Rejected Time:')); } else if (estimate.Status == 4 || estimate.Status == 5) { td.text(GetTextByKey('P_WO_APPROVEDTIME_COLON', 'Approved Time:')); } tr.append(td); td = $(''); tr.append(td); ipt = $('').text(estimate.CustomerResponseTimeStr); td.append(ipt); } else { tr.append(''); } tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_PARTSCOST_COLON', 'Parts Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(estimate.PartsCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_TRAVELTIMECOST_COLON', 'Travel Time Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(estimate.TravelCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); if ([3, 4, 5].indexOf(estimate.Status) >= 0) { td = $(''); if (estimate.Status == 3) { td.text(GetTextByKey('P_WO_REASONFORREJECTION_COLON', 'Reason for Rejection:')); } else if (estimate.Status == 4 || estimate.Status == 5) { td.text(GetTextByKey('P_WO_PONUMBER_COLON', 'PO #:')); } tr.append(td); td = $(''); tr.append(td); if (estimate.Status == 3) { ipt = $('').text(estimate.RejectReason); td.append(ipt); } else if (estimate.Status == 4 || estimate.Status == 5) { ipt = $('').text(estimate.PONumber); td.append(ipt); } } else { tr.append(''); } tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_LABORCOST_COLON', 'Labor Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(estimate.LaborCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_TIMETOCOMPLATEHOURS_COLON', 'Labor Hours:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(estimate.HoursToComplete).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_TAXES_COLON', 'Taxes ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(estimate.Taxes, disabled)).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_POREQUIRED_COLON', 'PO Required:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').prop('checked', estimate.PORequired).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_CUSTOMERISSUES_COLON', 'Customer Issues:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(estimate.CustomerIssues).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); if ([3, 4, 5].indexOf(estimate.Status) >= 0) { td = $('').text(GetTextByKey('P_WO_CUSTOMERNOTES_COLON', 'Customer Notes:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(estimate.CustomerNotes); td.append(ipt); } else { tr.append(''); } tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_TECHNICIANNOTES_COLON', 'Technician Notes:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(estimate.TechnicianNotes).change((function (id) { return function () { inputChanged(id) } })(estid)); td.append(ipt); if (([3, 4, 5].indexOf(estimate.Status) >= 0) && estimate.Signature != null && estimate.Signature && estimate.Signature.length > 0) { td = $('').text(GetTextByKey('P_WO_SIGNATURE_COLON', 'Signature:')); tr.append(td); td = $(''); tr.append(td); var jpeg = estimate.Signature; if (typeof (estimate.Signature) !== "string") { jpeg = arrayBufferToBase64(estimate.Signature); } var imgsig = $('').attr('src', 'data:image/png;base64,' + jpeg); td.append(imgsig); } else { tr.append(''); } if (estimate.Status === 0) { tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_ATTACHMENTS_COLON', ' Attachments:')); tr.append(td); td = $(''); tr.append(td); var div_att = $('
'); td.append(div_att); if (!WOReadOnly) { var span_addfile = $('').text(GetTextByKey('P_FR_ADDFILE', 'Add File...')); span_addfile.on('click', estid, function (e) { openWOEstAttachmentDialog(e.data); }) div_att.append(span_addfile); } } tr = $(''); table.append(tr); td = $('').text(estimate.Status === 0 ? "" : GetTextByKey('P_WO_ATTACHMENTS_COLON', 'Attachments:')); tr.append(td); td = $(''); tr.append(td); var tb_att = $(''); td.append(tb_att); var tr_att = $(''); tb_att.append(tr_att); var td_att = $(''); tr_att.append(td_att); div_att = $('
'); td_att.append(div_att); tb_att = $('
'); div_att.append(tb_att); showEstimateAttachment(estid); tr = $(''); table.append(tr); td = $(''); tr.append(td); ipt = $('').text(GetTextByKey('P_WO_AVAILABLETOCUSTOMER_COLON', 'Available to Customer:')).hide(); td.append(ipt); td = $(''); tr.append(td); ipt = $('').prop('checked', estimate.VisibleToCustomer).hide().change((function (id) { return function () { updateWOEstimateVisibleToCustomer(id) } })(estid)); td.append(ipt); td = $(''); tr.append(td); ipt = $('').val(GetTextByKey('P_WO_SAVE', 'Save')).hide(); ipt.on('click', estid, function (e) { onSaveWorkOrderEstimate(e.data); }); td.append(ipt); ipt = $('').val(GetTextByKey('P_WO_PUBLISH', 'Publish')).hide(); ipt.on('click', estid, function (e) { openPublishDialog(e.data); }); td.append(ipt); ipt = $('').val(GetTextByKey('P_WO_REVOKE', 'Revoke')).hide(); ipt.on('click', estid, function (e) { OnRevokeEstimate(e.data); }); td.append(ipt); if (!WOReadOnly) { if (estimate.Status === 0) { $('#btn_estimatesave' + estid).show(); $('#btn_estimatepublish' + estid).show(); } if (estimate.Status === 1 || estimate.Status === 4) { $('#btn_estimaterevoke' + estid).show(); } } if (disabled || WOReadOnly) setEstimateDisabled(estid, true); if (estimate.Status === 3) { $('#span_eststatus' + estid).css('color', 'red'); $('#dialog_est_status' + estid).css('color', 'red'); } if (estimate.Status === 4) { $('#span_eststatus' + estid).css('color', '#2eda2e'); $('#dialog_est_status' + estid).css('color', '#2eda2e'); } if ([3, 4, 5].indexOf(estimate.Status) >= 0) { $('#lable_est_visibletocustomer' + estid).show(); $('#dialog_est_visibletocustomer' + estid).show(); } } function arrayBufferToBase64(buffer) { var binary = ''; var bytes = new Uint8Array(buffer); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return window.btoa(binary); } function OnRevokeEstimate(estid) { if (!estid) return; showConfirm(GetTextByKey("P_WO_DOYOUWANTTOREVOKETHEESTIMATE", 'Do you want to revoke the estimate?'), GetTextByKey("P_WO_REVOKEESTIMATE", 'Revoke Estimate'), function () { worequest("RevokeWorkOrderEstimate", estid, function (data) { if (data === "OK") { getEstimates(true); } }, function (err) { showAlert(GetTextByKey("P_WO_FAILEDTOREVOKETHISESTIMATE", 'Failed to revoke this estimate.'), GetTextByKey("P_WO_REVOKEESTIMATE", 'Revoke Estimate')); }); }); } function OnDeleteEstimate(estid) { if (!estid) return; showConfirm(GetTextByKey("P_WO_DOYOUWANTTODELETETHEESTIMATE", 'Do you want to delete the estimate?'), GetTextByKey("P_WO_DELETEESTIMATE", 'Delete Estimate'), function () { worequest("DeleteWorkOrderEstimate", estid, function (data) { if (data === "OK") { getEstimates(true); } }, function (err) { showAlert(GetTextByKey("P_WO_FAILEDTODELETETHISESTIMATE", 'Failed to delete this estimate.'), GetTextByKey("P_WO_DELETEESTIMATE", 'Delete Estimate')); }); }); } function onSaveWorkOrderEstimate(estid, next) { var estimateid = -1; var status = 0; var alerttitle = GetTextByKey("P_WO_ADDESTIMATE", "Add Estimate"); if (estid > 0) { alerttitle = GetTextByKey("P_WO_EDITESTIMATE", "Edit Estimate"); var estimate = $('#tabestimate' + estid).data('estimate'); if (!estimate) return; estimateid = estimate.Id; status = estimate.Status; } var estsufix = estid > 0 ? String(estid) : ''; var item = { 'Id': estimateid, 'WorkOrderId': _this.option.workorderid, 'Status': status, 'EstimateNumber': $('#dialog_est_number' + estsufix).val(), 'TotalCost': $('#dialog_est_totalcosts' + estsufix).val(), 'OtherCost': $('#dialog_est_othercost' + estsufix).val(), 'PartsCost': $('#dialog_est_partscost' + estsufix).val(), 'TravelCost': $('#dialog_est_traveltimecost' + estsufix).val(), 'LaborCost': $('#dialog_est_laborcost' + estsufix).val(), 'HoursToComplete': $('#dialog_est_timetocomplete' + estsufix).val(), 'CustomerIssues': $('#dialog_est_custissues' + estsufix).val(), 'TechnicianNotes': $('#dialog_est_technotes' + estsufix).val(), 'Taxes': $('#dialog_est_taxes' + estsufix).val(), 'PORequired': $('#dialog_est_porequired' + estsufix).prop('checked') }; if (isNaN(item.TotalCost) || item.TotalCost < 0) { showAlert(GetTextByKey('P_WO_TOTALCOST_INVALID', 'Total cost is not a valid number.'), alerttitle, function () { $('#dialog_est_totalcosts' + estsufix).focus() }); return; } if (isNaN(item.OtherCost) || item.OtherCost < 0) { showAlert(GetTextByKey('P_WO_OTHERCOST_INVALID', 'Other cost is not a valid number.'), alerttitle, function () { $('#dialog_est_totalcosts' + estsufix).focus() }); return; } if (isNaN(item.PartsCost) || item.PartsCost < 0) { showAlert(GetTextByKey('P_WO_PARTSCOST_INVALID', 'Parts cost is not a valid number.'), alerttitle, function () { $('#dialog_est_partscost' + estsufix).focus() }); return; } if (isNaN(item.TravelCost) || item.TravelCost < 0) { showAlert(GetTextByKey('P_WO_TRAVELTIMECOST_INVALID', 'Travel time cost is not a valid number.'), alerttitle, function () { $('#dialog_est_traveltimecost' + estsufix).focus() }); return; } if (isNaN(item.LaborCost) || item.LaborCost < 0) { showAlert(GetTextByKey('P_WO_LABORCOST_INVALID', 'Labor cost is not a valid number.'), alerttitle, function () { $('#dialog_est_laborcost' + estsufix).focus() }); return; } if (isNaN(item.HoursToComplete) || item.HoursToComplete < 0) { showAlert(GetTextByKey('P_WO_TIMETOCOMPLETE_INVALID', 'Time to complete is not a valid number.'), alerttitle, function () { $('#dialog_est_timetocomplete' + estsufix).focus() }); return; } if (isNaN(item.Taxes) || item.Taxes < 0) { showAlert(GetTextByKey('P_WO_TAXES_INVALID', 'Taxes is not a valid number.'), alerttitle, function () { $('#dialog_est_taxes' + estsufix).focus() }); return; } $('#btn_estimatesave' + estsufix).attr('disabled', true); var param = JSON.stringify(item); param = htmlencode(param); worequest("SaveWorkOrderEstimate", param, function (data) { if (typeof (data) === "string") { $('#btn_estimatesave' + estsufix).attr('disabled', false); showAlert(data, alerttitle); } else { $('#btn_estimatesave' + estsufix).attr('disabled', false); if (estid <= 0) {//新增 if (addestfiledatas && addestfiledatas.length > 0) { SaveEstimateAttachmentFiles(addestfiledatas, data); addestfiledatas = []; } if (next) next(data); else { getEstimates(true); } hideEstimatePopup(); } else {//编辑 if (next) next(estid); else { showAlert(GetTextByKey("P_WO_SAVSUCCESSFULLY", "Saved successfully."), alerttitle); $('#span_estnumber' + estsufix).text($('#dialog_est_number' + estsufix).val()); } } } }, function (err) { $('#btn_estimatesave' + estsufix).attr('disabled', false); console.log(err); showAlert(GetTextByKey("P_WO_FAILEDTORSAVEESTIMATE", 'Failed to save estimate.'), alerttitle); }); } function OnAddEstimate() { addestfiledatas = []; $('#tab_est_atts').empty(); $('#tab_est_attachments').hide(); if (!_this.option.workorderid || _this.option.workorderid === "") { showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), GetTextByKey("P_WO_ADDESTIMATE", "Add Estimate")); return; } $('#dialog_est_number').val(""); $('#dialog_est_status').text(GetTextByKey('P_WO_DRAFT', 'Draft')); $('#dialog_est_totalcosts').val(""); $('#dialog_est_othercost').val(""); $('#dialog_est_partscost').val(""); $('#dialog_est_traveltimecost').val(""); $('#dialog_est_laborcost').val(""); $('#dialog_est_timetocomplete').val(""); $('#dialog_est_custissues').val(""); $('#dialog_est_technotes').val(""); $('#dialog_est_taxes').val(""); $('#dialog_est_porequired').prop('checked', WorkorderParams.DefaultPORequired); if (_this.option.workorderdata) { $('#dialog_est_totalcosts').val(_this.option.workorderdata.WorkOrderTotalCost == 0 ? "" : _this.option.workorderdata.WorkOrderTotalCost); $('#dialog_est_othercost').val(_this.option.workorderdata.OtherCost == 0 ? "" : _this.option.workorderdata.OtherCost); $('#dialog_est_partscost').val(_this.option.workorderdata.PartsCost == 0 ? "" : _this.option.workorderdata.PartsCost); $('#dialog_est_traveltimecost').val(_this.option.workorderdata.TravelTimeCost == 0 ? "" : _this.option.workorderdata.TravelTimeCost); $('#dialog_est_laborcost').val(_this.option.workorderdata.LaborCost == 0 ? "" : _this.option.workorderdata.LaborCost); $('#dialog_est_timetocomplete').val(_this.option.workorderdata.HoursToComplete == 0 ? "" : _this.option.workorderdata.HoursToComplete); $('#dialog_est_custissues').val(_this.option.workorderdata.Description); getEstimateTotalCost(""); } showEstimatePopup(); } function inputChanged(estid) { $('#tabestimate' + estid).data('changed', true); } function setEstimateDisabled(estid, di) { $('#dialog_est_number' + estid).attr('disabled', di); $('#dialog_est_totalcosts' + estid).attr('disabled', di); $('#dialog_est_othercost' + estid).attr('disabled', di); $('#dialog_est_partscost' + estid).attr('disabled', di); $('#dialog_est_traveltimecost' + estid).attr('disabled', di); $('#dialog_est_laborcost' + estid).attr('disabled', di); $('#dialog_est_timetocomplete' + estid).attr('disabled', di); $('#dialog_est_custissues' + estid).attr('disabled', di); $('#dialog_est_technotes' + estid).attr('disabled', di); $('#dialog_est_taxes' + estid).attr('disabled', di); $('#dialog_est_porequired' + estid).attr('disabled', di); } function getEstimateTotalCost(estid) { var othercost = $('#dialog_est_othercost' + estid).val(); var partscost = $('#dialog_est_partscost' + estid).val(); var traveltimecost = $('#dialog_est_traveltimecost' + estid).val(); var laborcost = $('#dialog_est_laborcost' + estid).val(); var taxes = $('#dialog_est_taxes' + estid).val(); var totalcost = 0; if (othercost !== "" && !isNaN(othercost)) totalcost += eval(othercost); if (partscost !== "" && !isNaN(partscost)) totalcost += eval(partscost); if (traveltimecost !== "" && !isNaN(traveltimecost)) totalcost += eval(traveltimecost); if (laborcost !== "" && !isNaN(laborcost)) totalcost += eval(laborcost); if (taxes !== "" && !isNaN(taxes)) totalcost += eval(taxes); $('#dialog_est_totalcosts' + estid).val(totalcost.toFixed(2)); } this.getEstimateStatus = function (s) { var text = ""; if (s === 0) text = GetTextByKey('P_WO_DRAFT', 'Draft'); else if (s === 1) text = GetTextByKey('P_WO_AWAITINGCUSTOMERAPPROVAL', 'Awaiting Customer Approval'); else if (s === 2) text = GetTextByKey('P_WO_CANCELLEDBYDEALER', 'Cancelled by Dealer'); else if (s === 3) text = GetTextByKey('P_WO_CUSTOMERREJECTED', 'Customer Rejected'); else if (s === 4) text = GetTextByKey('P_WO_CUSTOMERAPPROVED', 'Customer Approved'); else if (s === 5) text = GetTextByKey('P_WO_VOID', 'Void'); else if (s === 100) text = ""; return text; } function showPublishEstimatePopup() { if (publishestid <= 0) estimateDialog.find('.maskbg').show(); else estimatePublishMask.fadeIn(100); //showmaskbg(true); $('#dialog_est_textmsg').val(WorkorderParams.EstimateMessage); $('#dialog_est_chkSendAttachment') .prop('disabled', (publishestid <= 0) ? (addestfiledatas.length <= 0) : !(estimatedata.find(e => e.Id === publishestid)?.Attachments?.length > 0)) .prop('checked', false); $('#dialog_est_spanAttachmentName').hide(); publishestattach = null; estimatePublishDialog.css({ 'top': (document.documentElement.clientHeight - estimatePublishDialog.height()) / 3, 'left': (document.documentElement.clientWidth - estimatePublishDialog.width()) / 2 }).showDialogfixed(); } function hidePublishEstimatePopup() { if (publishestid <= 0) estimateDialog.find('.maskbg').hide(); else estimatePublishMask.fadeOut(100); publishestid = 0; estimatePublishDialog.hide(); } function openPublishDialog(estid) { if (estid <= 0) { publishestid = estid; showPublishEstimatePopup(); } else { onSaveWorkOrderEstimate(estid, function () { publishestid = estid; showPublishEstimatePopup(); }); } } function onPublishEstimate() { var changed = $('#tabestimate' + publishestid).data('changed'); if (publishestid <= 0)//add and publish changed = true; if (changed) onSaveWorkOrderEstimate(publishestid <= 0 ? "" : publishestid, PublishEstimate) else PublishEstimate(publishestid); } function PublishEstimate(estid) { if (!estid) return; var pmemails = []; var checked = $('#dialog_est_chksendtextmsg').prop('checked'); if (checked) { var phoneemail = $('#dialog_est_phonenum').val(); if (phoneemail !== "") { var phoneemails = phoneemail.split(';'); for (var i = 0; i < phoneemails.length; i++) { var pm = phoneemails[i]; if (checkPhoneNumber(pm) || isEmail(pm)) { pmemails.push({ 'Key': pm, 'Value': pm }); } else { if (_this.option.customercontacts) { for (var j = 0; j < _this.option.customercontacts.length; j++) { var c = _this.option.customercontacts[j]; if (c.OptOut || c.OptOut_BC) continue; var mp = $.trim(c.MobilePhone); var email = $.trim(c.Email); if (c.Name === pm) { if (c.ContactPreference == "0" && checkPhoneNumber(mp)) { pmemails.push({ 'Key': mp, 'Value': pm }); break; } if (c.ContactPreference == "1" && isEmail(email)) { pmemails.push({ 'Key': email, 'Value': pm }); break; } } } } } } } } var msg = $('#dialog_est_textmsg').val(); var includeStatusLink = $('#dialog_est_chkIncludeStatusLink').prop("checked"); var param = JSON.stringify([estid, _this.option.workorderid, JSON.stringify(pmemails), msg, (includeStatusLink ? "1" : "0")]); param = htmlencode(param); var url = _network.root + 'Maintenance/AddWorkOrder.aspx'; var method = 'PublishEstimateToCustomer'; var data = new FormData(); data.append('MethodName', method); data.append('ClientData', param); if (publishestattach != null) { if (Object.prototype.hasOwnProperty.call(publishestattach, 'id')) { var attap = { Id: publishestattach.id, Caption: publishestattach.name }; data.append('AttaData', htmlencode(JSON.stringify(attap))); } else { data.append('attachment', publishestattach.file); } } estimatePublishDialog.find('.maskbg').show(); $.ajax({ url: url, type: 'POST', dataType: 'json', processData: false, contentType: false, cache: false, data: data, success: function (data) { if (data !== "") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } getEstimates(true); hidePublishEstimatePopup(); }, error: function (request, textStatus, errorThrown) { showAlert(GetTextByKey("P_WO_FAILEDTOPUBLISHTHISESTIMATE", 'Failed to publish this estimate.'), GetTextByKey("P_WO_PUBLISHESTIMATE", 'Publish Estimate')); if (request?.readyState == 0) { console.log(request); } else { writelog_ironintel("PublishEstimate", url + ".-1." + method + "." + JSON.stringify(param), JSON.stringify(request), textStatus + errorThrown); } }, complete: function () { estimatePublishDialog.find('.maskbg').hide(); } }); } function updateWOEstimateVisibleToCustomer(estid) { var estimate = $('#tabestimate' + estid).data('estimate'); if (!estimate) return; var checked = $('#dialog_est_visibletocustomer' + estid).prop('checked'); var param = JSON.stringify([estimate.Id, checked]); param = htmlencode(param); worequest("UpdateWOEstimateVisibleToCustomer", param, function (data) { if (data !== "") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } }, function (err) { showAlert(GetTextByKey("P_WO_FAILEDTOPUBLISHTHISESTIMATE", 'Failed to publish this estimate.'), GetTextByKey("P_WO_AVAILABLETOCUSTOMER", 'Available to Customer')); }); } function SaveEstimateAttachmentFiles(filedatas, estid) { var formData = new FormData(); var notesdata = []; for (var i = 0; i < filedatas.length; i++) { formData.append("iconFile" + i, filedatas[i].File); notesdata.push(encodeURIComponent(filedatas[i].Notes)); } var p = JSON.stringify([estid, JSON.stringify(notesdata)]); formData.append("MethodName", "AddEstimateAttachment"); formData.append("ClientData", p); var url = 'AddWorkOrder.aspx'; $.ajax({ url: url, type: 'POST', dataType: 'json', processData: false, contentType: false, data: formData, async: true, success: function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File')); } else { if (estid > 0) { hideWOEstAttachmentPopup(); getEstimateAttachment(estid); } else getEstimates(true); } }, error: function (err) { showAlert(GetTextByKey("P_WO_UPLOADFAILED", 'Upload failed'), GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File')); } }); } function getEstimateAttachment(estid) { var estimate = $('#tabestimate' + estid).data('estimate'); if (!estimate) return; $('#tab_est_atts' + estid).empty(); $('#tab_est_attachments' + estid).hide(); worequest("GetEstimateAttachment", estimate.Id, function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data && data.length > 0) { showEstimateAttachment(estid, data); } var estimate = estimatedata.find(e => e.Id === estid); if (estimate != null) { estimate.Attachments = data; } }, function (err) { }); } function showEstimateAttachment(estid, atts) { var isdelete = false; if (!atts) { var estimate = $('#tabestimate' + estid).data('estimate'); if (!estimate) return; atts = estimate.Attachments; if (estimate.Status === 0) isdelete = true; } else isdelete = true; $('#tab_est_atts' + estid).empty(); $('#tab_est_attachments' + estid).hide(); if (atts && atts.length > 0) { $('#tab_est_attachments' + estid).show(); for (var i = 0; i < atts.length; i++) { var att = atts[i]; var tr = $('').attr('id', att.AttachmentId); var tdfile = $(''); var filename = $("").text(att.Notes === "" ? att.FileName : att.Notes).click(function () { window.open("../filesvc.ashx?attchid=" + this.parentElement.parentElement.id + "&sourceType=woestimateattachment"); }); var span = $('').text(att.AddedByName).css("margin-right", 5).css("margin-left", 5).css("color", "black"); var spanby = $('').text(att.AddedOnLocalStr).css("color", "black"); tdfile.append(filename, span, spanby); if (!WOReadOnly && isdelete) { var tdimg = $(''); var imgDom = $('').click(function () { deleteEstimateAttachment(this.parentElement.parentElement.id, estid); }); tdimg.append(imgDom); tr.append(tdimg); } tr.append(tdfile).appendTo($('#tab_est_atts' + estid)); } } } function deleteEstimateAttachment(attid, estid) { if (confirm(GetTextByKey("P_WO_DELETEATTACHMENTTIPS", "Are you sure you want to delete the attachment?"))) { worequest("DeleteEstimateAttachment", attid, function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_DELETEATTACHMENT", 'Delete Attachment')); } else { getEstimateAttachment(estid); } }, function (err) { }); } } function hideWOEstAttachmentPopup() { if (cur_uploadestid <= 0) estimateDialog.find('.maskbg').hide(); else showmaskbg(false); estimateAttachmentDialog.hide(); } function openWOEstAttachmentDialog(estid) { cur_uploaddata = undefined; cur_uploadestid = estid; if (estid <= 0) estimateDialog.find('.maskbg').show(); else showmaskbg(true); btn_woestattasave.attr('disabled', false); $('#tab_woest_atts').empty(); $('#tab_woest_attachments').hide(); $('#dialog_estatt_notes').val(''); estimateAttachmentDialog.css({ 'top': (document.documentElement.clientHeight - estimateAttachmentDialog.height()) / 3, 'left': (document.documentElement.clientWidth - estimateAttachmentDialog.width()) / 2 }).showDialogfixed(); } function dragOverAddEstimateAttachment(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = 'link'; } function dropAddEstimateAttachment(ev) { ev.preventDefault(); ev.stopPropagation(); var df = ev.dataTransfer; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } if (files.length > 0) { for (var i = 0; i < files.length; i++) { cur_uploaddata = files[i]; onSaveWOEstAttachment(); } } } function cutAddEstimateAttachment(ev) { ev.stopPropagation(); var df = ev.clipboardData; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } if (files.length > 0) { for (var i = 0; i < files.length; i++) { cur_uploaddata = files[i]; onSaveWOEstAttachment(); } } } function UpLoadEstimateAttachment() { var file = $(''); file.change(function () { var files = this.files; if (files.length == 0) return; if (files[0].size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return false; } if (files[0].size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return false; } var notes = $('#dialog_estatt_notes').val(); cur_uploaddata = { 'File': files[0], 'Notes': notes }; createNewEstimateAttachment(cur_uploaddata); }).click(); } function createNewEstimateAttachment(data) { $('#tab_woest_atts').empty(); $('#tab_woest_attachments').show(); var tr = $(''); var tdfile = $(''); var filename = $("").text(data.Notes === "" ? data.File.name : data.Notes); tdfile.append(filename); var tdimg = $(''); var imgDom = $('').click(function () { this.parentElement.parentElement.remove(); cur_uploaddata = undefined; $('#tab_woest_attachments').hide(); }); tdimg.append(imgDom); tr.append(tdimg); tr.append(tdfile).appendTo($('#tab_woest_atts')); } function onSaveWOEstAttachment() { if (!cur_uploaddata) return; btn_woestattasave.attr('disabled', true); var notes = $('#dialog_estatt_notes').val(); cur_uploaddata.Notes = notes; if (cur_uploadestid <= 0) { addestfiledatas.push(cur_uploaddata); createAddEstimateAttachment(cur_uploaddata); hideWOEstAttachmentPopup(); btn_woestattasave.attr('disabled', false); } else { SaveEstimateAttachmentFiles([cur_uploaddata], cur_uploadestid); } } function createAddEstimateAttachment(data) { var notes = data.Notes; var file = data.File; $('#tab_est_attachments').show(); var tr = $(''); var tdfile = $(''); var filename = $("").text(notes === "" ? file.name : notes); tdfile.append(filename); var tdimg = $(''); var imgDom = $('').data('filedata', data).click(function () { this.parentElement.parentElement.remove(); var fd = $(this).data('filedata'); addestfiledatas.splice(addestfiledatas.indexOf(fd), 1); if (addestfiledatas.length == 0) $('#tab_est_attachments').hide(); }); tdimg.append(imgDom); tr.append(tdimg); tr.append(tdfile).appendTo($('#tab_est_atts')); } } } /*****************************************End Estimate*********************************************/ /*****************************************Begin Invoice*********************************************/ if (typeof ($woinvoice) !== "function") { $woinvoice = function (option) { this.option = option || {}; var _this = this; var invoicedata = []; var publish_invoice_id = 0; var publish_invoice_var = null; var publish_invoice_attach = null; var add_invoice_filedatas = []; var cur_invoice_uploaddata; var cur_invoice_uploadid = 0; this.changewo = function (woid) { //if (woid !== option.workorderid) { var keepui = this.option.workorderid === woid; this.option.workorderid = woid; //hideInvoicePopup(); //hidePublishInvoicePopup(); //hideWOInvoiceAttachmentPopup(); //hideWOInvoiceMakePaidPopup(); getInvoices(keepui); //} } this.close = function () { invoiceDialog?.remove(); invoicePublishMask?.remove(); invoicePublishDialog?.remove(); invoiceAttachmentDialog?.remove(); invoiceMarkPaidDialog?.remove(); } this.setwodata = function (wodata) { this.option.workorderdata = wodata; } this.updatecontact = function (contacts) { this.option.customercontacts = contacts if (this.option.customercontacts) { var names = ""; for (var i = 0; i < this.option.customercontacts.length; i++) { var c = this.option.customercontacts[i]; if (c.OptOut || c.OptOut_BC) continue; var mp = $.trim(c.MobilePhone); var email = $.trim(c.Email); if ((c.ContactPreference == "0" && (checkPhoneNumber(mp)) || (c.ContactPreference == "1" && isEmail(email)))) { if (names == "") names = c.Name; else names += ";" + c.Name; } } $('#dialog_invoice_phonenum').val(names); } else { $('#dialog_invoice_phonenum').val(''); } } this.createInvoice = function (p_div) { p_div.addClass('tab_invoices'); var div = $('
'); p_div.append(div); var span_add = $('Add Invoice'); span_add.click(OnAddInvoice); div.append(span_add); p_div.applyFleetLanguageText(true); } this.createInvoice(this.option.parent); var invoiceDialog = createInvoiceDialog(); var invoicePublishMask = $('
').hide(); $(document.body).append(invoicePublishMask); var invoicePublishDialog = createPublishInvoiceDialog(); var invoiceAttachmentDialog = createInvoiceAttachmentDialog(); var invoiceMarkPaidDialog = createInvoiceMarkPaidDialog(); function createInvoiceDialog() { var dialog = $(''); dialog.on('drop', function (ev) { dropAddInvoiceAttachment(ev.originalEvent); }).on('dragover', function (ev) { dragOverAddInvoiceAttachment(ev.originalEvent); }).on('paste', function (ev) { cutAddInvoiceAttachment(ev.originalEvent); }); dialog.append('
Add Invoice
'); var tb = $('
'); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('Invoice #:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_number = $('').appendTo(td); td = $('Other Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_othercost = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Invoice Total Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_totalcosts = $('').appendTo(td); td = $('Travel Time Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_traveltimecost = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Parts Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_partscost = $('').appendTo(td); td = $('Taxes ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_taxes = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Labor Cost ($):').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_laborcost = $('').appendTo(td); td = $('Invoice Status:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_status = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Payment By:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_paymentby = $('').appendTo(td); dialog_invoice_paymentby.append($('').text(GetTextByKey("P_WO_CREDITCARD", "Credit Card"))); dialog_invoice_paymentby.append($('').text(GetTextByKey("P_WO_CHECK", "Check"))); dialog_invoice_paymentby.append($('').text(GetTextByKey("P_WO_CASH", "Cash"))); td = $('Check #:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_checknumber = $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); td = $('Customer Visible:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_customervisible = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Notes:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_notes = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Attachments:').appendTo(tr); td = $('').appendTo(tr); var spanAtta = $('Add File').appendTo(td); spanAtta.on('click', function () { openWOInvoiceAttachmentDialog(''); }) tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); var tb_att = $(''); td.append(tb_att); var tr_att = $(''); tb_att.append(tr_att); var td_att = $(''); tr_att.append(td_att); div_att = $('
'); td_att.append(div_att); tb_att = $('
'); div_att.append(tb_att); var func = $('
'); dialog.append(func); func.append(''); var btnok = $(''); btnok.on('click', function () { onAddWorkOrderInvoice(''); }); func.append(btnok); func.append('
'); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { showmaskbg(false); }); dialog.applyFleetLanguageText(true); return dialog; } function createPublishInvoiceDialog() { var dialog = $(''); dialog.append('
Publish Invoice
'); var tb = $('
'); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('').appendTo(tr); var dialog_invoice_chksendtextmsg = $('').appendTo(td); dialog_invoice_chksendtextmsg.change(function () { var checked = $('#dialog_invoice_chksendtextmsg').prop('checked'); $('#dialog_invoice_phonenum').prop('disabled', !checked); $('#dialog_invoice_chkIncludeStatusLink').prop('disabled', !checked); $('#dialog_invoice_textmsg').prop('disabled', !checked); }); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); $('
').appendTo(td); td = $('').appendTo(tr); var dialog_invoice_phonenum = $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); var dialog_invoice_chkIncludeStatusLink = $('').appendTo(td); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); $('').on('click', function () { if (this.disabled) { return; } var attachmentName = document.querySelector('#dialog_invoice_spanAttachmentName'); if (!this.checked) { publish_invoice_attach = null; attachmentName.style.display = 'none'; return; } var source; if (publish_invoice_id <= 0) { source = add_invoice_filedatas.map(function (att) { return { file: att.File, name: att.Notes || att.File.name, enabled: /^image\//.test(att.File.type) || att.File.size <= 2 * 1024 * 1024 }; }); } else { source = invoicedata.find(i => i.Id === publish_invoice_id)?.Attachments?.map(function (att) { return { id: att.AttachmentId, name: att.Notes || att.FileName, enabled: true }; }); } var items = source.filter(function (s) { return s.enabled }); if (items.length === 1) { publish_invoice_attach = items[0]; attachmentName.innerText = publish_invoice_attach.name; attachmentName.style.display = 'block'; return; } publish_invoice_attach = null; var ui = window['lib-ui']; var container = ui.createElement('div'); container.style.width = '440px'; container.style.height = '300px'; var grid = new ui.Grid(container); grid.columns = [ { key: 'selected', type: ui.Grid.ColumnTypes.Checkbox, enabled: 'enabled', sortable: false, orderable: false, resizable: false, onchanged: function (item) { for (var it of this.source) { if (it !== item) { it.selected = false; } } this.refresh(); } }, { key: 'name', caption: GetTextByKey('P_WO_NAME', 'Name'), width: 340, orderable: false } ]; grid.init(); var popup = new ui.Popup({ title: GetTextByKey('P_WO_SELECTATTACHMENT', 'Select Attachment'), content: container, resolve: function () { var attachmentName = document.querySelector('#dialog_invoice_spanAttachmentName'); if (publish_invoice_attach == null) { document.querySelector('#dialog_invoice_chkSendAttachment').checked = false; attachmentName.style.display = 'none'; } else { attachmentName.innerText = publish_invoice_attach.name; attachmentName.style.display = 'block'; } }, buttons: [ { text: GetTextByKey('P_WO_ATTACH', 'Attach'), trigger: function () { var item = grid.source.filter(function (i) { return i.selected })[0]; if (item != null) { publish_invoice_attach = item; } } }, { text: GetTextByKey('P_WO_CANCEL', 'Cancel') } ] }); popup.show(dialog[0]).then(function () { grid.source = source }); }).appendTo(td); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('Message:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_variables = $('').appendTo(td); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); dialog_invoice_variables.append(''); var dialog_invoice_insertfield = $('
').appendTo(td); dialog_invoice_insertfield.on('click', function () { insertinvoicefield(); }); var dialog_invoice_textmsg = $('').appendTo(td); var func = $('
'); dialog.append(func); func.append(''); btn_publish = $(''); btn_publish.on('click', function () { onPublishInvoice(); }); func.append(btn_publish); func.append('
'); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { hidePublishInvoicePopup(); }); dialog.applyFleetLanguageText(true); return dialog; } function createInvoiceAttachmentDialog() { var dialog = $(''); dialog.append('
Add Attachment
'); var tb = $('
'); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('Caption:').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_att_notes = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Attachments:').appendTo(tr); td = $('').appendTo(tr); var dialog_woinvoiceatt_uploadattfile = $('').appendTo(td); dialog_woinvoiceatt_uploadattfile.on('click', function () { UpLoadInvoiceAttachment(); }); tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); var tb_att = $(''); td.append(tb_att); var tr_att = $(''); tb_att.append(tr_att); var td_att = $(''); tr_att.append(td_att); div_att = $('
'); td_att.append(div_att); tb_att = $('
'); div_att.append(tb_att); var func = $('
'); dialog.append(func); func.append(''); var btn_woinvoice_att_save = $(''); btn_woinvoice_att_save.on('click', function () { onSaveWOInvoiceAttachment(); }); func.append(btn_woinvoice_att_save); func.append('
'); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { hideWOInvoiceAttachmentPopup(); }); dialog.applyFleetLanguageText(true); return dialog; } function createInvoiceMarkPaidDialog() { var dialog = $(''); dialog.append('
Mark as Paid
'); var tb = $(''); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_markpaid_paymentby = $('').appendTo(td); dialog_invoice_markpaid_paymentby.append($('').text(GetTextByKey("P_WO_CREDITCARD", "Credit Card"))); dialog_invoice_markpaid_paymentby.append($('').text(GetTextByKey("P_WO_CHECK", "Check"))); dialog_invoice_markpaid_paymentby.append($('').text(GetTextByKey("P_WO_CASH", "Cash"))); tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); var dialog_invoice_markpaid_number = $('').appendTo(td); var func = $('
'); dialog.append(func); func.append(''); var btnok = $(''); btnok.on('click', function () { OnMarkAsPaid(); }); func.append(btnok); func.append('
'); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { showmaskbg(false); }); dialog.applyFleetLanguageText(true); return dialog; } function insertinvoicefield() { var field = $("#dialog_invoice_variables").find("option:selected").text(); $("#dialog_invoice_textmsg").focus(); document.execCommand('insertText', false, field); } function showInvoicePopup() { showmaskbg(true); invoiceDialog.show(); invoiceDialog.css({ 'top': (document.documentElement.clientHeight - invoiceDialog.height()) / 3, 'left': (document.documentElement.clientWidth - invoiceDialog.width()) / 2 }).showDialogfixed(); } function hideInvoicePopup() { showmaskbg(false); invoiceDialog.hide(); } var inloading = false; function getInvoices(keepui) { if (!keepui) { _this.option.parent.find('.estimates_div').remove(); _this.option.parent.find('.estimates_table').remove(); } if (!_this.option.workorderid || _this.option.workorderid == "") return; if (inloading) return; inloading = true; if (typeof _this.option.showloading == 'function') _this.option.showloading(true); worequest("GetWorkOrderInvoices", _this.option.workorderid, function (data) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data.WorkOrderID != _this.option.workorderid) { getInvoices(false); return; } data = data.Data; _this.option.parent.find('.estimates_div').remove(); _this.option.parent.find('.estimates_table').remove(); if (data) { if (data && data.length > 0) { invoicedata = data; for (var i = 0; i < data.length; i++) { showInvoice(data[i]); } } } }, function (err) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); }); } function dragOverInvoiceAttachment(ev, invid) { ev.preventDefault(); ev.dataTransfer.dropEffect = 'link'; } function dropInvoiceAttachment(ev, invid) { ev.preventDefault(); ev.stopPropagation(); var df = ev.dataTransfer; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } var invoice = $('#tabinvoice' + invid).data('invoice'); if (!invoice) return; if (invoice.Status !== 0) return; if (files.length > 0) SaveInvoiceAttachmentFiles(files, invid); } function cutInvoiceAttachment(ev, invid) { ev.stopPropagation(); var df = ev.clipboardData; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } var invoice = $('#tabinvoice' + invid).data('invoice'); if (!invoice) return; if (invoice.Status !== 0) return; if (files.length > 0) SaveInvoiceAttachmentFiles(files, invid); } function showInvoice(invoice) { var invid = invoice.Id; var statustext = getInvoiceStatus(invoice.Status); var div_invoices = _this.option.parent; var div_title = $('
'); div_title.on('drop', invid, function (ev) { dropInvoiceAttachment(ev.originalEvent, ev.data); }).on('dragover', function (ev) { dragOverInvoiceAttachment(ev.originalEvent, ev.data); }).on('paste', function (ev) { cutInvoiceAttachment(ev.originalEvent, ev.data); }); div_title.append(''); div_title.append('' + invoice.InvoiceNumber + ''); div_title.append('' + statustext + ''); if (!WOReadOnly) { if (invoice.Status === InvoiceStatus.Pending || invoice.Status === InvoiceStatus.PaymentCreated || invoice.Status === InvoiceStatus.Draft) { var ipt = $('').val(GetTextByKey('P_WO_MARKASPAID', 'Mark As Paid')); ipt.on("click", invid, function (e) { openWOInvoiceMarkPaidDialog(e.data); }); div_title.append(ipt); } if (invoice.Status === InvoiceStatus.Pending) { var ipt = $('').val(GetTextByKey('P_WO_REVOKE', 'Revoke')); ipt.on("click", invid, function (e) { OnRevokeInvoice(e.data); }); div_title.append(ipt); } if (invoice.Status == InvoiceStatus.Draft || invoice.Status === InvoiceStatus.Pending || invoice.Status === InvoiceStatus.Revoked) { var s_del = $(''); s_del.on("click", invid, function (e) { OnDeleteInvoice(e.data); }); div_title.append(s_del); } } div_title.append('
'); div_invoices.append(div_title); var disabled = invoice.Status === InvoiceStatus.Pending || invoice.Status === InvoiceStatus.PaymentCreated || invoice.Status === InvoiceStatus.Paid || invoice.Status === InvoiceStatus.Revoked || invoice.Status === InvoiceStatus.ManualPaid; var table = $('
Payment By:
Check #:
').data('invoice', invoice).hide(); table.on('drop', invid, function (ev) { dropInvoiceAttachment(ev.originalEvent, ev.data); }).on('dragover', function (ev) { dragOverInvoiceAttachment(ev.originalEvent, ev.data); }).on('paste', function (ev) { cutInvoiceAttachment(ev.originalEvent, ev.data); }); div_invoices.append(table); var tr = $(''); table.append(tr); var td = $('').text(GetTextByKey('P_WO_INVOICENUMBER', 'Invoice #:')); tr.append(td); td = $(''); tr.append(td); var ipt = $('').val(invoice.InvoiceNumber).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_OTHERCOST_COLON', 'Other Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(invoice.OtherCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); var tdDetail = $('').attr('id', 'invoice_payment_tab' + invid); tr.append(tdDetail); //if (invoice.Status == InvoiceStatus.Paid) { if (invoice.PaymentItem != null) { var btncancelpayment = ""; if (invoice.Status === InvoiceStatus.ManualPaid) { btncancelpayment = $('').val(GetTextByKey('P_WO_CANCELPAYMENT', 'Cancel Payment')); btncancelpayment.on('click', invid, function (e) { CancelPayment(e.data); }); } tdDetail.empty().append( $('
').append( $('').append( $('').text(GetTextByKey('P_WO_PAYMENTENTEREDBY_COLON', 'Payment Entered By:')), $('').text(invoice.PaymentItem.PaymentEnteredByName), $('').text(GetTextByKey('P_WO_CUSTOMERNAME', 'Customer Name:')), $('').text(invoice.PaymentItem.CustomerName) ), $('').append( $('').text(GetTextByKey('P_WO_PAYMENTTIME', 'Payment Time:')), $('').text(invoice.PaymentItem.CreatedLocalStr), $('').text(GetTextByKey('P_WO_CUSTOMEREMAIL', 'Customer Email:')), $('').text(invoice.PaymentItem.CustomerEmail) ), $('').append( $('').text(GetTextByKey('P_WO_PAYMENTTYPE_COLON', 'Payment Type:')), $('').text(invoice.PaymentItem.PaymentType), $(''), $('') ), $('').append( $('').text(GetTextByKey('P_WO_CHECK_COLON', 'Check #:')), $('').text(invoice.PaymentItem.CheckNumber), $(''), $('') ), $('').append( $('').text(GetTextByKey('P_WO_CARDNUMBER', 'Card Number:')), $('').text(invoice.PaymentItem.CardNumber), $('').text(GetTextByKey('P_WO_EXPIRATION', 'Expiration:')), $('').text(invoice.PaymentItem.CardExpiration) ), $('').append( $('').text(GetTextByKey('P_WO_CARDTYPE', 'Card Type:')), $('').text(invoice.PaymentItem.CardType), $('').text(GetTextByKey('P_WO_COUNTRY_COLON', 'Country:')), $('').text(invoice.PaymentItem.CustomerCountry) ), $('').append( $('').text(GetTextByKey('P_WO_ISSUER', 'Issuer:')), $('').text(invoice.PaymentItem.CardIssuer), $('').append(btncancelpayment), $('') ) ) ); } } tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_INVOICETOTALCOST', 'Invoice Total Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(invoice.TotalCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_TRAVELTIMECOST_COLON', 'Travel Time Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(invoice.TravelCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_PARTSCOST_COLON', 'Parts Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(invoice.PartsCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_TAXES_COLON', 'Taxes ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(invoice.Taxes, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_LABORCOST_COLON', 'Labor Cost ($):')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(locale(invoice.LaborCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); td = $('').text(GetTextByKey('P_WO_INVOICESTATUS', 'Invoice Status:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').text(statustext); td.append(ipt); tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_CUSTOMERVISIBLE_COLON', 'Customer Visible:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').prop("checked", invoice.CustomerVisible); if (invoice.Status === InvoiceStatus.Draft || invoice.Status === InvoiceStatus.Revoked) ipt.attr('disabled', true); else ipt.attr('disabled', false); ipt.change(invid, function (e) { ChangeWOInvoiceCustomerVisible(e.data, $(e.target).prop("checked")); }); td.append(ipt); tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WOS_NOTES_COLON', 'Notes:')); tr.append(td); td = $(''); tr.append(td); ipt = $('').val(invoice.Notes).change((function (id) { return function () { inputInvoiceChanged(id) } })(invid)); td.append(ipt); if (invoice.Status === InvoiceStatus.Draft) { tr = $(''); table.append(tr); td = $('').text(GetTextByKey('P_WO_ATTACHMENTS_COLON', ' Attachments:')); tr.append(td); td = $(''); tr.append(td); var div_att = $('
'); td.append(div_att); if (!WOReadOnly) { var span_addfile = $('').text(GetTextByKey('P_FR_ADDFILE', 'Add File...')); span_addfile.on("click", invid, function (e) { openWOInvoiceAttachmentDialog(e.data); }); div_att.append(span_addfile); } } tr = $(''); table.append(tr); td = $('').text(invoice.Status === InvoiceStatus.Draft ? "" : GetTextByKey('P_WO_ATTACHMENTS_COLON', 'Attachments:')); tr.append(td); td = $(''); tr.append(td); var tb_att = $(''); td.append(tb_att); var tr_att = $(''); tb_att.append(tr_att); var td_att = $(''); tr_att.append(td_att); div_att = $('
'); td_att.append(div_att); tb_att = $('
'); div_att.append(tb_att); showInvoiceAttachment(invid); tr = $(''); table.append(tr); td = $(''); tr.append(td); ipt = $('').val(GetTextByKey('P_WO_SAVE', 'Save')).hide(); ipt.on("click", invid, function (e) { onSaveWorkOrderInvoice(e.data); }); td.append(ipt); ipt = $('').val(GetTextByKey('P_WO_PUBLISH', 'Publish')).hide(); ipt.on("click", { id: invid, no: invoice.InvoiceNumber, cost: invoice.TotalCost }, function (e) { openPublishInvoiceDialog(e.data); }); td.append(ipt); if (!WOReadOnly) { if (invoice.Status === InvoiceStatus.Draft) { $('#btn_invoice_publish' + invid).show(); $('#btn_invoice_save' + invid).show(); } if (invoice.Status === InvoiceStatus.Pending) { $('#btn_invoice_revoke' + invid).show(); } if (invoice.Status === InvoiceStatus.Pending || invoice.Status === InvoiceStatus.PaymentCreated) { $('#btn_invoice_markaspaid' + invid).show(); } } if (disabled || WOReadOnly) setInvoiceDisabled(invid, true); if (invoice.Status === InvoiceStatus.PaymentCreated || invoice.Status === InvoiceStatus.Failed) { $('#span_invoice_status' + invid).css('color', 'red'); $('#dialog_invoice_status' + invid).css('color', 'red'); } if (invoice.Status === InvoiceStatus.Paid || invoice.Status === InvoiceStatus.ManualPaid) { $('#span_invoice_status' + invid).css('color', '#2eda2e'); $('#dialog_invoice_status' + invid).css('color', '#2eda2e'); } } function OnRevokeInvoice(invid) { if (invid <= 0) return; showConfirm(GetTextByKey("P_WO_CONFIRM_REVOKE_INVOICE", 'Do you want to revoke the invoice?'), GetTextByKey("P_WO_REVOKE_INVOICE", 'Revoke Invoice'), function () { worequest("RevokeWorkOrderInvoice", invid, function (data) { if (data === "OK") { getInvoices(true); } }, function (err) { showAlert(GetTextByKey("P_WO_FAILED_REVOKE_INVOICE", 'Failed to revoke this invoice.'), GetTextByKey("P_WO_REVOKE_INVOICE", 'Revoke Invoice')); }); }); } function CancelPayment(invid) { if (invid <= 0) return; showConfirm(GetTextByKey("P_WO_AREYOUSUREYOUWANTTOCANCELTHEPAYMENT", 'Are you sure you want to Cancel the Payment?'), GetTextByKey("P_WO_CANCELINVOICE", 'Cancel Invoice'), function () { worequest("CancelPayment", invid, function (data) { if (data === "OK") { getInvoices(); } }, function (err) { showAlert(GetTextByKey("P_WO_FAILED_REVOKE_INVOICE", 'Failed to cancel this payment.'), GetTextByKey("P_WO_CANCELINVOICE", 'Cancel Invoice')); }); }); } function ChangeWOInvoiceCustomerVisible(invid, visible) { if (invid <= 0) return; worequest("ChangeWOInvoiceCustomerVisible", JSON.stringify([invid, visible ? 1 : 0]), function (data) { }, function (err) { }); } function OnDeleteInvoice(invid) { if (invid <= 0) return; showConfirm(GetTextByKey("P_WO_CONFIRM_DELETE_INVOICE", 'Do you want to delete the invoice?'), GetTextByKey("P_WO_DELETE_INVOICE", 'Delete Invoice'), function () { worequest("DeleteWorkOrderInvoice", invid, function (data) { if (data === "OK") { getInvoices(true); } }, function (err) { showAlert(GetTextByKey("P_WO_FAILED_DELETE_INVOICE", 'Failed to delete this invoice.'), GetTextByKey("P_WO_DELETE_INVOICE", 'Delete Invoice')); }); }); } function onAddWorkOrderInvoice() { var status = parseInt($('#dialog_invoice_status').val()); if (status == InvoiceStatus.Pending) { var no = $('#dialog_invoice_number').val(); var cost = parseFloat($('#dialog_invoice_totalcosts').val()); openPublishInvoiceDialog({ id: -1, no: no, cost: cost }); } else onSaveWorkOrderInvoice(""); } function onSaveWorkOrderInvoice(invid, next) { var invoiceid = -1; var status = 0; var alerttitle = GetTextByKey("P_WO_ADDINVOICE", "Add Invoice"); if (invid > 0) { alerttitle = GetTextByKey("P_WO_EDITINVOICE", "Edit Invoice"); var invoice = $('#tabinvoice' + invid).data('invoice'); if (!invoice) return; invoiceid = invoice.Id; status = invoice.Status; } else status = parseInt($('#dialog_invoice_status').val()); var invsufix = invid > 0 ? String(invid) : ''; var item = { 'Id': invoiceid, 'WorkOrderId': _this.option.workorderid, 'Status': status, 'InvoiceNumber': $('#dialog_invoice_number' + invsufix).val(), 'TotalCost': $('#dialog_invoice_totalcosts' + invsufix).val(), 'OtherCost': $('#dialog_invoice_othercost' + invsufix).val(), 'PartsCost': $('#dialog_invoice_partscost' + invsufix).val(), 'TravelCost': $('#dialog_invoice_traveltimecost' + invsufix).val(), 'LaborCost': $('#dialog_invoice_laborcost' + invsufix).val(), 'Taxes': $('#dialog_invoice_taxes' + invsufix).val(), 'Notes': $('#dialog_invoice_notes' + invsufix).val(), 'CustomerVisible': $('#dialog_invoice_customervisible' + invsufix).prop("checked"), 'PaymentMethod': $('#dialog_invoice_paymentby' + invsufix).val(), 'CheckNumber': $('#dialog_invoice_checknumber' + invsufix).val(), }; if (isNaN(item.TotalCost) || item.TotalCost < 0) { showAlert(GetTextByKey('P_WO_TOTALCOST_INVALID', 'Total cost is not a valid number.'), alerttitle, function () { $('#dialog_invoice_totalcosts' + invsufix).focus() }); return; } if (isNaN(item.OtherCost) || item.OtherCost < 0) { showAlert(GetTextByKey('P_WO_OTHERCOST_INVALID', 'Other cost is not a valid number.'), alerttitle, function () { $('#dialog_invoice_othercost' + invsufix).focus() }); return; } if (isNaN(item.PartsCost) || item.PartsCost < 0) { showAlert(GetTextByKey('P_WO_PARTSCOST_INVALID', 'Parts cost is not a valid number.'), alerttitle, function () { $('#dialog_invoice_partscost' + invsufix).focus() }); return; } if (isNaN(item.TravelCost) || item.TravelCost < 0) { showAlert(GetTextByKey('P_WO_TRAVELTIMECOST_INVALID', 'Travel time cost is not a valid number.'), alerttitle, function () { $('#dialog_invoice_traveltimecost' + invsufix).focus() }); return; } if (isNaN(item.LaborCost) || item.LaborCost < 0) { showAlert(GetTextByKey('P_WO_LABORCOST_INVALID', 'Labor cost is not a valid number.'), alerttitle, function () { $('#dialog_invoice_laborcost' + invsufix).focus() }); return; } if (isNaN(item.Taxes) || item.Taxes < 0) { showAlert(GetTextByKey('P_WO_TAXES_INVALID', 'Taxes is not a valid number.'), alerttitle, function () { $('#dialog_invoice_taxes' + invsufix).focus() }); return; } if (status == InvoiceStatus.Pending) { if (item.TotalCost <= 0) { showAlert(GetTextByKey('P_WO_TOTALCOST_MUST_POSITIVE', 'Total cost must be a positive number.'), alerttitle, function () { $('#dialog_invoice_totalcosts' + invoiceid).focus() }); return; } } if ((status == InvoiceStatus.Pending || status == InvoiceStatus.ManualPaid) && !item.CustomerVisible) { var msg = GetTextByKey("P_WO_INVOICEWILLNOTBEDISPLAYEDONCUSTOMERFACINPAGE", "Invoice will not be displayed on Customer Facing Page.
Do you want to:"); showInvoiceConfirm(msg, alerttitle, function () { $('#dialog_invoice_customervisible' + invsufix).prop("checked", true) item.CustomerVisible = true; doSaveWorkOrderInvoice(item, invid, next, alerttitle); }, function () { doSaveWorkOrderInvoice(item, invid, next, alerttitle); }, null); } else doSaveWorkOrderInvoice(item, invid, next, alerttitle); } function doSaveWorkOrderInvoice(item, invid, next, alerttitle) { var invsufix = invid > 0 ? String(invid) : ''; $('#btn_invoice_save' + invsufix).attr('disabled', true); var param = JSON.stringify(item); param = htmlencode(param); worequest("SaveWorkOrderInvoice", param, function (data) { if (typeof (data) === "string") { $('#btn_invoice_save' + invsufix).attr('disabled', false); showAlert(data, alerttitle); } else { $('#btn_invoice_save' + invsufix).attr('disabled', false); item.Id = data; if (invid <= 0) {//新增 if (add_invoice_filedatas && add_invoice_filedatas.length > 0) { SaveInvoiceAttachmentFiles(add_invoice_filedatas, data); add_invoice_filedatas = []; } if (next) next(data); else { getInvoices(true); } hideInvoicePopup(); } else {//编辑 if (next) next(invid); else { showAlert(GetTextByKey("P_WO_SAVSUCCESSFULLY", "Saved successfully."), alerttitle); $('#span_invoice_number' + invsufix).text($('#dialog_invoice_number' + invsufix).val()); } } } }, function (err) { $('#btn_invoice_save' + invsufix).attr('disabled', false); console.log(err); showAlert(GetTextByKey("P_WO_FAILED_SAVE_INVOICE", 'Failed to save invoice.'), alerttitle); }); } function OnAddInvoice() { add_invoice_filedatas = []; $('#tab_invoice_atts').empty(); $('#tab_invoice_attachments').hide(); if (!_this.option.workorderid || _this.option.workorderid === "") { showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), GetTextByKey("P_WO_ADDINVOICE", "Add Invoice")); return; } $('#dialog_invoice_number').val(""); $('#dialog_invoice_status').val("0"); $('#tr_payment').hide(); $('#dialog_invoice_totalcosts').val(""); $('#dialog_invoice_othercost').val(""); $('#dialog_invoice_partscost').val(""); $('#dialog_invoice_traveltimecost').val(""); $('#dialog_invoice_laborcost').val(""); $('#dialog_invoice_taxes').val(""); $('#dialog_invoice_notes').val(""); $("#dialog_invoice_customervisible").prop('checked', false).attr('disabled', true); $('#dialog_invoice_paymentby').val("Credit Card"); $('#dialog_invoice_checknumber').val(""); if (_this.option.workorderdata) { $('#dialog_invoice_number').val(_this.option.workorderdata.InvoiceNumber || ''); $('#dialog_invoice_totalcosts').val(_this.option.workorderdata.WorkOrderTotalCost == 0 ? "" : _this.option.workorderdata.WorkOrderTotalCost); $('#dialog_invoice_othercost').val(_this.option.workorderdata.OtherCost == 0 ? "" : _this.option.workorderdata.OtherCost); $('#dialog_invoice_partscost').val(_this.option.workorderdata.PartsCost == 0 ? "" : _this.option.workorderdata.PartsCost); $('#dialog_invoice_traveltimecost').val(_this.option.workorderdata.TravelTimeCost == 0 ? "" : workorderdata.TravelTimeCost); $('#dialog_invoice_laborcost').val(_this.option.workorderdata.LaborCost == 0 ? "" : _this.option.workorderdata.LaborCost); $('#dialog_invoice_taxes').val(_this.option.workorderdata.Taxes == 0 ? "" : _this.option.workorderdata.Taxes); //getInvoiceTotalCost(""); } showInvoicePopup(); } function inputInvoiceChanged(invid) { $('#tabinvoice' + invid).data('changed', true); } function setInvoiceDisabled(invid, di) { $('#dialog_invoice_number' + invid).attr('disabled', di); $('#dialog_invoice_totalcosts' + invid).attr('disabled', di); $('#dialog_invoice_othercost' + invid).attr('disabled', di); $('#dialog_invoice_partscost' + invid).attr('disabled', di); $('#dialog_invoice_traveltimecost' + invid).attr('disabled', di); $('#dialog_invoice_laborcost' + invid).attr('disabled', di); $('#dialog_invoice_taxes' + invid).attr('disabled', di); $('#dialog_invoice_notes' + invid).attr('disabled', di); //$('#dialog_invoice_status' + invid).attr('disabled', di); //$('#dialog_invoice_customervisible' + invid).attr('disabled', di); } var InvoiceStatus = { Draft: 0, Pending: 1, Cancelled: 2, PaymentCreated: 3, Paid: 4, Failed: 5, ManualPaid: 6, Revoked: 10 }; function getInvoiceStatus(s) { var text = ""; if (s === InvoiceStatus.Draft) text = GetTextByKey('P_WO_DRAFT', 'Draft'); else if (s === InvoiceStatus.Pending) text = GetTextByKey('P_WO_AWATING_PAYMENT', 'Awaiting Payment'); else if (s === InvoiceStatus.Cancelled) text = GetTextByKey('P_WO_CANCELLEDBYDEALER', 'Cancelled by Dealer'); else if (s === InvoiceStatus.PaymentCreated) text = GetTextByKey('P_WO_AWATING_PAYMENT', 'Awaiting Payment'); else if (s === InvoiceStatus.Paid || s === InvoiceStatus.ManualPaid) text = GetTextByKey('P_WO_CUSTOMER_PAID', 'Customer Paid'); else if (s === InvoiceStatus.Failed) text = GetTextByKey('P_WO_PAYMENT_FAILURE', 'Payment Failure'); else if (s === InvoiceStatus.Revoked) text = GetTextByKey('P_WO_REVOKED', 'Revoked'); else if (s === 100) text = ""; return text; } function showPublishInvoicePopup() { if (publish_invoice_id <= 0) invoiceDialog.find('.maskbg').show(); else invoicePublishMask.fadeIn(100); //showmaskbg(true); $('#dialog_invoice_textmsg').val(WorkorderParams.InvoiceMessage); $('#dialog_invoice_chkSendAttachment') .prop('disabled', (publish_invoice_id < 0) ? (add_invoice_filedatas.length <= 0) : !(invoicedata.find(i => i.Id === publish_invoice_id)?.Attachments?.length > 0)) .prop('checked', false); $('#dialog_invoice_spanAttachmentName').hide(); publish_invoice_attach = null; invoicePublishDialog.css({ 'top': (document.documentElement.clientHeight - invoicePublishDialog.height()) / 3, 'left': (document.documentElement.clientWidth - invoicePublishDialog.width()) / 2 }).showDialogfixed(); } function hidePublishInvoicePopup() { if (publish_invoice_id <= 0) invoiceDialog.find('.maskbg').hide(); else invoicePublishMask.fadeOut(100); //showmaskbg(false); publish_invoice_id = 0; invoicePublishDialog.hide(); } function openPublishInvoiceDialog(inv) { publish_invoice_var = inv; var invid = inv.id; if (invid <= 0) { publish_invoice_id = invid; showPublishInvoicePopup(); } else { onSaveWorkOrderInvoice(invid, function () { publish_invoice_id = invid; showPublishInvoicePopup(); }); } } function onPublishInvoice() { var changed = $('#tabinvoice' + publish_invoice_id).data('changed'); if (publish_invoice_id <= 0)//add and publish changed = true; if (changed) onSaveWorkOrderInvoice(publish_invoice_id, PublishInvoice) else PublishInvoice(publish_invoice_id); } function PublishInvoice(invid) { if (invid <= 0) return; var pmemails = []; var checked = $('#dialog_invoice_chksendtextmsg').prop('checked'); if (checked) { var phoneemail = $('#dialog_invoice_phonenum').val(); if (phoneemail !== "") { var phoneemails = phoneemail.split(';'); for (var i = 0; i < phoneemails.length; i++) { var pm = phoneemails[i]; if (checkPhoneNumber(pm) || isEmail(pm)) { pmemails.push({ 'Key': pm, 'Value': pm }); } else { if (_this.option.customercontacts) { for (var j = 0; j < _this.option.customercontacts.length; j++) { var c = _this.option.customercontacts[j]; if (c.OptOut || c.OptOut_BC) continue; var mp = $.trim(c.MobilePhone); var email = $.trim(c.Email); if (c.Name === pm) { if (c.ContactPreference == "0" && checkPhoneNumber(mp)) { pmemails.push({ 'Key': mp, 'Value': pm }); break; } if (c.ContactPreference == "1" && isEmail(email)) { pmemails.push({ 'Key': email, 'Value': pm }); break; } } } } } } } } var msg = $('#dialog_invoice_textmsg').val(); var includeStatusLink = $('#dialog_invoice_chkIncludeStatusLink').prop("checked"); var param = JSON.stringify([invid, publish_invoice_var.no, publish_invoice_var.cost, _this.option.workorderid, JSON.stringify(pmemails), msg, (includeStatusLink ? "1" : "0")]); param = htmlencode(param); var url = _network.root + 'Maintenance/AddWorkOrder.aspx'; var method = 'PublishInvoiceToCustomer'; var data = new FormData(); data.append('MethodName', method); data.append('ClientData', param); if (publish_invoice_attach != null) { if (Object.prototype.hasOwnProperty.call(publish_invoice_attach, 'id')) { var attap = { Id: publish_invoice_attach.id, Caption: publish_invoice_attach.name }; data.append('AttaData', htmlencode(JSON.stringify(attap))); } else { data.append('attachment', publish_invoice_attach.file); } } invoicePublishDialog.find('.maskbg').show(); $.ajax({ url: url, type: 'POST', dataType: 'json', processData: false, contentType: false, cache: false, data: data, success: function (data) { if (data !== "") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } getInvoices(true); hidePublishInvoicePopup(); }, error: function (request, textStatus, errorThrown) { showAlert(GetTextByKey("P_WO_FAILED_PUBLISH_INVOICE", 'Failed to publish this invoice.'), GetTextByKey("P_WO_PUBLISH_INVOICE", 'Publish Invoice')); if (request?.readyState == 0) { console.log(request); } else { writelog_ironintel("PublishEstimate", url + ".-1." + method + "." + JSON.stringify(param), JSON.stringify(request), textStatus + errorThrown); } }, complete: function () { invoicePublishDialog.find('.maskbg').hide(); } }); } function SaveInvoiceAttachmentFiles(filedatas, invid) { var formData = new FormData(); var notesdata = []; for (var i = 0; i < filedatas.length; i++) { formData.append("iconFile" + i, filedatas[i].File); notesdata.push(encodeURIComponent(filedatas[i].Notes)); } var p = JSON.stringify([invid, JSON.stringify(notesdata)]); formData.append("MethodName", "AddInvoiceAttachment"); formData.append("ClientData", p); var url = 'AddWorkOrder.aspx'; $.ajax({ url: url, type: 'POST', dataType: 'json', processData: false, contentType: false, data: formData, async: true, success: function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File')); } else { if (invid > 0) { hideWOInvoiceAttachmentPopup(); getInvoiceAttachment(invid); } else getInvoices(true); } }, error: function (err) { showAlert(GetTextByKey("P_WO_UPLOADFAILED", 'Upload failed'), GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File')); } }); } function getInvoiceAttachment(invid) { var invoice = $('#tabinvoice' + invid).data('invoice'); if (!invoice) return; $('#tab_invoice_atts' + invid).empty(); $('#tab_invoice_attachments' + invid).hide(); worequest("GetWorkOrderInvoiceAttachments", invoice.Id, function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data && data.length > 0) { showInvoiceAttachment(invid, data); } var invoice = invoicedata.find(i => i.Id === invid); if (invoice != null) { invoice.Attachments = data; } }, function (err) { }); } function showInvoiceAttachment(invid, atts) { var candelete = false; if (!atts) { var invoice = $('#tabinvoice' + invid).data('invoice'); if (!invoice) return; atts = invoice.Attachments; if (invoice.Status === InvoiceStatus.Draft || invoice.Status === InvoiceStatus.Revoked) candelete = true; } else candelete = true; $('#tab_invoice_atts' + invid).empty(); $('#tab_invoice_attachments' + invid).hide(); if (atts && atts.length > 0) { $('#tab_invoice_attachments' + invid).show(); for (var i = 0; i < atts.length; i++) { var att = atts[i]; var tr = $('').attr('id', att.AttachmentId); var tdfile = $(''); var filename = $("").text(att.Notes === "" ? att.FileName : att.Notes).click(function () { window.open("../filesvc.ashx?attchid=" + this.parentElement.parentElement.id + "&sourceType=woestimateattachment"); }); var span = $('').text(att.AddedByName).css("margin-right", 5).css("margin-left", 5).css("color", "black"); var spanby = $('').text(att.AddedOnLocalStr).css("color", "black"); tdfile.append(filename, span, spanby); if (!WOReadOnly && candelete) { var tdimg = $(''); var imgDom = $('').click(function () { deleteInvoiceAttachment(this.parentElement.parentElement.id, invid); }); tdimg.append(imgDom); tr.append(tdimg); } tr.append(tdfile).appendTo($('#tab_invoice_atts' + invid)); } } } function deleteInvoiceAttachment(attid, invid) { if (confirm(GetTextByKey("P_WO_DELETEATTACHMENTTIPS", "Are you sure you want to delete the attachment?"))) { worequest("DeleteInvoiceAttachment", attid, function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_DELETEATTACHMENT", 'Delete Attachment')); } else { getInvoiceAttachment(invid); } }, function (err) { }); } } function hideWOInvoiceAttachmentPopup() { if (cur_invoice_uploadid <= 0) invoiceDialog.find('.maskbg').hide(); else showmaskbg(false); invoiceAttachmentDialog.hide(); } function openWOInvoiceAttachmentDialog(invid) { cur_invoice_uploaddata = undefined; cur_invoice_uploadid = invid; if (invid <= 0) invoiceDialog.find('.maskbg').show(); else showmaskbg(true); $('#btn_woinvoice_att_save').attr('disabled', false); $('#tab_woinvoice_atts').empty(); $('#tab_woinvoice_attachments').hide(); $('#dialog_invoice_att_notes').val(''); invoiceAttachmentDialog.css({ 'top': (document.documentElement.clientHeight - invoiceAttachmentDialog.height()) / 3, 'left': (document.documentElement.clientWidth - invoiceAttachmentDialog.width()) / 2 }).showDialogfixed(); } function dragOverAddInvoiceAttachment(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = 'link'; } function dropAddInvoiceAttachment(ev) { ev.preventDefault(); ev.stopPropagation(); var df = ev.dataTransfer; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } if (files.length > 0) { for (var i = 0; i < files.length; i++) { cur_invoice_uploaddata = files[i]; onSaveWOInvoiceAttachment(); } } } function cutAddInvoiceAttachment(ev) { ev.stopPropagation(); var df = ev.clipboardData; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); if (file.size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return; } if (file.size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return; } files.push({ 'File': file, 'Notes': '' }); } } } if (files.length > 0) { for (var i = 0; i < files.length; i++) { cur_invoice_uploaddata = files[i]; onSaveWOInvoiceAttachment(); } } } function UpLoadInvoiceAttachment() { var file = $(''); file.change(function () { var files = this.files; if (files.length == 0) return; if (files[0].size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return false; } if (files[0].size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return false; } var notes = $('#dialog_invoice_att_notes').val(); cur_invoice_uploaddata = { 'File': files[0], 'Notes': notes }; createNewInvoiceAttachment(cur_invoice_uploaddata); }).click(); } function createNewInvoiceAttachment(data) { $('#tab_woinvoice_atts').empty(); $('#tab_woinvoice_attachments').show(); var tr = $(''); var tdfile = $(''); var filename = $("").text(data.Notes === "" ? data.File.name : data.Notes); tdfile.append(filename); var tdimg = $(''); var imgDom = $('').click(function () { this.parentElement.parentElement.remove(); cur_invoice_uploaddata = undefined; $('#tab_woinvoice_attachments').hide(); }); tdimg.append(imgDom); tr.append(tdimg); tr.append(tdfile).appendTo($('#tab_woinvoice_atts')); } function onSaveWOInvoiceAttachment() { if (!cur_invoice_uploaddata) return; $('#btn_woinvoice_att_save').attr('disabled', true); var notes = $('#dialog_invoice_att_notes').val(); cur_invoice_uploaddata.Notes = notes; if (cur_invoice_uploadid <= 0) { add_invoice_filedatas.push(cur_invoice_uploaddata); createAddInvoiceAttachment(cur_invoice_uploaddata); hideWOInvoiceAttachmentPopup(); $('#btn_woinvoice_att_save').attr('disabled', false); } else { SaveInvoiceAttachmentFiles([cur_invoice_uploaddata], cur_invoice_uploadid); } } function createAddInvoiceAttachment(data) { var notes = data.Notes; var file = data.File; $('#tab_invoice_attachments').show(); var tr = $(''); var tdfile = $(''); var filename = $("").text(notes === "" ? file.name : notes); tdfile.append(filename); var tdimg = $(''); var imgDom = $('').data('filedata', data).click(function () { this.parentElement.parentElement.remove(); var fd = $(this).data('filedata'); add_invoice_filedatas.splice(add_invoice_filedatas.indexOf(fd), 1); if (add_invoice_filedatas.length == 0) $('#tab_invoice_attachments').hide(); }); tdimg.append(imgDom); tr.append(tdimg); tr.append(tdfile).appendTo($('#tab_invoice_atts')); } function hideWOInvoiceMakePaidPopup() { showmaskbg(false); invoiceMarkPaidDialog.hide(); } function openWOInvoiceMarkPaidDialog(invid) { cur_invoice_uploadid = invid; $('#btn_woinvoice_maikpaid_save').attr('disabled', false); showmaskbg(true); $('#dialog_invoice_markpaid_paymentby').val("Credit Card"); $('#dialog_invoice_markpaid_number').val(''); invoiceMarkPaidDialog.css({ 'top': (document.documentElement.clientHeight - invoiceMarkPaidDialog.height()) / 3, 'left': (document.documentElement.clientWidth - invoiceMarkPaidDialog.width()) / 2 }).showDialogfixed(); } function OnMarkAsPaid() { var changed = $('#tabinvoice' + cur_invoice_uploadid).data('changed'); if (changed) onSaveWorkOrderInvoice(cur_invoice_uploadid, MarkAsPaid) else MarkAsPaid(); } function MarkAsPaid() { var invoice = $('#tabinvoice' + cur_invoice_uploadid).data('invoice'); var item = [invoice.Id, $('#dialog_invoice_markpaid_paymentby').val(), $('#dialog_invoice_markpaid_number').val()]; var param = JSON.stringify(item); param = htmlencode(param); $("#dialog_woinvoice_markpaid .maskbg").show(); worequest('MarkAsPaid', param, function (data) { $("#dialog_woinvoice_markpaid .maskbg").hide(); if (data === 'OK') { hideWOInvoiceMakePaidPopup(); getInvoices(true); } }, function (err) { $("#dialog_woinvoice_markpaid .maskbg").hide(); }); } _dialog.showInvoiceConfirm = function (msg, title, fedit, fcancel, fclose, iniframe, shownote) { if (!fclose) fclose = fcancel; _dialog.showButtonDialog(msg, title, 'question', fclose, [{ value: GetTextByKey("P_WO_MARKASCUSTOMERVISIBLE", 'Mark as Customer Visible'), func: fcancel }, { value: GetTextByKey("P_WO_MCONTINUEWITHOUTMAKINGVISIBLE", 'Continue Without Making Visible'), func: fedit }], iniframe, shownote); }; function showInvoiceConfirm(msg, title, fcancel, fedit, fclose) { invoicePublishDialog.find('.maskbg').show(); _dialog.showInvoiceConfirm(msg, title, function (e) { invoicePublishDialog.find('.maskbg').show(); if (typeof fedit === 'function') { fedit(e); } }, function (e) { invoicePublishDialog.find('.maskbg').show(); if (typeof fcancel === 'function') { fcancel(e); } }, function (e) { invoicePublishDialog.find('.maskbg').show(); if (typeof fclose === 'function') { fclose(e); } }); } } } /*****************************************End Invoice*********************************************/ /*****************************************Begin Segment*********************************************/ if (typeof ($wosegment) !== "function") { $wosegment = function (option) { this.option = option || {}; var _this = this; var userdata = []; var jobsitedata = []; var components = []; var segmenttypes = []; var dialog_segmentuser; var dialog_segmenthour; var dialog_segmentjobsite; var dialog_segmentcost; var dialog_segmenttype; var dialog_segmentcomponent; var dialog_segmentbillable; var dialog_segmentcompleted; var dialog_segmentcompleteddate; var dialog_segmentdesc; var dialog_segmentnotes; this.changewo = function (woid) { //if (woid !== option.workorderid) { this.option.workorderid = woid; //hidePopup(); GetSegmentDataSource(getSegments); //} } this.close = function () { segmentDialog?.remove(); } this.loadsource = function () { GetSegmentDataSource(); } this.setwodata = function (wodata) { this.option.workorderdata = wodata; } this.hasSegment = function () { return segmentdata && segmentdata.length > 0 } this.createSegment = function (p_div) { p_div.addClass("tab_segments"); var div = $('
'); p_div.append(div); var span_add = $('Add Segment'); span_add.click(OnAddSegment); div.append(span_add); p_div.applyFleetLanguageText(true); } this.createSegment(this.option.parent); var segmentDialog = createSegmentDialog(); function createSegmentDialog() { var dialog = $(''); dialog.append('
Add Segment
'); var tb = $('
'); dialog.append($('
').append(tb)); var tr = $('').appendTo(tb); var td = $('User:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentuser = $('').appendTo(td); dialog_segmentuser.dropdown([], { search: true, valueKey: 'IID', textKey: 'DisplayName', parent: '.dialog-content' }); tr = $('').appendTo(tb); td = $('Hours:').appendTo(tr); td = $('').appendTo(tr); dialog_segmenthour = $('').appendTo(td); dialog_segmenthour.keydown(numberinput); tr = $('').appendTo(tb); td = $('Jobsite:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentjobsite = $('').appendTo(td); dialog_segmentjobsite.dropdown([], { search: true, valueKey: 'ID', textKey: 'Name', parent: '.dialog-content' }); tr = $('').appendTo(tb); td = $('Cost:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentcost = $('').appendTo(td); dialog_segmentcost.keydown(numberinput); tr = $('').appendTo(tb); td = $('Segment Type:').appendTo(tr); td = $('').appendTo(tr); dialog_segmenttype = $('').appendTo(td); dialog_segmenttype.dropdown([], { input: true, maxlength: 50, textKey: 'value', parent: '.dialog-content' }); tr = $('').appendTo(tb); td = $('Component:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentcomponent = $('').appendTo(td); dialog_segmentcomponent.dropdown([], { input: true, maxlength: 40, textKey: 'value', parent: '.dialog-content' }); tr = $('').appendTo(tb); td = $('Billable:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentbillable = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Completed:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentcompleted = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Completed Date:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentcompleteddate = $('').appendTo(td); dialog_segmentcompleteddate.datetimepicker({ timepicker: false, format: 'm/d/Y', enterLikeTab: false, scrollInput: false, onSelectDate: function (v, inp) { var date = new DateFormatter().formatDate(v, 'm/d/Y 00:00:00'); inp.parent().data('val', [date]); } }); dialog_segmentcompleteddate.change(function () { var date = dialog_segmentcompleteddate.val(); if (date.length > 0 && checkDate(date)) { dialog_segmentcompleted.prop('checked', true); } }); tr = $('').appendTo(tb); td = $('Description:*').appendTo(tr); td = $('').appendTo(tr); dialog_segmentdesc = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Notes:').appendTo(tr); td = $('').appendTo(tr); dialog_segmentnotes = $('').appendTo(td); var func = $('
'); dialog.append(func); func.append(''); var btnok = $(''); btnok.on('click', function () { SaveSegment(''); }); func.append(btnok); func.append('
'); $(document.body).append(dialog); dialog.dialog(function () { showmaskbg(false); }); dialog.applyFleetLanguageText(true); return dialog; } function numberinput(e) { var keyCode = e.which; if (keyCode === 9//tab || keyCode === 8 || keyCode === 46 //delete || keyCode === 110 || keyCode === 190//. || keyCode === 37 || keyCode === 39//left right || keyCode === 55 || keyCode === 56//home end || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) return true; else return false; } function GetSegmentDataSource(next) { worequest("GetSegmentDataSource", '', function (data) { if (data.Users && data.Users.length > 0) { userdata = data.Users; dialog_segmentuser.dropdownSource(userdata); } if (data.JobSites && data.JobSites.length > 0) { var jss = [{ ID: '-1', Name: ' ', html: ' ' }]; for (var js of data.JobSites) { jss.push(js); } jobsitedata = jss; dialog_segmentjobsite.dropdownSource(jobsitedata); } if (data.Components && data.Components.length > 0) { var source = []; for (var type of data.Components) { source.push({ value: type }); } components = source; dialog_segmentcomponent.dropdownSource(components); } if (data.SegmentTypes && data.SegmentTypes.length > 0) { var source = []; for (var type of data.SegmentTypes) { source.push({ value: type }); } segmenttypes = source; dialog_segmenttype.dropdownSource(segmenttypes); } if (next) next(); }, function (err) { console.log(err);; }); } function GetSegmentDataSource1(next) { worequest("GetSegmentDataSource1", '', function (data) { if (data.Components && data.Components.length > 0) { var source = []; for (var type of data.Components) { source.push({ value: type }); } components = source; $("#dialog_segmentcomponent").dropdownSource(components); } if (data.SegmentTypes && data.SegmentTypes.length > 0) { var source = []; for (var type of data.SegmentTypes) { source.push({ value: type }); } segmenttypes = source; $("#dialog_segmenttype").dropdownSource(segmenttypes); } if (next) next(); }, function (err) { console.log(err);; }); } function SetCompleted(segid) { var date = $('#dialog_segmentcompleteddate' + segid).val(); if (date.length > 0 && checkDate(date)) { $('#dialog_segmentcompleted' + segid).prop('checked', true); } } var segmentdata = []; function initControl(segid) { $('#dialog_segmentcompleteddate' + segid).datetimepicker({ timepicker: false, format: 'm/d/Y', enterLikeTab: false, onSelectDate: function (v, inp) { var date = new DateFormatter().formatDate(v, 'm/d/Y 00:00:00'); inp.parent().data('val', [date]); } }); $('#dialog_segmentuser' + segid).dropdown(userdata || [], { search: true, valueKey: 'IID', textKey: 'DisplayName' }); $("#dialog_segmentjobsite" + segid).dropdown(jobsitedata || [], { search: true, valueKey: 'ID', textKey: 'Name' }); $("#dialog_segmenttype" + segid).dropdown(segmenttypes || [], { input: true, maxlength: 50, textKey: 'value' }); $("#dialog_segmentcomponent" + segid).dropdown(components || [], { input: true, maxlength: 40, textKey: 'value' }); } var inloading = false; function getSegments(callback) { segmentindex = 0; _this.option.parent.find('.segments_table').remove(); if (!_this.option.workorderid || _this.option.workorderid == "") return; if (inloading) return; inloading = true; if (typeof _this.option.showloading == 'function') _this.option.showloading(true); worequest("GetSegments", _this.option.workorderid, function (data) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data.WorkOrderID != _this.option.workorderid) { getSegments(callback); return; } data = data.Data; segmentindex = 0; if (data && data.length > 0) { //$('#dialog_workordercosts').attr('disabled', true); segmentdata = data; var wocost = 0; for (var i = 0; i < segmentdata.length; i++) { wocost += segmentdata[i].Cost; showSegment(segmentdata[i]); } $('#dialog_workordercosts').val(wocost); } else { //$('#dialog_workordercosts').attr('disabled', false); if (_this.option.workorderdata) $('#dialog_workordercosts').val(_this.option.workorderdata.WorkOrderTotalCost == 0 ? "" : _this.option.workorderdata.WorkOrderTotalCost); segmentdata = []; if (callback) callback(); } }, function (err) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); }); } var segmentindex = 0; function showSegment(segment) { segmentindex++; var segid = segment.SegmentID; var div_segments = _this.option.parent; var table = $('
'); var tr1 = $(''); var tr1_td1 = $('' + GetTextByKey("P_WO_SEGMENT", "Segment") + " " + segmentindex + '"'); if (!WOReadOnly) { var s_del = $(''); s_del.on('click', segid, function (e) { DeleteSegment(e.data); }) tr1_td1.append(s_del); } var tr1_td2 = $('"'); tr1.append(tr1_td1).append(tr1_td2); table.append(tr1); var tr = $(''); var td1 = $('' + GetTextByKey("P_WO_USER_COLON", " User:") + '"'); var td2 = $('"'); var sel_user = $('').css("width", 320); td2.append(sel_user); var td3 = $('' + GetTextByKey("P_WO_COMPLETED_COLON", "Completed:") + '"'); var td4 = $('"'); var chk_completed = $(''); td4.append(chk_completed); tr.append(td1).append(td2).append(td3).append(td4); table.append(tr); tr = $(''); td1 = $('' + GetTextByKey("P_WO_HOURS_COLON", "Hours:") + '"'); td2 = $('"'); var input_hour = $('') .keydown(numberinput); td2.append(input_hour); td3 = $('' + GetTextByKey("P_WO_COMPLETEDDATE_COLON", "Completed Date:") + '"'); td4 = $('"'); var input_completeddate = $(''); input_completeddate.on("change", segid, function (e) { SetCompleted(e.data); }); td4.append(input_completeddate); tr.append(td1).append(td2).append(td3).append(td4); table.append(tr); tr = $(''); td1 = $('' + GetTextByKey("P_WO_JOBSITE_COLON", "Jobsite:") + '"'); td2 = $('"'); var sel_jobsite = $('').css("width", 320); td2.append(sel_jobsite); td3 = $('' + GetTextByKey("P_WO_DESCRIPTION_COLON", "Description:") + '*"'); td4 = $('"'); var input_desc = $(''); td4.append(input_desc); tr.append(td1).append(td2).append(td3).append(td4); table.append(tr); tr = $(''); td1 = $('' + GetTextByKey("P_WO_COST_COLON", "Cost:") + '"'); td2 = $('"'); var input_cost = $('') .keydown(numberinput); td2.append(input_cost); td3 = $('' + GetTextByKey("P_WO_NOTES_COLON", "Notes:") + '"'); td4 = $('"').css("vertical-align", "top"); var textarea_notes = $('') td4.append(textarea_notes); tr.append(td1).append(td2).append(td3).append(td4); table.append(tr); tr = $(''); td1 = $('' + GetTextByKey("P_WO_SEGMENTTYPE_COLON", "Segment Type:") + '"'); td2 = $('"'); var sel_segmenttype = $('').css("width", 320); td2.append(sel_segmenttype); tr.append(td1).append(td2); table.append(tr); tr = $(''); td1 = $('' + GetTextByKey("P_WO_COMPONENT_COLON", "Component:") + '"'); td2 = $('"'); var sel_component = $('').css("width", 320); td2.append(sel_component); tr.append(td1).append(td2); table.append(tr); tr = $(''); td1 = $('' + GetTextByKey("P_WO_BILLABLE_COLON", "Billable:") + '"'); td2 = $('"'); var chk_billable = $(''); td2.append(chk_billable); tr.append(td1).append(td2); table.append(tr); if (!WOReadOnly) { tr = $(''); td1 = $('"'); var input_save = $('').val(GetTextByKey("P_WO_SAVE", "Save")); input_save.on('click', segid, function (e) { SaveSegment(e.data); }) var input_cancel = $('').val(GetTextByKey("P_WO_CANCEL", "Cancel")); input_cancel.on('click', segid, function (e) { CancelSegment(e.data); }); td1.append(input_save).append(input_cancel); tr.append(td1); table.append(tr); } div_segments.append(table); initControl(segid); $('#tabsegment_' + segid).data('segment', segment); $('#dialog_segmentuser' + segid).dropdownVal(segment.UserIID); $('#dialog_segmentdesc' + segid).val(segment.Description); $('#dialog_segmenthour' + segid).val(segment.Hours === 0 ? "" : segment.Hours); $('#dialog_segmentnotes' + segid).val(segment.Notes); $('#dialog_segmentjobsite' + segid).dropdownVal(segment.JobsiteID); $('#dialog_segmentcost' + segid).val(segment.Cost === 0 ? "" : segment.Cost); $('#dialog_segmenttype' + segid).dropdownVal(segment.SegmentType); $('#dialog_segmentcompleted' + segid).prop('checked', segment.Completed); $('#dialog_segmentcompleteddate' + segid).val(segment.CompletedDateStr); $('#dialog_segmentcomponent' + segid).dropdownVal(segment.Component); $('#dialog_segmentbillable' + segid).prop('checked', segment.Billable); } function OnAddSegment() { if (!_this.option.workorderid || _this.option.workorderid === "") { showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), GetTextByKey("P_WO_ADDSEGMENT", "Add Segment")); return; } $('#dialog_segmentuser').dropdownVal(''); $('#dialog_segmentdesc').val(''); $('#dialog_segmenthour').val(''); $('#dialog_segmentnotes').val(''); $('#dialog_segmentjobsite').dropdownVal(''); $('#dialog_segmentcost').val(''); $('#dialog_segmentcompleted').prop('checked', false); $('#dialog_segmentcompleteddate').val(''); $('#dialog_segmenttype').dropdownVal(''); $('#dialog_segmentcomponent').dropdownVal(''); $('#dialog_segmentbillable').prop('checked', false); showPopup(); } function DeleteSegment(segid) { var segment = $('#tabsegment_' + segid).data('segment'); if (!segment) return; showConfirm(GetTextByKey("P_WO_DOYOUWANTTODELETETHESEGMENT", 'Do you want to delete the segment?'), GetTextByKey("P_WO_DELETESEGMENT", 'Delete Segment'), function () { worequest("DeleteSegment", segment.SegmentID, function (data) { GetSegmentDataSource1(function () { if (typeof getTotalCost == 'function') getSegments(getTotalCost); else getSegments(); }); }, function (err) { showAlert(GetTextByKey("P_WO_FAILEDDELETESEGMENT", 'Failed to delete this segment.'), GetTextByKey("P_WO_DELETESEGMENT", 'Delete Segment')); }); }); } function CancelSegment(segid) { var segment = $('#tabsegment_' + segid).data('segment'); if (!segment) return; $('#dialog_segmentuser' + segid).dropdownVal(segment.UserIID); $('#dialog_segmentdesc' + segid).val(segment.Description); $('#dialog_segmenthour' + segid).val(segment.Hours); $('#dialog_segmentnotes' + segid).val(segment.Notes); $('#dialog_segmentjobsite' + segid).dropdownVal(segment.JobsiteID); $('#dialog_segmentcost' + segid).val(segment.Cost); $('#dialog_segmentcompleted' + segid).prop('checked', segment.Completed); $('#dialog_segmentcompleteddate' + segid).val(segment.CompletedDateStr); $('#dialog_segmenttype' + segid).dropdownVal(segment.SegmentType); $('#dialog_segmentcomponent' + segid).dropdownVal(segment.Component); $('#dialog_segmentbillable' + segid).prop('checked', segment.Billable); } function SaveSegment(segid) { $('#btn_savesegment' + segid).attr('disabled', true); var segmentid = -1; var alerttitle = GetTextByKey("P_WO_ADDSEGMENT", "Add Segment"); if (segid > 0) { var alerttitle = GetTextByKey("P_WO_EDITSEGMENT", "Edit Segment"); segmentid = segid; } var item = { 'SegmentID': segmentid, 'WorkOrderID': _this.option.workorderid, 'UserIID': $('#dialog_segmentuser' + segid).dropdownVal(), 'Description': $('#dialog_segmentdesc' + segid).val(), 'Hours': $('#dialog_segmenthour' + segid).val(), 'Notes': $('#dialog_segmentnotes' + segid).val(), 'JobsiteID': $('#dialog_segmentjobsite' + segid).dropdownVal(), 'Cost': $('#dialog_segmentcost' + segid).val(), 'Completed': $('#dialog_segmentcompleted' + segid).prop('checked'), 'CompletedDate': $('#dialog_segmentcompleteddate' + segid).val(), 'SegmentType': $('#dialog_segmenttype' + segid).dropdownVal(), 'Component': $('#dialog_segmentcomponent' + segid).dropdownVal(), 'Billable': $('#dialog_segmentbillable' + segid).prop('checked') }; if (item.Description === "" || item.Description.length == 0) { showAlert(GetTextByKey("P_WO_DESCRIPTIONREQUIRED", 'Description is required.'), alerttitle); $('#btn_savesegment' + segid).attr('disabled', false); return; } if (item.Hours !== "") { if (isNaN(item.Hours)) { showAlert(GetTextByKey("P_WO_HOURSFORMATERROR", 'Hours format error.'), alerttitle); $('#btn_savesegment' + segid).attr('disabled', false); return; } else { if (item.Hours <= 0) { showAlert(GetTextByKey("P_WO_HOURSMUSTBEGREATERTHAN0", 'Hours must be greater than 0.'), alerttitle); $('#btn_savesegment' + segid).attr('disabled', false); return; } } } if (item.Cost !== "") { if (isNaN(item.Cost)) { showAlert(GetTextByKey("P_WO_COSTFORMATERROR", 'Cost format error.'), alerttitle); $('#btn_savesegment' + segid).attr('disabled', false); return; } else { if (item.Cost <= 0) { showAlert(GetTextByKey("P_WO_COSTMUSTBEGREATERTHAN0", 'Cost must be greater than 0.'), alerttitle); $('#btn_savesegment' + segid).attr('disabled', false); return; } } } if (item.Cost === "") item.Cost = -1; if (item.Hours === "") item.Hours = -1; var param = JSON.stringify(item); param = htmlencode(param); worequest("SaveSegment", param, function (data) { if (typeof (data) === "string") { $('#btn_savesegment' + segid).attr('disabled', false); showAlert(data, alerttitle); } else { $('#btn_savesegment' + segid).attr('disabled', false); if (segid > 0) { showAlert(GetTextByKey("P_WO_SAVSUCCESSFULLY", "Saved successfully."), alerttitle); } GetSegmentDataSource1(function () { if (typeof getTotalCost == 'function') getSegments(getTotalCost); else getSegments(); }); hidePopup(); } }, function (err) { $('#btn_savesegment' + segid).attr('disabled', false); console.log(err); showAlert(GetTextByKey("P_WO_FAILEDTOSAVESEGMENT", 'Failed to save segment.'), alerttitle); }); } function showPopup() { showmaskbg(true); segmentDialog.css({ 'top': (document.documentElement.clientHeight - segmentDialog.height()) / 3, 'left': (document.documentElement.clientWidth - segmentDialog.width()) / 2 }).showDialogfixed(); } function hidePopup() { showmaskbg(false); segmentDialog.hide(); } } } /*****************************************End Segment*********************************************/ /*****************************************Begin Alert*********************************************/ if (typeof ($woalert) !== "function") { $woalert = function (option) { this.option = option || {}; var _this = this; var alertids = this.option.alertids ? this.option.alertids : []; var divdtcalerts; var divpmaalerts; var divinspectalerts; var divoilalerts; var span_addalerts; var span_removealerts; var span_addpmalerts; this.refresh = function () { getAlerts(); } this.changewo = function (woid, aid) { //if (woid !== option.workorderid) { this.option.workorderid = woid; if (aid) this.option.machineid = aid; //hideAlertPopup(); //hideAllPMSchedulePopup(); getAlerts(); //} } this.close = function () { alertpopupdialog?.remove(); allpmschedulepopupdialog?.remove(); } this.changeasset = function (aid) { this.option.machineid = aid; } this.getalertids = function () { return alertids; } this.createAlert = function (p_div) { if (!WOReadOnly) { var div_ftitle = $('
'); p_div.append(div_ftitle); span_addalerts = $('Add Alerts'); span_addalerts.click(OnAddAlerts); div_ftitle.append(span_addalerts); span_removealerts = $('Remove Alerts'); span_removealerts.click(OnRemoveAlerts); div_ftitle.append(span_removealerts); p_div.append('
'); } //DTC Alerts divdtcalerts = $('
'); divdtcalerts.append('
DTC Alerts
'); divdtcalerts.append('
'); p_div.append(divdtcalerts); //PM Alerts divpmaalerts = $('
'); var divpmaalerts_title = $('
'); divpmaalerts_title.append('PM Alerts'); if (!WOReadOnly) { span_addpmalerts = $('Add PM Alerts (Alerts not yet triggered)'); span_addpmalerts.click(OnAddAllPMSchedules); divpmaalerts_title.append(span_addpmalerts); } divpmaalerts.append(divpmaalerts_title); divpmaalerts.append('
'); p_div.append(divpmaalerts); //Inspect Alerts divinspectalerts = $('
'); divinspectalerts.append('
Inspect Alerts
'); divinspectalerts.append('
'); p_div.append(divinspectalerts); //Oil Alerts divoilalerts = $('
'); divoilalerts.append('
Oil Alerts
'); divoilalerts.append('
'); p_div.append(divoilalerts); p_div.applyFleetLanguageText(true); } this.createAlert(this.option.parent); InitDTCAlertGridData(); InitPMAAlertGridData(); InitInspectAlertGridData(); InitOilAlertGridData(); var alertpopupdialog = createNoneAssignedAlertDialog(); var allpmschedulepopupdialog = createAllPMSchedulesDialog(); function showAllAlerts(alerts) { if (alerts.DTCAlerts && alerts.DTCAlerts.length > 0) { _DTCAlerts = alerts.DTCAlerts; divdtcalerts.show(); showAlerts(_DTCAlerts, grid_dtcalertdt); } else { _DTCAlerts = []; showAlerts(_DTCAlerts, grid_dtcalertdt); } if (alerts.PMAlerts && alerts.PMAlerts.length > 0) { _PMAAlerts = alerts.PMAlerts; //divpmaalerts.show(); showAlerts(_PMAAlerts, grid_pmaalertdt); $('#dialog_expectedcost').val(alerts.AllExpectedCost === 0 ? '' : alerts.AllExpectedCost); } else { _PMAAlerts = []; showAlerts(_PMAAlerts, grid_pmaalertdt); } if (alerts.InspectAlerts && alerts.InspectAlerts.length > 0) { _InspectAlerts = alerts.InspectAlerts; divinspectalerts.show(); showAlerts(_InspectAlerts, grid_inspectalertdt); } else { _InspectAlerts = []; showAlerts(_InspectAlerts, grid_inspectalertdt); } if (alerts.OilAlerts && alerts.OilAlerts.length > 0) { _OilAlerts = alerts.OilAlerts; divoilalerts.show(); showAlerts(_OilAlerts, grid_oilalertdt); } else { _OilAlerts = []; showAlerts(_OilAlerts, grid_oilalertdt); } } function showAlerts(data, grid_dt) { var rows = []; for (var i = 0; i < data.length; i++) { var r = data[i]; alertids.push(r.AlertID); if (r.RepeatedAlerts) { for (var j = 0; j < r.RepeatedAlerts.length; j++) { alertids.push(r.RepeatedAlerts[j]); } } for (var j in r) { if (j === "EngineHours") r["EngineHoursObj"] = { DisplayValue: r["EngineHours"] == 0 ? "" : r["EngineHours"], Value: r["EngineHours"] }; else if (j === "AlertLocalTime") r["AlertLocalTime"] = { DisplayValue: r["AlertLocalTimeStr"], Value: r["AlertLocalTime"] }; } rows.push(r); } grid_dt.setData(rows); } var grid_dtcalertdt; function InitDTCAlertGridData() { grid_dtcalertdt = createGridView('#dtcalertslist'); var list_columns = [ { name: 'Selected', caption: "", valueIndex: 'Selected', type: 3, css: { 'width': 45, 'text-align': 'center' } }, { name: 'EngineHours', caption: GetTextByKey("P_WO_HOURS", "Hours"), valueIndex: 'EngineHoursObj', css: { 'width': 150, 'text-align': 'left' } }, { name: 'AlertType', caption: GetTextByKey("P_WO_ALERTTYPE", "Alert Type"), valueIndex: 'AlertType', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Description', caption: GetTextByKey("P_WO_DESCRIPTION", "Description"), valueIndex: 'Description', css: { 'width': 480, 'text-align': 'left' } }, //{ name: 'ServiceDescription', caption: GetTextByKey("P_WO_SERVICEDESCRIPTION", "Service Description"), valueIndex: 'ServiceDescription', css: { 'width': 240, 'text-align': 'left' } }, { name: 'AlertCount', caption: GetTextByKey("P_WO_COUNT", "Count"), valueIndex: 'AlertCount', css: { 'width': 100, 'text-align': 'left' } }, { name: 'AlertLocalTime', caption: GetTextByKey("P_WO_LATESTDATETIME", "Latest DateTime"), valueIndex: 'AlertLocalTime', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Comment', caption: GetTextByKey("P_AM_COMMENT", "Comment"), valueIndex: 'Comment', css: { 'width': 150, 'text-align': 'left' } } ]; var columns = []; // head for (var hd in list_columns) { var col = {}; col.name = list_columns[hd].name; col.caption = list_columns[hd].caption; col.visible = true; col.sortable = true; col.type = list_columns[hd].type; col.width = list_columns[hd].css.width; col.align = list_columns[hd].css["text-align"] col.key = list_columns[hd].valueIndex; columns.push(col); if (col.name === "Selected") { col.allcheck = true; } else if (col.name === 'Comment') { col.type = NoteColumn; col.readonly = true; } } grid_dtcalertdt.multiSelect = false; grid_dtcalertdt.columns = columns; grid_dtcalertdt.init(); } var grid_pmaalertdt; function InitPMAAlertGridData() { grid_pmaalertdt = createGridView('#pmaalertslist'); var list_columns = [ { name: 'Selected', caption: "", valueIndex: 'Selected', type: 3, css: { 'width': 45, 'text-align': 'center' } }, { name: 'EngineHours', caption: GetTextByKey("P_WO_HOURS", "Hours"), valueIndex: 'EngineHoursObj', css: { 'width': 150, 'text-align': 'left' } }, { name: 'AlertType', caption: GetTextByKey("P_WO_ALERTTYPE", "Alert Type"), valueIndex: 'AlertType', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Description', caption: GetTextByKey("P_WO_DESCRIPTION", "Description"), valueIndex: 'Description', css: { 'width': 240, 'text-align': 'left' } }, { name: 'ServiceDescription', caption: GetTextByKey("P_WO_SERVICEDESCRIPTION", "Service Description"), valueIndex: 'ServiceDescription', css: { 'width': 240, 'text-align': 'left' } }, { name: 'ExpectedCost', caption: GetTextByKey("P_PM_EXPECTEDCOST", "Expected Cost"), valueIndex: 'ExpectedCost', css: { 'width': 100, 'text-align': 'left' } }, { name: 'AlertCount', caption: GetTextByKey("P_WO_COUNT", "Count"), valueIndex: 'AlertCount', css: { 'width': 100, 'text-align': 'left' } }, { name: 'AlertLocalTime', caption: GetTextByKey("P_WO_LATESTDATETIME", "Latest DateTime"), valueIndex: 'AlertLocalTime', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Comment', caption: GetTextByKey("P_AM_COMMENT", "Comment"), valueIndex: 'Comment', css: { 'width': 150, 'text-align': 'left' } } ]; var columns = []; // head for (var hd in list_columns) { var col = {}; col.name = list_columns[hd].name; col.caption = list_columns[hd].caption; col.visible = true; col.sortable = true; col.type = list_columns[hd].type; col.width = list_columns[hd].css.width; col.align = list_columns[hd].css["text-align"] col.key = list_columns[hd].valueIndex; columns.push(col); if (col.name === "Selected") { col.allcheck = true; } else if (col.name === 'Comment') { col.type = NoteColumn; col.readonly = true; } } grid_pmaalertdt.multiSelect = false; grid_pmaalertdt.columns = columns; grid_pmaalertdt.init(); } var grid_inspectalertdt; function InitInspectAlertGridData() { grid_inspectalertdt = createGridView('#inspectalertslist'); var list_columns = [ { name: 'Selected', caption: "", valueIndex: 'Selected', type: 3, css: { 'width': 45, 'text-align': 'center' } }, { name: 'EngineHours', caption: GetTextByKey("P_WO_HOURS", "Hours"), valueIndex: 'EngineHoursObj', css: { 'width': 150, 'text-align': 'left' } }, { name: 'AlertType', caption: GetTextByKey("P_WO_ALERTTYPE", "Alert Type"), valueIndex: 'AlertType', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Description', caption: GetTextByKey("P_WO_DESCRIPTION", "Description"), valueIndex: 'Description', css: { 'width': 480, 'text-align': 'left' } }, //{ name: 'ServiceDescription', caption: GetTextByKey("P_WO_SERVICEDESCRIPTION", "Service Description"), valueIndex: 'ServiceDescription', css: { 'width': 240, 'text-align': 'left' } }, { name: 'AlertCount', caption: GetTextByKey("P_WO_COUNT", "Count"), valueIndex: 'AlertCount', css: { 'width': 100, 'text-align': 'left' } }, { name: 'AlertLocalTime', caption: GetTextByKey("P_WO_LATESTDATETIME", "Latest DateTime"), valueIndex: 'AlertLocalTime', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Comment', caption: GetTextByKey("P_AM_COMMENT", "Comment"), valueIndex: 'Comment', css: { 'width': 150, 'text-align': 'left' } } ]; var columns = []; // head for (var hd in list_columns) { var col = {}; col.name = list_columns[hd].name; col.caption = list_columns[hd].caption; col.visible = true; col.sortable = true; col.type = list_columns[hd].type; col.width = list_columns[hd].css.width; col.align = list_columns[hd].css["text-align"] col.key = list_columns[hd].valueIndex; columns.push(col); if (col.name === "Selected") { col.allcheck = true; } else if (col.name === 'Comment') { col.type = NoteColumn; col.readonly = true; } } grid_inspectalertdt.multiSelect = false; grid_inspectalertdt.columns = columns; grid_inspectalertdt.init(); } var grid_oilalertdt; function InitOilAlertGridData() { grid_oilalertdt = createGridView('#oilalertslist'); var list_columns = [ { name: 'Selected', caption: "", valueIndex: 'Selected', type: 3, css: { 'width': 45, 'text-align': 'center' } }, { name: 'EngineHours', caption: GetTextByKey("P_WO_HOURS", "Hours"), valueIndex: 'EngineHoursObj', css: { 'width': 150, 'text-align': 'left' } }, { name: 'AlertType', caption: GetTextByKey("P_WO_ALERTTYPE", "Alert Type"), valueIndex: 'AlertType', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Description', caption: GetTextByKey("P_WO_DESCRIPTION", "Description"), valueIndex: 'Description', css: { 'width': 480, 'text-align': 'left' } }, //{ name: 'ServiceDescription', caption: GetTextByKey("P_WO_SERVICEDESCRIPTION", "Service Description"), valueIndex: 'ServiceDescription', css: { 'width': 240, 'text-align': 'left' } }, { name: 'AlertCount', caption: GetTextByKey("P_WO_COUNT", "Count"), valueIndex: 'AlertCount', css: { 'width': 100, 'text-align': 'left' } }, { name: 'AlertLocalTime', caption: GetTextByKey("P_WO_LATESTDATETIME", "Latest DateTime"), valueIndex: 'AlertLocalTime', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Comment', caption: GetTextByKey("P_AM_COMMENT", "Comment"), valueIndex: 'Comment', css: { 'width': 150, 'text-align': 'left' } } ]; var columns = []; // head for (var hd in list_columns) { var col = {}; col.name = list_columns[hd].name; col.caption = list_columns[hd].caption; col.visible = true; col.sortable = true; col.type = list_columns[hd].type; col.width = list_columns[hd].css.width; col.align = list_columns[hd].css["text-align"] col.key = list_columns[hd].valueIndex; columns.push(col); if (col.name === "Selected") { col.allcheck = true; } else if (col.name === 'Comment') { col.type = NoteColumn; col.readonly = true; } } grid_oilalertdt.multiSelect = false; grid_oilalertdt.columns = columns; grid_oilalertdt.init(); } function createNoneAssignedAlertDialog() { var dialog = $(''); dialog.append('
Add Alerts
'); var noneassignedalertlist = $('
'); dialog.append($('
').append(noneassignedalertlist)) var func = $('
'); dialog.append(func); func.append(''); var btnok = $(''); btnok.on('click', function () { OnSaveAlerts(); }); func.append(btnok); func.append('
'); $(document.body).append(dialog); dialog.dialog(function () { showmaskbg(false); }); InitNoneAssignedAlertGridData(noneassignedalertlist); dialog.applyFleetLanguageText(true); return dialog; } var grid_noneassignedalertdt; function InitNoneAssignedAlertGridData(pdiv) { grid_noneassignedalertdt = createGridView(pdiv); var list_columns = [ { name: 'Selected', caption: "", valueIndex: 'Selected', type: 3, css: { 'width': 45, 'text-align': 'center' } }, { name: 'EngineHours', caption: GetTextByKey("P_WO_HOURS", "Hours"), valueIndex: 'EngineHours', css: { 'width': 80, 'text-align': 'left' } }, { name: 'AlertType', caption: GetTextByKey("P_WO_ALERTTYPE", "Alert Type"), valueIndex: 'AlertType', css: { 'width': 150, 'text-align': 'left' } }, { name: 'Description', caption: GetTextByKey("P_WO_DESCRIPTION", "Description"), valueIndex: 'Description', css: { 'width': 200, 'text-align': 'left' } }, { name: 'ServiceDescription', caption: GetTextByKey("P_WO_SERVICEDESCRIPTION", "Service Description"), valueIndex: 'ServiceDescription', css: { 'width': 200, 'text-align': 'left' } }, { name: 'AlertTime', caption: GetTextByKey("P_WO_LATESTDATETIME", "Latest DateTime"), valueIndex: 'AlertLocalTime', css: { 'width': 125, 'text-align': 'left' } } ]; var columns = []; // head for (var hd in list_columns) { var col = {}; col.name = list_columns[hd].name; col.caption = list_columns[hd].caption; col.visible = true; col.sortable = true; col.type = list_columns[hd].type; col.width = list_columns[hd].css.width; col.align = list_columns[hd].css["text-align"] col.key = list_columns[hd].valueIndex; columns.push(col); if (col.name === "Selected") { col.allcheck = true; } } grid_noneassignedalertdt.multiSelect = false; grid_noneassignedalertdt.columns = columns; grid_noneassignedalertdt.init(); } function clearAlertData() { _DTCAlerts = []; _PMAAlerts = []; _InspectAlerts = []; _OilAlerts = []; grid_dtcalertdt.setData([]); grid_pmaalertdt.setData([]); grid_inspectalertdt.setData([]); grid_oilalertdt.setData([]); } var _DTCAlerts = []; var _PMAAlerts = []; var _InspectAlerts = []; var _OilAlerts = []; var inloading = false; function getAlerts() { alertids = []; divdtcalerts.hide(); //divpmaalerts.hide(); divinspectalerts.hide(); divoilalerts.hide(); clearAlertData(); if (inloading) return; inloading = true; if (typeof _this.option.showloading == 'function') _this.option.showloading(true); alertrequest("GETWORKORDERALERTS", _this.option.workorderid, function (data) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data.WorkOrderID != _this.option.workorderid) { getAlerts(); return; } data = data.Data; showAllAlerts(data); _this.reshowalertgrid(); //resizeContent(); }, function (err) { inloading = false; if (typeof _this.option.showloading == 'function') _this.option.showloading(false); }); } this.getAssetAlerts = function (mid) {//widget里面不会调用这个方法 alertids = []; divdtcalerts.hide(); //divpmaalerts.hide(); divinspectalerts.hide(); divoilalerts.hide(); clearAlertData(); if (mid) _this.option.machineid = mid; if (typeof _this.option.showloading == 'function') _this.option.showloading(true); alertrequest("GETASSETALERTS", _this.option.machineid + String.fromCharCode(170) + JSON.stringify(alertids), function (data) { if (typeof _this.option.showloading == 'function') _this.option.showloading(false); if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } if (data.MachineID != _this.option.machineid) return; data = data.Data; showAllAlerts(data); }, function (err) { if (typeof _this.option.showloading == 'function') _this.option.showloading(false); }); } this.reshowalertgrid = function () { setTimeout(function () { $("#dtcalertslist").css("height", 240); grid_dtcalertdt && grid_dtcalertdt.resize(); $("#pmaalertslist").css("height", 240); grid_pmaalertdt && grid_pmaalertdt.resize(); $("#inspectalertslist").css("height", 240); grid_inspectalertdt && grid_inspectalertdt.resize(); $("#oilalertslist").css("height", 240); grid_oilalertdt && grid_oilalertdt.resize(); }); } function showAlertPopup() { showmaskbg(true); alertpopupdialog.css({ 'top': (document.documentElement.clientHeight - alertpopupdialog.height()) / 3, 'left': (document.documentElement.clientWidth - alertpopupdialog.width()) / 2 }).showDialogfixed(); grid_noneassignedalertdt && grid_noneassignedalertdt.resize(); } function hideAlertPopup() { alertpopupdialog.hide(); showmaskbg(false); } function OnAddAlerts() { if (!_this.option.workorderid || _this.option.workorderid === "") { showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), GetTextByKey("P_WO_ADDALERTS", 'Add Alerts')); return; } getNoneAssignedAlerts(); } var noneassignedalerts = []; function getNoneAssignedAlerts() { if (!_this.option.machineid) { showAlert(GetTextByKey("P_WO_PLEASESELECTANASSET", "Please select an Asset."), GetTextByKey("P_WO_SENDEMAIL", "Send Email")); $('#dialog_machine').focus(); return; } worequest("GetNoneAssignedAlerts", _this.option.machineid, function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } showAlertPopup(); noneassignedalerts = data; showNoneAssienedAlerts(noneassignedalerts); }, function (err) { }); } function showNoneAssienedAlerts(data) { var rows = []; for (var i = 0; i < data.length; i++) { var r = data[i]; for (var j in r) { if (j === "EngineHours") r[j] = { DisplayValue: r[j] == 0 ? "" : r[j], Value: r[j] }; else if (j === "AlertLocalTime") r[j] = { DisplayValue: r["AlertLocalTimeStr"], Value: r[j] }; } rows.push(r); } grid_noneassignedalertdt.setData(rows); } function AddOrRemoveAlertsFromWorkOrder(isadd, alertids) { worequest("AddOrRemoveAlertsFromWorkOrder", _this.option.workorderid + String.fromCharCode(170) + JSON.stringify(alertids) + String.fromCharCode(170) + isadd, function (data) { if (isadd) hideAlertPopup(); getAlerts(); }, function (err) { }); } function OnRemoveAlerts() { var alerts = []; alertids = []; if (_DTCAlerts.length > 0) { for (var i = _DTCAlerts.length - 1; i >= 0; i--) { var alert = _DTCAlerts[i]; if (alert.Selected) { alerts.push(alert.AlertID); _DTCAlerts.splice(i, 1); if (alert.RepeatedAlerts) { for (var j = 0; j < alert.RepeatedAlerts.length; j++) { alerts.push(alert.RepeatedAlerts[j]); } } } } showAlerts(_DTCAlerts, grid_dtcalertdt); } if (_PMAAlerts.length > 0) { for (var i = _PMAAlerts.length - 1; i >= 0; i--) { var alert = _PMAAlerts[i]; if (alert.Selected) { alerts.push(alert.AlertID); _PMAAlerts.splice(i, 1); if (alert.RepeatedAlerts) { for (var j = 0; j < alert.RepeatedAlerts.length; j++) { alerts.push(alert.RepeatedAlerts[j]); } } } } showAlerts(_PMAAlerts, grid_pmaalertdt); //grid_pmaalertdt.setData(_PMAAlerts); } if (_InspectAlerts.length > 0) { for (var i = _InspectAlerts.length - 1; i >= 0; i--) { var alert = _InspectAlerts[i]; if (alert.Selected) { alerts.push(alert.AlertID); _InspectAlerts.splice(i, 1); if (alert.RepeatedAlerts) { for (var j = 0; j < alert.RepeatedAlerts.length; j++) { alerts.push(alert.RepeatedAlerts[j]); } } } } showAlerts(_InspectAlerts, grid_inspectalertdt); } if (_OilAlerts.length > 0) { for (var i = _OilAlerts.length - 1; i >= 0; i--) { var alert = _OilAlerts[i]; if (alert.Selected) { alerts.push(alert.AlertID); _OilAlerts.splice(i, 1); if (alert.RepeatedAlerts) { for (var j = 0; j < alert.RepeatedAlerts.length; j++) { alerts.push(alert.RepeatedAlerts[j]); } } } } showAlerts(_OilAlerts, grid_oilalertdt); } if (alerts.length == 0) { showAlert(GetTextByKey("P_WO_PLEASESELECTANALERT", "Please select an Alert."), GetTextByKey("P_WO_REMOVEALERTS", "Remove Alerts")); return; } if (_this.option.workorderid && _this.option.workorderid !== "") { AddOrRemoveAlertsFromWorkOrder(false, alerts); } } function OnSaveAlerts() { var alerts = []; if (noneassignedalerts.length > 0) { for (var i in noneassignedalerts) { var alert = noneassignedalerts[i]; if (alert.Selected) { alerts.push(alert.ID); } } } if (alerts.length == 0) { showAlert(GetTextByKey("P_WO_PLEASESELECTANALERT", "Please select an Alert."), GetTextByKey("P_WO_ADDALERTS", "Add Alerts")); return; } AddOrRemoveAlertsFromWorkOrder(true, alerts); } //**********************************Add PM Alerts (Alerts not yet triggered)***********************************************/ function createAllPMSchedulesDialog() { var dialog = $(''); dialog.append('
Select Plan for Alert
'); var allpmpmalertslist = $('
'); dialog.append($('
').append(allpmpmalertslist)) var func = $('
'); dialog.append(func); func.append(''); var btnok = $(''); btnok.on('click', function () { GenerateManualPMAlerts(); }); func.append(btnok); func.append('
'); $(document.body).append(dialog); dialog.dialog(function () { showmaskbg(false); }); InitAllPMSchedulesGridData(allpmpmalertslist); dialog.applyFleetLanguageText(true); return dialog; } function showAllPMSchedules(data) { grid_pmschedulesdt.setData(data); } var grid_pmschedulesdt; function InitAllPMSchedulesGridData(pdiv) { grid_pmschedulesdt = createGridView(pdiv); var list_columns = [ { name: 'Selected', caption: "", valueIndex: 'Selected', type: 3, css: { 'width': 45, 'text-align': 'center' } }, { name: 'Name', caption: GetTextByKey("P_MV_SCHEDULENAME", "Schedule Name"), valueIndex: 'Name', css: { 'width': 300, 'text-align': 'left' } } ]; var columns = []; // head for (var hd in list_columns) { var col = {}; col.name = list_columns[hd].name; col.caption = list_columns[hd].caption; col.visible = true; col.sortable = true; col.type = list_columns[hd].type; col.width = list_columns[hd].css.width; col.align = list_columns[hd].css["text-align"] col.key = list_columns[hd].valueIndex; columns.push(col); if (col.name === "Selected") { col.allcheck = true; } } grid_pmschedulesdt.multiSelect = false; grid_pmschedulesdt.columns = columns; grid_pmschedulesdt.init(); } function showAllPMSchedulePopup() { showmaskbg(true); allpmschedulepopupdialog.css({ 'top': (document.documentElement.clientHeight - allpmschedulepopupdialog.height()) / 3, 'left': (document.documentElement.clientWidth - allpmschedulepopupdialog.width()) / 2 }).showDialogfixed(); grid_pmschedulesdt && grid_pmschedulesdt.resize(); } function hideAllPMSchedulePopup() { allpmschedulepopupdialog.hide(); showmaskbg(false); } function OnAddAllPMSchedules() { if (!_this.option.workorderid || _this.option.workorderid === "") { showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), GetTextByKey("P_WO_ADDALERTS", 'Add Alerts')); return; } GetPMSchedulesByAsset(); } var allpmschedules = []; function GetPMSchedulesByAsset() { if (!_this.option.machineid) { showAlert(GetTextByKey("P_WO_PLEASESELECTANASSET", "Please select an Asset."), GetTextByKey("P_WO_SENDEMAIL", "Send Email")); $('#dialog_machine').focus(); return; } showAllPMSchedulePopup(); worequest("GetPMSchedulesByAsset", _this.option.machineid, function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } allpmschedules = data; showAllPMSchedules(allpmschedules); }, function (err) { }); } function GenerateManualPMAlerts() { var schids = []; if (allpmschedules.length > 0) { for (var i in allpmschedules) { var pmsch = allpmschedules[i]; if (pmsch.Selected) { schids.push(pmsch.Id); } } } if (schids.length == 0) { showAlert(GetTextByKey("P_WO_PLEASESELECTAPLAN", "Please select a plan."), GetTextByKey("P_WO_ADDALERTS", "Add Alerts")); return; } if (!_this.option.machineid) { showAlert(GetTextByKey("P_WO_PLEASESELECTANASSET", "Please select an Asset."), GetTextByKey("P_WO_SENDEMAIL", "Send Email")); $('#dialog_machine').focus(); return; } worequest("GenerateManualPMAlerts", JSON.stringify([_this.option.machineid, _this.option.workorderid, JSON.stringify(schids)]) , function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } else { var msg = ""; for (var i = 0; i < data.length; i++) { var r = data[i]; if (r.Status == -1) msg += GetTextByKey("P_WO_FAILEDTOGENERATEALERT", "Failed to generate alert.") + " (" + r.ScheduleName + ")\r\n"; else if (r.Status == 1) msg += GetTextByKey("P_WO_FAILEDTOGENERATEALERT1", "Unable to generate alert because there already exists an unmaintained alert.") + " (" + r.ScheduleName + ")\r\n"; else if (r.Status == 2) { if (r.UOM == "hour(s)") msg += GetTextByKey("P_WO_FAILEDTOGENERATEALERT2", "Unable to generate alert until Hour Meter is higher than ") + r.NextTargetValue.toLocaleString() + " " + r.UOM + " (" + r.ScheduleName + ")\r\n"; else if (r.UOM == "day(s)") msg += GetTextByKey("P_WO_FAILEDTOGENERATEALERT3", "Unable to generate alert until {0} later {1}").replace('{0}', r.NextTargetValue.toLocaleString() + " " + r.UOM).replace('{1}', " (" + r.ScheduleName + ")\r\n"); else msg += GetTextByKey("P_WO_FAILEDTOGENERATEALERT4", "Unable to generate alert until odometer is higher than ") + r.NextTargetValue.toLocaleString() + " " + r.UOM + " (" + r.ScheduleName + ")\r\n"; } } if (msg !== "") showAlert(msg, GetTextByKey("P_WO_ERROR", 'Error')); } hideAllPMSchedulePopup(); getAlerts(); }, function (err) { }); } function resizeContent() { grid_dtcalertdt && grid_dtcalertdt.resize(); grid_pmaalertdt && grid_pmaalertdt.resize(); grid_inspectalertdt && grid_inspectalertdt.resize(); grid_oilalertdt && grid_oilalertdt.resize(); grid_noneassignedalertdt && grid_noneassignedalertdt.resize(); grid_pmschedulesdt && grid_pmschedulesdt.resize(); } window.onresize = resizeContent; resizeContent(); } } /*****************************************End Alert*********************************************/ /*****************************************Begin Attachment*********************************************/ if (typeof ($woattachment) !== "function") { $woattachment = function (option) { this.option = option || {}; var _this = this; var allAttachments; var viewtype = 0; var div_attlarge; var div_woatts; var div_aatts; var div_iatts; var div_attlist; var woattslist_tbody; var woassetattslist_tbody; var woiptattslist_tbody; var panddlist; var btn_print; var btn_download; var btn_ok; var attupload_ul; var cur_wo_uploaddata; viewtype = getCookie("woattachmentviewtype"); this.refresh = function () { getWorkOrderAttachments(true); } this.changewo = function (woid, aid) { //if (woid !== option.workorderid) { var keepui = allAttachments && this.option.workorderid === woid && this.option.machineid === aid; this.option.workorderid = woid; if (aid) this.option.machineid = aid; //hideWOAttachmentPopup(); //hidePAndDAttachmentPopup(); getWorkOrderAttachments(keepui); //} } this.close = function () { dialog_panddattachments?.remove(); woattachmentDialog?.remove(); wosendattachmentDialog?.remove(); } this.updatecontact = function (contacts) { this.option.customercontacts = contacts if (this.option.customercontacts) { var names = ""; for (var i = 0; i < this.option.customercontacts.length; i++) { var c = this.option.customercontacts[i]; if (c.OptOut || c.OptOut_BC) continue; var mp = $.trim(c.MobilePhone); var email = $.trim(c.Email); if ((c.ContactPreference == "0" && (checkPhoneNumber(mp)) || (c.ContactPreference == "1" && isEmail(email)))) { if (names == "") names = c.Name; else names += ";" + c.Name; } } $('#dialog_atta_phonenum').val(names); } else { $('#dialog_atta_phonenum').val(''); } } this.createAttachment = function (p_div) { var div_ftitle = $('
'); p_div.append(div_ftitle); var span_add = $('Add File'); span_add.click(UpLoadWorkOrderAttachment);//openWOAttachmentDialog div_ftitle.append(span_add); if (this.option.canExport) { var span_print = $('Print'); span_print.click(function () { openPAndDGDialog(0) }); div_ftitle.append(span_print); var span_down = $('Download'); span_down.click(function () { openPAndDGDialog(1) }); div_ftitle.append(span_down); } if (AllowCustomer) { var span_access = $('Customer Access'); span_access.click(function () { openPAndDGDialog(2) }); div_ftitle.append(span_access); } var div_view = $('
'); div_ftitle.append(div_view); var span_view = $('View'); div_view.append(span_view); span_view.click(function (ev) { if ($('.panel_holder.attviewtypemenus').is(':visible')) { return; } hidePanels(); var left = $(this).offset().left; var top = $(this).offset().top; $('.panel_holder.attviewtypemenus').css({ 'opacity': 0, 'left': -35, 'right': 'auto', 'top': 27 }).show().animate({ 'opacity': 1 }, 100); $('.panel_holder.attviewtypemenus .trigledown').css({ 'left': 50, 'right': 'auto', 'top': -20 }); return false; }); //View Menu var div_viewmenu = $('
'); div_view.append(div_viewmenu); var attviewtypemenu_panel = $('
'); div_viewmenu.append(attviewtypemenu_panel); var viewmenu_ul = $('') attviewtypemenu_panel.append(viewmenu_ul); var viewlarge_li = $('
  • Large
  • '); viewlarge_li.click(function () { onViewAttachment(0); }); viewmenu_ul.append(viewlarge_li); var viewlist_li = $('
  • List
  • '); viewlist_li.click(function () { onViewAttachment(1); }); viewmenu_ul.append(viewlist_li); attviewtypemenu_panel.append('
    '); attviewtypemenu_panel.append('
    '); //Large div_attlarge = $('
    '); p_div.append(div_attlarge); //WO Attachments Large var tb_woattlarge = $('
    '); tb_woattlarge.on('drop', function (ev) { dropWOAttachment(ev.originalEvent); }).on('dragover', function (ev) { dragOverWOAttachment(ev.originalEvent); }).on('paste', function (ev) { cutWOAttachment(ev.originalEvent); }); div_attlarge.append(tb_woattlarge); tb_woattlarge.append('Work Order Attachments'); var tr = $('').appendTo(tb_woattlarge); var td = $('').appendTo(tr); div_woatts = $('
    ').appendTo(td); //Asset Attachments Large var tb_assetattlarge = $('
    '); div_attlarge.append(tb_assetattlarge); tb_assetattlarge.append('Asset Attachments'); var tr = $('').appendTo(tb_assetattlarge); var td = $('').appendTo(tr); div_aatts = $('
    ').appendTo(td) //Inspection Attachments Large var tb_ispattlarge = $('
    '); div_attlarge.append(tb_ispattlarge); tb_ispattlarge.append('Inspection Attachments'); var tr = $('').appendTo(tb_ispattlarge); var td = $('').appendTo(tr); div_iatts = $('
    ').appendTo(td); //List div_attlist = $('
    '); p_div.append(div_attlist); //WO Attachments List var tb_wolist = $('
    '); tb_wolist.on('drop', function (ev) { dropWOAttachment(ev.originalEvent); }).on('dragover', function (ev) { dragOverWOAttachment(ev.originalEvent); }).on('paste', function (ev) { cutWOAttachment(ev.originalEvent); }); div_attlist.append(tb_wolist); var tr_wolist = $(''); tb_wolist.append(tr_wolist); var td_wolist = $(''); tr_wolist.append(td_wolist); var div_wolist = $('
    '); td_wolist.append(div_wolist); div_wolist.append(''); div_wolist.append('Work Order Attachments'); if (AllowCustomer) div_wolist.append('Available to Customer'); else div_wolist.append(''); div_wolist.append(''); tr_wolist = $(''); tb_wolist.append(tr_wolist); td_wolist = $(''); tr_wolist.append(td_wolist); var tab_woattslist = $('
    '); td_wolist.append(tab_woattslist); woattslist_tbody = $('').appendTo(tab_woattslist); //Asset Attachments List var tb_assetlist = $('
    '); div_attlist.append(tb_assetlist); var tr_assetlist = $(''); tb_assetlist.append(tr_assetlist); var td_assetlist = $(''); tr_assetlist.append(td_assetlist); td_assetlist.append(''); td_assetlist.append('Asset Attachments'); tr_assetlist = $(''); tb_assetlist.append(tr_assetlist); td_assetlist = $(''); tr_assetlist.append(td_assetlist); var tab_assetattslist = $('
    '); td_assetlist.append(tab_assetattslist); woassetattslist_tbody = $('').appendTo(tab_assetattslist); //Inspection Attachments List var tb_isplist = $('
    '); div_attlist.append(tb_isplist); var tr_isplist = $(''); tb_isplist.append(tr_isplist); var td_isplist = $(''); tr_isplist.append(td_isplist); td_isplist.append(''); td_isplist.append('Inspection Attachments'); tr_isplist = $(''); tb_isplist.append(tr_isplist); tb_isplist = $(''); tr_isplist.append(tb_isplist); var tab_ispattslist = $('
    '); tb_isplist.append(tab_ispattslist); woiptattslist_tbody = $('').appendTo(tab_ispattslist); var div_attuoloadmsgmenus = $('
    ') p_div.append(div_attuoloadmsgmenus); var attuplodmsg_panel = $('
    '); div_attuoloadmsgmenus.append(attuplodmsg_panel); attupload_ul = $(''); attuplodmsg_panel.append(attupload_ul); attuplodmsg_panel.append('
    '); attuplodmsg_panel.append('
    '); p_div.applyFleetLanguageText(true); } this.createAttachment(this.option.parent); var dialog_panddattachments = createPAndDAttachmentDialog(); var woattachmentDialog = createWOAttachmentDialog(); var wosendattachmentDialog = createSendAttachmentDialog(); function createWOAttachmentDialog() { var dialog = $(''); dialog.append('
    Add Attachment
    '); var tb = $('
    '); dialog.append($('
    ').append(tb)); var tr = $('').appendTo(tb); var td = $('Caption:').appendTo(tr); td = $('').appendTo(tr); var dialog_wo_att_notes = $('').appendTo(td); tr = $('').appendTo(tb); td = $('Attachments:').appendTo(tr); td = $('').appendTo(tr); var dialog_wo_att_uploadattfile = $('').appendTo(td); dialog_wo_att_uploadattfile.on('click', function () { UpLoadWOAttachment(); }); tr = $('').appendTo(tb); td = $('').appendTo(tr); td = $('').appendTo(tr); var tb_att = $(''); td.append(tb_att); var tr_att = $(''); tb_att.append(tr_att); var td_att = $(''); tr_att.append(td_att); div_att = $('
    '); td_att.append(div_att); tb_att = $('
    '); div_att.append(tb_att); var func = $('
    '); dialog.append(func); func.append(''); var btn_wo_att_save = $(''); btn_wo_att_save.on('click', function () { onSaveWONewAttachment(); }); func.append(btn_wo_att_save); func.append('
    '); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { hideWOAttachmentPopup(); }); dialog.applyFleetLanguageText(true); return dialog; } function openWOAttachmentDialog() {//上传附件时弹出输入Caption的功能取消,还原为批量上传,代码暂时保留 showmaskbg(true); $('#btn_wo_att_save').attr('disabled', false); $('#tab_wo_atts').empty(); $('#tab_wo_attachments').hide(); $('#dialog_wo_att_notes').val(''); woattachmentDialog.css({ 'top': (document.documentElement.clientHeight - woattachmentDialog.height()) / 3, 'left': (document.documentElement.clientWidth - woattachmentDialog.width()) / 2 }).showDialogfixed(); } function hideWOAttachmentPopup() { showmaskbg(false); woattachmentDialog.hide(); } function hidePAndDAttachmentPopup() { showmaskbg(false); dialog_panddattachments.hideDialog(); } function hideSendWOAttachmentPopup() { showmaskbg(false); wosendattachmentDialog.hide(); } function openSendAttachmentPopup(atta) { showmaskbg(true); $('#dialog_atta_textmsg').val(""); var attname = atta ? (atta.Notes === "" ? atta.FileName : atta.Notes) : ""; $('#dialog_atta_sendattaname').text(attname).attr('title', attname); wosendattachmentDialog.data('atta', atta); wosendattachmentDialog.css({ 'top': (document.documentElement.clientHeight - wosendattachmentDialog.height()) / 3, 'left': (document.documentElement.clientWidth - wosendattachmentDialog.width()) / 2 }).showDialogfixed(); } function createSendAttachmentDialog() { var dialog = $(''); dialog.append('
    Send Attachments
    '); var tb = $('
    '); dialog.append($('
    ').append(tb)); var tr = $('').appendTo(tb); var td = $('').appendTo(tr); $('
    ').appendTo(td); td = $('').appendTo(tr); var dialog_atta_phonenum = $('').appendTo(td); tr = $('').appendTo(tb); td = $('').appendTo(tr); var dialog_atta_chkIncludeStatusLink = $('').appendTo(td); td = $('').appendTo(tr); $('').appendTo(td); tr = $('').appendTo(tb); td = $('Message:').appendTo(tr); td = $('').appendTo(tr); var dialog_atta_variables = $('').appendTo(td); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); dialog_atta_variables.append(''); var dialog_atta_insertfield = $('
    ').appendTo(td); dialog_atta_insertfield.on('click', function () { insertattafield(); }); var dialog_atta_textmsg = $('').appendTo(td); tr = $('').appendTo(tb); td = $('
    ').appendTo(tr); td = $('').appendTo(tr); var dialog_atta_sendattaname = $('').appendTo(td); var func = $('
    '); dialog.append(func); func.append(''); var btn_send = $(''); btn_send.on('click', function () { var phoneemail = $('#dialog_atta_phonenum').val(); SendAttachmentMsg(phoneemail); }); func.append(btn_send); func.append('
    '); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { hideSendWOAttachmentPopup(); }); dialog.applyFleetLanguageText(true); return dialog; } function insertattafield() { var field = $("#dialog_atta_variables").find("option:selected").text(); $("#dialog_atta_textmsg").focus(); document.execCommand('insertText', false, field); } function UpLoadWOAttachment() { var file = $(''); file.change(function () { var files = this.files; if (files.length == 0) return; if (files[0].size == 0) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); return false; } if (files[0].size > 50 * 1024 * 1024) { alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); return false; } var notes = $('#dialog_wo_att_notes').val(); cur_wo_uploaddata = files[0];// { 'File': files[0], 'Notes': notes }; cur_wo_uploaddata.Notes = notes createNewWOAttachment(cur_wo_uploaddata); }).click(); } function createNewWOAttachment(data) { $('#tab_wo_atts').empty(); $('#tab_wo_attachments').show(); var tr = $(''); var tdfile = $(''); var filename = $("").text(data.Notes === "" ? data.name : data.Notes); tdfile.append(filename); var tdimg = $(''); var imgDom = $('').click(function () { this.parentElement.parentElement.remove(); cur_wo_uploaddata = null; $('#tab_wo_attachments').hide(); }); tdimg.append(imgDom); tr.append(tdimg); tr.append(tdfile).appendTo($('#tab_wo_atts')); } function onSaveWONewAttachment() { if (!cur_wo_uploaddata) return; $('#btn_wo_att_save').attr('disabled', true); var notes = $('#dialog_wo_att_notes').val(); cur_wo_uploaddata.Notes = notes; hideWOAttachmentPopup(); onSaveWOAttachment([cur_wo_uploaddata]); cur_wo_uploaddata = null; } function createPAndDAttachmentDialog() { var dialog = $(''); dialog.append('
    Attachments
    '); panddlist = $('
    '); dialog.append($('
    ').append(panddlist)); var func = $('
    '); dialog.append(func); func.append(''); btn_print = $(''); btn_print.on('click', function () { printWOAttachments(); }); func.append(btn_print); btn_download = $(''); btn_download.on('click', function () { downloadWOAttachments(); }); func.append(btn_download); btn_ok = $(''); btn_ok.on('click', function () { updateWOAttachmentExtensionBatch(); }); func.append(btn_ok); func.append('
    '); dialog.append(''); $(document.body).append(dialog); dialog.dialog(function () { showmaskbg(false); }); dialog.applyFleetLanguageText(true); return dialog; } function UpLoadWorkOrderAttachment() { var file = $(''); file.change(function () { var files = this.files; if (files.length > 0) { onSaveWOAttachment(files); } }).click(); } var filesinuploading = []; var uploadingindex = -1; var fileupload_errors = ""; function onSaveWOAttachment(files) { fileupload_errors = ""; if (!_this.option.workorderid) { OnSave(0, function (item) { _this.option.workorderid = item.Id; showLoading(true); $('.span_attupload').show(); $('.span_vieuploadmsg').css('margin-left', 0); $('.span_vieuploadmsg').show(); if (filesinuploading.length > 0) { for (var i = 0; i < files.length; i++) filesinuploading.push(_this.option.workorderid, files[i]); showUploadingStatus(0); } else { filesinuploading = files; DoUploadWorkOrderAttachments(_this.option.workorderid); } }); } else { showLoading(true); $('.span_attupload').show(); $('.span_vieuploadmsg').css('margin-left', 0); $('.span_vieuploadmsg').show(); if (filesinuploading.length > 0) { for (var i = 0; i < files.length; i++) filesinuploading.push(files[i]); showUploadingStatus(0); } else { filesinuploading = files; DoUploadWorkOrderAttachments(_this.option.workorderid); } } } function DoUploadWorkOrderAttachments(woid) { if (woid != _this.option.workorderid) { filesinuploading = []; uploadingindex = -1; return; } uploadingindex++; if (uploadingindex >= filesinuploading.length) { uploadingindex--; showUploadingStatus(3); filesinuploading = []; uploadingindex = -1; $('.span_attupload').hide(); $('.span_vieuploadmsg').css('margin-left', 200); getWorkOrderAttachments(true); hideLoading(); if (fileupload_errors !== "") showAlert(fileupload_errors, GetTextByKey("P_WO_UPLOADFAILED", 'Upload failed')); return; } var file = filesinuploading[uploadingindex]; if (file.name.length > 200) { showUploadingStatus(2, GetTextByKey("P_WO_ATTACHMENTNAMELENGTHCANNOTBEGREATERTHAN", "Attachment name length cannot be greater than 200.")); DoUploadWorkOrderAttachments(woid); return; } if (file.size == 0) { showUploadingStatus(2, GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed.")); DoUploadWorkOrderAttachments(woid); return; } if (file.size > 50 * 1024 * 1024) { showUploadingStatus(2, GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB.")); DoUploadWorkOrderAttachments(woid); return; } showUploadingStatus(0); var top = $(window).height() / 2 - 100; var left = $(window).width() / 2 - 100; var width = $('#dialogattmask .lable_attuploadname').width(); $('#dialogattmask .loading_icon').css({ top: top, left: left }); $('#dialogattmask .lable_attuploadname').css({ top: top + 70, left: ($(window).width() - width - 100) / 2 }); var p = JSON.stringify([woid, file.Notes]); var formData = new FormData(); formData.append("iconFile", file); formData.append("MethodName", "AddAttachment"); formData.append("ClientData", p); var url = 'AddWorkOrder.aspx'; $.ajax({ url: url, type: 'POST', dataType: 'json', processData: false, contentType: false, data: formData, async: true, success: function (data) { if (data !== 'OK') { showAlert(GetTextByKey("P_WO_UPLOADFAILED", 'Upload failed'), GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File')); } showUploadingStatus(1); DoUploadWorkOrderAttachments(woid); }, error: function (err) { showUploadingStatus(2, GetTextByKey("P_WO_UPLOADFAILED", 'Upload failed')); DoUploadWorkOrderAttachments(woid); } }); } function showUploadingStatus(status, msg) { if (filesinuploading.length == 0) return; var filename = filesinuploading[uploadingindex].name; if (filename.length > 50) filename = filename.substring(0, 49) + "..."; var statustxt = ""; if (status == 0) { statustxt = "Uploading " + filename + " (" + (uploadingindex + 1) + "/" + filesinuploading.length + ")"; $('.lable_attuploadname').text(statustxt); } else if (status == 1) { statustxt = filename; attupload_ul.append('
  • ' + statustxt + '
  • '); } else if (status == 2) { statustxt = filename + " - " + msg; attupload_ul.append('
  • ' + statustxt + '
  • '); if (fileupload_errors === "") fileupload_errors = statustxt; else fileupload_errors = fileupload_errors + " \n " + statustxt; } else if (status == 3) { statustxt = "Upload Completed"; statustxt = ""; $('.lable_attuploadname').text(statustxt); } } function deleteAttachment(attID, target) { if (confirm(GetTextByKey("P_WO_DELETEATTACHMENTTIPS", "Are you sure you want to delete the attachment?"))) { worequest("DeleteAttachment", attID, function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_DELETEATTACHMENT", 'Delete Attachment')); } else { target.parent().parent().remove(); //getWorkOrderAttachments(); } }, function (err) { showAlert(GetTextByKey("P_WO_FAILEDDELETEATTACHMENT", 'Failed to delete this attachment.'), GetTextByKey("P_WO_DELETEATTACHMENT", 'Delete Attachment')); }); } } function onViewAttachment(type) { viewtype = type; if (typeof setCookie === "function") setCookie("woattachmentviewtype", viewtype); $(".woattafoldicon").removeClass("iconchevronright").addClass("iconchevrondown"); $(".woattafoldtr").show(); showWOAttachments(); } function showWOAttachments() { if (!viewtype) viewtype = 0; if (parseInt(viewtype) === 1) { div_attlarge.hide(); div_attlist.show(); showAttachmentList(allAttachments); } else { div_attlarge.show(); div_attlist.hide(); showWorkOrderAttachments(allAttachments); } $('#dialogattmask').height($(document).outerHeight(false)).width($(document).outerWidth(false)); } var inloading = false; function getWorkOrderAttachments(keepui) { if (!_this.option.workorderid && !_this.option.machineid) return; if (inloading) return; inloading = true; if (!keepui) { div_woatts.empty(); div_aatts.empty(); div_iatts.empty(); woattslist_tbody.empty(); woassetattslist_tbody.empty(); woiptattslist_tbody.empty(); if (typeof _this.option.showloading == 'function') _this.option.showloading(true); } worequest('GetAttachments', JSON.stringify([_this.option.workorderid, _this.option.machineid]), function (data) { inloading = false; if (!keepui) { if (typeof _this.option.showloading == 'function') _this.option.showloading(false); } if (data && typeof data != "string") { if (data.WorkOrderID != _this.option.workorderid) { getWorkOrderAttachments(false); return; } data = data.Data; allAttachments = data; showWOAttachments(allAttachments); } }, function () { inloading = false; if (!keepui) { if (typeof _this.option.showloading == 'function') _this.option.showloading(false); } }); } var imgTypes = [".jfif", ".jpg", ".jpeg", ".bmp", ".png", ".tiff", ".gif"]; var printTypes = ['.pdf', ".jfif", ".jpg", ".jpeg", ".bmp", ".png", ".tiff", ".gif"];//types to be loaded to print function showWorkOrderAttachments(attas) { if (attas.WorkOrderAttachments && attas.WorkOrderAttachments.length > 0) { var divs = div_woatts.children('div'); for (var i = 0; i < attas.WorkOrderAttachments.length; i++) { var att = attas.WorkOrderAttachments[i]; var pdiv = $('
    '); var div = createAttaDiv(att, true); if (AllowCustomer) { var div1 = $('
    '); var ext_span = $('').text(GetTextByKey("P_WO_AVAILABLETOCUSTOMER", 'Available to Customer')); var ext_chk = $('').prop('checked', att.AvailableToCustomer).click(att, function (e) { updateWOAttachmentExtension(e.data.AttachmentId, $(this).prop('checked')); }); ext_chk.data('aid', att.AttachmentId); div1.append(ext_chk).append(ext_span); pdiv.append(div1); } if (AllowDeleteAtta) { var sdel = $('').attr('title', GetTextByKey("P_WO_DELETE", 'Delete')).click(att, function (e) { deleteAttachment(e.data.AttachmentId, $(e.target)); }); div.append(sdel); } var ssend = $('').attr('title', GetTextByKey("P_WO_SEND", 'Send')).click(att, function (e) { openSendAttachmentPopup(e.data); }).css('right', 55); div.append(ssend); if ($.inArray(att.FileType.toLowerCase(), printTypes) >= 0) { var sprint = $('').attr('title', GetTextByKey("P_WO_PRINT", 'Print')).click(att, function (e) { openPrintFrame(e.data.AttachmentType, e.data.AttachmentIdStr); }).css('right', 30); div.append(sprint); } else ssend.css('right', 30); var sdownload = $('').attr('title', GetTextByKey("P_WO_DOWNLOAD", 'Download')).click(att, function (e) { openDownloadFrame(e.data.Url + "&d=1"); }); div.append(sdownload); pdiv.append(div); var caption = att.Notes === "" ? att.FileName : att.Notes; var div3 = $('
    '); var iptcaption = $('').attr('data-ori', caption).val(caption); iptcaption.data('attdata', att); if (!caption || caption == '') iptcaption.attr('placeholder', 'Click to Add caption'); div3.append(iptcaption); iptcaption.focus({ AttachmentId: att.AttachmentId, iptcaption: iptcaption }, function (e) { e.data.iptcaption.addClass('focused'); }); iptcaption.blur({ div: div, AttachmentId: att.AttachmentId, iptcaption: iptcaption, caption: caption }, function (e) { e.data.iptcaption.removeClass('focused'); updateWOAttachmentCaption(e.data); }); iptcaption.keydown({ div: div, AttachmentId: att.AttachmentId, iptcaption: iptcaption, caption: caption }, function (e) { if (e.keyCode == 13 || e.keyCode == 9) { e.data.iptcaption.blur(); } }); pdiv.append(div3); var div_exists = divs[i]; if (div_exists) { pdiv.insertAfter(div_exists); div_exists.remove(); } else div_woatts.append(pdiv); } for (var i = attas.WorkOrderAttachments.length; i < divs.length; i++) { divs[i].remove(); } } else div_woatts.empty(); if (attas.AssetAttachments && attas.AssetAttachments.length > 0) { var divs = div_aatts.children('div'); for (var i = 0; i < attas.AssetAttachments.length; i++) { var att = attas.AssetAttachments[i]; if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0) att.ThumbnailUrl = att.Url + "&thumb=1"; var div = createAttaDiv(att, false, 300); if ($.inArray(att.FileType.toLowerCase(), printTypes) >= 0) { var sprint = $('').attr('title', GetTextByKey("P_WO_PRINT", 'Print')).click(att, function (e) { openPrintFrame(e.data.AttachmentType, e.data.AttachmentIdStr); }).css('right', 30); div.append(sprint); } if (att.FileType.toLowerCase() != "url") { var sdownload = $('').attr('title', GetTextByKey("P_WO_DOWNLOAD", 'Download')).click(att, function (e) { openDownloadFrame(e.data.Url + "&d=1"); }); div.append(sdownload); } var div_exists = divs[i]; if (div_exists) { div.insertAfter(div_exists); div_exists.remove(); } else div_aatts.append(div); } for (var i = attas.AssetAttachments.length; i < divs.length; i++) { divs[i].remove(); } } else div_aatts.empty(); if (attas.InspectionAttachments && attas.InspectionAttachments.length > 0) { var divs = div_iatts.children('div'); for (var i = 0; i < attas.InspectionAttachments.length; i++) { var att = attas.InspectionAttachments[i]; var div = createAttaDiv(att, false, 300); if ($.inArray(att.FileType.toLowerCase(), printTypes) >= 0) { var sprint = $('').attr('title', GetTextByKey("P_WO_PRINT", 'Print')).click(att, function (e) { openPrintFrame(e.data.AttachmentType, e.data.AttachmentIdStr); }).css('right', 30); div.append(sprint); } var sdownload = $('').attr('title', GetTextByKey("P_WO_DOWNLOAD", 'Download')).click(att, function (e) { openDownloadFrame(e.data.Url + "&d=1"); }); div.append(sdownload); var div_exists = divs[i]; if (div_exists) { div.insertAfter(div_exists); div_exists.remove(); } else div_iatts.append(div); } for (var i = attas.AssetAttachments.length; i < divs.length; i++) { divs[i].remove(); } } else div_iatts.empty(); } function createAttaDiv(att, iswoatta, size) { var div = $('
    ').attr('title', att.FileName); if (iswoatta) div.attr('title', att.Notes === "" ? att.FileName : att.Notes) if (!att.FileType || att.FileType == "") att.FileType = ".jpg"; if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0) { var url = att.ThumbnailUrl; if (size > 0) { url += "&size=" + size; } var pic = $('').attr('src', url); pic.click(att, function (e) { window.open(e.data.Url, "_blank") }); div.append(pic); } else { var sdown = $('').click(att, function (e) { window.open(e.data.Url); }); setAttachemntIcon(att.FileType, sdown); div.append(sdown); } return div } function updateWOAttachmentExtension(attID, chk) { var item = { 'Key': "1", 'Value': chk }; var param = JSON.stringify(item); param = htmlencode(param); worequest('UpdateWOAttachmentExtension', JSON.stringify([attID, param]), function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_AVAILABLETOCUSTOMER", 'Available to Customer')); } if (allAttachments && allAttachments.WorkOrderAttachments) { for (var i = 0; i < allAttachments.WorkOrderAttachments.length; i++) { if (allAttachments.WorkOrderAttachments[i].AttachmentId == attID) { allAttachments.WorkOrderAttachments[i].AvailableToCustomer = chk; break; } } } }, function (err) { }); } function updateWOAttachmentExtensionBatch() { var atts = []; if (grid_panddattachments) { var tempsource = grid_panddattachments.source || []; for (var i = 0; i < tempsource.length; i++) { var a = tempsource[i]; atts.push({ Id: a.AttachmentIdStr, Visible: a.Selected }); } } var param = JSON.stringify(atts); param = encodeURIComponent(param); worequest('UpdateWOAttachmentExtensionBatch', param, function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_AVAILABLETOCUSTOMER", 'Available to Customer')); return; } hidePAndDAttachmentPopup(); if (div_woatts != null) { var inps = div_woatts.find('input[type="checkbox"]'); inps.each(function () { var id = $(this).data('aid'); if (id != null) { var selected = atts.find(function (a) { return a.Id == id })?.Visible; this.checked = selected; } }); } if (allAttachments && allAttachments.WorkOrderAttachments) { for (var i = 0; i < allAttachments.WorkOrderAttachments.length; i++) { var att = allAttachments.WorkOrderAttachments[i]; var a = atts.find(function (n) { return n.Id == att.AttachmentId }); if (a != null) { att.AvailableToCustomer = a.Visible; } } } }, function () { }); } var grid_panddattachments function InitPAndDGrid() { grid_panddattachments = new GridView(panddlist); var list_columns = [ { name: 'Selected', caption: "", valueIndex: 'Selected', type: 3, css: { 'width': 45, 'text-align': 'center' } }, { name: 'ThumbnailUrl', caption: "", valueIndex: 'ThumbnailUrl', css: { 'width': 42, 'text-align': 'center' } }, { name: 'FileName', caption: GetTextByKey("P_WO_NAME", "Name"), valueIndex: 'FileName', css: { 'width': 280, 'text-align': 'left' } } ]; var columns = []; for (var hd in list_columns) { var col = {}; if (list_columns[hd].type) { col.type = list_columns[hd].type; } col.name = list_columns[hd].name; col.caption = list_columns[hd].caption; col.visible = true; col.sortable = true; col.width = list_columns[hd].css.width; col.align = list_columns[hd].css["text-align"] col.key = list_columns[hd].valueIndex; columns.push(col); if (col.name == "Selected") { col.allcheck = true; col.sortable = false; } else if (col.name == "ThumbnailUrl") { col.type = ThumbnailUrlColumn; col.sortable = false; //col.filter = function (item) { // if (imgTypes.indexOf(item.FileType.toLowerCase()) >= 0) // return $('').attr('src', item.ThumbnailUrl); // else { // var sdown = $('') // setAttachemntIcon(item.FileType, sdown); // return sdown; // } //} //col.styleFilter = function () { // return { "width": "100%", 'margin': 0 }; //} } } grid_panddattachments.multiSelect = true; grid_panddattachments.columns = columns; grid_panddattachments.init(); } function openPAndDGDialog(type) { if (!allAttachments) return; var d = dialog_panddattachments; if (!d.data("loaded")) { d.data("loaded", true); InitPAndDGrid(); } btn_print.css('display', type == 0 ? '' : 'none'); btn_download.css('display', type == 1 ? '' : 'none'); btn_ok.css('display', type == 2 ? '' : 'none'); var data = []; if (allAttachments.AssetAttachments && allAttachments.AssetAttachments.length > 0) data = data.concat(allAttachments.AssetAttachments); if (allAttachments.WorkOrderAttachments && allAttachments.WorkOrderAttachments.length > 0) data = data.concat(allAttachments.WorkOrderAttachments); if (allAttachments.InspectionAttachments && allAttachments.InspectionAttachments.length > 0) data = data.concat(allAttachments.InspectionAttachments); var count = 0; var rows = []; for (var i = 0; i < data.length; i++) { var att = data[i]; if (att.FileType.toLowerCase() == "url") continue; var f; if (type == 2) { f = att.AttachmentType == 2; } else { f = type == 1 || $.inArray(att.FileType.toLowerCase(), printTypes) >= 0; } if (f) { var fr = { FileName: att.Notes === "" ? att.FileName : att.Notes, FileType: att.FileType, Url: att.Url, ThumbnailUrl: att.ThumbnailUrl, AttachmentType: att.AttachmentType, AttachmentIdStr: att.AttachmentIdStr, Selected: type == 2 && att.AvailableToCustomer, }; rows.push(fr); count++; } } d.find('.dialog-title span.title').text(GetTextByKey("P_WO_ATTACHMENTS", 'Attachments') + " (" + count + ")"); showmaskbg(true); d.css({ 'top': (document.documentElement.clientHeight - d.height()) / 3, 'left': (document.documentElement.clientWidth - d.width()) / 2 }).showDialogfixed(); setTimeout(function () { grid_panddattachments.setData(rows); grid_panddattachments.clearHeaderCheckbox(); }); } function getSelectedPAndDAttas() { var sels = []; if (grid_panddattachments) { var tempsource = grid_panddattachments.source || []; for (var i = 0; i < tempsource.length; i++) { var a = tempsource[i]; if (a.Selected) sels.push(a); } } return sels; } function printWOAttachments() { var sels = getSelectedPAndDAttas(); if (!sels || sels.length == 0) return; if (sels && sels.length > 0) { for (var i = 0; i < sels.length; i++) { var att = sels[i]; if ($.inArray(att.FileType.toLowerCase(), printTypes) >= 0) { openPrintFrame(att.AttachmentType, att.AttachmentIdStr); } } } hidePAndDAttachmentPopup(); } function openPrintFrame(attatype, id) { var frame = $(""); $(document.body).after(frame); //frame.attr("src", url); frame.attr("src", _network.root + "Print.aspx?pt=3&at=" + attatype + "&id=" + id); frame.on('load', function () { setTimeout(function () { frame.contents().find("body").css("text-align", "center"); //frame.contents().find("img").css("max-height", window.screen.availHeight).css("max-width", window.screen.availWidth); frame.contents().find("img").css("max-height", "98%").css("max-width", "98%"); frame[0].contentWindow.print(); }); setTimeout(function () { frame.remove(); }, 60000); }); } function downloadWOAttachments() { var sels = getSelectedPAndDAttas(); if (!sels || sels.length == 0) return; if (sels && sels.length > 0) { for (var i = 0; i < sels.length; i++) { var att = sels[i]; openDownloadFrame(att.Url + "&d=1"); } } hidePAndDAttachmentPopup(); } function openDownloadFrame(url) { var frame = $(""); $(document.body).after(frame); frame.attr("src", url); worequest('RecordDownloadLog', JSON.stringify([url]), function (data) { }, function (err) { }); var timer = setInterval(function () { if (frame[0].contentDocument && (frame[0].contentDocument.readyState == "complete" || frame[0].contentDocument.readyState == 4)) { frame.remove(); clearInterval(timer); } }, 5000); } function updateWOAttachmentCaption(edata) { var attid = edata.AttachmentId; var caption = edata.iptcaption.val(); //if (caption === "") { // var pcap = edata.caption; // if (edata.iptcaption.data('caption')) // pcap = edata.iptcaption.data('caption'); // edata.iptcaption.val(pcap); // return; //} var att = edata.iptcaption.data('attdata'); att.Notes = caption; if (allAttachments && allAttachments.WorkOrderAttachments) { for (var i = 0; i < allAttachments.WorkOrderAttachments.length; i++) { if (allAttachments.WorkOrderAttachments[i].AttachmentId == att.AttachmentId) { allAttachments.WorkOrderAttachments[i] = att; break; } } } worequest('UpdateWorkOrderAttachmentCaption', JSON.stringify([attid, htmlencode(caption)]), function (data) { if (data !== 'OK') { showAlert(data, GetTextByKey("P_WO_UPDATECAPTION", 'Update Caption')); } else { if (edata.div) edata.div.attr('title', caption); edata.iptcaption.data('caption', caption); } }, function (err) { }); } //***********************************Begin Attachment List************************************// function showAttachmentList(data) { if (data.WorkOrderAttachments && data.WorkOrderAttachments.length > 0) { var trs = woattslist_tbody.children('tr'); for (var i = 0; i < data.WorkOrderAttachments.length; i++) { var att = data.WorkOrderAttachments[i]; var tr = createWOAttachmentTr(att); var tr_exists = trs[i]; if (tr_exists) { tr.insertAfter(tr_exists); tr_exists.remove(); } else woattslist_tbody.append(tr); } for (var i = data.WorkOrderAttachments.length; i < trs.length; i++) { trs[i].remove(); } } else woattslist_tbody.empty(); if (data.AssetAttachments && data.AssetAttachments.length > 0) { var trs = woassetattslist_tbody.children('tr'); for (var i = 0; i < data.AssetAttachments.length; i++) { var att = data.AssetAttachments[i]; if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0) att.ThumbnailUrl = att.Url + "&thumb=1"; var tr = createWOOtherAttachmentTr(att, 60); var tr_exists = trs[i]; if (tr_exists) { tr.insertAfter(tr_exists); tr_exists.remove(); } else woassetattslist_tbody.append(tr); } for (var i = data.AssetAttachments.length; i < trs.length; i++) { trs[i].remove(); } } else woassetattslist_tbody.empty(); if (data.InspectionAttachments && data.InspectionAttachments.length > 0) { var trs = woiptattslist_tbody.children('tr'); for (var i = 0; i < data.InspectionAttachments.length; i++) { var att = data.InspectionAttachments[i]; //if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0) // att.ThumbnailUrl = att.Url & "&thumb=1"; var tr = createWOOtherAttachmentTr(att, 60); var tr_exists = trs[i]; if (tr_exists) { tr.insertAfter(tr_exists); tr_exists.remove(); } else woiptattslist_tbody.append(tr); } for (var i = data.InspectionAttachments.length; i < trs.length; i++) { trs[i].remove(); } } else woiptattslist_tbody.empty(); } function createWOAttachmentTr(att) { var caption = att.Notes === "" ? att.FileName : att.Notes; var tr = $('').attr('data-id', att.AttachmentId); var td; tr.append(''); td = $(''); if (!att.FileType || att.FileType == "") att.FileType = ".jpg"; var divpic = $('
    '); td.append(divpic); if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0) { var pic = $('').attr('src', att.ThumbnailUrl); pic.click(att, function (e) { window.open(e.data.Url, "_blank") }); divpic.append(pic); } else { var sdown = $('').click(att, function (e) { window.open(e.data.Url); }); setAttachemntIcon(att.FileType, sdown); divpic.append(sdown); } tr.append(td); td = $(''); var iptcaption = $('').css('width', '100%').attr('data-ori', caption).val(caption); iptcaption.data('attdata', att); if (!caption || caption == '') iptcaption.attr('placeholder', 'Click to Add caption'); td.append(iptcaption); iptcaption.focus({ AttachmentId: att.AttachmentId, iptcaption: iptcaption }, function (e) { e.data.iptcaption.addClass('focused'); }); iptcaption.blur({ AttachmentId: att.AttachmentId, iptcaption: iptcaption, caption: caption }, function (e) { e.data.iptcaption.removeClass('focused'); updateWOAttachmentCaption(e.data); }); iptcaption.keydown({ AttachmentId: att.AttachmentId, iptcaption: iptcaption, caption: caption }, function (e) { if (e.keyCode == 13 || e.keyCode == 9) { e.data.iptcaption.blur(); } }); tr.append(td); td = $(''); if (AllowCustomer) { var chk_tocust = $('').attr('data-ori', att.AvailableToCustomer).prop('checked', att.AvailableToCustomer); td.append(chk_tocust); chk_tocust.click(att, function (e) { updateWOAttachmentExtension(e.data.AttachmentId, $(this).prop('checked')); }); } tr.append(td); td = $(''); var sdel = $('').attr('title', GetTextByKey("P_WO_DELETE", 'Delete')).click(att, function (e) { deleteAttachment(e.data.AttachmentId, $(e.target)); }); td.append(sdel); var ssend = $('').attr('title', GetTextByKey("P_WO_SEND", 'Send')).click(att, function (e) { openSendAttachmentPopup(e.data); }); td.append(ssend); var sdownload = $('').attr('title', GetTextByKey("P_WO_DOWNLOAD", 'Download')).click(att, function (e) { openDownloadFrame(e.data.Url + "&d=1"); }); td.append(sdownload); if ($.inArray(att.FileType.toLowerCase(), printTypes) >= 0) { var sprint = $('').attr('title', GetTextByKey("P_WO_PRINT", 'Print')).click(att, function (e) { openPrintFrame(e.data.AttachmentType, e.data.AttachmentIdStr); }); td.append(sprint); } tr.append(td); return tr; } function createWOOtherAttachmentTr(att, size) { var tr = $('').attr('data-id', att.AttachmentId); var td; tr.append(''); td = $(''); if (!att.FileType || att.FileType == "") att.FileType = ".jpg"; var divpic = $('
    '); td.append(divpic); if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0) { var url = att.ThumbnailUrl; if (size > 0) { url += "&size=" + size; } var pic = $('').attr('src', url); pic.click(att, function (e) { window.open(e.data.Url, "_blank") }); divpic.append(pic); } else { var sdown = $('').click(att, function (e) { window.open(e.data.Url); }); setAttachemntIcon(att.FileType, sdown); divpic.append(sdown); } tr.append(td); td = $('').text(att.FileName); tr.append(td); td = $(''); if (att.FileType.toLowerCase() != "url") { var sdownload = $('').attr('title', GetTextByKey("P_WO_DOWNLOAD", 'Download')).click(att, function (e) { openDownloadFrame(e.data.Url + "&d=1"); }); td.append(sdownload); } if ($.inArray(att.FileType.toLowerCase(), printTypes) >= 0) { var sprint = $('').attr('title', GetTextByKey("P_WO_PRINT", 'Print')).click(att, function (e) { openPrintFrame(e.data.AttachmentType, e.data.AttachmentIdStr); }); td.append(sprint); } tr.append(td); return tr; } function SendAttachmentMsg(phoneemail) { var phoneemail = phoneemail;// $('#txtphonenum_statuschange').val(); if (!phoneemail || phoneemail.trim() == "") { showAlert(GetTextByKey("P_WO_PLEASEINPUTTHEPHONENUMBEROREMAL", "Please input the phone number or email."), GetTextByKey("P_WO_ERROR", 'Error')); return; } var phoneemails = phoneemail.split(';'); var pmemails = []; for (var i = 0; i < phoneemails.length; i++) { var pm = phoneemails[i]; if (checkPhoneNumber(pm) || isEmail(pm)) { pmemails.push({ 'Key': pm, 'Value': pm }); } else { if (_this.option.customercontacts) { for (var j = 0; j < _this.option.customercontacts.length; j++) { var c = _this.option.customercontacts[j]; if (c.OptOut || c.OptOut_BC) continue; var mp = $.trim(c.MobilePhone); var email = $.trim(c.Email); if (c.Name === pm) { if (c.ContactPreference == "0" && checkPhoneNumber(mp)) { pmemails.push({ 'Key': mp, 'Value': pm }); break; } if (c.ContactPreference == "1" && isEmail(email)) { pmemails.push({ 'Key': email, 'Value': pm }); break; } } } } } } var comm = $('#dialog_atta_textmsg').val(); if ($.trim(comm) == "") { showAlert(GetTextByKey("P_WO_PLEASEINPUTTHEMESSAGE", "Please input the message."), GetTextByKey("P_WO_ERROR", 'Error')); return; } $('#dialogattmask').show(); $('#dialogattmask').css('z-index', 1000); var includeStatusLink = $('#dialog_atta_chkIncludeStatusLink').prop("checked"); var url = 'AddWorkOrder.aspx'; var method = 'AddWorkOrderCommunication'; var data = new FormData(); data.append('MethodName', method); data.append('WorkorderId', _this.option.workorderid); data.append('PMEmails', JSON.stringify(pmemails)); data.append('Comment', encodeURIComponent(comm)); data.append('IncludeStatusLink', includeStatusLink ? "1" : "0"); var atta = wosendattachmentDialog.data('atta'); var attap = { AttaType: '2', Id: atta.AttachmentId, Filename: atta.FileName, Caption: atta.Notes }; data.append('AttaData', encodeURIComponent(JSON.stringify(attap))); if (imgTypes.indexOf(atta.FileType.toLowerCase()) < 0) {//图片无需验证大小 data.append('IsAttachment', "1"); } $.ajax({ url: url, type: 'POST', dataType: 'json', processData: false, contentType: false, cache: false, data: data, success: function (data) { $('#dialogattmask').hide(); $('#dialogattmask').css('z-index', 'unset'); //$('#mask_over_bg').hide(); if (data !== "") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } hideSendWOAttachmentPopup(); }, error: function (request, textStatus, errorThrown) { $('#dialogattmask').hide(); $('#dialogattmask').css('z-index', 'unset'); if (request?.readyState == 0) { console.log(request); } else { writelog_ironintel("onAddMessage", url + ".-1." + method + "." + JSON.stringify(param), JSON.stringify(request), textStatus + errorThrown); } } }); } //***********************************End Attachment List************************************// function dragOverWOAttachment(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = 'link'; } function dropWOAttachment(ev) { ev.preventDefault(); ev.stopPropagation(); var df = ev.dataTransfer; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); files.push(file); } } } if (files.length > 0) onSaveWOAttachment(files); } function cutWOAttachment(ev) { ev.stopPropagation(); var df = ev.clipboardData; var files = []; if (df.items !== undefined) { for (var i = 0; i < df.items.length; i++) { var item = df.items[i]; if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) { var file = item.getAsFile(); files.push(file); } } } if (files.length > 0) onSaveWOAttachment(files); } } } /*****************************************End Attachment*********************************************/ function getMessageStatusHistoryText(p) { var getStatusText = function (s) { switch (s) { case 0: return GetTextByKey('P_CU_PENDING', 'Pending'); case 1: return GetTextByKey('P_WO_SENT', 'Sent'); case 5: return GetTextByKey('P_CU_DELIVERYCONFIRMED', 'Delivery Confirmed'); case 6: return GetTextByKey('P_CU_RESENT', 'Resent'); case 9: case 10: case 412: return GetTextByKey('P_MA_FAILED', 'Failed'); default: return GetTextByKey('P_CU_UNKNOWN', 'Unknown'); } }; var msg = GetTextByKey('P_CU_UPDATESTATUSDESC', 'Status changed from {0} to {1}\nBy {2} on {3}') .replace('{0}', getStatusText(p.History.StatusFrom)) .replace('{1}', getStatusText(p.History.StatusTo)) .replace('{2}', p.History.UpdatedBy) .replace('{3}', p.UpdatedOnStr); return msg; } /*****************************************Begin Customer Communication*********************************************/ if (typeof $wocommunication !== 'function') { $wocommunication = function (option) { var _this = this; this.customercontacts = []; this.followers = []; this.changewo = function (woid, aid, wo) { option.workorderid = woid; if (aid) option.machineid = aid; if (wo) option.wo = wo; this.updatecontact([]);//清空联系人 this.followers = []; this.customer.followers = []; this.getWorkOrderFollowers(woid); this.getCommunications(true); var customer = this.customer; if (customer && option.wo) { customer.companyName = option.wo.CustomerName; customer.companyCode = option.wo.CustomerCode; customer.setData('companyCode', option.wo.CustomerCode); customer.autoUpdates = option.wo.AutoText?.Value; } }; this.updatecontact = function (contacts) { this.customercontacts = contacts this.showCustomerContacts(this.customercontacts); } this.close = function () { } this.resetCommunications = function () { var customer = _this.customer; if (typeof customer !== 'undefined') { customer.text = ''; customer.load(); } } var communicationsLoading = false; var communicationsLoadingWaitCount = 0; /**Communication */ this.getCommunications = function (reset) { if (reset) { _this.resetCommunications(); } if (communicationsLoading) { communicationsLoadingWaitCount++; return; } communicationsLoading = true; if (!option.workorderid || option.workorderid == "") return; option.showloading(true); worequest("GetCommunications", option.workorderid, function (data) { communicationsLoading = false; option.showloading(false); if (typeof (data) === "string") { return; } _this.customer?.load(data, _this.customercontacts, _this.followers); if (communicationsLoadingWaitCount > 0) { communicationsLoadingWaitCount = 0; _this.getCommunications(reset); } }, function () { communicationsLoading = false; if (communicationsLoadingWaitCount > 0) { communicationsLoadingWaitCount = 0; _this.getCommunications(reset); } option.showloading(false); }); }; this.showCustomerContacts = function (data) { var customer = this.customer; if (customer != null) { //customer.setData('contacts', data); customer.contacts = data; } }; this.getCustomerContacts = function (custid, next) { worequest('GetCustomerContacts', custid, function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record")); if (next) next([]);//next 在Communication选Contacts时传入 return; } if (next) { next(data);//next 在Communication选Contacts时传入 return; } _this.showCustomerContacts(data); _this.SaveWorkorderContact(); }, function () { }); } this.SaveWorkorderContact = function (data, next) { var workorderid = option.workorderid; if (!workorderid || workorderid == "") return; var custid = option.wo.CustomerId; if (!custid) custid = -1; var param = JSON.stringify([workorderid, custid, JSON.stringify(data ?? _this.customercontacts)]); param = htmlencode(param); worequest("SaveWorkOrderContact", param, function (data) { if (typeof next === 'function') { next(data); return; } if (typeof data === "string") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } }, function () { //showmaskbg(false); }); }; this.SaveWorkOrderFollower = function (next) { var workorderid = option.workorderid; if (!workorderid || workorderid == "") return; var param = JSON.stringify([workorderid, JSON.stringify(_this.followers)]); param = htmlencode(param); worequest("SaveWorkOrderFollower", param, function (data) { if (typeof next === 'function') { next(data); } else { if (data !== "OK") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } } }, function () { //showmaskbg(false); }); }; this.getWorkOrderFollowers = function (woid) { worequest('GetWorkOrderFollowers', woid, function (data) { if (typeof (data) === "string") { showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record")); return; } _this.followers = data; _this.customer.followers = _this.followers; }, function () { }); }; var isloadfollower = false; var allfollowers = []; this.getAllFollowers = function (next) { worequest('GetAllFollowers', '', function (data) { if (typeof next === 'function') { next(data); } else { if (typeof (data) === "string") { showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record")); return; } isloadfollower = true; allfollowers = data; _this.customer.setData('allfollowers', data); } }, function () { }); }; window.customer = this.customer = new window['lib-app'].CustomerCommunication({ getText: GetTextByKey, autoUpdates: false, readonly: WOReadOnly || COMMReadOnly, recordReadonly: !AllowCustomer || WOReadOnly || CRReadOnly, contactCollapsed: spliterProps.contactCollapsed, onMasking: window.parent.onmaskbg, onContactCollapsed: function (checked) { spliterProps.contactCollapsed = checked; localStorage.setItem('spliter_props', JSON.stringify(spliterProps)); }, onStatusLinkChanged: function (checked) { this.freeze = true; var customer = document.querySelector('#iframeworkorder').contentWindow?.customer; if (customer != null) { customer.statusLink = checked; } this.freeze = false; }, onAddMessage: function () { var customer = _this.customer; var pmemails = customer?.contacts; if (pmemails == null || pmemails.length === 0) { customer.loading = false; showAlert(GetTextByKey("P_WO_PLEASEINPUTTHEPHONENUMBEROREMAL", "Please input the phone number or email."), GetTextByKey("P_WO_ERROR", 'Error')); return; } var comm = customer?.text; if ($.trim(comm) == "") { customer.loading = false; showAlert(GetTextByKey("P_WO_PLEASEINPUTTHEMESSAGE", "Please input the message."), GetTextByKey("P_WO_ERROR", 'Error')); return; } var includeStatusLink = customer?.statusLink; option.showloading(true); var url = 'Maintenance/WorkOrderMaintenance.aspx'; var method = 'AddWorkOrderCommunication'; var data = new FormData(); data.append('MethodName', method); data.append('WorkorderId', option.workorderid); data.append('PMEmails', JSON.stringify(pmemails)); data.append('Comment', encodeURIComponent(comm)); data.append('IncludeStatusLink', includeStatusLink ? "1" : "0"); var file = customer?.file; if (file != null) { data.append('Attachment', file); } $.ajax({ url: _network.root + url, type: 'POST', dataType: 'json', processData: false, contentType: false, cache: false, data: data, success: function (data) { option.showloading(false); customer.loading = false; if (data !== "") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } customer.text = ''; customer.file = null; }, error: function (request, textStatus, errorThrown) { option.showloading(false); customer.loading = false; if (request?.readyState == 0) { console.log(request); } else { writelog_ironintel("onAddMessage", url + ".-1." + method + "." + JSON.stringify(param), JSON.stringify(request), textStatus + errorThrown); } } }); }, onUpdateMessageStatus: function (msgs) { if (msgs?.length > 0) { worequest('UpdateMessageStatus', JSON.stringify(msgs), function (data) { if (data !== 'OK') { ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error'); return; } _this.getCommunications(); }); } }, onMessageStatusClicked: function (p) { worequest('GetMessageStatusHistory', String(p.Id), function (data) { if (typeof data === 'string') { ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error'); return; } if (data.length > 0) { var msg = data.map(function (p) { return getMessageStatusHistoryText(p) }).join('\n\n'); ui.showAlert(data[0].CustomerNumberFormatted, msg); } }); }, onSave: function (item, add) { var contact; if (!add) { contact = _this.customercontacts.filter(function (f) { return f.Id < 0 ? f.Name === item.OldName && f.MobilePhone === item.OldMobilePhone : f.Id === item.Id })[0]; } var array = []; for (let c of _this.customercontacts) { if (c === contact) { let ct = { ...contact, Name: item.Name, ContactPreference: item.ContactPreference, Email: item.Email, MobilePhone: item.MobilePhone, OptOut: item.OptOut, Notes: item.Notes, SaveToCustomer: item.SaveToCustomer }; if (parseInt(ct.ContactPreference) == 0) { ct.ContactPreferenceStr = GetTextByKey("P_CR_TEXT", "Text"); } else if (parseInt(ct.ContactPreference) == 1) { ct.ContactPreferenceStr = GetTextByKey("P_CR_EMAIL", "Email"); } else if (parseInt(ct.ContactPreference) == 2) { ct.ContactPreferenceStr = GetTextByKey("P_CR_PHONE", "Phone"); } array.push(ct) } else { array.push(c); } } if (add) { item.Id = -1; array.push(item); } return new Promise(function (resolve, reject) { _this.SaveWorkorderContact(array, function (data) { if (typeof data === 'string') { ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error') reject(); } else { for (let d of data) { const c = _this.customercontacts.find(function (c) { return c.Id < 0 ? c.Name === d.Name && c.MobilePhone === d.MobilePhone : c.Id === d.Id }); if (c != null) { d.selected = c.selected; } else { d.selected = true; } } _this.showCustomerContacts(_this.customercontacts = data); resolve(data); } }); }); }, onDelete: function (_op, item, customer) { var index; var customercontacts = _this.customercontacts; if (customer) { index = customercontacts.findIndex(function (c) { return c.Id === item.Id }); } else { index = customercontacts.findIndex(function (c) { return c.Name === item.Name && c.MobilePhone === item.MobilePhone }); } if (index >= 0) { customercontacts.splice(index, 1); _this.SaveWorkorderContact(); _this.showCustomerContacts(customercontacts); // from customer record if (customer) { _network.request("Maintenance/AddCustomerRecord.aspx", -1, 'DeleteContact', item.Id, function () { }, function (e) { console.log(e); ui.showAlert(GetTextByKey("P_WO_ERROR", 'Error'), GetTextByKey('P_UM_PAGEERROR', 'An unknown error occurred. Please refresh page.'), 'error'); }); } } }, onChanged: function (source) { _this.customer.contacts = source; }, onDeleteFollower: function (_op, f) { var followers = _this.followers; var index = followers.findIndex(function (c) { return c.UserIID === f.UserIID }); if (index < 0) { return; } followers.splice(index, 1); _this.SaveWorkOrderFollower(); _this.customer.followers = followers; }, onChangeFollower: function (_op, f, text, email) { var follower = _this.followers.find(function (c) { return c.UserIID === f.UserIID }); if (follower != null) { follower.SendText = text; follower.SendEmail = email; _this.SaveWorkOrderFollower(); _this.customer.followers = followers; } }, onInitFollower: function (selfollowers) { if (isloadfollower && allfollowers?.length > 0) { for (let f of allfollowers) { f.Email = false; f.Text = false; if (selfollowers) { var tf = selfollowers.find(function (c) { return c.UserIID.toLowerCase() === f.IID.toLowerCase() }); if (tf) { f.Email = tf.SendEmail; f.Text = tf.SendText; } } } return Promise.resolve(allfollowers); } return new Promise(function (resolve) { _this.getAllFollowers(function (data) { if (Array.isArray(data)) { isloadfollower = true; allfollowers = data; } for (let f of allfollowers) { f.Email = false; f.Text = false; if (selfollowers) { var tf = selfollowers.find(function (c) { return c.UserIID.toLowerCase() === f.IID.toLowerCase() }); if (tf) { f.Email = tf.SendEmail; f.Text = tf.SendText; } } } resolve(data); }); }); }, onAddFollower: function (list) { var followers = _this.followers = []; for (let f of list) { let o = { Id: -1, UserIID: f.IID, Name: f.DisplayName, Email: f.ID, MobilePhone: f.Mobile, SendEmail: f.Email, SendText: f.Text }; followers.push(o); } return new Promise(function (resolve, reject) { _this.SaveWorkOrderFollower(function (data) { if (data !== 'OK') { ui.showAlert(GetTextByKey("P_WO_ERROR", 'Error'), data, 'error') reject(); } else { resolve(followers); } }); }); }, onOpenSelectCRContacts: function () { return new Promise(function (resolve) { var customerid = option.wo.CustomerId; if (!customerid || customerid === "") { setTimeout(function () { resolve([]) }, 0); return; } _this.getCustomerContacts(customerid, function (data) { resolve(data); }); }); }, onSelectCRContacts: function (list) { if (_this.customercontacts) { var temp = []; for (var i = 0; i < _this.customercontacts.length; i++) {//移除上一个Customer的Contacts if (_this.customercontacts[i].Id > 0) continue; temp.push(_this.customercontacts[i]); } _this.customercontacts = temp; } for (var i = 0; i < list.length; i++) { var r = list[i]; var item = { ...r }; var contactexists = false; if (_this.customercontacts) { for (var j = 0; j < _this.customercontacts.length; j++) { var ct = _this.customercontacts[j]; if (ct.Name === item.Name && ct.MobilePhone === item.MobilePhone) { ct.Id = item.Id; contactexists = true; break; } } } if (!contactexists) _this.customercontacts.push(item); } _this.showCustomerContacts(_this.customercontacts); _this.SaveWorkorderContact(); } }); option.parent.append(this.customer.create()); } } /*****************************************End Customer Communication*********************************************/ /*****************************************Begin Internal Communcation*********************************************/ if (typeof $wointernal !== 'function') { $wointernal = function (option) { var _this = this; this.changewo = function (woid, aid) { //if (woid !== option.workorderid) { option.workorderid = woid; if (aid) option.machineid = aid; this.getComments(true); //} }; this.close = function () { } this.updatecontact = function (contacts) { var internal = this.internal; if (internal != null) { internal.contacts = contacts; } } this.resetComments = function () { var internal = this.internal; if (internal != null) { internal.text = ''; internal.load(); } }; this.getComments = function (reset) { option.showloading(true); if (reset) { this.resetComments(); } var workorderid = option.workorderid; if (!workorderid || workorderid == "") return; worequest("GetComments", workorderid, function (data) { option.showloading(false); if (typeof (data) === "string") { return; } $("#li_comments").data("loaded", true); _this.internal?.load(data); }, function () { option.showloading(false); }); }; window.internal = this.internal = new window['lib-app'].InternalComment({ getText: GetTextByKey, readonly: WOReadOnly, onAddMessage: openSendICEmail, onAddComment: function (comment) { if ($.trim(comment) == "") { //showAlert(GetTextByKey("P_FR_PLEASEINPUTTHECOMMENT", "Please input the comment."), GetTextByKey("P_WO_ERROR", 'Error')); return; } option.showloading(true); var url = 'Maintenance/AddWorkOrder.aspx'; var method = 'SendInternalComments'; var data = new FormData(); data.append('MethodName', method); data.append('WorkorderId', workorderid); data.append('Comment', encodeURIComponent(comment)); //data.append('Emails', JSON.stringify(emailaddress)); //data.append('Phones', JSON.stringify(phonenumbers)); var file = internal?.file; if (file != null) { data.append('Attachment', file); } $.ajax({ url: _network.root + url, type: 'POST', dataType: 'json', processData: false, contentType: false, cache: false, data: data, success: function (data) { option.showloading(false); _this.internal.loading = false; if (data !== "") { showAlert(data, GetTextByKey("P_WO_ERROR", 'Error')); return; } _this.internal.text = ''; _this.internal.file = null; $('#commentsinputcount').text("0/" + $('#dialog_comments').attr("maxlength")); //setTimeout(function () { _this.getComments() }, 400); }, error: function () { _this.internal.loading = false; option.showloading(false); } }); }, onUpdateMessageStatus: function (msgs) { if (msgs?.length > 0) { worequest('UpdateMessageStatus', JSON.stringify(msgs), function (data) { if (data !== 'OK') { ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error'); return; } _this.getComments(); }); } }, onMessageStatusClicked: function (p) { worequest('GetMessageStatusHistory', String(p.Id), function (data) { if (typeof data === 'string') { ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error'); return; } if (data.length > 0) { var msg = data.map(function (p) { return getMessageStatusHistoryText(p) }).join('\n\n'); ui.showAlert(data[0].CustomerNumberFormatted, msg); } }); } }); option.parent.append(this.internal.create()); }; } /*****************************************End Internal Communcation*********************************************/ /*****************************************Begin Customer Record Communcation*********************************************/ if (typeof $wocrcomment !== 'function') { $wocrcomment = function (option) { var _this = this; this.changewo = function (woid, aid, wo) { //if (woid !== option.workorderid) { if (wo) { option.customerid = wo.CustomerId; } this.getComments(true); //} }; this.close = function () { } this.resetComments = function () { var comment = this.comment; if (comment != null) { comment.text = ''; comment.load(); } }; this.getComments = function (reset) { option.showloading(true); if (reset) { this.resetComments(); } var customerid = option.customerid; if (isNaN(customerid) || customerid <= 0) { option.showloading(false); if (_this.comment != null) { _this.comment.load(); _this.comment.readonly = true; } return; } crrequest("GetCustomerComments", customerid, function (data) { option.showloading(false); if (typeof (data) === "string") { return; } $("#li_comments").data("loaded", true); if (_this.comment != null) { _this.comment.load(data); _this.comment.readonly = CRReadOnly; } }, function () { option.showloading(false); }); }; window.customerComment = this.comment = new window['lib-app'].CustomerRecordComment({ getText: GetTextByKey, readonly: CRReadOnly, onAddComment: function (comment) { if ($.trim(comment) == "") { //showAlert(GetTextByKey("P_FR_PLEASEINPUTTHECOMMENT", "Please input the comment."), GetTextByKey("P_WO_ERROR", 'Error')); return; } var param = JSON.stringify([option.customerid, false, comment]); param = htmlencode(param); option.showloading(true); crrequest("SubmitComment", param, function (data) { option.showloading(false); if (data !== "") { showAlert(data, GetTextByKey("P_FR_ERROR", 'Error')); return; } _this.comment.text = ''; $('#commentsinputcount').text("0/" + $('#dialog_comments').attr("maxlength")); setTimeout(function () { _this.getComments() }, 400); }, function () { option.showloading(false); }); } }); option.parent.append(this.comment.create()); }; } /*****************************************End Customer Record Communcation*********************************************/