using Foresight.Data; using Foresight.Fleet.Services.Asset; using Foresight.Fleet.Services.AssetHealth; using Foresight.Fleet.Services.Attachment; using Foresight.Fleet.Services.JobSite; using Foresight.ServiceModel; using IronIntel.Contractor.Attachment; using IronIntel.Contractor.JobSites; using IronIntel.Contractor.Machines; using IronIntel.Contractor.Maintenance; using IronIntel.Contractor.MapView; using IronIntel.Contractor.Users; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace IronIntel.Contractor.Site.Maintenance { public class WorkOrderBasePage : ContractorBasePage { protected void ProcessRequest(string methodName) { object result = null; if (methodName != null) { switch (methodName.ToUpper()) { case "GETWORKORDERS": result = GetWorkOrders(); break; case "SAVEWORKORDER": result = SaveWorkOrder(); break; case "DELETEWORKORDER": result = DeleteWorkOrder(); break; case "GETCONTACTS": result = GetContacts(); break; case "GETMACHINES": result = GetMachines(); break; case "GETWORKORDERINFO": result = GetWorkOrderInfo(); break; case "GETOPENWORKORDERID": result = GetOpenWorkOrderID(); break; case "GETSEGMENTS": result = GetSegments(); break; case "SAVESEGMENT": result = SaveSegment(); break; case "DELETESEGMENT": result = DeleteSegment(); break; case "GETSEGMENTCLIENT": result = GetSegmentClient(); break; case "GETNONEASSIGNEDALERTS": result = GetNoneAssignedAlerts(); break; case "ADDORREMOVEALERTSFROMWORKORDER": result = AddOrRemoveAlertsFromWorkOrder(); break; case "GETATTACHMENTS": result = GetAttachments(); break; case "ADDATTACHMENT": result = AddAttachment(); break; case "DELETEATTACHMENT": result = DeleteAttachment(); break; case "GETASSETATTACHMENTS": result = GetAssetAttachments(); break; case "GETMACHINECONTACTS": result = GetMachineContacts(); break; case "SENDWORKORDER": result = SendWorkOrder(); break; case "GETINVOICENUMBER": result = GetInvoiceNumber(); break; case "GETALERTSFORWORKORDER": result = GetAlertsForWorkOrder(); break; } } string json = JsonConvert.SerializeObject(result); Response.Write(json); Response.End(); } private object GetWorkOrders() { try { var session = GetCurrentLoginSession(); if (session != null) { var clientdata = Request.Form["ClientData"]; clientdata = HttpUtility.HtmlDecode(clientdata); WorkOrderQueryParams p = JsonConvert.DeserializeObject(clientdata); WorkOrderItem[] workorders = null; if (p.AssetID > 0) workorders = CreateClient().GetWorkOrderItemsByAsset(SystemParams.CompanyID, p.AssetID); else workorders = CreateClient().GetWorkOrderItems(SystemParams.CompanyID, p.Contacts, p.Status, p.AssetGroups, p.SearchText, session.User.UID); WorkOrderInfo[] maintenanceworkorders = null;// if (p.ShowMaintenance) maintenanceworkorders = MaintenanceManagement.GetMaintenanceWorkOrders(session.SessionID, SystemParams.CompanyID, p.Contacts, p.AssetGroups, p.SearchText, session.User.UID); //普通用户机器权限过滤 var user = GetCurrentUser(); long[] availableAssetsids = null; if (user.UserType < UserTypes.Admin) availableAssetsids = CreateClient().GetAvailableAssetsForUsers(SystemParams.CompanyID, session.User.UID); List list = new List(); if (maintenanceworkorders != null) { foreach (WorkOrderInfo wi in maintenanceworkorders) { if (availableAssetsids != null && !availableAssetsids.Contains(wi.AssetID)) continue; list.Add(wi); } } foreach (WorkOrderItem wo in workorders) { WorkOrderInfo wi = new WorkOrderInfo(); Helper.CloneProperty(wi, wo); if (availableAssetsids != null && !availableAssetsids.Contains(wi.AssetID)) continue; list.Add(wi); } return list.OrderBy(m => m.ID).ToArray(); } else return new WorkOrderInfo[0]; } catch (Exception ex) { AddLog("ERROR", "WorkOrderBasePage.GetWorkOrders", ex.Message, ex.ToString()); return ex.Message; } } private object GetWorkOrderInfo() { try { if (GetCurrentLoginSession() != null) { var woid = Request.Form["ClientData"]; WorkOrderDetail wod = CreateClient().GetWorkOrderDetail(SystemParams.CompanyID, Convert.ToInt64(woid)); WorkOrderDetailInfo wo = new WorkOrderDetailInfo(); Helper.CloneProperty(wo, wod); return wo; } else return new WorkOrderDetailInfo(); } catch (Exception ex) { AddLog("ERROR", "WorkOrderBasePage.GetWorkOrderInfo", ex.Message, ex.ToString()); return ex.Message; } } private object GetAlertsForWorkOrder() { try { if (GetCurrentLoginSession() != null) { var clientdata = Request.Form["ClientData"]; clientdata = HttpUtility.HtmlDecode(clientdata); string[] ps = JsonConvert.DeserializeObject(clientdata); var woid = ps[0]; var aid = ps[1]; long workorderid = Convert.ToInt64(woid); long assetid = Convert.ToInt64(aid); AlertManager am = new AlertManager(SystemParams.DataDbConnectionString); AlertInfo[] alerts = am.GetAlertsByWorkOrder(workorderid); AssetAlertItem[] aAlerts = CreateClient().GetNoneAssignedAlerts(SystemParams.CompanyID, assetid); List assetAlerts = new List(); if (aAlerts != null) { foreach (var aa in aAlerts) { AlertInfo ai = new AlertInfo(); ai.AlertID = aa.ID; ai.MachineID = aa.AssetID; ai.AlertType = aa.AlertType; ai.Description = aa.Description; ai.AlertTime_UTC = aa.AlertTime; assetAlerts.Add(ai); } } WorkorderAlerts wa = new WorkorderAlerts(); wa.Alerts = alerts; wa.AssetAlerts = assetAlerts.ToArray(); ; return wa; } else return null; } catch (Exception ex) { AddLog("ERROR", "AlertsBasePage.GetAlertsByWorkOrder", ex.Message, ex.ToString()); return ex.Message; } } private object GetOpenWorkOrderID() { try { if (GetCurrentLoginSession() != null) { var mid = Request.Form["ClientData"]; long aid = 0; long.TryParse(mid, out aid); var wos = CreateClient().GetWorkOrderItemsByAsset(SystemParams.CompanyID, aid); List workorderids = new List(); foreach (var wo in wos) { if (!wo.Completed) workorderids.Add(wo.ID); } //WorkOrderManager workordermanager = new WorkOrderManager(SystemParams.DataDbConnectionString); //long[] workorderids = workordermanager.GetOpenWorkOrderID(mid); string ids = string.Join(", ", workorderids); ids = mid + "|" + ids; return ids; } else return new WorkOrderInfo(); } catch (Exception ex) { AddLog("ERROR", "WorkOrderBasePage.GetOpenWorkOrderID", ex.Message, ex.ToString()); return ex.Message; } } private object SaveWorkOrder() { try { var session = GetCurrentLoginSession(); if (session != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var workorderitem = HttpUtility.HtmlDecode(clientdata[0]); var ids = HttpUtility.HtmlDecode(clientdata[1]); long[] alertids = JsonConvert.DeserializeObject(ids); WorkOrderDetailInfo wdi = JsonConvert.DeserializeObject(workorderitem); if (wdi.CompleteDate != null) wdi.Status = "Completed"; WorkOrderDetail wo = new WorkOrderDetail(); Helper.CloneProperty(wo, wdi); long workorderid = wo.ID; if (wo.ID == -1) { wo = CreateClient().AddNewWorkOrder(SystemParams.CompanyID, wo, alertids, session.User.UID); workorderid = wo.ID; } else { WorkOrderDetail oldwo = CreateClient().GetWorkOrderDetail(SystemParams.CompanyID, workorderid); var user = UserManagement.GetUserByIID(session.User.UID); if (oldwo.Status == "Completed" && user.UserType < UserTypes.Admin) { return ""; } CreateClient().UpdateWorkOrder(SystemParams.CompanyID, wo, session.User.UID); } return workorderid; } else return "Failed"; } catch (Exception ex) { return ex.Message; } } private object DeleteWorkOrder() { try { var session = GetCurrentLoginSession(); if (session != null) { string clientdata = Request.Form["ClientData"]; int id = Convert.ToInt32(HttpUtility.HtmlDecode(clientdata)); CreateClient().DeleteWorkOrder(SystemParams.CompanyID, id, session.User.UID); return "OK"; } return "Failed"; } catch (Exception ex) { return ex.Message; ; } } private UserInfo[] GetContacts() { var session = GetCurrentLoginSession(); UserInfo[] users = null; if (GetCurrentLoginSession() != null) { //contact = ContactManagement.GetContacts(); users = UserManagement.GetActiveUsers(session.SessionID); users = users.OrderBy(u => u.DisplayName).ToArray(); } else { users = new UserInfo[0]; } return users; } private MachineItem[] GetMachines() { var session = GetCurrentLoginSession(); MachineItem[] machines = null; if (GetCurrentLoginSession() != null) { machines = MachineManagement.GetMachines(session.SessionID, session.User.UID, ""); } else { machines = new MachineItem[0]; } return machines.Where(m => m.Hide == false).OrderBy(m => m.DisplayName).ToArray(); } private object GetNoneAssignedAlerts() { try { if (GetCurrentLoginSession() != null) { var id = Request.Form["ClientData"]; long assetid = Convert.ToInt64(id); AssetAlertItem[] alerts = CreateClient().GetNoneAssignedAlerts(SystemParams.CompanyID, assetid); if (alerts == null || alerts.Length == 0) return new AssetAlertInfo[0]; List list = new List(); foreach (AssetAlertItem alert in alerts) { AssetAlertInfo ai = new AssetAlertInfo(); Helper.CloneProperty(ai, alert); ai.AlertTime = ai.AlertTime.ToLocalTime(); ai.CompletedDate = ai.AlertTime.ToLocalTime(); list.Add(ai); } return list.ToArray(); } else return new AssetAlertInfo[0]; } catch (Exception ex) { AddLog("ERROR", "AlertsBasePage.GetNoneAssignedAlerts", ex.Message, ex.ToString()); return ex.Message; } } private object AddOrRemoveAlertsFromWorkOrder() { try { var session = GetCurrentLoginSession(); if (session != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var woid = HttpUtility.HtmlDecode(clientdata[0]); var ids = HttpUtility.HtmlDecode(clientdata[1]); var isaddstr = HttpUtility.HtmlDecode(clientdata[2]); bool isadd = Helper.IsTrue(isaddstr); long[] alertids = JsonConvert.DeserializeObject(ids); CreateClient().AddOrRemoveAlertsFromWorkOrder(SystemParams.CompanyID, Convert.ToInt64(woid), alertids, isadd, session.User.UID); return "OK"; } else return "Failed"; } catch (Exception ex) { return ex.Message; } } #region Segment private object GetSegmentClient() { try { var session = GetCurrentLoginSession(); if (session != null) { SegmentClient client = new SegmentClient(); client.Users = UserManagement.GetUsers(); if (client.Users == null) client.Users = new UserInfo[0]; var jss = CreateClient().GetJobSiteItems(SystemParams.CompanyID, "", false); List list = new List(); foreach (var js in jss) { JobSiteViewItem item = new JobSiteViewItem(); item.ID = js.ID; item.Name = js.Name; list.Add(item); } client.JobSites = list.ToArray(); if (client.JobSites == null) client.JobSites = new JobSiteViewItem[0]; return client; } else return new SegmentClient(); } catch (Exception ex) { AddLog("ERROR", "WorkOrderBasePage.GetSegmentClient", ex.Message, ex.ToString()); return ex.Message; } } private object GetSegments() { try { var session = GetCurrentLoginSession(); if (session != null) { string clientdata = Request.Form["ClientData"]; long woid = Convert.ToInt64(HttpUtility.HtmlDecode(clientdata)); WorkOrderSegmentItem[] segments = CreateClient().GetSegments(SystemParams.CompanyID, woid); if (segments == null || segments.Length == 0) return new SegmentInfo[0]; List list = new List(); foreach (WorkOrderSegmentItem se in segments) { SegmentInfo si = new SegmentInfo(); Helper.CloneProperty(si, se); list.Add(si); } return list.ToArray(); } else return new SegmentInfo[0]; } catch (Exception ex) { AddLog("ERROR", "WorkOrderBasePage.GetSegments", ex.Message, ex.ToString()); return ex.Message; } } private object SaveSegment() { try { var session = GetCurrentLoginSession(); if (session != null) { string clientdata = Request.Form["ClientData"]; SegmentInfo si = JsonConvert.DeserializeObject(clientdata); if (si.CompletedDate != null) si.Completed = true; WorkOrderSegmentItem segment = new WorkOrderSegmentItem(); Helper.CloneProperty(segment, si); long segmentid = segment.SegmentID; if (segmentid == -1) { segment = CreateClient().AddSegment(SystemParams.CompanyID, segment, session.User.UID); segmentid = segment.SegmentID; } else { CreateClient().UpdateSegment(SystemParams.CompanyID, segment, session.User.UID); } return segmentid; } else return "Failed"; } catch (Exception ex) { return ex.Message; } } private object DeleteSegment() { try { var session = GetCurrentLoginSession(); if (session != null) { string clientdata = Request.Form["ClientData"]; int id = Convert.ToInt32(HttpUtility.HtmlDecode(clientdata)); CreateClient().DeleteSegment(SystemParams.CompanyID, id, session.User.UID); return "OK"; } return "Failed"; } catch (Exception ex) { return ex.Message; ; } } #endregion #region Attachment private object GetAttachments() { try { if (GetCurrentLoginSession() != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var woid = HttpUtility.HtmlDecode(clientdata[0]); AttachmentInfo[] atts = CreateClient().GetAttachments(SystemParams.CompanyID, "WorkOrder", woid); if (atts == null || atts.Length <= 0) return new AttachmentItem[0]; List list = new List(); foreach (AttachmentInfo att in atts) { AttachmentItem item = new AttachmentItem(); Helper.CloneProperty(item, att); item.AddedOn = item.AddedOn.AddHours(SystemParams.GetHoursOffset()); list.Add(item); } return list.OrderBy(m => m.AddedOn).ToArray(); } else return new AttachmentItem[0]; } catch (Exception ex) { return ex.Message; } } private object AddAttachment() { try { var session = GetCurrentLoginSession(); if (session != null) { string woid = HttpUtility.HtmlDecode(Request.Form["ClientData"]); HttpPostedFile uploadFile = null; byte[] iconfilebyte = null; if (Request.Files.Count > 0) { uploadFile = Request.Files[0]; iconfilebyte = ConvertFile2bytes(uploadFile); } AttachmentInfo attachment = new AttachmentInfo(); attachment.StringID = Guid.NewGuid().ToString().ToUpper(); attachment.FileName = uploadFile == null ? "" : uploadFile.FileName; attachment.Source = "WorkOrder"; attachment.SourceID = woid; attachment.FileData = iconfilebyte; attachment.AddedByUserIID = session.User.UID; string attid = CreateClient().AddAttachmentLegacy(SystemParams.CompanyID, attachment); return "OK"; } return "Failed"; } catch (Exception ex) { return ex.Message; } } private object DeleteAttachment() { try { var session = GetCurrentLoginSession(); if (session != null) { string attachid = HttpUtility.HtmlDecode(Request.Form["ClientData"]); CreateClient().DeleteAttachmentLegacy(SystemParams.CompanyID, attachid, session.User.UID); return "OK"; } return "Failed"; } catch (Exception ex) { return ex.Message; } } private object GetAssetAttachments() { try { if (GetCurrentLoginSession() != null) { var assetid = Request.Form["ClientData"]; AssetAttachmentInfo[] atts = CreateClient().GetAttachments(SystemParams.CompanyID, Convert.ToInt64(assetid)).Where(m => m.VisibleOnWorkOrder == true).ToArray(); if (atts == null || atts.Length <= 0) return new AssetAttachmentItem[0]; List list = new List(); foreach (AssetAttachmentInfo att in atts) { AssetAttachmentItem item = new AssetAttachmentItem(); Helper.CloneProperty(item, att); item.AddedOn = item.AddedOn.AddHours(SystemParams.GetHoursOffset()); list.Add(item); } return list.OrderBy(m => m.AddedOn).ToArray(); } else return new AssetAttachmentInfo[0]; } catch (Exception ex) { return ex.Message; } } #endregion #region Sned Email private object GetMachineContacts() { try { var session = GetCurrentLoginSession(); if (session != null) { var assetid = Request.Form["ClientData"]; return UserManagement.GetUsersByAssetID(session.SessionID, Convert.ToInt64(assetid), SystemParams.CompanyID); } else return new UserInfo[0]; } catch (Exception ex) { return ex.Message; } } private object SendWorkOrder() { try { var session = GetCurrentLoginSession(); if (session != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var woid = HttpUtility.HtmlDecode(clientdata[0]); var address = HttpUtility.HtmlDecode(clientdata[1]); var desc = HttpUtility.HtmlDecode(clientdata[2]); string[] emailaddress = JsonConvert.DeserializeObject(address); WorkOrderDetail wod = CreateClient().GetWorkOrderDetail(SystemParams.CompanyID, Convert.ToInt64(woid)); WorkOrderDetailInfo wo = new WorkOrderDetailInfo(); Helper.CloneProperty(wo, wod); SendMail(wo, emailaddress, desc, session.User); return "OK"; } else return "Failed"; } catch (Exception ex) { return ex.Message; } } private void SendMail(WorkOrderDetailInfo wo, string[] emailaddress, string desc, Services.Users.UserInfoEx user) { if (emailaddress == null || emailaddress.Length == 0) return; string Subject = "Work Order " + wo.ID; string Body = OrdinaryEmailFormat(wo, desc, user.ID); CreateClient().SendWorkOrderEmail(SystemParams.CompanyID, wo.ID, Subject, Body, emailaddress.ToArray(), user.UID); } private string OrdinaryEmailFormat(WorkOrderDetailInfo wo, string desc, string userid) { string EmailFormat = ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += "
Details for work order <{3}> are listed below.To view or edit this work order,please click the below link:
Link
Message from: {0}
Description: 
{1}
Work Order Information: 
{2}
"; string absuri = Context.Request.Url.AbsoluteUri; string wourl = absuri.Substring(0, absuri.LastIndexOf("/Maintenance", StringComparison.OrdinalIgnoreCase)); wourl = wourl + "/jump.aspx?p=" + Convert.ToBase64String(Encoding.UTF8.GetBytes("jt=woe;woid=" + wo.ID)); return string.Format(EmailFormat, userid, desc.Replace("\n", "
"), WorkOrderFormat(wo), wo.ID, wourl); } public static string WorkOrderFormat(WorkOrderDetailInfo wo) { string EmailFormat = ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; if (string.Compare(wo.MeterType, "HourMeter", true) == 0 || string.Compare(wo.MeterType, "Both", true) == 0) EmailFormat += ""; if (string.Compare(wo.MeterType, "Odometer", true) == 0 || string.Compare(wo.MeterType, "Both", true) == 0) EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += ""; EmailFormat += "
Work Order Type: {0}
Assigned To: {1}
Status: {2}
Due Date: {3}
Description: {4}
Meter Type: {5}
Hour Meter: {6}
Odometer: {7} {8}
Work Order Total Costs ($): {9}
Other Cost ($): {19}
Parts Cost ($): {14}
Travel Time Cost ($): {15}
Labor Cost ($): {16}
Hourly Rate: {17}
Time To Complete(Hrs): {10}
Completed Date: {11}
Internal ID: {12}
Invoice Number: {18}
Notes: {13}
"; string SendStr = string.Format(EmailFormat, HttpUtility.HtmlEncode(wo.WorkOrderType), HttpUtility.HtmlEncode(wo.AssignedToName), HttpUtility.HtmlEncode(wo.Status), HttpUtility.HtmlEncode(wo.DueDateStr), HttpUtility.HtmlEncode(wo.Description).Replace("\n", "
"), HttpUtility.HtmlEncode(wo.MeterType), HttpUtility.HtmlEncode(wo.HourMeter), HttpUtility.HtmlEncode(wo.Odometer), HttpUtility.HtmlEncode(wo.OdometerUnits), HttpUtility.HtmlEncode(wo.WorkOrderTotalCost), HttpUtility.HtmlEncode(wo.HoursToComplete), HttpUtility.HtmlEncode(wo.CompleteDateStr), HttpUtility.HtmlEncode(wo.InternalID), HttpUtility.HtmlEncode(wo.Notes).Replace("\n", "
"), HttpUtility.HtmlEncode(wo.PartsCost), HttpUtility.HtmlEncode(wo.TravelTimeCost), HttpUtility.HtmlEncode(wo.LaborCost), HttpUtility.HtmlEncode(wo.HourlyRate), HttpUtility.HtmlEncode(wo.InvoiceNumber), HttpUtility.HtmlEncode(wo.OtherCost)); return SendStr; } #endregion private object GetInvoiceNumber() { try { if (GetCurrentLoginSession() != null) { var woid = Request.Form["ClientData"]; return new WorkOrderManager(SystemParams.DataDbConnectionString).GetInvoiceNumber(woid); } else return new string[0]; } catch (Exception ex) { return ex.Message; } } } public class SegmentClient { public UserInfo[] Users { get; set; } public JobSiteViewItem[] JobSites { get; set; } } public class WorkOrderQueryParams { public long AssetID { get; set; } public string SearchText { get; set; } public string[] Contacts { get; set; } public string[] Status { get; set; } public string[] AssetGroups { get; set; } public bool ShowMaintenance { get; set; } } class WorkorderAlerts { public AlertInfo[] Alerts { get; set; } public AlertInfo[] AssetAlerts { get; set; } } }