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 = $('
');
dialog.append($('').append(tb));
var tr = $('
').appendTo(tb);
var td = $('Payment By: | ').appendTo(tr);
td = $(' | ').appendTo(tr);
var dialog_invoice_markpaid_paymentby = $('').appendTo(td);
tr = $('
').appendTo(tb);
td = $('Check #: | ').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);
});
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() {
invoice_index = 0;
_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);
_this.option.parent.find('.estimates_div').remove();
_this.option.parent.find('.estimates_table').remove();
if (data.WorkOrderID != _this.option.workorderid) {
getInvoices();
return;
}
data = data.Data;
if (typeof (data) === "string") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
if (data) {
if (data && data.length > 0) {
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, index) {
ev.preventDefault();
ev.dataTransfer.dropEffect = 'link';
}
function dropInvoiceAttachment(ev, index) {
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' + index).data('invoice');
if (!invoice)
return;
if (invoice.Status !== 0)
return;
if (files.length > 0)
SaveInvoiceAttachmentFiles(files, invoice.Id, index);
}
function cutInvoiceAttachment(ev, index) {
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' + index).data('invoice');
if (!invoice)
return;
if (invoice.Status !== 0)
return;
if (files.length > 0)
SaveInvoiceAttachmentFiles(files, invoice.Id, index);
}
function showInvoice(invoice) {
invoice_index++;
var statustext = getInvoiceStatus(invoice.Status);
var div_invoices = _this.option.parent;
var div_title = $('');
div_title.on('drop', invoice_index, 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_XXXXXX', 'Mark As Paid'));
ipt.on("click", invoice_index, 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", invoice_index, 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", invoice_index, 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 = $('').data('invoice', invoice).data('index', invoice_index).hide();
table.on('drop', invoice_index, 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) } })(invoice_index));
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) } })(invoice_index));
td.append(ipt);
var tdDetail = $(' | ').attr('id', 'invoice_payment_tab' + invoice_index);
tr.append(tdDetail);
//if (invoice.Status == InvoiceStatus.Paid)
{
if (invoice.PaymentItem != null) {
var btncancelpayment = "";
if (invoice.Status === InvoiceStatus.ManualPaid) {
btncancelpayment = $('').val(GetTextByKey('P_WO_XXXXXX', 'Cancel Payment'));
btncancelpayment.on('click', invoice_index, function (e) {
CancelPayment(e.data);
});
}
tdDetail.empty().append(
$('').append(
$('
').append(
$(' | ').text(GetTextByKey('P_WO_XXXXXX', '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_XXXXXX', 'Payment Type:')),
$(' | ').text(invoice.PaymentItem.PaymentType),
$(' | '),
$(' | ')
),
$('
').append(
$(' | ').text(GetTextByKey('P_WO_XXXXXX', '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) } })(invoice_index));
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) } })(invoice_index));
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) } })(invoice_index));
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) } })(invoice_index));
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) } })(invoice_index));
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_XXXXXX_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(invoice_index, 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) } })(invoice_index));
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", invoice_index, 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(invoice_index);
tr = $('
');
table.append(tr);
td = $(' | ');
tr.append(td);
ipt = $('').val(GetTextByKey('P_WO_SAVE', 'Save')).hide();
ipt.on("click", invoice_index, function (e) {
onSaveWorkOrderInvoice(e.data);
});
td.append(ipt);
ipt = $('').val(GetTextByKey('P_WO_PUBLISH', 'Publish')).hide();
ipt.on("click", invoice_index, function (e) {
openPublishInvoiceDialog(e.data);
});
td.append(ipt);
if (!WOReadOnly) {
if (invoice.Status === InvoiceStatus.Draft) {
$('#btn_invoice_publish' + invoice_index).show();
$('#btn_invoice_save' + invoice_index).show();
}
if (invoice.Status === InvoiceStatus.Pending) {
$('#btn_invoice_revoke' + invoice_index).show();
}
if (invoice.Status === InvoiceStatus.Pending || invoice.Status === InvoiceStatus.PaymentCreated) {
$('#btn_invoice_markaspaid' + invoice_index).show();
}
}
if (disabled || WOReadOnly)
setInvoiceDisabled(invoice_index, true);
if (invoice.Status === InvoiceStatus.PaymentCreated ||
invoice.Status === InvoiceStatus.Failed) {
$('#span_invoice_status' + invoice_index).css('color', 'red');
$('#dialog_invoice_status' + invoice_index).css('color', 'red');
}
if (invoice.Status === InvoiceStatus.Paid || invoice.Status === InvoiceStatus.ManualPaid) {
$('#span_invoice_status' + invoice_index).css('color', '#2eda2e');
$('#dialog_invoice_status' + invoice_index).css('color', '#2eda2e');
}
}
function OnRevokeInvoice(index) {
var invoice = $('#tabinvoice' + index).data('invoice');
if (!invoice)
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", invoice.Id, function (data) {
if (data === "OK") {
getInvoices();
}
}, function (err) {
showAlert(GetTextByKey("P_WO_FAILED_REVOKE_INVOICE", 'Failed to revoke this invoice.'), GetTextByKey("P_WO_REVOKE_INVOICE", 'Revoke Invoice'));
});
});
}
function CancelPayment(index) {
var invoice = $('#tabinvoice' + index).data('invoice');
if (!invoice)
return;
showConfirm(GetTextByKey("P_WO_CONFIRM_XXXXXX_INVOICE", 'Are you sure you want to Cancel the Payment?'), GetTextByKey("P_WO_XXXXXX_INVOICE", 'Cancel Invoice'), function () {
worequest("CancelPayment", invoice.Id, function (data) {
if (data === "OK") {
getInvoices();
}
}, function (err) {
showAlert(GetTextByKey("P_WO_FAILED_REVOKE_INVOICE", 'Failed to cancel this payment.'), GetTextByKey("P_WO_XXXXXX_INVOICE", 'Cancel Invoice'));
});
});
}
function ChangeWOInvoiceCustomerVisible(index, visible) {
var invoice = $('#tabinvoice' + index).data('invoice');
if (!invoice)
return;
worequest("ChangeWOInvoiceCustomerVisible", JSON.stringify([invoice.Id, visible ? 1 : 0]), function (data) {
}, function (err) {
});
}
function OnDeleteInvoice(index) {
var invoice = $('#tabinvoice' + index).data('invoice');
if (!invoice)
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", invoice.Id, function (data) {
if (data === "OK") {
getInvoices();
}
}, 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) {
openPublishInvoiceDialog(-1);
}
else
onSaveWorkOrderInvoice("");
}
function onSaveWorkOrderInvoice(index, next) {
var invoiceid = -1;
var status = 0;
var alerttitle = GetTextByKey("P_WO_ADDINVOICE", "Add Invoice");
if (index !== "") {
alerttitle = GetTextByKey("P_WO_EDITINVOICE", "Edit Invoice");
var invoice = $('#tabinvoice' + index).data('invoice');
if (!invoice)
return;
invoiceid = invoice.Id;
status = invoice.Status;
}
else
status = parseInt($('#dialog_invoice_status').val());
var item = {
'Id': invoiceid,
'WorkOrderId': _this.option.workorderid,
'Status': status,
'InvoiceNumber': $('#dialog_invoice_number' + index).val(),
'TotalCost': $('#dialog_invoice_totalcosts' + index).val(),
'OtherCost': $('#dialog_invoice_othercost' + index).val(),
'PartsCost': $('#dialog_invoice_partscost' + index).val(),
'TravelCost': $('#dialog_invoice_traveltimecost' + index).val(),
'LaborCost': $('#dialog_invoice_laborcost' + index).val(),
'Taxes': $('#dialog_invoice_taxes' + index).val(),
'Notes': $('#dialog_invoice_notes' + index).val(),
'CustomerVisible': $('#dialog_invoice_customervisible' + index).prop("checked"),
'PaymentMethod': $('#dialog_invoice_paymentby' + index).val(),
'CheckNumber': $('#dialog_invoice_checknumber' + index).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' + index).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' + index).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' + index).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' + index).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' + index).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' + index).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' + index).focus() });
return;
}
}
if ((status == InvoiceStatus.Pending || status == InvoiceStatus.ManualPaid)
&& !item.CustomerVisible) {
var msg = GetTextByKey("P_WO_XXX", "Invoice will not be displayed on Customer Facing Page.
Do you want to:");
showInvoiceConfirm(msg, alerttitle,
function () {
$('#dialog_invoice_customervisible' + index).prop("checked", true)
item.CustomerVisible = true;
doSaveWorkOrderInvoice(item, index, next, alerttitle);
}, function () {
doSaveWorkOrderInvoice(item, index, next, alerttitle);
}, null);
}
else
doSaveWorkOrderInvoice(item, index, next, alerttitle);
}
function doSaveWorkOrderInvoice(item, index, next, alerttitle) {
$('#btn_invoice_save' + index).attr('disabled', true);
var param = JSON.stringify(item);
param = htmlencode(param);
worequest("SaveWorkOrderInvoice", param, function (data) {
if (typeof (data) === "string") {
$('#btn_invoice_save' + index).attr('disabled', false);
showAlert(data, alerttitle);
} else {
$('#btn_invoice_save' + index).attr('disabled', false);
item.Id = data;
if (index === "") {//新增
if (add_invoice_filedatas && add_invoice_filedatas.length > 0) {
SaveInvoiceAttachmentFiles(add_invoice_filedatas, data);
add_invoice_filedatas = [];
}
if (next)
next("", data);
else {
getInvoices();
}
hideInvoicePopup();
}
else {//编辑
if (next)
next("", data);
else {
showAlert(GetTextByKey("P_WO_SAVSUCCESSFULLY", "Saved successfully."), alerttitle);
$('#span_invoice_number' + index).text($('#dialog_invoice_number' + index).val());
}
}
}
}, function (err) {
$('#btn_invoice_save' + index).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(index) {
$('#tabinvoice' + index).data('changed', true);
}
function setInvoiceDisabled(index, di) {
$('#dialog_invoice_number' + index).attr('disabled', di);
$('#dialog_invoice_totalcosts' + index).attr('disabled', di);
$('#dialog_invoice_othercost' + index).attr('disabled', di);
$('#dialog_invoice_partscost' + index).attr('disabled', di);
$('#dialog_invoice_traveltimecost' + index).attr('disabled', di);
$('#dialog_invoice_laborcost' + index).attr('disabled', di);
$('#dialog_invoice_taxes' + index).attr('disabled', di);
$('#dialog_invoice_notes' + index).attr('disabled', di);
//$('#dialog_invoice_status' + index).attr('disabled', di);
//$('#dialog_invoice_customervisible' + index).attr('disabled', di);
}
function getInvoiceTotalCost(index) {
var othercost = $('#dialog_invoice_othercost' + index).val();
var partscost = $('#dialog_invoice_partscost' + index).val();
var traveltimecost = $('#dialog_invoice_traveltimecost' + index).val();
var laborcost = $('#dialog_invoice_laborcost' + index).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);
$('#dialog_invoice_totalcosts' + index).val(locale(totalcost, true));
}
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_index <= 0)
invoiceDialog.find('.maskbg').show();
else
showmaskbg(true);
$('#dialog_invoice_textmsg').val(WorkorderParams.InvoiceMessage);
invoicePublishDialog.css({
'top': (document.documentElement.clientHeight - invoicePublishDialog.height()) / 3,
'left': (document.documentElement.clientWidth - invoicePublishDialog.width()) / 2
}).showDialogfixed();
}
function hidePublishInvoicePopup() {
if (publish_invoice_index <= 0)
invoiceDialog.find('.maskbg').hide();
else
showmaskbg(false);
publish_invoice_index = 0;
invoicePublishDialog.hide();
}
function openPublishInvoiceDialog(index) {
if (index == -1) {
publish_invoice_index = index;
showPublishInvoicePopup();
}
else {
onSaveWorkOrderInvoice(index, function () {
publish_invoice_index = index;
showPublishInvoicePopup();
});
}
}
function onPublishInvoice() {
var changed = $('#tabinvoice' + publish_invoice_index).data('changed');
if (publish_invoice_index === -1)//add and publish
changed = true;
if (changed)
onSaveWorkOrderInvoice(publish_invoice_index === -1 ? "" : publish_invoice_index, PublishInvoice)
else
PublishInvoice(publish_invoice_index);
}
function PublishInvoice(index, invoiceid) {
if (index !== "") {
var invoice = $('#tabinvoice' + index).data('invoice');
invoiceid = invoice.Id;
}
if (!invoiceid)
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([invoiceid, _this.option.workorderid, JSON.stringify(pmemails), msg, (includeStatusLink ? "1" : "0")]);
param = htmlencode(param);
worequest("PublishInvoiceToCustomer", param, function (data) {
if (data !== "") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
getInvoices();
hidePublishInvoicePopup();
}, function (err) {
showAlert(GetTextByKey("P_WO_FAILED_PUBLISH_INVOICE", 'Failed to publish this invoice.'), GetTextByKey("P_WO_PUBLISH_INVOICE", 'Publish Invoice'));
});
}
function SaveInvoiceAttachmentFiles(filedatas, invoiceid, index) {
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([invoiceid, 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 (index) {
hideWOInvoiceAttachmentPopup();
getInvoiceAttachment(index);
}
else
getInvoices();
}
},
error: function (err) {
showAlert(err.statusText, GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File'));
}
});
}
function getInvoiceAttachment(index) {
var invoice = $('#tabinvoice' + index).data('invoice');
if (!invoice)
return;
$('#tab_invoice_atts' + index).empty();
$('#tab_invoice_attachments' + index).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(index, data);
}
}, function (err) {
});
}
function showInvoiceAttachment(index, atts) {
var candelete = false;
if (!atts) {
var invoice = $('#tabinvoice' + index).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' + index).empty();
$('#tab_invoice_attachments' + index).hide();
if (atts && atts.length > 0) {
$('#tab_invoice_attachments' + index).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 = $('').data('index', index).click(function () {
deleteInvoiceAttachment(this.parentElement.parentElement.id, $(this).data('index'));
});
tdimg.append(imgDom);
tr.append(tdimg);
}
tr.append(tdfile).appendTo($('#tab_invoice_atts' + index));
}
}
}
function deleteInvoiceAttachment(attid, index) {
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(index);
}
}, function (err) { });
}
}
function hideWOInvoiceAttachmentPopup() {
if (cur_invoice_uploadindex == '')
invoiceDialog.find('.maskbg').hide();
else
showmaskbg(false);
invoiceAttachmentDialog.hide();
}
function openWOInvoiceAttachmentDialog(index) {
cur_invoice_uploaddata = undefined;
cur_invoice_uploadindex = index;
if (index == '')
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 invoice = $('#tabinvoice' + cur_invoice_uploadindex).data('invoice');
var notes = $('#dialog_invoice_att_notes').val();
cur_invoice_uploaddata.Notes = notes;
if (!invoice) {
add_invoice_filedatas.push(cur_invoice_uploaddata);
createAddInvoiceAttachment(cur_invoice_uploaddata);
hideWOInvoiceAttachmentPopup();
$('#btn_woinvoice_att_save').attr('disabled', false);
}
else {
SaveInvoiceAttachmentFiles([cur_invoice_uploaddata], invoice.Id, cur_invoice_uploadindex);
}
}
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(index) {
cur_invoice_uploadindex = index;
$('#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_uploadindex).data('changed');
if (changed)
onSaveWorkOrderInvoice(cur_invoice_uploadindex, MarkAsPaid)
else
MarkAsPaid();
}
function MarkAsPaid() {
var invoice = $('#tabinvoice' + cur_invoice_uploadindex).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();
}
}, 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_XXX", 'Mark as Customer Visible'),
func: fcancel
}, {
value: GetTextByKey("P_WO_XXX", '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;
GetSegmentDataSource(getSegments);
//}
}
this.close = function () {
segmentDialog?.remove();
}
this.loadsource = function () {
GetSegmentDataSource();
}
this.setwodata = function (wodata) {
this.option.workorderdata = wodata;
}
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);
}
this.createSegment(this.option.parent);
var segmentDialog = createSegmentDialog();
function createSegmentDialog() {
var dialog = $('');
dialog.append('
');
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);
});
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(index) {
var date = $('#dialog_segmentcompleteddate' + index).val();
if (date.length > 0 && checkDate(date)) {
$('#dialog_segmentcompleted' + index).prop('checked', true);
}
}
var segmentdata = [];
function initControl(index) {
$('#dialog_segmentcompleteddate' + index).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' + index).dropdown(userdata || [], {
search: true,
valueKey: 'IID',
textKey: 'DisplayName'
});
$("#dialog_segmentjobsite" + index).dropdown(jobsitedata || [], {
search: true,
valueKey: 'ID',
textKey: 'Name'
});
$("#dialog_segmenttype" + index).dropdown(segmenttypes || [], {
input: true,
maxlength: 50,
textKey: 'value'
});
$("#dialog_segmentcomponent" + index).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;
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 div_segments = _this.option.parent;
var table = $('');
table.data('index', segmentindex);
var tr1 = $('
');
var tr1_td1 = $('' + GetTextByKey("P_WO_SEGMENT", "Segment") + " " + segmentindex + ' | "');
if (!WOReadOnly) {
var s_del = $('');
s_del.on('click', segmentindex, 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", segmentindex, 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_XXXXXX_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_XXXXXX_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', segmentindex, function (e) {
SaveSegment(e.data);
})
var input_cancel = $('').val(GetTextByKey("P_WO_CANCEL", "Cancel"));
input_cancel.on('click', segmentindex, function (e) {
CancelSegment(e.data);
});
td1.append(input_save).append(input_cancel);
tr.append(td1);
table.append(tr);
}
div_segments.append(table);
initControl(segmentindex);
$('#tabsegment_' + segmentindex).data('segment', segment);
$('#dialog_segmentuser' + segmentindex).dropdownVal(segment.UserIID);
$('#dialog_segmentdesc' + segmentindex).val(segment.Description);
$('#dialog_segmenthour' + segmentindex).val(segment.Hours === 0 ? "" : segment.Hours);
$('#dialog_segmentnotes' + segmentindex).val(segment.Notes);
$('#dialog_segmentjobsite' + segmentindex).dropdownVal(segment.JobsiteID);
$('#dialog_segmentcost' + segmentindex).val(segment.Cost === 0 ? "" : segment.Cost);
$('#dialog_segmenttype' + segmentindex).dropdownVal(segment.SegmentType);
$('#dialog_segmentcompleted' + segmentindex).prop('checked', segment.Completed);
$('#dialog_segmentcompleteddate' + segmentindex).val(segment.CompletedDateStr);
$('#dialog_segmentcomponent' + segmentindex).dropdownVal(segment.Component);
$('#dialog_segmentbillable' + segmentindex).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(index) {
var segment = $('#tabsegment_' + index).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(index) {
var segment = $('#tabsegment_' + index).data('segment');
if (!segment)
return;
$('#dialog_segmentuser' + index).dropdownVal(segment.UserIID);
$('#dialog_segmentdesc' + index).val(segment.Description);
$('#dialog_segmenthour' + index).val(segment.Hours);
$('#dialog_segmentnotes' + index).val(segment.Notes);
$('#dialog_segmentjobsite' + index).dropdownVal(segment.JobsiteID);
$('#dialog_segmentcost' + index).val(segment.Cost);
$('#dialog_segmentcompleted' + index).prop('checked', segment.Completed);
$('#dialog_segmentcompleteddate' + index).val(segment.CompletedDateStr);
$('#dialog_segmenttype' + index).dropdownVal(segment.SegmentType);
$('#dialog_segmentcomponent' + index).dropdownVal(segment.Component);
$('#dialog_segmentbillable' + index).prop('checked', segment.Billable);
}
function SaveSegment(index) {
$('#btn_savesegment' + index).attr('disabled', true);
var segmentid = -1;
var alerttitle = GetTextByKey("P_WO_ADDSEGMENT", "Add Segment");
if (index !== "") {
var alerttitle = GetTextByKey("P_WO_EDITSEGMENT", "Edit Segment");
var segment = $('#tabsegment_' + index).data('segment');
if (!segment)
return;
segmentid = segment.SegmentID;
}
var item = {
'SegmentID': segmentid,
'WorkOrderID': _this.option.workorderid,
'UserIID': $('#dialog_segmentuser' + index).dropdownVal(),
'Description': $('#dialog_segmentdesc' + index).val(),
'Hours': $('#dialog_segmenthour' + index).val(),
'Notes': $('#dialog_segmentnotes' + index).val(),
'JobsiteID': $('#dialog_segmentjobsite' + index).dropdownVal(),
'Cost': $('#dialog_segmentcost' + index).val(),
'Completed': $('#dialog_segmentcompleted' + index).prop('checked'),
'CompletedDate': $('#dialog_segmentcompleteddate' + index).val(),
'SegmentType': $('#dialog_segmenttype' + index).dropdownVal(),
'Component': $('#dialog_segmentcomponent' + index).dropdownVal(),
'Billable': $('#dialog_segmentbillable' + index).prop('checked')
};
if (item.Description === "" || item.Description.length == 0) {
showAlert(GetTextByKey("P_WO_DESCRIPTIONREQUIRED", 'Description is required.'), alerttitle);
$('#btn_savesegment' + index).attr('disabled', false);
return;
}
if (item.Hours !== "") {
if (isNaN(item.Hours)) {
showAlert(GetTextByKey("P_WO_HOURSFORMATERROR", 'Hours format error.'), alerttitle);
$('#btn_savesegment' + index).attr('disabled', false);
return;
}
else {
if (item.Hours <= 0) {
showAlert(GetTextByKey("P_WO_HOURSMUSTBEGREATERTHAN0", 'Hours must be greater than 0.'), alerttitle);
$('#btn_savesegment' + index).attr('disabled', false);
return;
}
}
}
if (item.Cost !== "") {
if (isNaN(item.Cost)) {
showAlert(GetTextByKey("P_WO_COSTFORMATERROR", 'Cost format error.'), alerttitle);
$('#btn_savesegment' + index).attr('disabled', false);
return;
}
else {
if (item.Cost <= 0) {
showAlert(GetTextByKey("P_WO_COSTMUSTBEGREATERTHAN0", 'Cost must be greater than 0.'), alerttitle);
$('#btn_savesegment' + index).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' + index).attr('disabled', false);
showAlert(data, alerttitle);
} else {
$('#btn_savesegment' + index).attr('disabled', false);
if (index !== "") {
showAlert(GetTextByKey("P_WO_SAVSUCCESSFULLY", "Saved successfully."), alerttitle);
}
GetSegmentDataSource1(function () {
if (typeof getTotalCost == 'function')
getSegments(getTotalCost);
else
getSegments();
});
hidePopup();
}
}, function (err) {
$('#btn_savesegment' + index).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;
getAlerts();
//}
}
this.close = function () {
}
this.changeasset = function (aid) {
this.option.machineid = aid;
}
this.getalertids = function () {
return alertids;
}
this.createAlert = function (p_div) {
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 = $('');
span_addpmalerts = $('Add PM Alerts (Alerts not yet triggered)');
span_addpmalerts.click(OnAddAllPMSchedules);
divpmaalerts_title.append('PM Alerts');
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);
}
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) {
r["EngineHoursObj"] = { DisplayValue: r["EngineHours"] == 0 ? "" : r["EngineHours"], Value: r["EngineHours"] };
r["AlertLocalTime"] = { DisplayValue: r["AlertLocalTimeStr"], Value: r["AlertLocalTime"] };
}
var fr = { Values: r };
rows.push(fr);
}
grid_dt.setData(rows);
}
var grid_dtcalertdt;
function InitDTCAlertGridData() {
grid_dtcalertdt = new GridView('#dtcalertslist');
grid_dtcalertdt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
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' } }
];
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_dtcalertdt.canMultiSelect = false;
grid_dtcalertdt.columns = columns;
grid_dtcalertdt.init();
grid_dtcalertdt.selectedrowchanged = function (rowindex) {
var rowdata = grid_dtcalertdt.source[rowindex];
if (rowdata) {
}
}
}
var grid_pmaalertdt;
function InitPMAAlertGridData() {
grid_pmaalertdt = new GridView('#pmaalertslist');
grid_pmaalertdt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
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' } }
];
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_pmaalertdt.canMultiSelect = false;
grid_pmaalertdt.columns = columns;
grid_pmaalertdt.init();
grid_pmaalertdt.selectedrowchanged = function (rowindex) {
var rowdata = grid_pmaalertdt.source[rowindex];
if (rowdata) {
}
}
}
var grid_inspectalertdt;
function InitInspectAlertGridData() {
grid_inspectalertdt = new GridView('#inspectalertslist');
grid_inspectalertdt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
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' } }
];
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_inspectalertdt.canMultiSelect = false;
grid_inspectalertdt.columns = columns;
grid_inspectalertdt.init();
grid_inspectalertdt.selectedrowchanged = function (rowindex) {
var rowdata = grid_inspectalertdt.source[rowindex];
if (rowdata) {
}
}
}
var grid_oilalertdt;
function InitOilAlertGridData() {
grid_oilalertdt = new GridView('#oilalertslist');
grid_oilalertdt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
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' } }
];
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_oilalertdt.canMultiSelect = false;
grid_oilalertdt.columns = columns;
grid_oilalertdt.init();
grid_oilalertdt.selectedrowchanged = function (rowindex) {
var rowdata = grid_oilalertdt.source[rowindex];
if (rowdata) {
}
}
}
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);
return dialog;
}
var grid_noneassignedalertdt;
function InitNoneAssignedAlertGridData(pdiv) {
grid_noneassignedalertdt = new GridView(pdiv);
grid_noneassignedalertdt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
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: 'AlertTime', 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.canMultiSelect = false;
grid_noneassignedalertdt.columns = columns;
grid_noneassignedalertdt.init();
grid_noneassignedalertdt.selectedrowchanged = function (rowindex) {
var rowdata = grid_noneassignedalertdt.source[rowindex];
if (rowdata) {
}
}
}
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] };
}
var fr = { Values: r };
rows.push(fr);
}
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 = [];
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);
return dialog;
}
function showAllPMSchedules(data) {
var rows = [];
for (var i = 0; i < data.length; i++) {
var r = data[i];
for (var j in r) {
}
var fr = { Values: r };
rows.push(fr);
}
grid_pmschedulesdt.setData(rows);
}
var grid_pmschedulesdt;
function InitAllPMSchedulesGridData(pdiv) {
grid_pmschedulesdt = new GridView(pdiv);
grid_pmschedulesdt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
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.canMultiSelect = false;
grid_pmschedulesdt.columns = columns;
grid_pmschedulesdt.init();
grid_pmschedulesdt.selectedrowchanged = function (rowindex) {
var rowdata = grid_pmschedulesdt.source[rowindex];
if (rowdata) {
}
}
}
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 attupload_ul;
viewtype = getCookie("woattachmentviewtype");
this.refresh = function () {
getWorkOrderAttachments();
}
this.changewo = function (woid, aid) {
//if (woid !== option.workorderid) {
this.option.workorderid = woid;
if (aid)
this.option.machineid = aid;
getWorkOrderAttachments();
//}
}
this.close = function () {
dialog_panddattachments?.remove();
}
this.createAttachment = function (p_div) {
var div_ftitle = $('');
p_div.append(div_ftitle);
var span_add = $('Add File');
span_add.click(UpLoadWorkOrderAttachment);
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);
}
var span_view = $('View
');
div_ftitle.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': 35
}).show().animate({ 'opacity': 1 }, 100);
$('.panel_holder.attviewtypemenus .trigledown').css({
'left': 50,
'right': 'auto',
'top': -20
});
return false;
});
//View Menu
var div_viewmenu = $('');
span_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);
td_wolist.append('');
td_wolist.append('Work Order Attachments');
td_wolist.append('');
tr_wolist = $('
');
tb_wolist.append(tr_wolist);
td_wolist = $(' | ');
tr_wolist.append(td_wolist);
var tab_woattslist = $('');
td_wolist.append(tab_woattslist);
tab_woattslist.append(' | | Caption | | |
');
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);
tab_assetattslist.append(' | | Caption | | |
---|
>
');
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);
tab_ispattslist.append(' | | Caption | | |
');
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('');
}
this.createAttachment(this.option.parent);
var dialog_panddattachments = createPAndDAttachmentDialog();
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);
func.append('');
dialog.append('');
$(document.body).append(dialog);
dialog.dialog(function () {
showmaskbg(false);
});
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 () {
showLoading();
$('.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();
$('.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();
hideLoading();
if (fileupload_errors !== "")
showAlert(fileupload_errors, GetTextByKey("P_WO_XXXXX", 'Upload failed'));
return;
}
var file = filesinuploading[uploadingindex];
if (file.name.length > 200) {
showUploadingStatus(2, GetTextByKey("P_WO_XXX", "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([_this.option.workorderid, ""]);
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_XXXXX", 'Upload failed'), GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File'));
}
showUploadingStatus(1);
DoUploadWorkOrderAttachments(woid);
},
error: function (err) {
showUploadingStatus(2, GetTextByKey("P_WO_XXXXX", '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) {
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 {
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() {
div_woatts.empty();
div_aatts.empty();
div_iatts.empty();
woattslist_tbody.empty();
woassetattslist_tbody.empty();
woiptattslist_tbody.empty();
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() {
div_woatts.empty();
div_aatts.empty();
div_iatts.empty();
woattslist_tbody.empty();
woassetattslist_tbody.empty();
woiptattslist_tbody.empty();
if (inloading)
return;
inloading = true;
if (typeof _this.option.showloading == 'function')
_this.option.showloading(true);
if (_this.option.workorderid) {
worequest('GetAttachments', JSON.stringify([_this.option.workorderid, _this.option.machineid]), function (data) {
inloading = false;
if (typeof _this.option.showloading == 'function')
_this.option.showloading(false);
if (data && typeof data != "string") {
if (data.WorkOrderID != _this.option.workorderid) {
getWorkOrderAttachments();
return;
}
data = data.Data;
allAttachments = data;
showWOAttachments(allAttachments);
}
}, function () {
inloading = false;
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) {
div_woatts.empty();
div_aatts.empty();
div_iatts.empty();
if (attas.AssetAttachments && attas.AssetAttachments.length > 0) {
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);
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);
});
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);
}
div_aatts.append(div);
}
}
if (attas.WorkOrderAttachments && attas.WorkOrderAttachments.length > 0) {
for (var i = 0; i < attas.WorkOrderAttachments.length; i++) {
var att = attas.WorkOrderAttachments[i];
var pdiv = $('');
var div = createAttaDiv(att, true);
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'));
});
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);
});
div.append(sdel);
}
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);
});
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);
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);
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);
div_woatts.append(pdiv);
}
}
if (attas.InspectionAttachments && attas.InspectionAttachments.length > 0) {
for (var i = 0; i < attas.InspectionAttachments.length; i++) {
var att = attas.InspectionAttachments[i];
var div = createAttaDiv(att);
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);
});
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);
div_iatts.append(div);
}
}
}
function createAttaDiv(att, iswoatta) {
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 pic = $('
').attr('src', att.ThumbnailUrl);
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) {
});
}
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.allowHtml = true;
col.filterCustom = true;
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.canMultiSelect = 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();
}
if (type == 0) {
btn_print.show();
btn_download.hide();
}
else {
btn_print.hide();
btn_download.show();
}
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;
if (type == 1 || $.inArray(att.FileType.toLowerCase(), printTypes) >= 0) {
var fr = {
Values: {
FileName: att.Notes === "" ? att.FileName : att.Notes,
FileType: att.FileType,
Url: att.Url,
ThumbnailUrl: att.ThumbnailUrl,
AttachmentType: att.AttachmentType,
AttachmentIdStr: att.AttachmentIdStr,
Selected: false,
}
};
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);
});
}
function getSelectedPAndDAttas() {
var sels = [];
if (grid_panddattachments && grid_panddattachments.source) {
for (var i = 0; i < grid_panddattachments.source.length; i++) {
var a = grid_panddattachments.source[i].Values;
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);
}
}
}
showmaskbg(false);
dialog_panddattachments.hideDialog();
}
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");
}
}
showmaskbg(false);
dialog_panddattachments.hideDialog();
}
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_XXX", 'Update Caption'));
}
else {
if (edata.div)
edata.div.attr('title', caption);
edata.iptcaption.data('caption', caption);
}
}, function (err) {
});
}
//***********************************Begin Attachment List************************************//
function showAttachmentList(data) {
woattslist_tbody.empty();
woassetattslist_tbody.empty();
woiptattslist_tbody.empty();
if (data.WorkOrderAttachments && data.WorkOrderAttachments.length > 0) {
for (var i = 0; i < data.WorkOrderAttachments.length; i++) {
var att = data.WorkOrderAttachments[i];
var tr = createWOAttachmentTr(att);
woattslist_tbody.append(tr);
}
}
if (data.AssetAttachments && data.AssetAttachments.length > 0) {
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);
woassetattslist_tbody.append(tr);
}
}
if (data.InspectionAttachments && data.InspectionAttachments.length > 0) {
for (var i = 0; i < data.InspectionAttachments.length; i++) {
var att = data.InspectionAttachments[i];
var tr = createWOOtherAttachmentTr(att);
woiptattslist_tbody.append(tr);
}
}
}
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);
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 = $(' | ');
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);
});
td.append(sdel);
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) {
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 = $(' | ').text(att.FileName);
tr.append(td);
tr.append(' | ');
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;
}
//***********************************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*********************************************/
/*****************************************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({
autoUpdates: false,
readonly: WOReadOnly || COMMReadOnly,
recordReadonly: !AllowCustomer || WOReadOnly || CRReadOnly,
onMasking: window.parent.onmaskbg,
onAddMessage: function () {
var customer = _this.customer;
var pmemails = customer?.contacts;
if (pmemails == null || pmemails.length === 0) {
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) == "") {
showAlert(GetTextByKey("P_WO_PLEASEINPUTTHEMESSAGE", "Please input the message."), GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
var includeStatusLink = customer?.statusLink;
var param = JSON.stringify([option.workorderid, JSON.stringify(pmemails), comm, (includeStatusLink ? "1" : "0")]);
param = htmlencode(param);
option.showloading(true);
worequest("AddWorkOrderCommunication", param, function (data) {
option.showloading(false);
if (data !== "") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
customer.text = '';
//setTimeout(function () { _this.getCommunications() }, 400);
}, function () {
option.showloading(false);
});
},
onSave: function (item, add) {
var contact;
if (!add) {
contact = _this.customercontacts.filter(function (f) { return f.Id < 0 ? f.Name === item.Name && f.MobilePhone === item.MobilePhone : 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.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({
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;
}
var param = JSON.stringify([option.workorderid, comment]);
param = htmlencode(param);
option.showloading(true);
worequest("AddWorkOrderComment", param, function (data) {
option.showloading(false);
if (data !== "") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
_this.internal.text = '';
$('#commentsinputcount').text("0/" + $('#dialog_comments').attr("maxlength"));
//setTimeout(function () { _this.getComments() }, 400);
}, function () {
option.showloading(false);
});
}
});
option.parent.append(this.internal.create());
};
}
/*****************************************End Internal Communcation*********************************************/