using Foresight.Data; using Foresight.Fleet.Services; using Foresight.Fleet.Services.Asset; using Foresight.Fleet.Services.AssetHealth; using Foresight.Fleet.Services.Device; using Foresight.Fleet.Services.User; using Foresight.ServiceModel; using IronIntel.Contractor.Machines; using IronIntel.Contractor.Maintenance; 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.Asset { public class AssetBasePage : ContractorBasePage { protected void ProcessRequest(string method) { object result = null; string methodName = Request.Params["MethodName"]; try { if (methodName != null) { switch (methodName.ToUpper()) { case "GETMACHINESBYCOMPANY": result = GetMachinesByCompany(); break; case "GETMACHINEINFO": result = GetMachineInfo(); break; case "SAVEMACHINE": result = SaveMachine(); break; case "CHANGEMACHINEICONFILE": result = ChangeMachineIconFile(); break; case "GETMACHINEATTRIBUTES": result = GetMachineAttributes(); break; case "GETCUSTOMERTIMEZONE": result = GetCustomerTimeZone(); break; case "GETODOMETERADJUSTMENTHISTORY": result = GetOdometerAdjustmentHistory(); break; case "GETENGINEHOURSADJUSTMENTHISTORY": result = GetEngineHoursAdjustmentHistory(); break; case "GETPMSCHEDULESBYASSET": result = GetPMSchedulesByAsset(); break; case "ADDASSETTOPMSCHEDULE": result = AddAssetToPMSchedule(); break; case "REMOVEASSETFROMPMSCHEDULE": result = RemoveAssetFromPMSchedule(); break; case "CHANGEASSETPROPERTY": result = ChangeAssetProperty(); break; } } } catch (Exception ex) { SystemParams.WriteLog("error", "AssetBasePage", ex.Message, ex.ToString()); throw ex; } string json = JsonConvert.SerializeObject(result); Response.Write(json); Response.End(); } private object GetMachinesByCompany() { try { var session = GetCurrentLoginSession(); if (session != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var companyid = HttpUtility.HtmlDecode(clientdata[0]); bool showHidden = HttpUtility.HtmlDecode(clientdata[1]) == "1"; var searchtxt = HttpUtility.HtmlDecode(clientdata[2]); if (string.IsNullOrEmpty(companyid)) companyid = SystemParams.CompanyID; if (string.IsNullOrWhiteSpace(companyid) && SystemParams.IsDealer) return new MachineItem[0]; //GpsDeviceInfo[] devs = SystemParams.DeviceProvider.GetDeviceItems(contractorid, ""); AssetBasicInfo[] assets = CreateClient(companyid).GetAssetBasicInfoByUser(companyid, searchtxt, session.User.UID); List list = new List(); foreach (var a in assets) { if (!showHidden && a.Hide) continue; AssetBasicItem asset = new AssetBasicItem(); Helper.CloneProperty(asset, a); list.Add(asset); } return list.OrderBy((m) => m.VIN).ToArray(); } else return new MachineItem[0]; } catch (Exception ex) { AddLog("ERROR", "AssetBasePage.GetMachinesByCompany", ex.Message, ex.ToString()); return ex.Message; } } private object GetMachineInfo() { try { if (GetCurrentLoginSession() != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var companyid = HttpUtility.HtmlDecode(clientdata[0]); var mid = HttpUtility.HtmlDecode(clientdata[1]); long machineid = -1; long.TryParse(mid, out machineid); string connectionStr = string.Empty; if (!SystemParams.IsDealer) { companyid = SystemParams.CompanyID; connectionStr = SystemParams.DataDbConnectionString; } else { string connetionstring = SystemParams.GetDbStringByCompany(companyid); connectionStr = connetionstring; } var client = CreateClient(companyid); AssetDetailInfo2 assetDetail = client.GetAssetDetailInfo2(companyid, machineid); MachineOtherInfo mother = client.GetMachineOtherInfo(companyid, machineid); AssetDetailItem2 assetItem = new AssetDetailItem2(); Helper.CloneProperty(assetItem, assetDetail); assetItem.OnSiteJobsiteID = mother.JobSiteID; assetItem.ContactIDs = string.IsNullOrEmpty(mother.ContactIDs) ? new string[0] : mother.ContactIDs.Split(','); assetItem.MachineGroupIDs = string.IsNullOrEmpty(mother.GroupIDs) ? new string[0] : mother.GroupIDs.Split(','); //MachineRentalInfo[] machinerentals = new RentalManagement(connectionStr).SearchRentalsByAsset(machineid); //if (machinerentals != null && machinerentals.Length > 0) //{ // DateTime nowdate = DateTime.Now; // //当前时间所在的rental // MachineRentalInfo rental = machinerentals.FirstOrDefault(m => m.RentalDate <= nowdate && nowdate.Date <= ((m.ReturnDate ?? m.ProjectReturnDate ?? DateTime.MaxValue))); // if (rental == null)//当前时间的下一个rental // rental = machinerentals.Where(m => m.RentalDate >= nowdate.Date).OrderBy(m => m.RentalDate).FirstOrDefault(); // if (rental == null)//最新rental // rental = machinerentals[0]; // assetItem.MachineRental = rental; //} if (assetItem.UnderCarriageHours != null) assetItem.UnderCarriageHours = Math.Round(assetItem.UnderCarriageHours.Value, 2); return assetItem; } else return new AssetDetailItem2(); } catch (Exception ex) { SystemParams.WriteLog("error", "AssetBasePage.GetMachineInfo", ex.Message, ex.ToString()); return ex.Message; } } private object SaveMachine() { try { var session = GetCurrentLoginSession(); if (session != null) { if (!CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.MANAGE_ASSETS)) return ""; string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]); AssetDetailItem2 asset = JsonConvert.DeserializeObject(clientdata); if (SystemParams.IsDealer && string.IsNullOrWhiteSpace(asset.ContractorID)) return "Failed"; string connectionStr = string.Empty; string customerid = string.Empty; if (SystemParams.IsDealer) { string connetionstring = SystemParams.GetDbStringByCompany(asset.ContractorID); connectionStr = connetionstring; customerid = asset.ContractorID; } else { connectionStr = SystemParams.DataDbConnectionString; customerid = SystemParams.CompanyID; } AssetDataAdjustClient client = CreateClient(customerid); if (asset.ID > 0) { //没有权限修改的,保持原来的值 var oldMachine = client.GetAssetDetailInfo2(customerid, asset.ID); asset.EngineHours = oldMachine.EngineHours;//EngineHours单独保存 var user = UserManagement.GetUserByIID(session.User.UID); bool permission = CheckRight(SystemParams.CompanyID, Feature.MANAGE_ASSETS); if (!permission) { asset.VIN = oldMachine.VIN; asset.MakeID = oldMachine.MakeID; asset.MakeName = oldMachine.MakeName; asset.ModelID = oldMachine.ModelID; asset.ModelName = oldMachine.ModelName; asset.Odometer = oldMachine.Odometer; asset.OdometerUnits = oldMachine.OdometerUnits; } } else if (!asset.IgnoreDuplicate) { long[] dupassets = client.FindAssetsByVIN(customerid, asset.VIN); if (dupassets.Length > 0) { return new { Result = 0, Data = dupassets }; } } AssetDetailInfo2 a = new AssetDetailInfo2(); Helper.CloneProperty(a, asset); a.ID = client.UpdateAssetInfo(customerid, a, asset.ContactIDs, asset.MachineGroupIDs, (int)asset.OnSiteJobsiteID, session.User.UID); UpdateMachineAttributes(a.ID, asset.ContractorID, asset.MachineAttributes, session.User.UID); if (asset.VisibleOnWorkOrders != null) { foreach (StringKeyValue kv in asset.VisibleOnWorkOrders) { CreateClient(customerid).ChangeVisibleOnWorkOrder(customerid, Convert.ToInt32(kv.Key), Helper.IsTrue(kv.Value)); } } long rentalID = -1; if (asset.MachineRental != null) { asset.MachineRental.MachineID = a.ID; AssetRentalInfo rentalinfo = new AssetRentalInfo(); Helper.CloneProperty(rentalinfo, asset.MachineRental); rentalinfo.RentalRate = (double)asset.MachineRental.RentalRate; rentalID = CreateClient(customerid).SaveAssetRental(customerid, rentalinfo, session.User.UID); } return new { Result = 1, Data = new long[] { a.ID, rentalID } }; } else { return "Failed"; } } catch (BusinessException bex) { return bex.Message; } catch (Exception ex) { SystemParams.WriteLog("error", "AssetBasePage.SaveMachine", ex.Message, ex.ToString()); return ex.Message; } } private string ChangeAssetProperty() { try { var user = GetCurrentUser(); if (user != null) { var clientdata = Request.Form["ClientData"]; string[] ps = JsonConvert.DeserializeObject(clientdata); var contractorid = ps[0]; if (string.IsNullOrWhiteSpace(contractorid)) contractorid = SystemParams.CompanyID; long assetid = 0; long.TryParse(ps[1], out assetid); var name = ps[2]; bool value = Helper.IsTrue(ps[3]); switch (name) { case "Hide": CreateClient(contractorid).ChangeAssetHideProperty(contractorid, assetid, value, "", user.IID); break; case "OnRoad": CreateClient(contractorid).ChangeAssetOnRoadProperty(contractorid, assetid, value, "", user.IID); break; case "TelematicsEnabled": CreateClient(contractorid).ChangeAssetTelematicsProperty(contractorid, assetid, value, "", user.IID); break; default: break; } return "OK"; } else return "Failed"; } catch (Exception ex) { return ex.Message; } } #region Machine Attributes private object GetMachineAttributes() { try { if (GetCurrentLoginSession() != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var companyid = HttpUtility.HtmlDecode(clientdata[0]); var id = HttpUtility.HtmlDecode(clientdata[1]); long machineid = Convert.ToInt64(id); if (string.IsNullOrWhiteSpace(companyid)) { if (SystemParams.IsDealer) return new MachineAttributeCategoryClient[0]; companyid = SystemParams.CompanyID; } MachineAttributes abt = CreateClient(companyid).GetMachineAttributes(companyid, machineid); List list = new List(); if (abt != null && abt.Category.Count > 0) { ConvertMachineAttributesCategory(abt, ref list); } return list.OrderBy(m => m.OrderIndex); } else return new MachineAttributeCategoryClient[0]; } catch (Exception ex) { return ex.Message; } } private void UpdateMachineAttributes(long machineid, string companyid, MachineAttributeClient[] attributes, string useriid) { try { if (attributes != null && attributes.Length > 0) { if (string.IsNullOrWhiteSpace(companyid)) companyid = SystemParams.CompanyID; List attritems = new List(); foreach (MachineAttributeClient attclient in attributes) { MachineAttributeItem machineattributeitem = new MachineAttributeItem(); Helper.CloneProperty(machineattributeitem, attclient); attritems.Add(machineattributeitem); } List listcate = new List(); MachineAttributeCategory category = new MachineAttributeCategory(); category.Attributes.AddRange(attritems); listcate.Add(category); MachineAttributes att = new MachineAttributes(); att.Category.AddRange(listcate); CreateClient(companyid).UpdateMachineAttributes(companyid, machineid, att, useriid); } } catch (Exception ex) { AddLog("ERROR", "AssetBasePage.UpdateMachineAttributes", ex.Message, ex.ToString()); throw new Exception(ex.Message); } } private static void ConvertMachineAttributesCategory(MachineAttributes abtc, ref List list) { if (abtc != null && abtc.Category.Count > 0) { foreach (MachineAttributeCategory cateitem in abtc.Category) { MachineAttributeCategoryClient cateclt = new MachineAttributeCategoryClient(); Helper.CloneProperty(cateclt, cateitem); var tab = abtc.Tabs.FirstOrDefault(m => m.ID == cateitem.TabID); if (tab == null) continue; else { cateclt.TabName = tab.Name; cateclt.OrderIndex = abtc.Tabs.IndexOf(tab); } cateclt.MachineAttributes = new List(); foreach (MachineAttributeItem attitem in cateitem.Attributes) { MachineAttributeClient attclt = new MachineAttributeClient(); Helper.CloneProperty(attclt, attitem); cateclt.MachineAttributes.Add(attclt); } list.Add(cateclt); } } } private static void ConvertMachineAttributes(MachineAttributes abtc, ref List list) { if (abtc != null && abtc.Category.Count > 0) { foreach (MachineAttributeCategory cateitem in abtc.Category) { foreach (MachineAttributeItem attitem in cateitem.Attributes) { MachineAttributeClient attclt = new MachineAttributeClient(); Helper.CloneProperty(attclt, attitem); list.Add(attclt); } } } } #endregion #region Odometer Adjustment History private object GetOdometerAdjustmentHistory() { try { if (GetCurrentLoginSession() != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var customerid = HttpUtility.HtmlDecode(clientdata[0]); var assetid = HttpUtility.HtmlDecode(clientdata[1]); var sdate = HttpUtility.HtmlDecode(clientdata[2]); var edate = HttpUtility.HtmlDecode(clientdata[3]); if (string.IsNullOrEmpty(customerid)) customerid = SystemParams.CompanyID; DateTime starttime = Helper.DBMinDateTime; DateTime endtime = DateTime.MaxValue; if (!DateTime.TryParse(sdate, out starttime)) starttime = Helper.DBMinDateTime; if (!DateTime.TryParse(edate, out endtime)) endtime = DateTime.MaxValue; else endtime = endtime.Date.AddDays(1).AddSeconds(-1); AssetOdometerAdjustInfo[] odos = CreateClient(customerid).GetOdometerAdjustmentHistory(customerid, Convert.ToInt64(assetid), starttime, endtime); if (odos == null || odos.Length == 0) return new AssetOdometerAdjustItem[0]; List list = new List(); foreach (AssetOdometerAdjustInfo odo in odos) { AssetOdometerAdjustItem item = new AssetOdometerAdjustItem(); Helper.CloneProperty(item, odo); list.Add(item); } return list.ToArray(); } else return new AssetOdometerAdjustItem[0]; } catch (Exception ex) { return ex.Message; } } #endregion #region Engine Hours Adjustment History private object GetEngineHoursAdjustmentHistory() { try { if (GetCurrentLoginSession() != null) { var clientdata = Request.Form["ClientData"].Split((char)170); var customerid = HttpUtility.HtmlDecode(clientdata[0]); var assetid = HttpUtility.HtmlDecode(clientdata[1]); var sdate = HttpUtility.HtmlDecode(clientdata[2]); var edate = HttpUtility.HtmlDecode(clientdata[3]); if (string.IsNullOrEmpty(customerid)) customerid = SystemParams.CompanyID; DateTime starttime = Helper.DBMinDateTime; DateTime endtime = DateTime.MaxValue; if (!DateTime.TryParse(sdate, out starttime)) starttime = Helper.DBMinDateTime; if (!DateTime.TryParse(edate, out endtime)) endtime = DateTime.MaxValue; else endtime = endtime.Date.AddDays(1).AddSeconds(-1); AssetEngineHoursAdjustInfo[] hours = CreateClient(customerid).GetEngineHoursAdjustmentHistory(customerid, Convert.ToInt64(assetid), starttime, endtime); if (hours == null || hours.Length == 0) return new AssetEngineHoursAdjustItem[0]; List list = new List(); foreach (AssetEngineHoursAdjustInfo hour in hours) { AssetEngineHoursAdjustItem item = new AssetEngineHoursAdjustItem(); Helper.CloneProperty(item, hour); list.Add(item); } return list.ToArray(); } else return new AssetEngineHoursAdjustItem[0]; } catch (Exception ex) { return ex.Message; } } #endregion private object GetCustomerTimeZone() { try { var session = GetCurrentLoginSession(); if (session != null) { string custid = Request.Form["ClientData"]; FISqlConnection db = null; if (SystemParams.IsDealer) { if (string.IsNullOrEmpty(custid)) custid = SystemParams.CompanyID; string connetionstring = SystemParams.GetDbStringByCompany(custid); db = new FISqlConnection(connetionstring); } else custid = SystemParams.CompanyID; StringKeyValue kv = new StringKeyValue(); kv.Key = SystemParams.GetStringParam("CustomerTimeZone", false, db); TimeZoneInfo tz = SystemParams.GetTimeZoneInfo(custid, db); DateTime time = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Now.ToUniversalTime(), tz); kv.Value = time.ToString("MM/dd/yyyy HH:mm:ss"); return kv; } else { throw new Exception("not login."); } } catch (Exception ex) { return ex.Message; } } private object ChangeMachineIconFile() { try { if (GetCurrentLoginSession() != null) { string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]); StringKeyValue kv = JsonConvert.DeserializeObject(clientdata); HttpPostedFile uploadFile = null; byte[] iconfilebyte = null; if (Request.Files.Count > 0) { uploadFile = Request.Files[0]; iconfilebyte = ConvertFile2bytes(uploadFile); } FISqlConnection db = null; if (SystemParams.IsDealer) { string connetionstring = SystemParams.GetDbStringByCompany(kv.Key); db = new FISqlConnection(connetionstring); } MachineManagement.ChangeMachineIconFile(Convert.ToInt64(kv.Value), uploadFile == null ? "" : uploadFile.FileName, iconfilebyte, db); return "OK"; } return "Failed"; } catch (Exception ex) { return ex.Message; } } private object GetPMSchedulesByAsset() { try { var session = GetCurrentLoginSession(); if (session != null) { string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]); long assetid = 0; long.TryParse(clientdata, out assetid); return MaintenanceManagement.GetPmScheduleByAsset(session.SessionID, assetid); } else return new PmScheduleInfo[0]; } catch (Exception ex) { AddLog("ERROR", "AssetBasePage.GetPmSchedules", ex.Message, ex.ToString()); return ex.Message; } } private object AddAssetToPMSchedule() { try { var session = GetCurrentLoginSession(); if (session != null) { string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]); PMScheduleAssetItem p = JsonConvert.DeserializeObject(clientdata); PMAssetInfo pmAsset = new PMAssetInfo(); pmAsset.AssetId = p.AssetId; pmAsset.StartHours = p.StartHours; pmAsset.StartOdometer = p.StartOdometer; pmAsset.StartDate = p.StartDate; pmAsset.StartIntervalValue = p.StartIntervalValue; var client = CreateClient(); client.UpdatePMScheduleAsset(SystemParams.CompanyID, p.PmScheduleID, pmAsset, session.User.UID); if (!string.IsNullOrEmpty(p.SelectedIntervalID)) { //SystemParams.PMClient.TriggerPMAlert(SystemParams.CompanyID, p.PmScheduleID, pmAsset.AssetId); client.GenerateMissedPMAlert(SystemParams.CompanyID, p.SelectedIntervalID, pmAsset.AssetId); } } return "OK"; } catch (Exception ex) { AddLog("ERROR", "AssetBasePage.GetPmSchedules", ex.Message, ex.ToString()); return ex.Message; } } private object RemoveAssetFromPMSchedule() { try { var session = GetCurrentLoginSession(); if (session != null) { string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]); string[] ps = JsonConvert.DeserializeObject(clientdata); long assetid = 0; long.TryParse(ps[0], out assetid); CreateClient().DeleteAssetsFromSchedule(SystemParams.CompanyID, ps[1], new long[] { assetid }, session.User.UID); } return "OK"; } catch (Exception ex) { AddLog("ERROR", "AssetBasePage.GetPmSchedules", ex.Message, ex.ToString()); return ex.Message; } } class PMScheduleAssetItem { public long AssetId { get; set; } public string PmScheduleID { get; set; } public double? StartHours { get; set; } public double? StartOdometer { get; set; } public DateTime? StartDate { get; set; } public int? StartIntervalValue { get; set; } public string SelectedIntervalID { get; set; } } } }