2023-04-28 12:22:26 +08:00

3558 lines
145 KiB
JavaScript

$(function () {
InitGridData();
InitWorkOrderFollowerGridData();
InitAllFollowerGridData();
getWorkOrderCollapsed();
$('#dialog_customercontact').dialog(function () {
showmaskbg(false);
});
$('#dialog_estimate').dialog(function () {
showmaskbg(false);
});
$('#dialog_invoice').dialog(function () {
showmaskbg(false);
});
$('#dialog_panddattachments').dialog(function () {
showmaskbg(false);
});
$('#addfollowerpopupdialog').dialog(function () {
showmaskbg(false);
});
$('#selfollower_search').bind('input propertychange', function () {
searchFollower(false);
});
$('#selfollower_search').keydown(function () {
searchFollower(false);
});
});
/*************************Customer********************************/
var customerid;
var grid_dtcustomer;
function InitGridCustomers() {
grid_dtcustomer = new GridView('#customerlist');
grid_dtcustomer.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
var list_columns = [
{ name: 'Code', caption: GetTextByKey("P_CR_CODE", "Code"), valueIndex: 'Code', css: { 'width': 120, 'text-align': 'left' } },
{ name: 'Name', caption: GetTextByKey("P_CR_COMPANYNAME", "Company Name"), valueIndex: 'Name', css: { 'width': 200, 'text-align': 'left' } },
{ name: 'Address', caption: GetTextByKey("P_CR_ADDRESS", "Address"), valueIndex: 'Address', css: { 'width': 150, 'text-align': 'left' } },
{ name: 'Notes', caption: GetTextByKey("P_CR_NOTES", "Notes"), valueIndex: 'Notes', css: { 'width': 200, 'text-align': 'left' } }
];
var columns = [];
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.width = list_columns[hd].css.width;
col.align = list_columns[hd].css["text-align"]
col.key = list_columns[hd].valueIndex;
columns.push(col);
}
grid_dtcustomer.canMultiSelect = true;
grid_dtcustomer.columns = columns;
grid_dtcustomer.init();
grid_dtcustomer.rowdblclick = function (rowindex) {
var rowdata = grid_dtcustomer.source[rowindex];
if (rowdata) {
//setCustomerData(rowdata.Values);
OnSetSelectCustomer();
}
};
//grid_dtcustomer.selectedrowchanged = function (rowindex) {
// var rowdata = grid_dtcustomer.source[rowindex];
// if (rowdata) {
// }
//}
}
function showCustomerList(data) {
var rows = [];
for (var i = 0; i < data.length; i++) {
var r = data[i];
var fr = { Values: r };
rows.push(fr);
}
grid_dtcustomer.setData(rows);
}
function onSelectCustomer() {
grid_dtcustomer.setData([]);
$('#txt_customer_key').val('');
$('#txt_customer_key').attr('disabled', true);
$('#chkshowallcust').attr('checked', false);
$('#dialog_customer .dialog-title span.title').text(GetTextByKey("P_WO_SELECTCUSTOMER", 'Select Customer'));
$('#mask_bg').show();
$('#dialog_customer')
.attr('act', 'edit')
.css({
'top': (document.documentElement.clientHeight - $('#dialog_customer').height()) / 3,
'left': (document.documentElement.clientWidth - $('#dialog_customer').width()) / 2
})
.showDialog();
GetCustomerList();
}
var allcustomers;
function GetCustomerList() {
grid_dtcustomer.setData([]);
var chk = $('#chkshowallcust').prop('checked');
if (chk) {
$('#txt_customer_key').attr('disabled', false);
getAllCustomer();
} else {
$('#txt_customer_key').attr('disabled', true);
$('#txt_customer_key').val('');
getAssetCustomer();
}
}
function getAllCustomer() {
if (allcustomers)
getMatchCustomers();
else {
customerquery('GetPartners', '', function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
showmaskbg(false);
return;
}
allcustomers = data;
getMatchCustomers();
}, function (err) {
});
}
}
function getAssetCustomer() {
if (!machineid)
return;
customerquery('GetAssignedPartnersByMachine', machineid, function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
showmaskbg(false);
return;
}
showCustomerList(data);
}, function (err) {
});
}
function getMatchCustomers() {
var filter = $('#txt_customer_key').val().toLowerCase();
var _availablecustomers = [];
if (allcustomers) {
for (var i = 0; i < allcustomers.length; i++) {
var m = allcustomers[i];
if (filter == "" || m.Code.toLowerCase().indexOf(filter) >= 0 || m.Name.toLowerCase().indexOf(filter) >= 0) {
_availablecustomers.push(m);
}
}
}
showCustomerList(_availablecustomers);
}
function onCustomerKeyPress(e) {
if (e.keyCode === 13) {
GetCustomerList();
}
};
function OnSetSelectCustomer() {
var index = grid_dtcustomer.selectedIndex;
if (index < 0) {
showAlert(GetTextByKey("P_WO_PLEASESELECTACUSTOMER", "Please select a customer."), GetTextByKey("P_WO_SELECTCUSTOMER", "Select Customer")); return;
}
var cust = grid_dtcustomer.source[index].Values;
setCustomerData(cust);
}
function setCustomerData(cust) {
customerid = cust.Id;
$('#dialog_salesperson').dropdownVal(cust.SalespersonIID);
$('#dialog_custcustomername').text(cust.Name);
$('#dialog_custcustomercode').text(cust.Code);
if (typeof customer !== 'undefined') {
customer.companyName = cust.Name;
customer.companyCode = cust.Code;
customer.setData('companyCode', cust.Code);
}
getCustomerContacts(cust.Id);
getCustomerFollowers(cust.Id);
$('#dialog_customer').hideDialog();
showmaskbg(false);
}
function OnAddCustomer() {
execIframeFunc("init", [null, machineid], "iframeuser");
$('#contatcmask').show();
$('#dialog_addcustomer')
.showDialogRight();
}
function CloseCustomerDialog(type) {
$('#dialog_addcustomer').hideDialog();
allcustomers = null;
GetCustomerList();
$('#contatcmask').hide();
}
/************************* Customer********************************/
//*************************Contact********************************//
var contact;
var grid_dtcontact;
function InitGridData() {
grid_dtcontact = new GridView('#cusomercontactlist');
grid_dtcontact.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
var list_columns = [
{ name: 'Name', caption: GetTextByKey("P_CR_CONTACTNAME", "Contact Name"), valueIndex: 'Name', css: { 'width': 150, 'text-align': 'left' } },
{ name: 'ContactEmail', caption: GetTextByKey("P_CR_CONTACTEMAIL", "Contact Email"), valueIndex: 'Email', css: { 'width': 130, 'text-align': 'left' } },
{ name: 'ContactMobilePhone', caption: GetTextByKey("P_CR_CONTACTMOBILE", "Contact Mobile"), valueIndex: 'MobilePhoneDisplayText', css: { 'width': 120, 'text-align': 'left' } },
{ name: 'ContactPreferenceStr', caption: GetTextByKey("P_CR_CONTACTPREFERENCES", "Contact Preferences"), valueIndex: 'ContactPreferenceStr', css: { 'width': 100, 'text-align': 'left' } },
{ name: 'OptOut', caption: GetTextByKey("P_CR_OPTOUT", "Opt Out"), valueIndex: 'OptOut', type: 3, css: { 'width': 60, 'text-align': 'center' } },
{ name: 'Notes', caption: GetTextByKey("P_CR_NOTES", "Notes"), valueIndex: 'Notes', css: { 'width': 150, 'text-align': 'left' } },
{ name: 'Edit', caption: "", css: { 'width': 30, 'text-align': 'center' } },
{ name: 'Delete', caption: "", css: { 'width': 30, 'text-align': 'center' } }
];
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.width = list_columns[hd].css.width;
col.align = list_columns[hd].css["text-align"]
col.key = list_columns[hd].valueIndex;
col.allowFilter = list_columns[hd].allowFilter;
if (list_columns[hd].type) {
col.type = list_columns[hd].type;
}
if (CRReadOnly && (col.name === "Edit" || col.name === "Delete")) {
continue;
}
if (col.name === "Edit") {
col.isurl = true;
col.text = "\uf044";
col.sortable = false;
col.events = {
onclick: function () {
onEditContact();
}
};
col.styleFilter = function (e) {
if (!IsAdmin && workorderdata && workorderdata.Completed) {
return {
display: 'none'
};
}
}
col.classFilter = function (e) {
return "icon-col";
}
col.attrs = { 'title': GetTextByKey("P_UM_EDIT", 'Edit') };
}
else if (col.name === "Delete") {
col.isurl = true;
col.text = "\uf00d";
col.sortable = false;
col.events = {
onclick: function () {
onDeleteContact(this);
}
};
col.styleFilter = function (e) {
if (!IsAdmin && workorderdata && workorderdata.Completed) {
return {
display: 'none'
};
}
}
col.classFilter = function (e) {
return "icon-col";
};
col.attrs = { 'title': GetTextByKey("P_UM_DELETE", 'Delete') };
}
else if (col.name === "OptOut") {
col.enabled = !CRReadOnly;
col.events = {
onchange: function () {
if (typeof customer !== 'undefined') {
customer.contacts = customercontacts;
}
SaveWorkorderContact();
}
};
}
columns.push(col);
}
grid_dtcontact.canMultiSelect = false;
grid_dtcontact.columns = columns;
grid_dtcontact.init();
if (!CRReadOnly)
grid_dtcontact.rowdblclick = onEditContact;
}
function getCustomerContacts(custid) {
worequest('GetCustomerContacts', custid, function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
showcontatcmask(false);
return;
}
if (customercontacts) {
for (var i = 0; i < customercontacts.length; i++) {
customercontacts[i].Id = -1;
customercontacts[i].SaveToCustomer = 0;
}
}
for (var i = 0; i < data.length; i++) {
var r = data[i];
var item = {
'Id': r.Id,
'Name': r.Name,
'ContactPreference': r.ContactPreference,
'ContactPreferenceStr': r.ContactPreferenceStr,
'Email': r.Email,
'MobilePhone': r.MobilePhone,
//'Address': r.Address,
'Notes': r.Notes,
'OptOut': r.OptOut,
'OptOut_BC': r.OptOut
};
var contactexists = false;
for (var j = 0; j < grid_dtcontact.source.length; j++) {
var ct = grid_dtcontact.source[j].Values;
if (ct.Name === item.Name && ct.MobilePhone === item.MobilePhone) {
contactexists = true;
break;
}
}
if (contactexists) {
if (customercontacts) {
for (var j = 0; j < customercontacts.length; j++) {
var ct = customercontacts[j];
if (ct.Name === item.Name && ct.MobilePhone === item.MobilePhone) {
ct.Id = item.Id;
break;
}
}
}
}
else
customercontacts.push(item);
}
SaveWorkorderContact();
showCustomerContacts(customercontacts);
}, function (err) {
});
}
function showCustomerContacts(data) {
customer?.setData('contacts', data);
var rows = [];
for (var i = 0; i < data.length; i++) {
var r = data[i];
var fr = { Values: r };
rows.push(fr);
}
grid_dtcontact.setData(rows);
setPhoneNumber();
setPhoneNumber_statuschange();
}
function onAddContact() {
contact = null;
for (var i = 0; i < grid_dtcontact.source.length; i++) {
grid_dtcontact.source[i].Values.IsCurrent = false;
}
$('#btn_contactrecord').val(GetTextByKey('P_WO_ADDCONTACTRECORD', 'Add Contact Record'));
if (AllowCustomer && customerid && customerid != -1)
$('#btn_contactrecord').show();
else
$('#btn_contactrecord').hide();
$('#dialog_contactname').val("");
$('#dialog_contactpreference').dropdownVal('0');
$('#dialog_emailaddress').val("");
$('#dialog_mobile').val("");
//$('#dialog_address').val("");
$('#dialog_optout').prop('checked', false);
$('#dialog_contactnotes').val("");
$('#dialog_customercontact .dialog-title span.title').text(GetTextByKey("P_CR_ADDCONTACT", 'Add Contact'));
$('#mask_bg').show();
$('#dialog_customercontact')
.css({
'top': (document.documentElement.clientHeight - $('#dialog_customercontact').height()) / 3,
'left': (document.documentElement.clientWidth - $('#dialog_customercontact').width()) / 2
}).showDialogfixed();
}
function onEditContact() {
var index = grid_dtcontact.selectedIndex;
if (index < 0) return;
$('#btn_contactrecord').val(GetTextByKey('P_WO_EDITCONTACTRECORD', 'Edit Contact Record'));
if (AllowCustomer && customerid && customerid != -1)
$('#btn_contactrecord').show();
else
$('#btn_contactrecord').hide();
for (var i = 0; i < grid_dtcontact.source.length; i++) {
if (index == i) {
grid_dtcontact.source[index].Values.IsCurrent = true;
contact = grid_dtcontact.source[index].Values;
} else
grid_dtcontact.source[i].Values.IsCurrent = false;
}
$('#dialog_contactname').val(contact.Name);
$('#dialog_contactpreference').dropdownVal(contact.ContactPreference);
$('#dialog_emailaddress').val(contact.Email);
$('#dialog_mobile').val(contact.MobilePhone);
//$('#dialog_address').val(contact.Address);
$('#dialog_optout').prop('checked', contact.OptOut);
$('#dialog_contactnotes').val(contact.Notes);
$('#dialog_customercontact .dialog-title span.title').text(GetTextByKey("P_CR_EDITCONTACT", 'Edit Contact'));
$('#mask_bg').show();
$('#dialog_customercontact')
.css({
'top': (document.documentElement.clientHeight - $('#dialog_customercontact').height()) / 3,
'left': (document.documentElement.clientWidth - $('#dialog_customercontact').width()) / 2
}).showDialogfixed();
}
function onSaveContact(type) {//0.work order only;1.contact record
var item = {
'Name': $.trim($('#dialog_contactname').val()),
'ContactPreference': $.trim($('#dialog_contactpreference').dropdownVal()),
'ContactPreferenceStr': $('#dialog_contactpreference').data('dropdown').selected.text,
'Email': $.trim($('#dialog_emailaddress').val()),
'MobilePhone': $.trim($('#dialog_mobile').val()),
//'Address': $('#dialog_address').val(),
'OptOut': $('#dialog_optout').prop('checked'),
'Notes': $.trim($('#dialog_contactnotes').val()),
'SaveToCustomer': type
};
var alerttitle;
if (contact) {
alerttitle = GetTextByKey("P_CR_EDITCONTACT", "Edit Contact");
} else {
alerttitle = GetTextByKey("P_CR_ADDCONTACT", "Add Contact");
}
if (!item.Name || item.Name.length == 0) {
showAlert(GetTextByKey("P_CR_CONTACTNAMECANNOTBEEMPTY", 'Contact Name cannot be empty.'), alerttitle, undefined, function () { $('#dialog_contactname').focus(); });
return;
}
if ((!item.Email || item.Email.length == 0) && (!item.MobilePhone || item.MobilePhone.length == 0)) {
showAlert(GetTextByKey("P_CR_EMAILANDMOBILEPHONECANNOTBOTHBEEMPTY", 'Email and Mobile Phone cannot both be empty. '), alerttitle);
return;
}
if (item.Email !== "" && !isEmail(item.Email)) {
showAlert(GetTextByKey("P_CR_EMAILISNOTAVALIDEMAILADDRESS", 'The email address is invalid.'), alerttitle);
return;
}
var contactexists = false;
for (var i = 0; i < grid_dtcontact.source.length; i++) {
var ct = grid_dtcontact.source[i].Values;
if (!ct.IsCurrent && ct.Name === item.Name && ct.MobilePhone === item.MobilePhone) {
contactexists = true;
break;
}
}
if (contactexists) {
showAlert(GetTextByKey("P_WO_CONTACTNAMEANDMOBILEUNIQUECOMBINATION", 'Contact name and contact mobile must be a unique combination.'), alerttitle);
return;
}
if (contact) {
contact.Name = $.trim($('#dialog_contactname').val());
contact.ContactPreference = $.trim($('#dialog_contactpreference').dropdownVal());
contact.Email = $.trim($('#dialog_emailaddress').val());
contact.MobilePhone = $.trim($('#dialog_mobile').val());
//contact.Address = $('#dialog_address').val();
contact.OptOut = $('#dialog_optout').prop('checked');
contact.Notes = $.trim($('#dialog_contactnotes').val());
contact.SaveToCustomer = type;
if (parseInt(contact.ContactPreference) == 0)
contact.ContactPreferenceStr = GetTextByKey("P_CR_TEXT", "Text");
else if (parseInt(contact.ContactPreference) == 1)
contact.ContactPreferenceStr = GetTextByKey("P_CR_EMAIL", "Email");
else if (parseInt(contact.ContactPreference) == 2)
contact.ContactPreferenceStr = GetTextByKey("P_CR_PHONE", "Phone");
}
else {
item.Id = -1;
customercontacts.push(item);
}
showmaskbg(false);
$('#dialog_customercontact').hideDialog();
SaveWorkorderContact(null, function (data) {
if (typeof data === "string") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
showCustomerContacts(customercontacts = data);
});
//showCustomerContacts(customercontacts);
}
function onDeleteContact(c) {
if (!c) {
return;
}
showConfirm(GetTextByKey("P_CR_DOYOUWANTTODELETETHISCONTACT", 'Do you want to delete this contact?'), GetTextByKey("P_CR_DELETECONTACT", 'Delete Contact'), function () {
var index = customercontacts.indexOf(c);
customercontacts.splice(index, 1);
SaveWorkorderContact();
showCustomerContacts(customercontacts);
});
}
function SaveWorkorderContact(data, next) {
if (!workorderid || workorderid == "")
return;
var custid = customerid;
if (!custid)
custid = -1;
var param = JSON.stringify([workorderid, custid, JSON.stringify(data ?? 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 (err) {
//showmaskbg(false);
});
}
/*************************End Contact********************************/
//*************************Follwer********************************//
var grid_dtfollower;
function InitWorkOrderFollowerGridData() {
grid_dtfollower = new GridView('#followerlist');
grid_dtfollower.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
var list_columns = [
{ name: 'Name', caption: GetTextByKey("P_CR_CONTACTNAME", "Contact Name"), valueIndex: 'Name', css: { 'width': 150, 'text-align': 'left' } },
{ name: 'ContactEmail', caption: GetTextByKey("P_CR_CONTACTEMAIL", "Contact Email"), valueIndex: 'Email', css: { 'width': 130, 'text-align': 'left' } },
{ name: 'ContactMobilePhone', caption: GetTextByKey("P_CR_CONTACTMOBILE", "Contact Mobile"), valueIndex: 'MobilePhoneDisplayText', css: { 'width': 120, 'text-align': 'left' } },
{ name: 'ContactPreferenceStr', caption: GetTextByKey("P_CR_CONTACTPREFERENCES", "Contact Preferences"), valueIndex: 'ContactPreferenceStr', css: { 'width': 100, 'text-align': 'left' } },
{ name: 'Delete', caption: "", css: { 'width': 30, 'text-align': 'center' } }
];
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.width = list_columns[hd].css.width;
col.align = list_columns[hd].css["text-align"]
col.key = list_columns[hd].valueIndex;
col.allowFilter = list_columns[hd].allowFilter;
if (list_columns[hd].type) {
col.type = list_columns[hd].type;
}
if (CRReadOnly && (col.name === "Edit" || col.name === "Delete")) {
continue;
}
if (col.name == "ContactPreferenceStr") {
col.filter = function (item) {
var text = "";
if (item.SendEmail)
text = "Email";
if (item.SendText) {
if (text == "")
text = "Text";
else
text += ", Text";
}
return text;
}
}
else if (col.name === "Delete") {
col.isurl = true;
col.text = "\uf00d";
col.sortable = false;
col.events = {
onclick: function () {
onDeleteFollower(this);
}
};
col.styleFilter = function (e) {
if (!IsAdmin && workorderdata && workorderdata.Completed) {
return {
display: 'none'
};
}
}
col.classFilter = function (e) {
return "icon-col";
};
col.attrs = { 'title': GetTextByKey("P_UM_DELETE", 'Delete') };
}
columns.push(col);
}
grid_dtfollower.canMultiSelect = false;
grid_dtfollower.columns = columns;
grid_dtfollower.init();
}
function getWorkOrderContacts(woid) {
worequest('GetWorkOrderContacts', woid, function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
showmaskbg(false);
return;
}
customercontacts = data || [];
showCustomerContacts(customercontacts);
}, function (err) {
});
}
function showWorkOrderFollowers(data) {
if (typeof customer !== 'undefined') {
customer.followers = data;
}
var rows = [];
for (var i = 0; i < data.length; i++) {
var r = data[i];
var fr = { Values: r };
rows.push(fr);
}
grid_dtfollower.setData(rows);
}
function getWorkOrderFollowers(woid) {
worequest('GetWorkOrderFollowers', woid, function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
showmaskbg(false);
return;
}
followers = data;
showWorkOrderFollowers(followers);
}, function (err) {
});
}
function getCustomerFollowers(custid) {
worequest('GetCustomerFollowers', custid, function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
showcontatcmask(false);
return;
}
for (var i = 0; i < data.length; i++) {
var fl = data[i];
var item = {};
item.Id = -1;
item.UserIID = fl.UserIID;
item.Name = fl.Name;
item.Email = fl.Email;
item.MobilePhone = fl.MobilePhone;
item.SendEmail = fl.SendEmail;
item.SendText = fl.SendText;
var followerexists = false;
for (var j = 0; j < grid_dtfollower.source.length; j++) {
var ct = grid_dtfollower.source[j].Values;
if (ct.UserIID === item.UserIID) {
followerexists = true;
break;
}
}
if (followerexists) {
if (followers) {
for (var j = 0; j < followers.length; j++) {
var ct = followers[j];
if (ct.UserIID === item.UserIID) {
ct.Id = item.Id;
break;
}
}
}
}
else
followers.push(item);
}
SaveWorkOrderFollower();
showWorkOrderFollowers(followers);
}, function (err) {
});
}
var isloadfollower = false;
var allfollowers = [];
function onAddFollower() {
$('#selfollower_search').val('').attr('placeholder', GetTextByKey('P_IPT_SEARCH', 'Search'));
if (!isloadfollower)
getAllFollowers();
else
searchFollower(true);
$('#addfollowerpopupdialog .dialog-title span.title').text(GetTextByKey("P_CR_XXXXXX", 'Add Followers'));
$('#mask_bg').show();
$('#addfollowerpopupdialog')
.css({
'top': (document.documentElement.clientHeight - $('#addfollowerpopupdialog').height()) / 3,
'left': (document.documentElement.clientWidth - $('#addfollowerpopupdialog').width()) / 2
}).showDialogfixed();
setTimeout(function () {
grid_allfollower && grid_allfollower.resize();
});
}
var grid_allfollower;
function InitAllFollowerGridData() {
grid_allfollower = new GridView('#allfollowerlist');
grid_allfollower.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
var list_columns = [
{ name: 'DisplayName', caption: GetTextByKey("P_WO_CONTACTNAME", "Contact Name"), valueIndex: 'DisplayName', css: { 'width': 240, 'text-align': 'left' } },
{ name: 'ContactTypeName', caption: GetTextByKey("P_WO_CONTACTTYPE", "Contact Type"), valueIndex: 'ContactTypeName', css: { 'width': 120, 'text-align': 'left' } },
{ name: 'Text', caption: "Text", valueIndex: 'Text', type: 3, css: { 'width': 60, 'text-align': 'center' } },
{ name: 'Email', caption: GetTextByKey("P_WO_EMAIL", "Email"), valueIndex: 'Email', type: 3, css: { 'width': 70, 'text-align': 'center' } }
];
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.width = list_columns[hd].css.width;
col.align = list_columns[hd].css["text-align"]
col.key = list_columns[hd].valueIndex;
if (list_columns[hd].type) {
col.type = list_columns[hd].type;
}
columns.push(col);
if (col.name === "Text") {
col.enabled = function (item) {
return item.Mobile != null && $.trim(item.Mobile).length > 0;
};
}
if (col.name === "Email") {
col.enabled = function (item) {
return item.ID !== '';
};
}
}
grid_allfollower.canMultiSelect = false;
grid_allfollower.columns = columns;
grid_allfollower.init();
}
function getAllFollowers(next) {
worequest('GetAllFollowers', '', function (data) {
if (typeof next === 'function') {
next(data);
} else {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
showmaskbg(false);
return;
}
isloadfollower = true;
allfollowers = data;
showAllFollower(data);
}
}, function (err) {
});
}
function showAllFollower(data) {
if (typeof customer !== 'undefined') {
customer.setData('allfollowers', data);
}
var rows = [];
for (var i = 0; i < data.length; i++) {
var r = data[i];
for (var j in r) {
var a = r[j];
}
if (!r.Text)
r.Text = false;
if (!r.Email)
r.Email = false;
var fr = { Values: r };
rows.push(fr);
}
grid_allfollower.setData(rows);
}
function searchFollower(newopen) {//newopen新打开
var filter = $('#selfollower_search').val().trim().toLowerCase();
if (isloadfollower && allfollowers) {
var emails = [];
for (var i = 0; i < allfollowers.length; i++) {
var m = allfollowers[i];
if (newopen) {
m.Text = false;
m.Email = false;
emails.push(m);
}
else {
if (!m.Text && !m.Email) {
if (m.ID.toLowerCase().indexOf(filter) >= 0 || m.DisplayName.toLowerCase().indexOf(filter) >= 0)
emails.push(m);
}
else
emails.push(m);
}
}
showAllFollower(emails);
}
}
function onSelectFollowers() {
for (var i = 0; i < grid_allfollower.source.length; i++) {
var ct = grid_allfollower.source[i].Values;
if (ct.Email || ct.Text) {
var f = {};
f.Id = -1;
f.UserIID = ct.IID;
f.Name = ct.DisplayName;
f.Email = ct.ID;
f.MobilePhone = ct.Mobile;
f.SendEmail = ct.Email;
f.SendText = ct.Text;
if (followers && followers.length > 0) {
for (var j = 0; j < followers.length; j++) {
if (followers[j].UserIID.toLowerCase() == f.UserIID.toLowerCase()) {
f.Id = followers[j].Id;
followers.splice(j, 1);
break;
}
}
}
followers.push(f);
}
}
SaveWorkOrderFollower();
showWorkOrderFollowers(followers);
showmaskbg(false);
$('#addfollowerpopupdialog').hideDialog();
}
function onDeleteFollower(c) {
if (!c) {
return;
}
showConfirm(GetTextByKey("P_CR_XXXXXX", 'Do you want to delete this follower?'), GetTextByKey("P_CR_XXXXXX", 'Delete Follower'), function () {
var index = followers.indexOf(c);
followers.splice(index, 1);
SaveWorkOrderFollower();
showWorkOrderFollowers(followers);
});
}
function SaveWorkOrderFollower(next) {
if (!workorderid || workorderid == "")
return;
var param = JSON.stringify([workorderid, JSON.stringify(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 (err) {
//showmaskbg(false);
});
}
/*************************End Follwer********************************/
/*************************Inspections********************************/
var assetworkorders;
function getWOInspectItems() {
assetworkorders = [];
if (!workorderid || workorderid == "") return;
worequest("GetWOInspectItems", JSON.stringify([workorderid, machineid]), function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
if (data && data.length > 0) {
assetworkorders = data[0].WorkOrders;
ShowWOInspects(data);
}
else {
var div = $('#divinspections');
div.empty();
div.append($('<div class="noinspection"></div>').text(GetTextByKey("P_WO_NOINSPECTION", 'No Inspection')));
}
}, function (err) {
});
}
function ShowWOInspects(inspects) {
var div = $('#divinspections');
div.empty();
for (var i = 0; i < inspects.length; i++) {
var ipt = inspects[i];
var targetid = "tbinspect_" + i;
var div_title = $('<div class="subtitle" style="position:relative;"></div>');
var spimg = $('<span class="sbutton iconchevronright" target="' + targetid + '" style="margin-left: 0; padding-right: 5px;"></span>').data('iptid', ipt.Id).click(function () {
var t = $(this);
var tid = t.attr("target");
if (t.hasClass("iconchevrondown")) {
t.removeClass("iconchevrondown").addClass("iconchevronright");
$("#" + tid).hide();
}
else {
t.removeClass("iconchevronright").addClass("iconchevrondown");
$("#" + tid).show();
var iptid = t.data("iptid");
var iframe = $("#iframe_" + iptid);
if (iframe.data("load") == 0) {
iframe.attr('src', '../Inspection/ReportForWorkOrder.aspx?rid=' + iptid);
iframe.data("load", 1);
}
}
});
var span = $('<span></span>').text(ipt.TemplateName);
div_title.append(spimg).append(span);
span = $('<span style="margin-left:80px;"></span>').text(ipt.CommitTimeLocalStr + ' by ' + ipt.CommitedByUserName);
div_title.append(span);
var ext_chk = $('<input type="checkbox" style="margin-left:80px;"/>').prop('checked', ipt.VisibleToCustomer).click(ipt, function (e) {
updateInspectVisibleToCustomer(e.data.Id, $(this).prop('checked'));
});
div_title.append(ext_chk);
span = $('<span style="margin-left:5px;"></span>').text(GetTextByKey('P_WO_VISIBLETOCUSTOMER', 'Visible To Customer'));
if (WOReadOnly)
ext_chk.prop('disabled', true);
div_title.append(span);
if (AllowReassignWorkorders) {
span = $('<span style="margin-left:80px;"></span>').text(GetTextByKey('P_WO_WORKORDERASSIGNMENT', 'Work Order Assignment'));
div_title.append(span);
var div_editableselect = $('<div style="margin-left:8px;width: 200px;display:inline-block;" class="dropdown"></div>');
div_editableselect
.attr({
'inspection-id': ipt.Id,
'old-wo-id': ipt.WorkOrderId
})
.dropdown(assetworkorders || [], {
input: true,
valueKey: 'Id',
textKey: 'WorkOrderNumber',
selected: ipt.WorkOrderNumber
}).on('select', function (_e, wo) {
console.log(1)
var et = $(_e.target);
if (wo) {
var msg1 = GetTextByKey('P_WO_AREYOUSURETHATYOUWANTTOPROCEED', 'Are you sure that you want to proceed ?');
var msg = GetTextByKey('P_WO_YOUAREREASSIGNINGTHISWORKORDER', 'You are reassigning this work order. ') + "<br/>" + msg1;
if (wo.Completed)
msg = GetTextByKey('P_WO_YOUAREREASSIGNINGTHISWORKORDERTOACLOSEDWORKORDER', 'You are reassigning this Work Order to a CLOSED Work Order.') + "<br/>" + msg1;
showConfirm(msg, GetTextByKey("P_WO_WORKORDERASSIGNMENT", 'Work Order Assignment'), function () {
updateInspectionWorkOrder(et.attr('inspection-id'), wo.Id);
}, function () {
et.dropdownVal(et.attr('old-wo-id'));
});
}
});
div_title.append(div_editableselect);
}
div_title.append('<hr />');
div.append(div_title);
var tab = $('<table style="display: none;width:100%;height:100%;" id="' + targetid + '"></table>');
tr = $("<tr></tr>");
td = $('<td></td>');
var iframe = $('<iframe style="width: 100%; height: 100%; display: block; border: none;"></iframe>').attr("id", "iframe_" + ipt.Id).data("load", 0);
td.append(iframe);
tr.append(td);
tab.append(tr);
div.append(tab);
}
}
function updateInspectionWorkOrder(id, woid) {
var p = JSON.stringify([id, woid, workorderid]);
worequest("UpdateInspectionWorkOrder", htmlencode(p), function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey("P_WO_WORKORDERASSIGNMENT", 'Work Order Assignment'));
return;
}
getWOInspectItems();
getAlerts();
getWorkOrderAttachments();
}, function (err) {
});
}
function updateInspectVisibleToCustomer(id, chk) {
var item = [id, chk];
var param = JSON.stringify(item);
param = htmlencode(param);
worequest('UpdateInspectionVisibleToCustomer', param, function (data) {
if (data !== 'OK') {
showAlert(data, GetTextByKey("P_WO_AVAILABLETOCUSTOMER", 'Available to Customer'));
}
}, function (err) {
});
}
/*************************End Inspections********************************/
function getWorkOrderCollapsed() {
worequest("GetWorkOrderCollapsed", '', function (data) {
if (typeof (data) === "string") {
return;
}
if (data) {
for (var i = 0; i < data.length; i++) {
var item = data[i];
if (item.Value == "1" && $("#span" + item.Key).is(":visible")) {
$("#span" + item.Key).removeClass("iconchevronright").addClass("iconchevrondown");
$("#tb" + item.Key).show();
if ("customer" == item.Key)
grid_dtcontact && grid_dtcontact.resize();
else if ("follower" == item.Key)
grid_dtfollower && grid_dtfollower.resize();
}
else {
$("#span" + item.Key).removeClass("iconchevrondown").addClass("iconchevronright");
$("#tb" + item.Key).hide();
}
if (!AllowCustomer && item.Key === "customer") {
$("#tb" + item.Key).hide();
}
}
}
}, function (err) {
});
}
function saveWorkOrderCollapsed() {
var items = [];
items.push({ 'Key': 'asset', 'Value': $("#spanasset").hasClass('iconchevrondown') ? "1" : "0" });
items.push({ 'Key': 'customer', 'Value': $("#spancustomer").hasClass('iconchevrondown') ? "1" : "0" });
items.push({ 'Key': 'follower', 'Value': $("#spanfollower").hasClass('iconchevrondown') ? "1" : "0" });
items.push({ 'Key': 'summary', 'Value': $("#spansummary").hasClass('iconchevrondown') ? "1" : "0" });
items.push({ 'Key': 'cost', 'Value': $("#spancost").hasClass('iconchevrondown') ? "1" : "0" });
var param = JSON.stringify(items);
param = htmlencode(param);
worequest("SetWorkOrderCollapsed", param, function (data) {
}, function (err) {
});
}
/*****************************************Begin Estimate*********************************************/
var EstimateStatus = {
Draft: 0,
Pending: 1,
Cancelled: 2,
Declined: 3,
Approved: 4,
Void: 5,
None: 100,
};
var estimateindex = 0;
var publishestindex = 0;
var addestfiledatas = [];
var cur_uploaddata;
var cur_uploadindex = "";
function showEstimatePopup() {
$('#popupestimatemask').css('height', $('#dialog_workorder').height());
$('#popupestimatemask').show();
$('#dialog_estimate').show();
$('#dialog_estimate').css({
"top": ($("#popupestimatemask").height() - $('#dialog_estimate').height()) / 3,
"left": ($("#popupestimatemask").width() - $('#dialog_estimate').width()) / 3
});
$('#dialog_segmentuser').focus();
}
function hideEstimatePopup() {
$('#popupestimatemask').hide();
$('#dialog_estimate').hide();
}
function getEstimates() {
estimateindex = 0;
$('#tab_estimates .estimates_div').remove();
$('#tab_estimates .estimates_table').remove();
if (!workorderid || workorderid == "") return;
worequest("GetWorkOrderEstimates", workorderid, function (data) {
$('#tab_estimates .estimates_div').remove();
$('#tab_estimates .estimates_table').remove();
if (typeof (data) === "string") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
if (data) {
if (data && data.length > 0) {
if (AllowCustomer)
$('#dialog_estimatestatus').text(getEstimateStatus(data[data.length - 1].Status));
for (var i = 0; i < data.length; i++) {
showEstimate(data[i]);
}
}
else {
if (AllowCustomer)
$('#dialog_estimatestatus').text(getEstimateStatus(100))
}
}
}, function (err) {
});
}
function dragOverEstimateAttachment(ev, index) {
ev.preventDefault();
ev.dataTransfer.dropEffect = 'link';
}
function dropEstimateAttachment(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 estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
if (estimate.Status !== 0)
return;
if (files.length > 0)
SaveEstimateAttachmentFiles(files, estimate.Id, index);
}
function cutEstimateAttachment(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 estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
if (estimate.Status !== 0)
return;
if (files.length > 0)
SaveEstimateAttachmentFiles(files, estimate.Id, index);
}
function showEstimate(estimate) {
estimateindex++;
var statustext = getEstimateStatus(estimate.Status);
var div_estimates = $('#tab_estimates');
var div_title = $('<div id="divestimate' + estimateindex + '" class="subtitle estimates_div" style="margin-right:0px;" ondrop="dropEstimateAttachment(event,' + estimateindex + ')" ondragover="dragOverEstimateAttachment(event,' + estimateindex + ')" onpaste="cutEstimateAttachment(event,' + estimateindex + ')"></div>');
div_title.append('<span class="sbutton iconchevronright" target="tabestimate' + estimateindex + '" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>');
div_title.append('<span id="span_estnumber' + estimateindex + '">' + estimate.EstimateNumber + '</span>');
div_title.append('<span id="span_eststatus' + estimateindex + '" style="margin-left:80px;font-weight:bold;">' + statustext + '</span>');
if (!WOReadOnly && (estimate.Status == 0 || estimate.Status === 1)) {
var s_del = $('<span class="sbutton icondelete" style="float:right;margin-right: 10px; padding: 0px 0px 0px 5px;" onclick="OnDeleteEstimate(' + estimateindex + ');"></span>');
div_title.append(s_del);
}
div_title.append('<hr />');
div_estimates.append(div_title);
var table = $('<table id="tabestimate' + estimateindex + '" class="estimates_table" ondrop="dropEstimateAttachment(event,' + estimateindex + ')" ondragover="dragOverEstimateAttachment(event,' + estimateindex + ')" onpaste="cutEstimateAttachment(event,' + estimateindex + ')"></table>').data('estimate', estimate).data('index', estimateindex).hide();
div_estimates.append(table);
var tr = $('<tr></tr>');
table.append(tr);
var td = $('<td class="label"></td>').text(GetTextByKey('P_WO_ESTIMATENUMBER_COLON', 'Estimate #:'));
tr.append(td);
td = $('<td style="width:150px;"></td>');
tr.append(td);
var ipt = $('<input type="text" id="dialog_est_number' + estimateindex + '" tabindex="1" class="inputbox" maxlength="50" autocomplete="off" />').val(estimate.EstimateNumber).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_ESTIMATESTATUS_COLON', 'Estimate Status:'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<span style="font-weight:bold;" id="dialog_est_status' + estimateindex + '"></span>').text(statustext);
td.append(ipt);
if ([3, 4, 5].indexOf(estimate.Status) >= 0) {
td = $('<td class="label"></td>');
if (estimate.Status == 3) {
td.text(GetTextByKey('P_WO_REJECTEDBY_COLON', 'Rejected By:'));
}
else if (estimate.Status == 4 || estimate.Status == 5) {
td.text(GetTextByKey('P_WO_APPROVEDBY_COLON', 'Approved By:'));
}
tr.append(td);
td = $('<td></td>');
tr.append(td);
var byph = "";
if (estimate.ResponsePhoneStr !== "")
byph = " (" + estimate.ResponsePhoneStr + ")";
ipt = $('<span id="dialog_est_crn' + estimateindex + '"></span>').text(estimate.ResponseName + byph);
td.append(ipt);
}
else {
tr.append('<td cospan="2"></td>');
}
var disabled = estimate.Status === EstimateStatus.Pending || estimate.Status === EstimateStatus.Declined || estimate.Status === EstimateStatus.Approved || estimate.Status === EstimateStatus.Void;
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_ESTIMATETOTALCOST_COLON', 'Estimate Total Cost ($):'));
tr.append(td);
td = $('<td style="display: inline-flex;"></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_est_totalcosts' + estimateindex + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off"/>').val(locale(estimate.TotalCost, disabled));
td.append(ipt);
var btntotal = $("<span class='sbutton iconequel' style='padding:3px 1px 3px 6px;font-size:12px;margin-left:2px;'></span>").click(estimateindex, function (e) {
getEstimateTotalCost(e.data);
}).attr("title", GetTextByKey('P_WO_CALCULATINGTOTALS', 'Calculating Totals'));
td.append(btntotal);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_OTHERCOST_COLON', 'Other Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_est_othercost' + estimateindex + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(estimate.OtherCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
if ([3, 4, 5].indexOf(estimate.Status) >= 0) {
td = $('<td class="label"></td>');
if (estimate.Status == 3) {
td.text(GetTextByKey('P_WO_REJECTEDTIME_COLON', 'Rejected Time:'));
}
else if (estimate.Status == 4 || estimate.Status == 5) {
td.text(GetTextByKey('P_WO_APPROVEDTIME_COLON', 'Approved Time:'));
}
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<span id="dialog_est_crt' + estimateindex + '"></span>').text(estimate.CustomerResponseTimeStr);
td.append(ipt);
}
else {
tr.append('<td cospan="2"></td>');
}
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_PARTSCOST_COLON', 'Parts Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_est_partscost' + estimateindex + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(estimate.PartsCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_TRAVELTIMECOST_COLON', 'Travel Time Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td); ipt = $('<input type="text" id="dialog_est_traveltimecost' + estimateindex + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(estimate.TravelCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
if ([3, 4, 5].indexOf(estimate.Status) >= 0) {
td = $('<td class="label"></td>');
if (estimate.Status == 3) {
td.text(GetTextByKey('P_WO_REASONFORREJECTION_COLON', 'Reason for Rejection:'));
}
else if (estimate.Status == 4 || estimate.Status == 5) {
td.text(GetTextByKey('P_WO_XXXXXX_COLON', 'PO #:'));
}
tr.append(td);
td = $('<td></td>');
tr.append(td);
if (estimate.Status == 3) {
ipt = $('<span id="dialog_est_rfr' + estimateindex + '"></span>').text(estimate.RejectReason);
td.append(ipt);
}
else if (estimate.Status == 4 || estimate.Status == 5) {
ipt = $('<span id="dialog_est_rfr' + estimateindex + '"></span>').text(estimate.PONumber);
td.append(ipt);
}
}
else {
tr.append('<td cospan="2"></td>');
}
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_LABORCOST_COLON', 'Labor Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_est_laborcost' + estimateindex + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(estimate.LaborCost, disabled)).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_TIMETOCOMPLATEHOURS_COLON', 'Time To Complete(Hrs):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_est_timetocomplete' + estimateindex + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(estimate.HoursToComplete).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_TAXES_COLON', 'Taxes ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_est_taxes' + estimateindex + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(estimate.Taxes, disabled)).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_XXX', 'PO Required:'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="checkbox" id="dialog_est_porequired' + estimateindex + '" tabindex="1" style="width: auto;" />').prop('checked', estimate.PORequired).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label" style="vertical-align:top;"></td>').text(GetTextByKey('P_WO_CUSTOMERISSUES_COLON', 'Customer Issues:'));
tr.append(td);
td = $('<td colspan="3"></td>');
tr.append(td);
ipt = $('<textarea id="dialog_est_custissues' + estimateindex + '" tabindex="1" maxlength="2000" style="width: 480px; height: 80px; margin-top: 5px;"></textarea>').val(estimate.CustomerIssues).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
if ([3, 4, 5].indexOf(estimate.Status) >= 0) {
td = $('<td class="label" style="vertical-align:top;"></td>').text(GetTextByKey('P_WO_CUSTOMERNOTES_COLON', 'Customer Notes:'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<textarea id="dialog_est_custnotes' + estimateindex + '" tabindex="1" maxlength="2000" disabled="disabled" style="width: 520px; height: 80px; margin-top: 5px;"></textarea>').val(estimate.CustomerNotes);
td.append(ipt);
}
else {
tr.append('<td cospan="2"></td>');
}
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label" style="vertical-align:top;"></td>').text(GetTextByKey('P_WO_TECHNICIANNOTES_COLON', 'Technician Notes:'));
tr.append(td);
td = $('<td colspan="3"></td>');
tr.append(td);
ipt = $('<textarea id="dialog_est_technotes' + estimateindex + '" tabindex="1" maxlength="2000" style="width: 480px; height: 80px; margin-top: 5px;" ></textarea>').val(estimate.TechnicianNotes).change((function (id) { return function () { inputChanged(id) } })(estimateindex));
td.append(ipt);
if (([3, 4, 5].indexOf(estimate.Status) >= 0) && estimate.Signature != null && estimate.Signature && estimate.Signature.length > 0) {
td = $('<td class="label" style="vertical-align:top;"></td>').text(GetTextByKey('P_WO_SIGNATURE_COLON', 'Signature:'));
tr.append(td);
td = $('<td rowspan="2"></td>');
tr.append(td);
var jpeg = estimate.Signature;
if (typeof (estimate.Signature) !== "string") {
jpeg = arrayBufferToBase64(estimate.Signature);
}
var imgsig = $('<img style="height: 110px;" />').attr('src', 'data:image/png;base64,' + jpeg);
td.append(imgsig);
}
else {
tr.append('<td rowspan="2"></td>');
}
if (estimate.Status === 0) {
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_ATTACHMENTS_COLON', ' Attachments:'));
tr.append(td);
td = $('<td colspan="3"></td>');
tr.append(td);
var div_att = $('<div></div>');
td.append(div_att);
if (!WOReadOnly) {
var span_addfile = $('<span class="sbutton iconadd" onclick="openWOEstAttachmentDialog(' + estimateindex + ');" />').text(GetTextByKey('P_FR_ADDFILE', 'Add File...'));
div_att.append(span_addfile);
}
}
tr = $('<tr id="tr_est_atts' + estimateindex + '"></tr>');
table.append(tr);
td = $('<td class="label" style="vertical-align:top;"></td>').text(estimate.Status === 0 ? "" : GetTextByKey('P_WO_ATTACHMENTS_COLON', 'Attachments:'));
tr.append(td);
td = $('<td colspan="3"></td>');
tr.append(td);
var tb_att = $('<table id="tab_est_attachments' + estimateindex + '" style="border: 1px solid #a8a8a8; line-height: 25px; width: 480px; display: none;"></table>');
td.append(tb_att);
var tr_att = $('<tr></tr>');
tb_att.append(tr_att);
var td_att = $('<td></td>');
tr_att.append(td_att);
div_att = $('<div class="content_main" style="max-height: 80px; overflow: auto;"></div>');
td_att.append(div_att);
tb_att = $('<table id="tab_est_atts' + estimateindex + '" style="table-layout: fixed;"></table>');
div_att.append(tb_att);
showEstimateAttachment(estimateindex);
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>');
tr.append(td);
ipt = $('<lable id="lable_est_visibletocustomer' + estimateindex + '"></lable>').text(GetTextByKey('P_WO_XXX', 'Available to Customer:')).hide();
td.append(ipt);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="checkbox" id="dialog_est_visibletocustomer' + estimateindex + '" tabindex="1" style="width: auto;" />').prop('checked', estimate.VisibleToCustomer).hide().change((function (id) { return function () { updateWOEstimateVisibleToCustomer(id) } })(estimateindex));
td.append(ipt);
td = $('<td style="text-align: right; height: 33px"></td>');
tr.append(td);
ipt = $('<input type="button" style="width: 80px; height: 25px;" id="btn_estimatesave' + estimateindex + '" onclick="onSaveWorkOrderEstimate(' + estimateindex + ')" />').val(GetTextByKey('P_WO_SAVE', 'Save')).hide();
td.append(ipt);
ipt = $('<input type="button" style="width: 80px; height: 25px;margin-left:16px;" id="btn_estimatepublish' + estimateindex + '" onclick="openPublishDialog(' + estimateindex + ')" />').val(GetTextByKey('P_WO_PUBLISH', 'Publish')).hide();
td.append(ipt);
ipt = $('<input type="button" style="width: 80px; height: 25px;" id="btn_estimaterevoke' + estimateindex + '" onclick="OnRevokeEstimate(' + estimateindex + ')" />').val(GetTextByKey('P_WO_REVOKE', 'Revoke')).hide();
td.append(ipt);
if (!WOReadOnly) {
if (estimate.Status === 0) {
$('#btn_estimatesave' + estimateindex).show();
$('#btn_estimatepublish' + estimateindex).show();
}
if (estimate.Status === 1 || estimate.Status === 4) {
$('#btn_estimaterevoke' + estimateindex).show();
}
}
if (disabled || WOReadOnly)
setEstimateDisabled(estimateindex, true);
if (estimate.Status === 3) {
$('#span_eststatus' + estimateindex).css('color', 'red');
$('#dialog_est_status' + estimateindex).css('color', 'red');
}
if (estimate.Status === 4) {
$('#span_eststatus' + estimateindex).css('color', '#2eda2e');
$('#dialog_est_status' + estimateindex).css('color', '#2eda2e');
}
if ([3, 4, 5].indexOf(estimate.Status) >= 0) {
$('#lable_est_visibletocustomer' + estimateindex).show();
$('#dialog_est_visibletocustomer' + estimateindex).show();
}
}
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
function OnRevokeEstimate(index) {
var estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
showConfirm(GetTextByKey("P_WO_DOYOUWANTTOREVOKETHEESTIMATE", 'Do you want to revoke the estimate?'), GetTextByKey("P_WO_REVOKEESTIMATE", 'Revoke Estimate'), function () {
worequest("RevokeWorkOrderEstimate", estimate.Id, function (data) {
if (data === "OK") {
getEstimates();
}
}, function (err) {
showAlert(GetTextByKey("P_WO_FAILEDTOREVOKETHISESTIMATE", 'Failed to revoke this estimate.'), GetTextByKey("P_WO_REVOKEESTIMATE", 'Revoke Estimate'));
});
});
}
function OnDeleteEstimate(index) {
var estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
showConfirm(GetTextByKey("P_WO_DOYOUWANTTODELETETHEESTIMATE", 'Do you want to delete the estimate?'), GetTextByKey("P_WO_DELETEESTIMATE", 'Delete Estimate'), function () {
worequest("DeleteWorkOrderEstimate", estimate.Id, function (data) {
if (data === "OK") {
getEstimates();
}
}, function (err) {
showAlert(GetTextByKey("P_WO_FAILEDTODELETETHISESTIMATE", 'Failed to delete this estimate.'), GetTextByKey("P_WO_DELETEESTIMATE", 'Delete Estimate'));
});
});
}
function onSaveWorkOrderEstimate(index, next) {
var estimateid = -1;
var status = 0;
var alerttitle = GetTextByKey("P_WO_ADDESTIMATE", "Add Estimate");
if (index !== "") {
alerttitle = GetTextByKey("P_WO_EDITESTIMATE", "Edit Estimate");
var estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
estimateid = estimate.Id;
status = estimate.Status;
}
var item = {
'Id': estimateid,
'WorkOrderId': workorderid,
'Status': status,
'EstimateNumber': $('#dialog_est_number' + index).val(),
'TotalCost': $('#dialog_est_totalcosts' + index).val(),
'OtherCost': $('#dialog_est_othercost' + index).val(),
'PartsCost': $('#dialog_est_partscost' + index).val(),
'TravelCost': $('#dialog_est_traveltimecost' + index).val(),
'LaborCost': $('#dialog_est_laborcost' + index).val(),
'HoursToComplete': $('#dialog_est_timetocomplete' + index).val(),
'CustomerIssues': $('#dialog_est_custissues' + index).val(),
'TechnicianNotes': $('#dialog_est_technotes' + index).val(),
'Taxes': $('#dialog_est_taxes' + index).val(),
'PORequired': $('#dialog_est_porequired' + index).prop('checked')
};
if (isNaN(item.TotalCost) || item.TotalCost < 0) {
showAlert(GetTextByKey('P_WO_XXXXXX_INVALID', 'Total cost is not a valid number.'), alerttitle, function () { $('#dialog_est_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_est_totalcosts' + 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_est_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_est_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_est_laborcost' + index).focus() });
return;
}
if (isNaN(item.HoursToComplete) || item.HoursToComplete < 0) {
showAlert(GetTextByKey('P_WO_TIMETOCOMPLETE_INVALID', 'Time to complete is not a valid number.'), alerttitle, function () { $('#dialog_est_timetocomplete' + index).focus() });
return;
}
if (isNaN(item.Taxes) || item.Taxes < 0) {
showAlert(GetTextByKey('P_WO_XXXXX_INVALID', 'Taxes is not a valid number.'), alerttitle, function () { $('#dialog_est_taxes' + index).focus() });
return;
}
$('#btn_estimatesave' + index).attr('disabled', true);
var param = JSON.stringify(item);
param = htmlencode(param);
worequest("SaveWorkOrderEstimate", param, function (data) {
if (typeof (data) === "string") {
$('#btn_estimatesave' + index).attr('disabled', false);
showAlert(data, alerttitle);
} else {
$('#btn_estimatesave' + index).attr('disabled', false);
if (index === "") {//新增
if (addestfiledatas && addestfiledatas.length > 0) {
SaveEstimateAttachmentFiles(addestfiledatas, data);
addestfiledatas = [];
}
if (next)
next("", data);
else {
getEstimates();
}
hideEstimatePopup();
}
else {//编辑
if (next)
next(index);
else {
showAlert(GetTextByKey("P_WO_SAVSUCCESSFULLY", "Saved successfully."), alerttitle);
$('#span_estnumber' + index).text($('#dialog_est_number' + index).val());
}
}
}
}, function (err) {
$('#btn_estimatesave' + index).attr('disabled', false);
console.log(err);
showAlert(GetTextByKey("P_WO_FAILEDTORSAVEESTIMATE", 'Failed to save estimate.'), alerttitle);
});
}
function OnAddEstimate() {
addestfiledatas = [];
$('#tab_est_atts').empty();
$('#tab_est_attachments').hide();
if (!workorderid || workorderid === "") {
showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), GetTextByKey("P_WO_ADDESTIMATE", "Add Estimate"));
return;
}
$('#dialog_est_number').val("");
$('#dialog_est_status').text(GetTextByKey('P_WO_DRAFT', 'Draft'));
$('#dialog_est_totalcosts').val("");
$('#dialog_est_othercost').val("");
$('#dialog_est_partscost').val("");
$('#dialog_est_traveltimecost').val("");
$('#dialog_est_laborcost').val("");
$('#dialog_est_timetocomplete').val("");
$('#dialog_est_custissues').val("");
$('#dialog_est_technotes').val("");
$('#dialog_est_taxes').val("");
$('#dialog_est_porequired').prop('checked', WorkorderParams.DefaultPORequired);
if (workorderdata) {
$('#dialog_est_totalcosts').val(workorderdata.WorkOrderTotalCost == 0 ? "" : workorderdata.WorkOrderTotalCost);
$('#dialog_est_othercost').val(workorderdata.OtherCost == 0 ? "" : workorderdata.OtherCost);
$('#dialog_est_partscost').val(workorderdata.PartsCost == 0 ? "" : workorderdata.PartsCost);
$('#dialog_est_traveltimecost').val(workorderdata.TravelTimeCost == 0 ? "" : workorderdata.TravelTimeCost);
$('#dialog_est_laborcost').val(workorderdata.LaborCost == 0 ? "" : workorderdata.LaborCost);
$('#dialog_est_timetocomplete').val(workorderdata.HoursToComplete == 0 ? "" : workorderdata.HoursToComplete);
$('#dialog_est_custissues').val(workorderdata.Description);
getEstimateTotalCost("");
}
showEstimatePopup();
}
function inputChanged(index) {
$('#tabestimate' + index).data('changed', true);
}
function setEstimateDisabled(index, di) {
$('#dialog_est_number' + index).attr('disabled', di);
$('#dialog_est_totalcosts' + index).attr('disabled', di);
$('#dialog_est_othercost' + index).attr('disabled', di);
$('#dialog_est_partscost' + index).attr('disabled', di);
$('#dialog_est_traveltimecost' + index).attr('disabled', di);
$('#dialog_est_laborcost' + index).attr('disabled', di);
$('#dialog_est_timetocomplete' + index).attr('disabled', di);
$('#dialog_est_custissues' + index).attr('disabled', di);
$('#dialog_est_technotes' + index).attr('disabled', di);
$('#dialog_est_taxes' + index).attr('disabled', di);
$('#dialog_est_porequired' + index).attr('disabled', di);
}
function getEstimateTotalCost(index) {
var othercost = $('#dialog_est_othercost' + index).val();
var partscost = $('#dialog_est_partscost' + index).val();
var traveltimecost = $('#dialog_est_traveltimecost' + index).val();
var laborcost = $('#dialog_est_laborcost' + index).val();
var taxes = $('#dialog_est_taxes' + 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);
if (taxes !== "" && !isNaN(taxes))
totalcost += eval(taxes);
$('#dialog_est_totalcosts' + index).val(totalcost.toFixed(2));
}
function getEstimateStatus(s) {
var text = "";
if (s === 0)
text = GetTextByKey('P_WO_DRAFT', 'Draft');
else if (s === 1)
text = GetTextByKey('P_WO_AWAITINGCUSTOMERAPPROVAL', 'Awaiting Customer Approval');
else if (s === 2)
text = GetTextByKey('P_WO_CANCELLEDBYDEALER', 'Cancelled by Dealer');
else if (s === 3)
text = GetTextByKey('P_WO_CUSTOMERREJECTED', 'Customer Rejected');
else if (s === 4)
text = GetTextByKey('P_WO_CUSTOMERAPPROVED', 'Customer Approved');
else if (s === 5)
text = GetTextByKey('P_WO_XXXX', 'Void');
else if (s === 100)
text = "";
return text;
}
function showPublishEstimatePopup() {
$('#popupepublishstimatemask').css('height', $('#dialog_workorder').height());
$('#popupepublishstimatemask').show();
$('#dialog_publishestimate').show();
$('#dialog_est_textmsg').val(WorkorderParams.EstimateMessage);
$('#dialog_publishestimate').css({
"top": ($("#popupepublishstimatemask").height() - $('#dialog_publishestimate').height()) / 3,
"left": ($("#popupepublishstimatemask").width() - $('#dialog_publishestimate').width()) / 3
});
$('#dialog_est_phonenum').focus();
}
function hidePublishEstimatePopup() {
publishestindex = 0;
$('#popupepublishstimatemask').hide();
$('#dialog_publishestimate').hide();
}
function openPublishDialog(index) {
if (index == -1) {
publishestindex = index;
showPublishEstimatePopup();
}
else {
onSaveWorkOrderEstimate(index, function () {
publishestindex = index;
showPublishEstimatePopup();
});
}
}
function onPublishEstimate() {
var changed = $('#tabestimate' + publishestindex).data('changed');
if (publishestindex === -1)//add and publish
changed = true;
if (changed)
onSaveWorkOrderEstimate(publishestindex === -1 ? "" : publishestindex, PublishEstimate)
else
PublishEstimate(publishestindex);
}
function PublishEstimate(index, estid) {
if (index !== "") {
var estimate = $('#tabestimate' + index).data('estimate');
estid = estimate.Id;
}
if (!estid)
return;
var pmemails = [];
var checked = $('#dialog_est_chksendtextmsg').prop('checked');
if (checked) {
var phoneemail = $('#dialog_est_phonenum').val();
if (phoneemail !== "") {
var phoneemails = phoneemail.split(';');
for (var i = 0; i < phoneemails.length; i++) {
var pm = phoneemails[i];
if (checkPhoneNumber(pm) || isEmail(pm)) {
pmemails.push({ 'Key': pm, 'Value': pm });
}
else {
if (customercontacts) {
for (var j = 0; j < customercontacts.length; j++) {
var c = customercontacts[j];
if (c.OptOut || c.OptOut_BC) continue;
var mp = $.trim(c.MobilePhone);
var email = $.trim(c.Email);
if (c.Name === pm) {
if (c.ContactPreference == "0" && checkPhoneNumber(mp)) {
pmemails.push({ 'Key': mp, 'Value': pm });
break;
}
if (c.ContactPreference == "1" && isEmail(email)) {
pmemails.push({ 'Key': email, 'Value': pm });
break;
}
}
}
}
}
}
}
}
var msg = $('#dialog_est_textmsg').val();
var includeStatusLink = $('#dialog_est_chkIncludeStatusLink').prop("checked");
var param = JSON.stringify([estid, workorderid, JSON.stringify(pmemails), msg, (includeStatusLink ? "1" : "0")]);
param = htmlencode(param);
worequest("PublishEstimateToCustomer", param, function (data) {
if (data !== "") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
getEstimates();
hidePublishEstimatePopup();
}, function (err) {
showAlert(GetTextByKey("P_WO_FAILEDTOPUBLISHTHISESTIMATE", 'Failed to publish this estimate.'), GetTextByKey("P_WO_PUBLISHESTIMATE", 'Publish Estimate'));
});
}
function updateWOEstimateVisibleToCustomer(index) {
var estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
var checked = $('#dialog_est_visibletocustomer' + index).prop('checked');
var param = JSON.stringify([estimate.Id, checked]);
param = htmlencode(param);
worequest("UpdateWOEstimateVisibleToCustomer", param, function (data) {
if (data !== "") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
}, function (err) {
showAlert(GetTextByKey("P_WO_XXXX", 'Failed to publish this estimate.'), GetTextByKey("P_WO_AVAILABLETOCUSTOMER", 'Available to Customer'));
});
}
function SaveEstimateAttachmentFiles(filedatas, estid, 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([estid, JSON.stringify(notesdata)]);
formData.append("MethodName", "AddEstimateAttachment");
formData.append("ClientData", p);
var url = 'AddWorkOrder.aspx';
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: formData,
async: true,
success: function (data) {
if (data !== 'OK') {
showAlert(data, GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File'));
} else {
if (index) {
hideWOEstAttachmentPopup();
getEstimateAttachment(index);
}
else
getEstimates();
}
},
error: function (err) {
showAlert(GetTextByKey("P_WO_XXXXX", 'Upload failed'), GetTextByKey("P_WO_ATTACHMENTFILE", 'Attachment File'));
}
});
}
function getEstimateAttachment(index) {
var estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
$('#tab_est_atts' + index).empty();
$('#tab_est_attachments' + index).hide();
worequest("GetEstimateAttachment", estimate.Id, function (data) {
if (typeof (data) === "string") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
if (data && data.length > 0) {
showEstimateAttachment(index, data);
}
}, function (err) {
});
}
function showEstimateAttachment(index, atts) {
var isdelete = false;
if (!atts) {
var estimate = $('#tabestimate' + index).data('estimate');
if (!estimate)
return;
atts = estimate.Attachments;
if (estimate.Status === 0)
isdelete = true;
}
else
isdelete = true;
$('#tab_est_atts' + index).empty();
$('#tab_est_attachments' + index).hide();
if (atts && atts.length > 0) {
$('#tab_est_attachments' + index).show();
for (var i = 0; i < atts.length; i++) {
var att = atts[i];
var tr = $('<tr></tr>').attr('id', att.AttachmentId);
var tdfile = $('<td style=""></td>');
var filename = $("<label style='border-bottom: 1px solid RGB(30, 144, 255);color: RGB(30,144,255);cursor:pointer;'></label>").text(att.Notes === "" ? att.FileName : att.Notes).click(function () {
window.open("../filesvc.ashx?attchid=" + this.parentElement.parentElement.id + "&sourceType=woestimateattachment");
});
var span = $('<span></span>').text(att.AddedByName).css("margin-right", 5).css("margin-left", 5).css("color", "black");
var spanby = $('<span></span>').text(att.AddedOnLocalStr).css("color", "black");
tdfile.append(filename, span, spanby);
if (!WOReadOnly && isdelete) {
var tdimg = $('<td style="width:18px;border:none;text-align:center;"></td>');
var imgDom = $('<span class="sbutton icondelete" style="padding:0;" ></span>').data('index', index).click(function () {
deleteEstimateAttachment(this.parentElement.parentElement.id, $(this).data('index'));
});
tdimg.append(imgDom);
tr.append(tdimg);
}
tr.append(tdfile).appendTo($('#tab_est_atts' + index));
}
}
}
function deleteEstimateAttachment(attid, index) {
if (confirm(GetTextByKey("P_WO_DELETEATTACHMENTTIPS", "Are you sure you want to delete the attachment?"))) {
worequest("DeleteEstimateAttachment", attid, function (data) {
if (data !== 'OK') {
showAlert(data, GetTextByKey("P_WO_DELETEATTACHMENT", 'Delete Attachment'));
}
else {
getEstimateAttachment(index);
}
}, function (err) { });
}
}
function hideWOEstAttachmentPopup() {
$('#popupewoestattachmentmask').hide();
$('#dialog_woestattachment').hide();
}
function openWOEstAttachmentDialog(index) {
cur_uploaddata = undefined;
cur_uploadindex = index;
$('#btn_woestattasave').attr('disabled', false);
$('#tab_woest_atts').empty();
$('#tab_woest_attachments').hide();
$('#popupewoestattachmentmask').css('height', $('#dialog_workorder').height());
$('#popupewoestattachmentmask').show();
$('#dialog_woestattachment').show();
$('#dialog_estatt_notes').val('');
$('#dialog_woestattachment').css({
"top": ($("#popupewoestattachmentmask").height() - $('#dialog_woestattachment').height()) / 3,
"left": ($("#popupewoestattachmentmask").width() - $('#dialog_woestattachment').width()) / 3
});
$('#dialog_estatt_notes').focus();
}
function dragOverAddEstimateAttachment(ev) {
ev.preventDefault();
ev.dataTransfer.dropEffect = 'link';
}
function dropAddEstimateAttachment(ev) {
ev.preventDefault();
ev.stopPropagation();
var df = ev.dataTransfer;
var files = [];
if (df.items !== undefined) {
for (var i = 0; i < df.items.length; i++) {
var item = df.items[i];
if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) {
var file = item.getAsFile();
if (file.size == 0) {
alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed."));
return;
}
if (file.size > 50 * 1024 * 1024) {
alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB."));
return;
}
files.push({ 'File': file, 'Notes': '' });
}
}
}
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
cur_uploaddata = files[i];
onSaveWOEstAttachment();
}
}
}
function cutAddEstimateAttachment(ev) {
ev.stopPropagation();
var df = ev.clipboardData;
var files = [];
if (df.items !== undefined) {
for (var i = 0; i < df.items.length; i++) {
var item = df.items[i];
if (item.kind === "file" && (item.webkitGetAsEntry() == null || item.webkitGetAsEntry().isFile)) {
var file = item.getAsFile();
if (file.size == 0) {
alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed."));
return;
}
if (file.size > 50 * 1024 * 1024) {
alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB."));
return;
}
files.push({ 'File': file, 'Notes': '' });
}
}
}
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
cur_uploaddata = files[i];
onSaveWOEstAttachment();
}
}
}
function UpLoadEstimateAttachment() {
var file = $('<input type="file" style="display: none;" />');
file.change(function () {
var files = this.files;
if (files.length == 0)
return;
if (files[0].size == 0) {
alert(GetTextByKey("P_WO_ATTACHMENTSTIPS", "Attachment size is 0kb, uploading failed."));
return false;
}
if (files[0].size > 50 * 1024 * 1024) {
alert(GetTextByKey("P_WO_ATTACHMENTSTIPS1", "Attachment is too large. Maximum file size is 50 MB."));
return false;
}
var notes = $('#dialog_estatt_notes').val();
cur_uploaddata = { 'File': files[0], 'Notes': notes };
createNewEstimateAttachment(cur_uploaddata);
}).click();
}
function createNewEstimateAttachment(data) {
$('#tab_woest_atts').empty();
$('#tab_woest_attachments').show();
var tr = $('<tr></tr>');
var tdfile = $('<td style=""></td>');
var filename = $("<label style='border-bottom: 1px solid RGB(30, 144, 255);color: RGB(30,144,255);cursor:pointer;'></label>").text(data.Notes === "" ? data.File.name : data.Notes);
tdfile.append(filename);
var tdimg = $('<td style="width:18px;border:none;text-align:center;"></td>');
var imgDom = $('<span class="sbutton icondelete" style="padding:0;" ></span>').click(function () {
this.parentElement.parentElement.remove();
cur_uploaddata = undefined;
$('#tab_woest_attachments').hide();
});
tdimg.append(imgDom);
tr.append(tdimg);
tr.append(tdfile).appendTo($('#tab_woest_atts'));
}
function onSaveWOEstAttachment() {
if (!cur_uploaddata)
return;
$('#btn_woestattasave').attr('disabled', true);
var estimate = $('#tabestimate' + cur_uploadindex).data('estimate');
var notes = $('#dialog_estatt_notes').val();
cur_uploaddata.Notes = notes;
if (!estimate) {
addestfiledatas.push(cur_uploaddata);
createAddEstimateAttachment(cur_uploaddata);
hideWOEstAttachmentPopup();
$('#btn_woestattasave').attr('disabled', false);
}
else {
SaveEstimateAttachmentFiles([cur_uploaddata], estimate.Id, cur_uploadindex);
}
}
function createAddEstimateAttachment(data) {
var notes = data.Notes;
var file = data.File;
$('#tab_est_attachments').show();
var tr = $('<tr></tr>');
var tdfile = $('<td style=""></td>');
var filename = $("<label style='border-bottom: 1px solid RGB(30, 144, 255);color: RGB(30,144,255);cursor:pointer;'></label>").text(notes === "" ? file.name : notes);
tdfile.append(filename);
var tdimg = $('<td style="width:18px;border:none;text-align:center;"></td>');
var imgDom = $('<span class="sbutton icondelete" style="padding:0;" ></span>').data('filedata', data).click(function () {
this.parentElement.parentElement.remove();
var fd = $(this).data('filedata');
addestfiledatas.splice(addestfiledatas.indexOf(fd), 1);
if (addestfiledatas.length == 0)
$('#tab_est_attachments').hide();
});
tdimg.append(imgDom);
tr.append(tdimg);
tr.append(tdfile).appendTo($('#tab_est_atts'));
}
/*****************************************End Estimate*********************************************/
/*****************************************Begin Invoice*********************************************/
var invoice_index = 0;
var publish_invoice_index = 0;
var add_invoice_filedatas = [];
var cur_invoice_uploaddata;
var cur_invoice_uploadindex = "";
function showInvoicePopup() {
$('#popupinvoicemask').css('height', $('#dialog_workorder').height());
$('#popupinvoicemask').show();
$('#dialog_invoice').show();
$('#dialog_invoice').css({
"top": ($("#popupinvoicemask").height() - $('#dialog_invoice').height()) / 3,
"left": ($("#popupinvoicemask").width() - $('#dialog_invoice').width()) / 3
});
$('#dialog_invoice_number').focus();
}
function hideInvoicePopup() {
$('#popupinvoicemask').hide();
$('#dialog_invoice').hide();
}
function getInvoices() {
invoice_index = 0;
$('#tab_invoices .estimates_div').remove();
$('#tab_invoices .estimates_table').remove();
if (!workorderid || workorderid == "") return;
worequest("GetWorkOrderInvoices", workorderid, function (data) {
$('#tab_invoices .estimates_div').remove();
$('#tab_invoices .estimates_table').remove();
if (typeof (data) === "string") {
showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
return;
}
if (data) {
if (data && data.length > 0) {
//if (AllowCustomer)
// $('#dialog_invoice_status').text(getInvoiceStatus(data[data.length - 1].Status));
for (var i = 0; i < data.length; i++) {
showInvoice(data[i]);
}
}
else {
// if (AllowCustomer)
// $('#dialog_invoice_status').text(getInvoiceStatus(100))
}
}
}, function (err) {
});
}
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 = $('#tab_invoices');
var div_title = $('<div id="divinvoice' + invoice_index + '" class="subtitle estimates_div" style="margin-right:0px;" ondrop="dropInvoiceAttachment(event,' + invoice_index + ')" ondragover="dragOverInvoiceAttachment(event,' + invoice_index + ')" onpaste="cutInvoiceAttachment(event,' + invoice_index + ')"></div>');
div_title.append('<span class="sbutton iconchevronright" target="tabinvoice' + invoice_index + '" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>');
div_title.append('<span id="span_invoice_number' + invoice_index + '">' + invoice.InvoiceNumber + '</span>');
div_title.append('<span id="span_invoice_status' + invoice_index + '" style="margin-left:80px;font-weight:bold;">' + statustext + '</span>');
if (!WOReadOnly) {
if (invoice.Status === InvoiceStatus.Pending || invoice.Status === InvoiceStatus.PaymentCreated || invoice.Status === InvoiceStatus.Draft) {
div_title.append($('<input type="button" style="width: 100px; height: 24px;margin-left:100px;" onclick="openWOInvoiceMarkPaidDialog(' + invoice_index + ')" />').val(GetTextByKey('P_WO_XXXXXX', 'Mark As Paid')));
}
if (invoice.Status === InvoiceStatus.Pending) {
div_title.append($('<input type="button" style="width: 80px; height: 24px;margin-left:20px;" onclick="OnRevokeInvoice(' + invoice_index + ')" />').val(GetTextByKey('P_WO_REVOKE', 'Revoke')));
}
if (invoice.Status == InvoiceStatus.Draft || invoice.Status === InvoiceStatus.Pending || invoice.Status === InvoiceStatus.Revoked) {
var s_del = $('<span class="sbutton icondelete" style="float:right;margin-right: 10px; padding: 0px 0px 0px 5px;" onclick="OnDeleteInvoice(' + invoice_index + ');"></span>');
div_title.append(s_del);
}
}
div_title.append('<hr />');
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 = $('<table id="tabinvoice' + invoice_index + '" class="estimates_table" ondrop="dropInvoiceAttachment(event,' + invoice_index + ')" ondragover="dragOverInvoiceAttachment(event,' + invoice_index + ')" onpaste="cutInvoiceAttachment(event,' + invoice_index + ')"></table>').data('invoice', invoice).data('index', invoice_index).hide();
div_invoices.append(table);
var tr = $('<tr></tr>');
table.append(tr);
var td = $('<td class="label"></td>').text(GetTextByKey('P_WO_INVOICENUMBER', 'Invoice #:'));
tr.append(td);
td = $('<td style="width:150px;"></td>');
tr.append(td);
var ipt = $('<input type="text" id="dialog_invoice_number' + invoice_index + '" tabindex="1" class="inputbox" maxlength="50" autocomplete="off" />').val(invoice.InvoiceNumber).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_OTHERCOST_COLON', 'Other Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_invoice_othercost' + invoice_index + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(invoice.OtherCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
var tdDetail = $('<td rowspan="7" style="vertical-align: top; padding-left: 20px"></td>').attr('id', 'invoice_payment_tab' + invoice_index);
tr.append(tdDetail);
//if (invoice.Status == InvoiceStatus.Paid)
{
if (invoice.PaymentItem != null) {
var btncancelpayment = "<span></span>";
if (invoice.Status === InvoiceStatus.ManualPaid) {
btncancelpayment = $('<input type="button" style="width: 100px; height: 24px;" onclick="CancelPayment(' + invoice_index + ')" />').val(GetTextByKey('P_WO_XXXXXX', 'Cancel Payment'));
}
tdDetail.empty().append(
$('<table style="width: 100%; table-layout: fixed"></table>').append(
$('<tr></tr>').append(
$('<td style="width: 150px" class="payment-label"></td>').text(GetTextByKey('P_WO_XXXXXX', 'Payment Entered By:')),
$('<td style="width: 320px"></td>').text(invoice.PaymentItem.PaymentEnteredByName),
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_CUSTOMERNAME', 'Customer Name:')),
$('<td></td>').text(invoice.PaymentItem.CustomerName)
),
$('<tr></tr>').append(
$('<td style="width: 150px" class="payment-label"></td>').text(GetTextByKey('P_WO_PAYMENTTIME', 'Payment Time:')),
$('<td style="width: 320px"></td>').text(invoice.PaymentItem.CreatedLocalStr),
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_CUSTOMEREMAIL', 'Customer Email:')),
$('<td></td>').text(invoice.PaymentItem.CustomerEmail)
),
$('<tr></tr>').append(
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_XXXXXX', 'Payment Type:')),
$('<td></td>').text(invoice.PaymentItem.PaymentType),
$('<td></td>'),
$('<td></td>')
),
$('<tr></tr>').append(
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_XXXXXX', 'Check #:')),
$('<td></td>').text(invoice.PaymentItem.CheckNumber),
$('<td></td>'),
$('<td></td>')
),
$('<tr></tr>').append(
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_CARDNUMBER', 'Card Number:')),
$('<td></td>').text(invoice.PaymentItem.CardNumber),
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_EXPIRATION', 'Expiration:')),
$('<td></td>').text(invoice.PaymentItem.CardExpiration)
),
$('<tr></tr>').append(
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_CARDTYPE', 'Card Type:')),
$('<td></td>').text(invoice.PaymentItem.CardType),
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_COUNTRY_COLON', 'Country:')),
$('<td></td>').text(invoice.PaymentItem.CustomerCountry)
),
$('<tr></tr>').append(
$('<td class="payment-label"></td>').text(GetTextByKey('P_WO_ISSUER', 'Issuer:')),
$('<td style="padding-right: 20px; white-space: nowrap"></td>').text(invoice.PaymentItem.CardIssuer),
$('<td style="text-align:right;"></td>').append(btncancelpayment),
$('<td></td>')
)
)
);
}
}
//if (invoice.Status == 3 || invoice.Status === 4) {
// td = $('<td class="label"></td>');
// if (invoice.Status == 3) {
// td.text(GetTextByKey('P_WO_REJECTEDBY_COLON', 'Rejected By:'));
// }
// else if (invoice.Status == 4) {
// td.text(GetTextByKey('P_WO_APPROVEDBY_COLON', 'Approved By:'));
// }
// tr.append(td);
// td = $('<td></td>');
// tr.append(td);
// var byph = "";
// if (invoice.ResponsePhoneStr !== "")
// byph = " (" + invoice.ResponsePhoneStr + ")";
// ipt = $('<span id="dialog_invoice_crn' + invoice_index + '"></span>').text(invoice.ResponseName + byph);
// td.append(ipt);
//}
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_INVOICETOTALCOST', 'Invoice Total Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_invoice_totalcosts' + invoice_index + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(invoice.TotalCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_TRAVELTIMECOST_COLON', 'Travel Time Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td); ipt = $('<input type="text" id="dialog_invoice_traveltimecost' + invoice_index + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(invoice.TravelCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_PARTSCOST_COLON', 'Parts Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_invoice_partscost' + invoice_index + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(invoice.PartsCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_TAXES_COLON', 'Taxes ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_invoice_taxes' + invoice_index + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(invoice.Taxes, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_LABORCOST_COLON', 'Labor Cost ($):'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="text" id="dialog_invoice_laborcost' + invoice_index + '" tabindex="1" class="inputbox" maxlength="12" autocomplete="off" />').val(locale(invoice.LaborCost, disabled)).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_INVOICESTATUS', 'Invoice Status:'));
tr.append(td);
td = $('<td style="width: 150px"></td>');
tr.append(td);
ipt = $('<span style="font-weight:bold;" id="dialog_invoice_status' + invoice_index + '"></span>').text(statustext);
td.append(ipt);
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_XXXXXX_COLON', 'Customer Visible:'));
tr.append(td);
td = $('<td></td>');
tr.append(td);
ipt = $('<input type="checkbox" id="dialog_invoice_customervisible' + invoice_index + '" tabindex="1" />').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 = $('<tr></tr>');
table.append(tr);
td = $('<td class="label" style="vertical-align:top;"></td>').text(GetTextByKey('P_WOS_NOTES_COLON', 'Notes:'));
tr.append(td);
td = $('<td colspan="3"></td>');
tr.append(td);
ipt = $('<textarea id="dialog_invoice_notes' + invoice_index + '" tabindex="1" maxlength="500" style="width: 480px; height: 80px; margin-top: 5px;" ></textarea>').val(invoice.Notes).change((function (id) { return function () { inputInvoiceChanged(id) } })(invoice_index));
td.append(ipt);
if (invoice.Status === InvoiceStatus.Draft) {
tr = $('<tr></tr>');
table.append(tr);
td = $('<td class="label"></td>').text(GetTextByKey('P_WO_ATTACHMENTS_COLON', ' Attachments:'));
tr.append(td);
td = $('<td colspan="3"></td>');
tr.append(td);
var div_att = $('<div></div>');
td.append(div_att);
if (!WOReadOnly) {
var span_addfile = $('<span class="sbutton iconadd" onclick="openWOInvoiceAttachmentDialog(' + invoice_index + ');" />').text(GetTextByKey('P_FR_ADDFILE', 'Add File...'));
div_att.append(span_addfile);
}
}
tr = $('<tr id="tr_invoice_atts' + invoice_index + '"></tr>');
table.append(tr);
td = $('<td class="label" style="vertical-align:top;"></td>').text(invoice.Status === InvoiceStatus.Draft ? "" : GetTextByKey('P_WO_ATTACHMENTS_COLON', 'Attachments:'));
tr.append(td);
td = $('<td colspan="3"></td>');
tr.append(td);
var tb_att = $('<table id="tab_invoice_attachments' + invoice_index + '" style="border: 1px solid #a8a8a8; line-height: 25px; width: 480px; display: none;"></table>');
td.append(tb_att);
var tr_att = $('<tr></tr>');
tb_att.append(tr_att);
var td_att = $('<td></td>');
tr_att.append(td_att);
div_att = $('<div class="content_main" style="max-height: 80px; overflow: auto;"></div>');
td_att.append(div_att);
tb_att = $('<table id="tab_invoice_atts' + invoice_index + '" style="table-layout: fixed;"></table>');
div_att.append(tb_att);
showInvoiceAttachment(invoice_index);
tr = $('<tr></tr>');
table.append(tr);
td = $('<td colspan="4" style="text-align: right; height: 33px"></td>');
tr.append(td);
ipt = $('<input type="button" style="width: 80px; height: 25px;" id="btn_invoice_save' + invoice_index + '" onclick="onSaveWorkOrderInvoice(' + invoice_index + ')" />').val(GetTextByKey('P_WO_SAVE', 'Save')).hide();
td.append(ipt);
ipt = $('<input type="button" style="width: 80px; height: 25px;margin-left:20px;" id="btn_invoice_publish' + invoice_index + '" onclick="openPublishInvoiceDialog(' + invoice_index + ')" />').val(GetTextByKey('P_WO_PUBLISH', 'Publish')).hide();
td.append(ipt);
//ipt = $('<input type="button" style="width: 100px; height: 25px;margin-left:20px;" id="btn_invoice_markaspaid' + invoice_index + '" onclick="openWOInvoiceMarkPaidDialog(' + invoice_index + ')" />').val(GetTextByKey('P_WO_XXXXXX', 'Mark As Paid')).hide();
//td.append(ipt);
//ipt = $('<input type="button" style="width: 80px; height: 25px;margin-left:20px;" id="btn_invoice_revoke' + invoice_index + '" onclick="OnRevokeInvoice(' + invoice_index + ')" />').val(GetTextByKey('P_WO_REVOKE', 'Revoke')).hide();
//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': 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.<br/> 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 (!workorderid || 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 (workorderdata) {
$('#dialog_invoice_number').val(workorderdata.InvoiceNumber || '');
$('#dialog_invoice_totalcosts').val(workorderdata.WorkOrderTotalCost == 0 ? "" : workorderdata.WorkOrderTotalCost);
$('#dialog_invoice_othercost').val(workorderdata.OtherCost == 0 ? "" : workorderdata.OtherCost);
$('#dialog_invoice_partscost').val(workorderdata.PartsCost == 0 ? "" : workorderdata.PartsCost);
$('#dialog_invoice_traveltimecost').val(workorderdata.TravelTimeCost == 0 ? "" : workorderdata.TravelTimeCost);
$('#dialog_invoice_laborcost').val(workorderdata.LaborCost == 0 ? "" : workorderdata.LaborCost);
$('#dialog_invoice_taxes').val(workorderdata.Taxes == 0 ? "" : 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));
}
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];
}
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() {
$('#popup_publish_invoice_mask').css('height', $('#dialog_workorder').height());
$('#popup_publish_invoice_mask').show();
$('#dialog_publish_invoice').show();
$('#dialog_invoice_textmsg').val(WorkorderParams.InvoiceMessage);
$('#dialog_publish_invoice').css({
"top": ($("#popup_publish_invoice_mask").height() - $('#dialog_publish_invoice').height()) / 3,
"left": ($("#popup_publish_invoice_mask").width() - $('#dialog_publish_invoice').width()) / 3
});
$('#dialog_invoice_phonenum').focus();
}
function hidePublishInvoicePopup() {
publish_invoice_index = 0;
$('#popup_publish_invoice_mask').hide();
$('#dialog_publish_invoice').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 (customercontacts) {
for (var j = 0; j < customercontacts.length; j++) {
var c = 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, 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 = $('<tr></tr>').attr('id', att.AttachmentId);
var tdfile = $('<td style=""></td>');
var filename = $("<label style='border-bottom: 1px solid RGB(30, 144, 255);color: RGB(30,144,255);cursor:pointer;'></label>").text(att.Notes === "" ? att.FileName : att.Notes).click(function () {
window.open("../filesvc.ashx?attchid=" + this.parentElement.parentElement.id + "&sourceType=woestimateattachment");
});
var span = $('<span></span>').text(att.AddedByName).css("margin-right", 5).css("margin-left", 5).css("color", "black");
var spanby = $('<span></span>').text(att.AddedOnLocalStr).css("color", "black");
tdfile.append(filename, span, spanby);
if (!WOReadOnly && candelete) {
var tdimg = $('<td style="width:18px;border:none;text-align:center;"></td>');
var imgDom = $('<span class="sbutton icondelete" style="padding:0;" ></span>').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() {
$('#popup_woinvoice_attachment_mask').hide();
$('#dialog_woinvoice_attachment').hide();
}
function openWOInvoiceAttachmentDialog(index) {
cur_invoice_uploaddata = undefined;
cur_invoice_uploadindex = index;
$('#btn_woinvoice_att_save').attr('disabled', false);
$('#tab_woinvoice_atts').empty();
$('#tab_woinvoice_attachments').hide();
$('#popup_woinvoice_attachment_mask').css('height', $('#dialog_workorder').height());
$('#popup_woinvoice_attachment_mask').show();
$('#dialog_woinvoice_attachment').show();
$('#dialog_invoice_att_notes').val('');
$('#dialog_woinvoice_attachment').css({
"top": ($("#popup_woinvoice_attachment_mask").height() - $('#dialog_woinvoice_attachment').height()) / 3,
"left": ($("#popup_woinvoice_attachment_mask").width() - $('#dialog_woinvoice_attachment').width()) / 3
});
$('#dialog_invoice_att_notes').focus();
}
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 = $('<input type="file" style="display: none;" />');
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 = $('<tr></tr>');
var tdfile = $('<td style=""></td>');
var filename = $("<label style='border-bottom: 1px solid RGB(30, 144, 255);color: RGB(30,144,255);cursor:pointer;'></label>").text(data.Notes === "" ? data.File.name : data.Notes);
tdfile.append(filename);
var tdimg = $('<td style="width:18px;border:none;text-align:center;"></td>');
var imgDom = $('<span class="sbutton icondelete" style="padding:0;" ></span>').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 = $('<tr></tr>');
var tdfile = $('<td style=""></td>');
var filename = $("<label style='border-bottom: 1px solid RGB(30, 144, 255);color: RGB(30,144,255);cursor:pointer;'></label>").text(notes === "" ? file.name : notes);
tdfile.append(filename);
var tdimg = $('<td style="width:18px;border:none;text-align:center;"></td>');
var imgDom = $('<span class="sbutton icondelete" style="padding:0;" ></span>').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() {
$('#popup_woinvoice_markpaid_mask').hide();
$('#dialog_woinvoice_markpaid').hide();
}
function openWOInvoiceMarkPaidDialog(index) {
cur_invoice_uploadindex = index;
$('#btn_woinvoice_maikpaid_save').attr('disabled', false);
$('#popup_woinvoice_markpaid_mask').css('height', $('#dialog_workorder').height());
$('#popup_woinvoice_markpaid_mask').show();
$('#dialog_woinvoice_markpaid').show();
$('#dialog_invoice_markpaid_paymentby').val("Credit Card");
$('#dialog_invoice_markpaid_number').val('');
$('#dialog_woinvoice_markpaid').css({
"top": ($("#popup_woinvoice_markpaid_mask").height() - $('#dialog_woinvoice_markpaid').height()) / 3,
"left": ($("#popup_woinvoice_markpaid_mask").width() - $('#dialog_woinvoice_markpaid').width()) / 3
});
$('#dialog_invoice_markpaid_paymentby').focus();
}
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();
});
}
/*****************************************End Invoice*********************************************/
/*****************************************Begin Completed Status**************************************************/
var cur_exit = 0;
var cur_callback = undefined;
function openCompletedStatusDialog(exit, callback) {
cur_exit = exit;
cur_callback = callback;
$('#popupecompletedstatusmask').css('height', $('#dialog_workorder').height());
$('#popupecompletedstatusmask').show();
$('#dialog_completedstatus').show();
$('#dialog_completed_status').dropdownVal('');
$('#dialog_completedstatus').css({
"top": ($("#popupecompletedstatusmask").height() - $('#dialog_completedstatus').height()) / 3,
"left": ($("#popupecompletedstatusmask").width() - $('#dialog_completedstatus').width()) / 3
});
$('#dialog_completed_status').focus();
}
function hideCompletedStatusPopup() {
$('#popupecompletedstatusmask').hide();
$('#dialog_completedstatus').hide();
}
function onSaveCompletedStatus() {
var s = $('#dialog_completed_status').dropdownVal();
$('#dialog_status').dropdownVal(s);
$('.span_required').show();
hideCompletedStatusPopup();
OnSave(cur_exit, cur_callback);
}
/*****************************************End Completed Status**************************************************/
function createSegment(p_div) {
var div = $('<div class="function_title"></div>');
p_div.append(div);
var span_add = $('<span class="sbutton iconadd" data-lgid="P_WO_ADDSEGMENT">Add Segment</span>');
span_add.click(OnAddSegment);
div.append(span_add);
}
function createEstimate(p_div) {
var div = $('<div class="function_title"></div>');
p_div.append(div);
var span_add = $('<span class="sbutton iconadd" data-lgid="P_WO_ADDESTIMATE">Add Estimate</span>');
span_add.click(OnAddEstimate);
div.append(span_add);
}
function createInvoice(p_div) {
var div = $('<div class="function_title"></div>');
p_div.append(div);
var span_add = $('<span class="sbutton iconadd" data-lgid="P_WO_ADDINVOICE">Add Invoice</span>');
span_add.click(OnAddInvoice);
div.append(span_add);
}
function createAlert(p_div) {
var div_ftitle = $('<div class="function_title"></div>');
p_div.append(div_ftitle);
var span_add = $('<span class="sbutton iconadd" id="span_addalerts" data-lgid="P_WO_ADDALERTS">Add Alerts</span>');
span_add.click(OnAddAlerts);
div_ftitle.append(span_add);
var span_del = $('<span class="sbutton icondelete" id="span_removealerts" data-lgid="P_WO_REMOVEALERTS">Remove Alerts</span>');
span_del.click(OnRemoveAlerts);
div_ftitle.append(span_del);
p_div.append('<div class="clear"></div>');
//DTC Alerts
var divdtcalerts = $('<div id="divdtcalerts" style="height: 260px; display: none;"></div>');
divdtcalerts.append('<div class="subtitle"><span data-lgid="P_WO_DTCALERTS">DTC Alerts</span></div>');
divdtcalerts.append('<div id="dtcalertslist"></div>');
p_div.append(divdtcalerts);
//PM Alerts
var divpmaalerts = $('<div id="divpmaalerts" style="height: 260px;"></div>');
var divpmaalerts_title = $('<div class="subtitle"></div>');
var span_addpmalerts = $('<span class="sbutton iconadd" id="btnaddpmalerts" style="color: black;" data-lgid="P_WO_ADDPMALERTS">Add PM Alerts (Alerts not yet triggered)</span>');
span_addpmalerts.click(OnAddAllPMSchedules);
divpmaalerts_title.append('<span data-lgid="P_WO_PMALERTS">PM Alerts</span>');
divpmaalerts_title.append(span_addpmalerts);
divpmaalerts.append(divpmaalerts_title);
divpmaalerts.append('<div id="pmaalertslist"></div>');
p_div.append(divpmaalerts);
//Inspect Alerts
var divispalerts = $('<div id="divinspectalerts" style="height: 260px; display: none;"></div>');
divispalerts.append('<div class="subtitle"><span data-lgid="P_WO_INSPECTALERTS">Inspect Alerts</span></div>');
divispalerts.append('<div id="inspectalertslist"></div>');
p_div.append(divispalerts);
//Oil Alerts
var divoilalerts = $('<div id="divoilalerts" style="height: 260px; display: none;"></div>');
divoilalerts.append('<div class="subtitle"><span data-lgid="P_WO_OILALERTS">Oil Alerts</span></div>');
divoilalerts.append('<div id="oilalertslist"></div>');
p_div.append(divoilalerts);
}
function createAttachment(p_div) {
var div_ftitle = $('<div class="function_title"></div>');
p_div.append(div_ftitle);
var span_add = $('<span class="sbutton iconadd" data-lgid="P_WO_ADDFILE">Add File</span>');
span_add.click(UpLoadWorkOrderAttachment);
div_ftitle.append(span_add);
var span_print = $('<span id="spPrint" class="sbutton iconprint" data-lgid="P_WO_PRINT">Print</span>');
span_print.click(function () { openPAndDGDialog(0) });
div_ftitle.append(span_print);
var span_view = $('<span class="sbutton iconviewatt" id="span_viewatttype" data-lgid="P_WO_XXX">View</span>');
div_ftitle.append(span_view);
//View Menu
var div_viewmenu = $('<div class="panel_holder attviewtypemenus"></div>');
p_div.append(div_viewmenu);
var attviewtypemenu_panel = $('<div id="attviewtypemenu_panel" class="panel" style="min-width: 150px; background-color: white;"></div>');
div_viewmenu.append(attviewtypemenu_panel);
var viewmenu_ul = $('<ul class="lefttitlemenu_ul" style="line-height: 32px;"></ul>')
attviewtypemenu_panel.append(viewmenu_ul);
var viewlarge_li = $('<li><a style="padding-left: 0;"><span class="sbutton iconlarge" data-lgid="P_WO_XXX">Large</span></a></li>');
viewlarge_li.click(function () { onViewAttachment(0); });
viewmenu_ul.append(viewlarge_li);
var viewlist_li = $('<li> <a style="padding-left: 0;"><span class="sbutton iconlist" data-lgid="P_WO_XXX">List</span></a></li>');
viewlist_li.click(function () { onViewAttachment(1); });
viewmenu_ul.append(viewlist_li);
attviewtypemenu_panel.append('<div class="trigledown"></div>');
attviewtypemenu_panel.append('<div class="trigledown white"></div>');
p_div.append('<div id="dialogattdragmask" class="maskbg" style="display: none; z-index: 501;"></div>');
//Large
var div_attlarge = $('<div id="div_attlarge"></div>');
p_div.append(div_attlarge);
//WO Attachments Large
var tb_woattlarge = $('<table id="tb_woattlarge" class="main_table maintenance" ondrop="dropWOAttachment(event)" ondragover="dragOverWOAttachment(event)" onpaste="cutWOAttachment(event)"></table>');
div_attlarge.append(tb_woattlarge);
tb_woattlarge.append('<tr style="line-height: 35px;"><td class="subtitle"><span class="sbutton iconchevrondown woattafoldicon" target="woaatts_tr" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span><span data-lgid="P_WO_WORKORDERATTACHMENTS">Work Order Attachments</span></td></tr>');
tb_woattlarge.append('<tr id="woaatts_tr" class="tr_intervals woattafoldtr"><td><div id="div_woatts" style="min-height: 80px; overflow: auto; padding-left: 20px;"></div></td></tr>');
//Asset Attachments Large
var tb_assetattlarge = $('<table class="main_table maintenance"></table>');
div_attlarge.append(tb_assetattlarge);
tb_assetattlarge.append('<tr style="line-height: 35px;"><td class="subtitle"><span class="sbutton iconchevrondown woattafoldicon" target="woassetatts_tr" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span><span data-lgid="P_WO_ASSETATTACHMENTS">Asset Attachments</span></td></tr>');
tb_assetattlarge.append('<tr id="woassetatts_tr" class="tr_intervals woattafoldtr"><td><div id="div_aatts" style="min-height: 80px; overflow: auto; padding-left: 20px;"></div></td></tr>');
//Inspection Attachments Large
var tb_ispattlarge = $('<table class="main_table maintenance"></table>');
div_attlarge.append(tb_ispattlarge);
tb_ispattlarge.append('<tr style="line-height: 35px;"><td class="subtitle"><span class="sbutton iconchevrondown woattafoldicon" target="woiptatts_tr" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span><span data-lgid="P_WO_INSPECTIONATTACHMENTS">Inspection Attachments</span></td></tr>');
tb_ispattlarge.append('<tr id="woiptatts_tr" class="tr_intervals woattafoldtr"><td><div id="div_iatts" style="min-height: 80px; overflow: auto; padding-left: 20px;"></div></td></tr>');
//List
var div_attlist = $('<div id="div_attlist" style="display: none;"></div>');
p_div.append(div_attlist);
//WO Attachments List
var tb_wolist = $('<table class="main_table maintenance" ondrop="dropWOAttachment(event)" ondragover="dragOverWOAttachment(event)" onpaste="cutWOAttachment(event)"></table>');
div_attlist.append(tb_wolist);
var tr_wolist = $('<tr style="line-height: 35px;"></tr>');
tb_wolist.append(tr_wolist);
var td_wolist = $('<td class="subtitle"></td>');
tr_wolist.append(td_wolist);
td_wolist.append('<span class="sbutton iconchevrondown woattafoldicon" target="woattslist_tr" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>');
td_wolist.append('<span data-lgid="P_WO_WORKORDERATTACHMENTS">Work Order Attachments</span>');
td_wolist.append('<lable class="lable_attuploadname" style="margin-left: 200px;"></lable>');
tr_wolist = $('<tr id="woattslist_tr" class="tr_intervals woattafoldtr"></tr>');
tb_wolist.append(tr_wolist);
td_wolist = $('<td></td>');
tr_wolist.append(td_wolist);
var tab_woattslist = $('<table class="table_intervals"></table>');
td_wolist.append(tab_woattslist);
tab_woattslist.append('<thead><tr><th style="width: 30px;"></th><th style="width: 60px;"></th><th style="width: 400px; padding-left: 20px;" data-lgid="P_WO_XXX">Caption</th><th style="width: 130px;" data-lgid="P_WO_AVAILABLETOCUSTOMER"></th><th class="td_funcs"></th></tr></thead>');
tab_woattslist.append('<tbody id="woattslist_tbody"></tbody>');
//Asset Attachments List
var tb_assetlist = $('<table class="main_table maintenance"></table>');
div_attlist.append(tb_assetlist);
var tr_assetlist = $('<tr style="line-height: 35px;"></tr>');
tb_assetlist.append(tr_assetlist);
var td_assetlist = $('<td class="subtitle"></td>');
tr_assetlist.append(td_assetlist);
td_assetlist.append('<span class="sbutton iconchevrondown woattafoldicon" target="woassetattslist_tr" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>');
td_assetlist.append('<span data-lgid="P_WO_ASSETATTACHMENTS">Asset Attachments</span>');
tr_assetlist = $('<tr id="woassetattslist_tr" class="tr_intervals woattafoldtr"></tr>');
tb_assetlist.append(tr_assetlist);
td_assetlist = $('<td></td>');
tr_assetlist.append(td_assetlist);
var tab_assetattslist = $('<table class="table_intervals"></table>');
td_assetlist.append(tab_assetattslist);
tab_assetattslist.append('<thead><tr><th style="width: 30px;"></th><th style="width: 60px;"></th><th style="width: 400px; padding-left: 20px;" data-lgid="P_WO_XXX">Caption</th><th style="width: 130px;"></th><th class="td_funcs"></th></<tr>></thead>');
tab_assetattslist.append('<tbody id="woassetattslist_tbody"></tbody>');
//Inspection Attachments List
var tb_isplist = $('<table class="main_table maintenance"></table>');
div_attlist.append(tb_isplist);
var tr_isplist = $('<tr style="line-height: 35px;"></tr>');
tb_isplist.append(tr_isplist);
var td_isplist = $('<td class="subtitle"></td>');
tr_isplist.append(td_isplist);
td_isplist.append('<span class="sbutton iconchevrondown woattafoldicon" target="woiptattslist_tr" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>');
td_isplist.append('<span data-lgid="P_WO_INSPECTIONATTACHMENTS">Inspection Attachments</span>');
tr_isplist = $('<tr id="woiptattslist_tr" class="tr_intervals woattafoldtr"></tr>');
tb_isplist.append(tr_isplist);
tb_isplist = $('<td></td>');
tr_isplist.append(tb_isplist);
var tab_ispattslist = $('<table class="table_intervals"></table>');
tb_isplist.append(tab_ispattslist);
tab_ispattslist.append('<thead><tr> <th style="width: 30px;"></th><th style="width: 60px;"></th><th style="width: 400px; padding-left: 20px;" data-lgid="P_WO_XXX">Caption</th><th style="width: 130px;"></th><th class="td_funcs"></th></tr></thead>');
tab_ispattslist.append('<tbody id="woiptattslist_tbody"></tbody>');
var div_attuoloadmsgmenus = $('<div class="panel_holder attuoloadmsgmenus"></div>')
p_div.append(div_attuoloadmsgmenus);
var attuplodmsg_panel = $('<div id="attuplodmsg_panel" class="panel" style="min-width: 150px; background-color: white; max-width: 480px; max-height: 400px;"></div>');
div_attuoloadmsgmenus.append(attuplodmsg_panel);
attuplodmsg_panel.append('<ul class="lefttitlemenu_ul" id="attupload_ul"></ul>')
attuplodmsg_panel.append('<div class="trigledown"></div>')
attuplodmsg_panel.append('<div class="trigledown white"></div>')
}