/// <summary> /// Ritorna i dati di barre e spezzoni in base al tipo di aggregazione /// </summary> /// <param name="machine"></param> /// <param name="period"></param> /// <returns>Lista dei dettagli di barre e spezzoni</returns> public List <HistoryBarModel> GetAggregationBar(MachineInfoModel machine, PeriodModel period) { var result = new List <HistoryBarModel>(); try { result = _context.Set <HistoryBar>().Where(hb => hb.MachineId == machine.Id && hb.Day >= period.StartDate && hb.Day <= period.EndDate).GroupBy(g => g.MachineId).Select(n => new HistoryBarModel { Count = n.Count(), Id = n.Max(i => i.Id), Length = n.Sum(i => i.Length), Day = n.Max(i => i.Day), MachineId = n.Key, OffcutCount = n.Sum(i => i.OffcutCount), OffcutLength = n.Sum(i => i.OffcutLength), Period = null, System = null, TypeHistory = "d" }).ToList(); } catch (Exception ex) { string errMessage = string.Format(ex.GetStringLog(), machine.Id.ToString(), string.Concat(period.StartDate.ToString(), " - ", period.EndDate.ToString(), " - ", period.Aggregation.ToString())); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
public List <UserModel> GetCustomers() { List <UserModel> result = null; try { List <string> plants = _fomMonitoringEntities.Set <Plant>().Select(p => p.UserId.ToString()).ToList(); var userQuery = _fomMonitoringEntities.Set <Users>() .Include("Roles_Users") .Include("Roles_Users.Roles") .Include("Languages").AsQueryable() .Where(w => w.Roles_Users.Any(a => a.Roles.IdRole == (int)enRole.Customer) && w.CompanyName != null && plants.Contains(w.ID.ToString())).OrderBy(o => o.CompanyName); var users = userQuery.ToList(); result = users.Adapt <List <Users>, List <UserModel> >(); } catch (Exception ex) { var errMessage = string.Format(ex.GetStringLog()); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
/// <summary> /// Ritorna l'elenco dei job in base all'aggregazione /// </summary> /// <param name="machine"></param> /// <param name="period"></param> /// <returns>Lista dei dettagli degli stati</returns> public List <HistoryJobModel> GetAggregationJobs(MachineInfoModel machine, PeriodModel period) { var result = new List <HistoryJobModel>(); try { result = _context.Set <HistoryJob>().Where(hb => hb.MachineId == machine.Id && hb.Day >= period.StartDate && hb.Day <= period.EndDate).ToList() .GroupBy(g => new { g.MachineId, g.Code, Day = g.Day.Value.Date }) .Select(n => new HistoryJobModel { Id = n.Max(i => i.Id), Code = n.Key.Code, Day = n.Key.Day, MachineId = n.Key.MachineId, TotalPieces = n.OrderByDescending(i => i.Id).FirstOrDefault()?.TotalPieces, ElapsedTime = n.Max(i => i.ElapsedTime), PiecesProduced = GetProdPieces(n.Max(i => i.Id), n.Key.Day), Period = null }).ToList(); } catch (Exception ex) { var errMessage = string.Format(ex.GetStringLog(), machine.Id.ToString(), string.Concat(period.StartDate.ToString(), " - ", period.EndDate.ToString(), " - ", period.Aggregation.ToString())); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
public List <ToolMachineModel> GetTools(MachineInfoModel machine, bool xmodule = false) { List <ToolMachineModel> result = new List <ToolMachineModel>(); try { List <ToolMachine> query = null; if (machine.Type.Id == (int)enMachineType.LineaTaglioLavoro) { Regex regex = new Regex(@"^[1-2]\d{3}$"); if (xmodule) { query = _context.Set <ToolMachine>().Where(w => w.IsActive && w.MachineId == machine.Id).ToList().Where(w => regex.IsMatch(w.Code)).OrderBy(w => w.CodeAsInt).ThenByDescending(w => w.CurrentLife).ToList(); } else { query = _context.Set <ToolMachine>().Where(w => w.IsActive && w.MachineId == machine.Id).ToList().Where(w => !regex.IsMatch(w.Code)).OrderBy(w => w.CodeAsInt).ThenByDescending(w => w.CurrentLife).ToList(); } } else { query = _context.Set <ToolMachine>().Where(w => w.IsActive && w.MachineId == machine.Id).ToList().OrderBy(w => w.CodeAsInt).ThenByDescending(w => w.CurrentLife).ToList(); } result = query.Adapt <List <ToolMachineModel> >(); } catch (Exception ex) { string errMessage = string.Format(ex.GetStringLog(), machine.Id.ToString()); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
public void HistoricizingStates(IFomMonitoringEntities context, int idMachine) { var maxHpDate = context.Set <HistoryState>().Where(historyState => historyState.MachineId == idMachine) .Max(a => a.Day); maxHpDate = maxHpDate?.Date ?? DateTime.MinValue; var historyStates = context.Set <StateMachine>() .Where(p => p.Day >= maxHpDate && p.MachineId == idMachine).ToList() .GroupBy(g => new { g.Day.Value.Date, g.Operator, g.StateId }) .Select(n => new HistoryState { Id = 0, Day = n.Key.Date, MachineId = idMachine, Operator = n.Key.Operator, Period = n.Key.Date.Year * 10000 + n.Key.Date.Month * 100 + n.Key.Date.Day, TypeHistory = "d", ElapsedTime = n.Sum(i => i.ElapsedTime), StateId = n.Key.StateId, OverfeedAvg = n.Key.StateId == 1 ? (n.Sum(i => i.ElapsedTime) > 0 ? n.Sum(i => i.Overfeed * i.ElapsedTime) / n.Sum(i => i.ElapsedTime) : 0) : null, }).ToList(); var aggregato = historyStates.GroupBy(c => new { c.Day, c.StateId }).Select(n => new HistoryState { Id = 0, Day = n.Key.Day.Value, MachineId = idMachine, Operator = null, Period = n.Key.Day.Value.Year * 10000 + n.Key.Day.Value.Month * 100 + n.Key.Day.Value.Day, ElapsedTime = n.Sum(i => i.ElapsedTime), TypeHistory = "d", StateId = n.Key.StateId, OverfeedAvg = n.Key.StateId == 1 ? n.Sum(i => i.ElapsedTime) > 0 ? n.Sum(i => i.OverfeedAvg * i.ElapsedTime) / n.Sum(i => i.ElapsedTime) : 0 : null }).ToList(); historyStates.AddRange(aggregato); foreach (var cur in historyStates) { var row = context.Set <HistoryState>().FirstOrDefault(historyState => historyState.MachineId == idMachine && historyState.Day == cur.Day && historyState.StateId == cur.StateId && (historyState.Operator == cur.Operator || historyState.Operator == null && cur.Operator == null)); if (row != null) { row.ElapsedTime = cur.ElapsedTime; row.OverfeedAvg = cur.OverfeedAvg; } else { context.Set <HistoryState>().Add(cur); } } context.SaveChanges(); }
private void ClearNotificationTable() { var user = _accountService.GetLoggedUser(); var toRemove = _dbContext.Set <MessageMachineNotification>().Where(m => m.UserId == user.ID.ToString()); if (toRemove.Any()) { _dbContext.Set <MessageMachineNotification>().RemoveRange(toRemove); _dbContext.SaveChanges(); } }
public void SetOverrideTimeZoneMachine(int idMachine, Guid idUser, string timezone) { var mapping = _fomMonitoringEntities.Set <UserMachineMapping>() .FirstOrDefault(m => m.MachineId == idMachine && m.UserId == idUser); if (mapping != null) { mapping.TimeZone = timezone; } _fomMonitoringEntities.SaveChanges(); }
public void HistoricizingBars(IFomMonitoringEntities context, int idMachine) { DateTime?maxHpDate = DateTime.MinValue; if (context.Set <HistoryBar>().Any(hp => hp.MachineId == idMachine)) { maxHpDate = context.Set <HistoryBar>().Where(hp => hp.MachineId == idMachine).Max(a => a.Day); } var historyBars = context.Set <Bar>() .Where(p => p.StartTime != null && p.StartTime >= maxHpDate && p.MachineId == idMachine).ToList() .GroupBy(g => g.StartTime.Value.Date) .Select(n => new HistoryBar { Id = 0, Day = n.Key, MachineId = idMachine, TypeHistory = "d", System = null, Period = n.Key.Year * 10000 + n.Key.Month * 100 + n.Key.Day, Length = n.Sum(i => i.IsOffcut == false ? i.Length : 0), OffcutCount = n.Count(i => i.IsOffcut == true), OffcutLength = n.Sum(i => i.IsOffcut == true ? (int)i.Length : 0), Count = n.Count() }).ToList(); foreach (var cur in historyBars) { var row = context.Set <HistoryBar>().FirstOrDefault(hp => hp.MachineId == idMachine && hp.Day == cur.Day); if (row != null) { row.Count = cur.Count; row.Length = cur.Length; row.OffcutCount = cur.OffcutCount; row.OffcutLength = cur.OffcutLength; } else { context.Set <HistoryBar>().Add(cur); } } }
public void HistoricizingMessages(IFomMonitoringEntities context, int idMachine) { var maxHpDate = context.Set <HistoryMessage>().Where(hp => hp.MachineId == idMachine) .OrderByDescending(a => a.Day).FirstOrDefault()?.Day; maxHpDate = maxHpDate?.Date ?? DateTime.MinValue; var historyMessages = context.Set <MessageMachine>() .Where(p => p.Day >= maxHpDate && p.MachineId == idMachine && p.MessagesIndex.IsVisibleLOLA && (p.MessagesIndex.MessageTypeId == 11 || p.MessagesIndex.MessageTypeId == 12 || p.MessagesIndex.MessageType.Id == 13)).ToList() .GroupBy(g => new{ g.Day.Value.Date, g.Params, g.MessagesIndexId }) .Select(n => new HistoryMessage { Day = n.Key.Date, Params = n.Key.Params, MessagesIndexId = n.Key.MessagesIndexId, MachineId = idMachine, Period = n.Key.Date.Year * 10000 + n.Key.Date.Month * 100 + n.Key.Date.Day, Count = n.Count(), TypeHistory = "d" }).ToList(); foreach (var cur in historyMessages) { var row = context.Set <HistoryMessage>().FirstOrDefault(hp => hp.MachineId == idMachine && hp.Day == cur.Day && hp.TypeHistory == cur.TypeHistory && hp.MessagesIndexId == cur.MessagesIndexId && hp.Params == cur.Params); if (row != null) { row.Count = cur.Count; } else { context.Set <HistoryMessage>().Add(cur); } } context.SaveChanges(); }
public void CheckVariableTresholds(IFomMonitoringEntities context, IMessageService messageService, Machine machine, ParameterMachineThreshold par, DataProcessing.Dto.Value value, decimal?oldValue, DateTime utcDatetime) { if (machine == null || par == null || value == null) { return; } if (oldValue != null && oldValue >= value.VariableValue) { return; } //controllo se il valore oltrepassa la soglia e non esiste già un msessaggio lo inserisco var min = par.ThresholdMin; var max = par.ThresholdMax; if (value.VariableValue < min || value.VariableValue > max) { var mes = context.Set <MessageMachine>().AsNoTracking().FirstOrDefault(mm => mm.MachineId == machine.Id && mm.MessagesIndex != null && mm.MessagesIndex.Id == par.MessagesIndex.Id); if (mes == null) { messageService.InsertMessageMachine(machine, par.MessagesIndex, utcDatetime); } else if (oldValue != null) { if (mes.Day < utcDatetime) { //verifico se il precedente valore era sotto la soglia inserisco un nuovo messaggio if (oldValue >= min && oldValue <= max) { messageService.InsertMessageMachine(machine, par.MessagesIndex, utcDatetime); } //in questo caso ero sopra la soglia e continuo ad essere sopra la soglia // controllo se il valore del parametro ha superato il prossimo multiplo del valore max else { var valOld = (decimal)oldValue; var valNew = value.VariableValue; if (valOld > max && valNew > valOld && max > 0) { var multiploOld = Math.Floor(valOld / max); var multiploNew = Math.Floor((valNew ?? 0) / max); if (multiploNew > multiploOld) { messageService.InsertMessageMachine(machine, par.MessagesIndex, utcDatetime); } } } } } } }
private void AddResetValue(IFomMonitoringEntities context, ParameterMachine parameterMachine, DateTime lastReset, decimal?variableValue, decimal?valueBeforeReset, int idMachine) { if (!parameterMachine.ParameterResetValue.Any(pm => pm.ResetDate == lastReset && pm.MachineId == idMachine)) { context.Set <ParameterResetValue>().Add( new ParameterResetValue() { ParameterMachineId = parameterMachine.Id, ResetDate = (DateTime)lastReset, ResetValue = variableValue, ValueBeforeReset = valueBeforeReset, MachineId = idMachine }); } }
public void InsertAuditLogin(bool accessed, string username, Guid?userId, string message) { ExtensionMethods.CheckGuidIsValidAndNotEmpty(userId.ToString(), out userId); var al = new FomMonitoringCore.SqlServer.AuditLogin { ID = Guid.NewGuid(), Accessed = accessed, Username = username, UserID = userId, MessageInfo = message, DateAndTime = DateTime.Now, IP = ExtensionMethods.GetUserConnectionIP() }; _fomMonitoringEntities.Set <FomMonitoringCore.SqlServer.AuditLogin>().Add(al); _fomMonitoringEntities.SaveChanges(); }
public bool LoginUser(string username, string password, string domain, out string message, out FomMonitoringCore.SqlServer.Users user) { try { if (domain != "") { user = _fomMonitoringEntities.Set <FomMonitoringCore.SqlServer.Users>() .Include("Roles_Users") .Include("Roles_Users.Roles") .SingleOrDefault(i => i.Username == username && i.Domain == domain); } else { user = _fomMonitoringEntities.Set <FomMonitoringCore.SqlServer.Users>() .Include("Roles_Users") .Include("Roles_Users.Roles") .SingleOrDefault(i => i.Username == username); } if (null == user) { message = "Username is wrong"; return(false); } if (user.Password != password) { message = "Password is wrong"; return(false); } if (user.Enabled == false) { message = "User is not enabled"; return(false); } message = "Login done successfully"; //Ritorna true per indicare che il login dell'utente è avvenuto correttamente return(true); } catch (Exception ex) { message = $"Non è stato possibile effettuare il login dell'utente perchè è stata rilevata la seguente eccezione: {ex.Message}"; user = null; return(false); } }
public List <EfficiencyStateMachineModel> GetOperatorsActivity(MachineInfoModel machine, DateTime dateFrom, DateTime dateTo) { var tmp = _context.Set <HistoryState>() .Where(w => w.MachineId == machine.Id && w.Day >= dateFrom && w.Day <= dateTo && w.Operator != null && w.Operator != "Other" && w.StateId != (int?)enState.Offline && w.Shift == null) .GroupBy(g => g.Operator).ToList(); var totTime = tmp.Select(s => new EfficiencyStateMachineModel { TotalTime = s.Sum(x => x.ElapsedTime), Operator = s.Key, machineType = machine.MachineTypeId }).ToList(); if (totTime.Count > 0) { foreach (var item in totTime) { //tot. pezzi prodotti var tmp2 = _context.Set <HistoryPiece>() .Where(w => w.MachineId == machine.Id && w.Day >= dateFrom && w.Day <= dateTo && w.Operator == item.Operator && w.Shift == null && w.Operator != null).ToList(); item.CompletedCount = tmp2.GroupBy(g => g.Operator) .Select(s => s.Sum(x => x.CompletedCount)).FirstOrDefault(); //tempo netto var tmp3 = _context.Set <HistoryState>() .Where(w => w.MachineId == machine.Id && w.Day >= dateFrom && w.Day <= dateTo && w.Operator == item.Operator && w.Shift == null && w.Operator != null && (w.StateId == (int)enState.Production || w.StateId == (int)enState.Manual)) .ToList(); item.StatesTime = tmp3.GroupBy(g => g.StateId) .ToDictionary(s => s.Key, s => s.Sum(x => x.ElapsedTime)); } } return(totTime); }
public void HistoricizingPieces(IFomMonitoringEntities context, int idMachine) { var maxHpDate = DateTime.MinValue; if (context.Set <HistoryPiece>().Any(hp => hp.MachineId == idMachine)) { maxHpDate = context.Set <HistoryPiece>().Where(hp => hp.MachineId == idMachine) .Max(a => a.Day).Date; } var historyPieces = context.Set <Piece>() .Where(p => p.Day >= maxHpDate && p.MachineId == idMachine).ToList() .GroupBy(g => new { g.Day.Value.Date, g.Operator }) .Select(n => new HistoryPiece { Id = 0, Day = n.Key.Date, MachineId = idMachine, Operator = n.Key.Operator, CompletedCount = n.Count(i => i.IsRedone == false), Period = n.Key.Date.Year * 10000 + n.Key.Date.Month * 100 + n.Key.Date.Day, ElapsedTime = n.Sum(i => i.ElapsedTime), ElapsedTimeCut = n.Sum(i => i.ElapsedTimeCut), ElapsedTimeProducing = n.Sum(i => i.ElapsedTimeProducing), ElapsedTimeTrim = n.Sum(i => i.ElapsedTimeTrim), ElapsedTimeWorking = n.Sum(i => i.ElapsedTimeWorking), PieceLengthSum = (int)n.Sum(i => i.IsRedone == true ? 0 : i.Length), RedoneCount = n.Count(i => i.IsRedone == true), TypeHistory = "d" }).ToList(); var aggregato = historyPieces.GroupBy(c => c.Day).Select(n => new HistoryPiece { Id = 0, Day = n.Key, MachineId = idMachine, Operator = null, Period = n.Key.Year * 10000 + n.Key.Month * 100 + n.Key.Day, CompletedCount = n.Sum(i => i.CompletedCount), ElapsedTime = n.Sum(i => i.ElapsedTime), ElapsedTimeCut = n.Sum(i => i.ElapsedTimeCut), ElapsedTimeProducing = n.Sum(i => i.ElapsedTimeProducing), ElapsedTimeTrim = n.Sum(i => i.ElapsedTimeTrim), ElapsedTimeWorking = n.Sum(i => i.ElapsedTimeWorking), PieceLengthSum = n.Sum(i => i.PieceLengthSum), RedoneCount = n.Sum(i => i.RedoneCount), TypeHistory = "d" }).ToList(); historyPieces.AddRange(aggregato); foreach (var cur in historyPieces) { var row = context.Set <HistoryPiece>().FirstOrDefault(hp => hp.MachineId == idMachine && hp.Day == cur.Day && (hp.Operator == cur.Operator || hp.Operator == null && cur.Operator == null)); if (row != null) { row.CompletedCount = cur.CompletedCount; row.ElapsedTime = cur.ElapsedTime; row.ElapsedTimeProducing = cur.ElapsedTimeProducing; row.ElapsedTimeCut = cur.ElapsedTimeCut; row.ElapsedTimeWorking = cur.ElapsedTimeWorking; row.ElapsedTimeTrim = cur.ElapsedTimeTrim; row.PieceLengthSum = cur.PieceLengthSum; row.RedoneCount = cur.RedoneCount; } else { context.Set <HistoryPiece>().Add(cur); } } }
public async Task AddOrUpdateMachineParameterAsync(ParametersMachineModelXml m) { var machineModel = _context.Set <MachineModel>().FirstOrDefault(mac => mac.ModelCodev997 == m.ModelCodeV997); if (machineModel != null) { var list = m.Parameters.Parameter.BuildAdapter().AddParameters("idMachineModel", machineModel.Id).AddParameters("modelCode", m.ModelCodeV997).AdaptToType <List <ParameterMachine> >(); foreach (var i in list) { var old = _context.Set <ParameterMachine>().FirstOrDefault(pm => pm.ModelCode == i.ModelCode && pm.VarNumber == i.VarNumber); i.Id = old?.Id ?? 0; i.MachineModelId = machineModel.Id; _context.Set <ParameterMachine>().AddOrUpdate(i); } //elimino i record che non esistono più var curparams = _context.Set <ParameterMachine>().Where(p => p.ModelCode == m.ModelCodeV997.ToString()).ToList(); var toDelete = curparams.Where(c => !list.Any(a => a.VarNumber == c.VarNumber.ToString())).ToList(); if (toDelete.Count > 0) { var ids = toDelete.Select(a => a.Id).ToList(); var values = _context.Set <ParameterMachineValue>().Where(v => ids.Contains(v.ParameterMachineId)).ToList(); if (values.Count > 0) { _context.Set <ParameterMachineValue>().RemoveRange(values); } var resets = _context.Set <ParameterResetValue>().Where(v => ids.Contains(v.ParameterMachineId)).ToList(); if (resets.Count > 0) { _context.Set <ParameterResetValue>().RemoveRange(resets); } var thresholds = _context.Set <ParameterMachineThreshold>().Where(v => ids.Contains(v.ParameterMachineId)).ToList(); if (thresholds.Count > 0) { _context.Set <ParameterMachineThreshold>().RemoveRange(thresholds); } _context.Set <ParameterMachine>().RemoveRange(toDelete); } } await _context.SaveChangesAsync(); }
/// <summary> /// Ritorna gli allarmi n base a tipo di dati da visualizzare in base al tipo di aggregazione /// </summary> /// <param name="machine"></param> /// <param name="period"></param> /// <param name="dataType"></param> /// <param name="actualMachineGroup"></param> /// <returns>Lista dei dettagli degli stati</returns> public List <HistoryMessageModel> GetAggregationMessages(MachineInfoModel machine, PeriodModel period, enDataType dataType, string actualMachineGroup = null) { try { var cl = _languageService.GetCurrentLanguage() ?? 0; var machineGroup = _context.Set <MachineGroup>() .FirstOrDefault(n => n.MachineGroupName == actualMachineGroup)?.Id; List <int> messTypes = (new int[] { 11, 12 }).ToList(); bool limitTime = true; var role = _accountService.GetLoggedUser().Role; if (role == enRole.Assistance || role == enRole.RandD || role == enRole.Administrator) { messTypes.Add(13); limitTime = false; } var queryResult = _historyMessageRepository .GetHistoryMessage(machine.Id, period.StartDate, period.EndDate, machineGroup, messTypes, limitTime); switch (dataType) { case enDataType.Historical: switch (period.Aggregation) { case enAggregation.Day: { int?Func(HistoryMessage hs) { return(hs.Period); } const string typeHistory = "d"; var result = BuildAggregationList(queryResult, typeHistory, Func); return(result.ToList()); } case enAggregation.Week: { int?Func(HistoryMessage hs) { return(hs.Day.HasValue ? (int?)hs.Day.Value.Year * 100 + hs.Day.Value.GetWeekNumber() : null); } const string typeHistory = "w"; var result = BuildAggregationList(queryResult, typeHistory, Func); return(result.ToList()); } case enAggregation.Month: { int?Func(HistoryMessage hs) { return(hs.Day.HasValue ? (int?)hs.Day.Value.Year * 100 + hs.Day.Value.Month : null); } const string typeHistory = "m"; var result = BuildAggregationList(queryResult, typeHistory, Func); return(result.ToList()); } case enAggregation.Quarter: { int?Func(HistoryMessage hs) { return(hs.Day.HasValue ? (int?)hs.Day.Value.Year * 100 + GetQuarter(hs.Day ?? DateTime.UtcNow) : null); } const string typeHistory = "q"; var result = BuildAggregationList(queryResult, typeHistory, Func); return(result.ToList()); } case enAggregation.Year: { int?Func(HistoryMessage hs) { return(hs.Day.HasValue ? (int?)hs.Day.Value.Year * 100 + hs.Day.Value.Year : null); } const string typeHistory = "y"; var result = BuildAggregationList(queryResult, typeHistory, Func); return(result.ToList()); } } break; case enDataType.Summary: var historyMessagesSummary = _historyMessageRepository .GetHistoryMessage(machine.Id, period.StartDate, period.EndDate, machineGroup, messTypes, limitTime) .GroupBy(g => new { g.MachineId, Description = g.GetDescription(cl), g.MessagesIndex.MessageCode, g.MessagesIndex?.MessageTypeId }).ToList().Select(s => new AggregationMessageModel { Id = s.Max(m => m.Id), Code = s.Key.MessageCode, Count = s.Sum(i => i.Count), Day = s.Max(i => i.Day), MachineId = s.Key.MachineId, TypeHistory = "y", Description = s.Key.Description, Type = s.Key.MessageTypeId }).ToList(); return(historyMessagesSummary.BuildAdapter().AdaptToType <List <HistoryMessageModel> >()); } } catch (Exception ex) { var errMessage = string.Format(ex.GetStringLog(), machine.Id.ToString(), string.Concat(period.StartDate.ToString(), " - ", period.EndDate.ToString(), " - ", period.Aggregation.ToString()), dataType.ToString()); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(new List <HistoryMessageModel>()); }
public List <Faq> GetFaqs() { return(_context.Set <Faq>().Where(f => f.IsVisible == true && f.IsInternalMenu == false).OrderBy(f => f.Order).ToList()); }
public List <PlantModel> GetPlants(string usernameCustomer) { List <PlantModel> result = null; try { using (FomMonitoringEntities entUM = new FomMonitoringEntities()) { //ent.Configuration.LazyLoadingEnabled = false; // Recupero la lista degli utenti associati al cliente List <Plant> customerPlants = new List <Plant>(); if (!string.IsNullOrWhiteSpace(usernameCustomer)) { var gc = entUM.Users.FirstOrDefault(f => f.Username == usernameCustomer)?.ID; customerPlants = _context.Set <Plant>().Where(w => w.UserId == gc).Distinct().ToList(); if (customerPlants.Count == 0) { return(result); } } else { customerPlants = _context.Set <Plant>().Include("Machine").ToList(); } result = customerPlants.Adapt <List <Plant>, List <PlantModel> >(); // Associo il cliente all'utente if (!string.IsNullOrWhiteSpace(usernameCustomer)) { result.ForEach(fe => fe.CustomerName = usernameCustomer); } else { var userCustomer = _context.Set <UserCustomerMapping>().ToList(); result.ForEach(fe => fe.CustomerName = userCustomer.FirstOrDefault(w => w.UserId == fe.UserId)?.CustomerName); } } } catch (Exception ex) { string errMessage = string.Format(ex.GetStringLog(), usernameCustomer); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
public List <MachineInfoModel> GetUserMachines(ContextModel ctx) { var result = new List <MachineInfoModel>(); try { Guid id = ctx.User.ID; if (ctx.AssistanceUserId != null && ctx.User.Role == enRole.Assistance || ctx.User.Role == enRole.RandD) { id = new Guid(ctx.AssistanceUserId); } var query = _context.Set <UserMachineMapping>().Where(w => w.UserId == id).Select(s => s.Machine).ToList(); result = query.Where(w => w.LastUpdate != null).Adapt <List <MachineInfoModel> >(); if (ctx.User.Role == enRole.Customer) { result.ForEach(mim => mim.TimeZone = _context.Set <UserMachineMapping>().FirstOrDefault(w => w.UserId == id && w.MachineId == mim.Id)?.TimeZone); } } catch (Exception ex) { var errMessage = string.Format(ex.GetStringLog(), ctx.User.ID.ToString()); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
public bool ElaborateJsonData(string json) { var result = false; try { var jObject = JsonConvert.DeserializeObject <JObject>(json); var token = jObject.Root.First; if (token.Path.ToLower() == "currentstate") { var currentStateDynamic = JsonConvert.DeserializeObject <List <dynamic> >(JsonConvert.SerializeObject(token.First)).First(); string machineSerial = currentStateDynamic.MachineSerial; var machine = _context.Set <Machine>().FirstOrDefault(f => f.Serial == machineSerial); if (machine != null) { var currentState = _context.Set <CurrentState>().FirstOrDefault(f => f.MachineId == machine.Id); var currentStateExists = true; if (currentState == null) { currentState = new CurrentState(); currentStateExists = false; } currentState.JobCode = currentStateDynamic.JobCode; currentState.JobProducedPieces = (int?)currentStateDynamic.JobProducedPieces; currentState.JobTotalPieces = (int?)currentStateDynamic.JobTotalPieces; currentState.LastUpdated = (currentStateDynamic.LastUpdated.Value is string || currentStateDynamic.LastUpdated.Value == null || ((DateTime)currentStateDynamic.LastUpdated).Year < 1900 ? (DateTime?)null : (DateTime)currentStateDynamic.LastUpdated); currentState.MachineId = machine.Id; currentState.Operator = currentStateDynamic.Operator; currentState.StateId = (int?)currentStateDynamic.State; currentState.StateTransitionCode = currentStateDynamic.StateTransitionCode; currentState.ResidueWorkingTime = currentStateDynamic.ResidueWorkingTime; currentState.ResidueWorkingTimeJob = currentStateDynamic.ResidueWorkingTimeJob; currentState.ResidueWorkingTimeBar = currentStateDynamic.ResidueWorkingTimeBar; if (!currentStateExists) { _context.Set <CurrentState>().Add(currentState); } machine.LastUpdate = currentState.LastUpdated; _context.SaveChanges(); result = true; /*var historyJobExist = _context.Set<HistoryJob>().Any(h => * h.Code == currentState.JobCode && h.MachineId == machine.Id && h.Day != null && * DbFunctions.TruncateTime(h.Day.Value) == DbFunctions.TruncateTime(currentState.LastUpdated)); * if (!historyJobExist && currentState.JobCode?.Trim().Length > 0 && currentState.JobProducedPieces > 0) * { * var newJob = new HistoryJob * { * Day = DateTime.UtcNow.Date, * Code = currentState.JobCode, * ElapsedTime = 0, * MachineId = machine.Id, * Period = (DateTime.UtcNow.Year * 10000) + (DateTime.UtcNow.Month * 100) + (DateTime.UtcNow.Day), * PiecesProduced = currentState.JobProducedPieces, * TotalPieces = currentState.JobTotalPieces, * TypeHistory = "d" * }; * _context.Set<HistoryJob>().Add(newJob); * _context.SaveChanges(); * }*/ } } } catch (Exception ex) { var errMessage = string.Format(ex.GetStringLog(), json); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
/// <summary> /// Ritorna il singolo utente con le sue info /// </summary> /// <param name="userId"></param> /// <returns></returns> public UserModel GetUser(Guid userId) { UserModel result = null; try { // Recupero l'utente dallo user manager var user = _fomMonitoringEntities.Set <Users>() .Include("Roles_Users") .Include("Roles_Users.Roles") .Include("Languages").FirstOrDefault(f => f.ID == userId); if (user == null) { return(null); } result = user.Adapt <Users, UserModel>(); // Recupero le sue macchine ed il customer associato var customerName = _fomMonitoringEntities.Set <UserCustomerMapping>().FirstOrDefault(f => f.UserId == userId)?.CustomerName; result.CustomerName = customerName; var userMachines = _fomMonitoringEntities.Set <UserMachineMapping>().Include("Machine").Where(w => w.UserId == userId).Select(s => s.Machine).ToList(); result.Machines = userMachines.Adapt <List <Machine>, List <MachineInfoModel> >(); } catch (Exception ex) { var errMessage = string.Format(ex.GetStringLog(), userId.ToString()); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
public int?GetOrSetPlantDefaultByUser(Guid userId) { var userM = _context.Set <UserCustomerMapping>().FirstOrDefault(m => m.UserId == userId); var plant = _context.Set <Plant>().FirstOrDefault(p => userId == p.UserId); if (plant == null) { var user = _context.Set <Users>().FirstOrDefault(u => u.ID == userM.UserId); plant = AddPlant(user); } return(plant?.Id); }
/// <summary> /// Ritorna gli aggregati pieces in base al tipo di aggregazione /// </summary> /// <param name="machine"></param> /// <param name="period"></param> /// <param name="dataType"></param> /// <returns>Lista dei dettagli degli stati</returns> public List <HistoryPieceModel> GetAggregationPieces(MachineInfoModel machine, PeriodModel period, enDataType dataType) { var result = new List <HistoryPieceModel>(); try { var query = _context.Set <HistoryPiece>().Where(hp => hp.MachineId == machine.Id && hp.Day >= period.StartDate && hp.Day <= period.EndDate); switch (dataType) { case enDataType.Dashboard: result = query.Where(hp => hp.Shift == null && hp.Operator == null).ToList() .GroupBy(g => g.System).Select(n => new HistoryPieceModel { Id = n.Max(i => i.Id), CompletedCount = n.Sum(i => i.CompletedCount), Day = n.Max(i => i.Day), ElapsedTime = n.Sum(i => i.ElapsedTime), ElapsedTimeProducing = n.Sum(i => i.ElapsedTimeProducing), ElapsedTimeCut = n.Sum(i => i.ElapsedTimeCut), ElapsedTimeWorking = n.Sum(i => i.ElapsedTimeWorking), ElapsedTimeTrim = n.Sum(i => i.ElapsedTimeTrim), MachineId = machine.Id, Operator = null, Period = null, PieceLengthSum = n.Sum(i => i.PieceLengthSum), RedoneCount = n.Sum(i => i.RedoneCount), Shift = null, System = n.Key, TypeHistory = "d" }).ToList(); break; case enDataType.Historical: { var queryResult = query.Where(hp => hp.Shift == null && hp.Operator == null).ToList(); switch (period.Aggregation) { case enAggregation.Day: { int?Func(HistoryPiece hs) { return(hs.Period); } const string typeHistory = "d"; var res = BuildAggregationList(queryResult, typeHistory, Func); return(res.ToList()); } case enAggregation.Week: { int?Func(HistoryPiece hs) { return(hs.WeekOfYearDay); } const string typeHistory = "w"; var res = BuildAggregationList(queryResult, typeHistory, Func); return(res.ToList()); } case enAggregation.Month: { int?Func(HistoryPiece hs) { return(hs.Day.Month); } const string typeHistory = "m"; var res = BuildAggregationList(queryResult, typeHistory, Func); return(res.ToList()); } case enAggregation.Quarter: { int?Func(HistoryPiece hs) { return(hs.QuarteOfYearDay); } const string typeHistory = "q"; var res = BuildAggregationList(queryResult, typeHistory, Func); return(res.ToList()); } case enAggregation.Year: { int?Func(HistoryPiece hs) { return(hs.Day.Year); } const string typeHistory = "y"; var res = BuildAggregationList(queryResult, typeHistory, Func); return(res.ToList()); } } break; } case enDataType.Operators: result = query.Where(hp => hp.Shift == null && hp.Operator != null).ToList() .GroupBy(g => new { g.System, g.Operator }) .Select(n => new HistoryPieceModel { Id = n.Max(i => i.Id), CompletedCount = n.Sum(i => i.CompletedCount), Day = n.Max(i => i.Day), ElapsedTime = n.Sum(i => i.ElapsedTime), ElapsedTimeProducing = n.Sum(i => i.ElapsedTimeProducing), ElapsedTimeCut = n.Sum(i => i.ElapsedTimeCut), ElapsedTimeWorking = n.Sum(i => i.ElapsedTimeWorking), ElapsedTimeTrim = n.Sum(i => i.ElapsedTimeTrim), MachineId = machine.Id, Operator = n.Key.Operator, Period = null, PieceLengthSum = n.Sum(i => i.PieceLengthSum), RedoneCount = n.Sum(i => i.RedoneCount), Shift = null, System = n.Key.System, TypeHistory = "d" }).ToList(); break; } } catch (Exception ex) { var errMessage = string.Format(ex.GetStringLog(), machine.Id.ToString(), string.Concat(period.StartDate.ToString(CultureInfo.InvariantCulture), " - ", period.EndDate.ToString(CultureInfo.InvariantCulture), " - ", period.Aggregation.ToString(), dataType.ToString())); LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex); } return(result); }
public bool UpdateActiveCustomersAndMachines() { var result = true; try { var apiUrl = ApplicationSettingService.GetWebConfigKey("UpdateCustomersAndMachinesSOAPUrl"); var apiUsername = ApplicationSettingService.GetWebConfigKey("UpdateCustomersAndMachinesSOAPUsername"); var apiPassword = ApplicationSettingService.GetWebConfigKey("UpdateCustomersAndMachinesSOAPPassword"); var webRequest = (HttpWebRequest)WebRequest.Create(apiUrl); webRequest.Headers.Add("SOAPAction", "http://tempuri.org/IService/ottieniListaMacchineRegistrate"); webRequest.ContentType = "text/xml;charset=\"utf-8\""; webRequest.Accept = "text/xml"; webRequest.Method = "POST"; webRequest.CookieContainer = new CookieContainer(); webRequest.Credentials = new NetworkCredential(apiUsername, apiPassword, ""); var soapEnvelopeXml = new XmlDocument(); soapEnvelopeXml.LoadXml(@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/""><soapenv:Header></soapenv:Header><soapenv:Body><tem:ottieniListaMacchineRegistrate/></soapenv:Body></soapenv:Envelope>"); using (var stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } var asyncResult = webRequest.BeginGetResponse(null, null); asyncResult.AsyncWaitHandle.WaitOne(); string soapResult; using (var webResponse = webRequest.EndGetResponse(asyncResult)) { using (var rd = new StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); } } var document = new XmlDocument(); document.LoadXml(soapResult); var customers = JsonConvert.DeserializeObject <JsonCustomersModel>(document.InnerText, new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" }); //elimino i customer non più presenti nella vip area var dbCustomers = _userManagerService.GetAllCustomers(); var customerNames = customers.customers.Select(j => j.username).Distinct(); var custmerToRemove = dbCustomers.Where(e => !customerNames.Contains(e.Username)).ToList(); if (custmerToRemove.Any()) { //rimuovo prima le associazioni var ids = custmerToRemove.Select(a => a.ID).ToList(); var names = custmerToRemove.Select(a => a.Username).ToList(); var us = _context.Set <UserCustomerMapping>().Where(uc => names.Contains(uc.CustomerName)).ToList(); //utenti associati al customer var usCust = new List <UserModel>(); if (us.Any()) { foreach (var item in us) { usCust.AddRange(_userManagerService.GetUsers(item.CustomerName)); } _context.Set <UserCustomerMapping>().RemoveRange(us); _context.SaveChanges(); } var um = _context.Set <UserMachineMapping>().Where(mh => ids.Contains(mh.UserId)).ToList(); if (um.Any()) { _context.Set <UserMachineMapping>().RemoveRange(um); _context.SaveChanges(); } usCust.AddRange(custmerToRemove); using (var transactionSuppress = new TransactionScope(TransactionScopeOption.Suppress)) { _userManagerService.RemoveUsers(usCust); transactionSuppress.Complete(); } } //pulizia della tabella UserCustomerMapping, potrebbero esserci record inseriti a mano con customerName non esistenti var machines = _context.Set <Machine>().ToList(); var users = _context.Set <Users>().ToList(); foreach (var customer in customers.customers) { try { //Aggiungo eventuali nuovi clienti var user = new UserModel(); using (var transactionSuppress = new TransactionScope(TransactionScopeOption.Suppress)) { user = users.FirstOrDefault(u => u.Username == customer.username)?.Adapt <Users, UserModel>(); if (user == null) { user = new UserModel { Username = customer.username, FirstName = customer.firstName, LastName = customer.lastName, CompanyName = customer.companyName, Enabled = true, Role = enRole.Customer, CustomerName = customer.username }; user.ID = _userManagerService.CreateUser(user); } else { user.FirstName = customer.firstName; user.LastName = customer.lastName; user.CompanyName = customer.companyName; _userManagerService.UpdateUserName(user); } transactionSuppress.Complete(); } //Aggiungo eventuali nuovi clienti nel DB dei dati var userCustomer = _context.Set <UserCustomerMapping>().FirstOrDefault(f => f.UserId == user.ID); if (userCustomer == null) { userCustomer = new UserCustomerMapping { UserId = user.ID, CustomerName = user.Username }; _context.Set <UserCustomerMapping>().Add(userCustomer); _context.SaveChanges(); } //Prendo la lista delle macchine esistenti nel DB a partire da quelle arrivate da JSON var machinesSerial = customer.machines.Select(s => s.serial).ToList(); var customersMachines = machines.Where(w => machinesSerial.Contains(w.Serial)).ToList(); //Rimuovo le associazioni cliente <=> macchina per macchine non più monitorate var machinesId = customersMachines.Select(s => s.Id).ToList(); var clientUsersMachines = _context.Set <UserMachineMapping>().Where(w => machinesId.Contains(w.MachineId)).Select(s => s.UserId).Distinct().ToList(); var usersMachinesToRemove = _context.Set <UserMachineMapping>().Where(w => !machinesId.Contains(w.MachineId) && clientUsersMachines.Contains(w.UserId)).ToList(); _context.Set <UserMachineMapping>().RemoveRange(usersMachinesToRemove); _context.SaveChanges(); var plant = _mesService.GetOrSetPlantDefaultByUser(user.ID); //Inserisco i nuovi mapping cliente <=> macchina foreach (var machine in customersMachines) { var jm = customer.machines.FirstOrDefault(f => f.serial == machine.Serial); if (jm != null) { var expirationDate = jm.expirationDate; var activationDate = jm.activationDate; var machineName = jm.machineName; var usersMachineMapped = _context.Set <UserMachineMapping>().Where(w => w.MachineId == machine.Id).ToList(); if (!usersMachineMapped.Any()) { var userMachine = new UserMachineMapping() { MachineId = machine.Id, UserId = user.ID }; _context.Set <UserMachineMapping>().Add(userMachine); _context.SaveChanges(); } //aggiorno l'activationDate della macchina prendendo la più vecchia // aggiorno anche il plantId var ma = _context.Set <Machine>().Find(machine.Id); if (ma.PlantId == null) { ma.PlantId = plant; } if (ma.ActivationDate == null || ma.ActivationDate > activationDate) { ma.ActivationDate = activationDate; } if (ma.ExpirationDate == null || ma.ExpirationDate < expirationDate) { ma.ExpirationDate = expirationDate; } if (!string.IsNullOrWhiteSpace(machineName)) { ma.MachineName = machineName; } _context.SaveChanges(); } } } catch (Exception ex) { LogService.WriteLog(ex.Message, LogService.TypeLevel.Error, ex); result = false; } } } catch (Exception ex) { LogService.WriteLog(ex.Message, LogService.TypeLevel.Error, ex); } return(result); }