Files
cms_thermo_active/Thermo.Active.Database/Controllers/AlarmsController.cs
T
2020-04-09 13:15:01 +02:00

296 lines
9.4 KiB
C#

using Termo.Active.Model.DatabaseModels;
using Termo.Active.Model.DTOModels;
using Termo.Active.Model.DTOModels.AlarmModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using static Termo.Active.Model.Constants;
using static Termo.Active.Config.ServerConfig;
using System.Diagnostics;
using Termo.Active.Config;
namespace Termo.Active.Database.Controllers
{
public class AlarmsController : IDisposable
{
private DatabaseContext dbCtx;
public AlarmsController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public List<DTOAlarmHistoricModel> GetPaginatedWithFilter(string title, List<ALARM_SOURCE> sources, int page, int pageSize, DateTime startDate, DateTime endDate, List<int?> userIds, Dictionary<int, string> plcMessages, out int pages)
{
pages = 0;
bool ifNoUser = false;
var index = userIds.IndexOf(-1);
if (userIds.IndexOf(-1) != -1)
ifNoUser = true;
List<int> ncAlarmDescIds = dbCtx
.AlarmDescriptions
.Where(x => x.Title.Contains(title))
.Select(x => x.AlarmId)
.ToList();
// Get Plc messages ids
List<int> plcAlarmDescIds =
plcMessages
.Where(x => x.Value.IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0)
//.Where(x => x.Value.Contains(title))
.Select(x => x.Key)
.ToList();
// Query
var occurrencesQuery = dbCtx
.AlarmOccurrences
.OrderBy(x => x.AlarmOccurrenceId)
.Include("Users")
.Where(x =>
x.TimeStamp >= startDate && x.TimeStamp <= endDate // Filter by date
&& sources.Contains(x.Source) // Check source
&& ( (ifNoUser && x.Users.Count() == 0) || x.Users.Any(y => userIds.Any(z => z == y.UserId))) // Check user
&&
((x.Source == ALARM_SOURCE.NC && ncAlarmDescIds.Contains(x.AlarmDescriptionId.Value)) // Check if message is contained in NC messages
|| (x.Source == ALARM_SOURCE.PLC && plcAlarmDescIds.Contains(x.AlarmId))) // Check if message is contained in PLC messages
).OrderByDescending(t => t.AlarmOccurrenceId);
double tmpPages = (double)occurrencesQuery.Count() / (double)pageSize;
pages = (int)Math.Ceiling(tmpPages);
var paginatedQuery = occurrencesQuery
.Skip(page * pageSize) // Paginate
.Take(pageSize)
.Include("AlarmDescription") // Include foreign key
.ToList();
return paginatedQuery
.Select(x => (DTOAlarmHistoricModel)x) // Convert to DTOALarmHistoricModel
.ToList();
}
public void InsertNewOccurrences(List<AlarmOccurrencesModel> alarms)
{
dbCtx.AlarmOccurrences.AddRange(alarms);
dbCtx.SaveChanges();
}
public void InsertNewNcAlarmDescriptions(List<AlarmDescriptionsModel> descriptions)
{
foreach (var desc in descriptions)
{
// Check if description exists already
var dbDesc = dbCtx.AlarmDescriptions.Where(x => x.AlarmId == desc.AlarmId).FirstOrDefault();
// If not add
if (dbDesc == null)
dbCtx.AlarmDescriptions.Add(desc);
}
dbCtx.SaveChanges();
}
public void InsertNewAlarmUser(List<AlarmUserModel> loggedUser)
{
dbCtx.AlarmUsers.AddRange(loggedUser);
dbCtx.SaveChanges(); // TODO check if it is the best solutions
}
public DTOAlarmsData GetAlarmsData(int pageSize)
{
// Get page numbers
int pagesNumbers = dbCtx.AlarmOccurrences.Count() / pageSize;
var firstAlarm = dbCtx.AlarmOccurrences.FirstOrDefault();
// Get first alarm date
DateTime date = firstAlarm == null ? DateTime.Now : firstAlarm.TimeStamp;
return new DTOAlarmsData
{
Pages = pagesNumbers,
FirstDate = date
};
}
public AlarmOccurrencesModel FindById(int id, ALARM_SOURCE source)
{
return dbCtx
.AlarmOccurrences
.Where(x => x.AlarmId == id && x.Source == source)
.FirstOrDefault();
}
public void CleanTable()
{
int numberOfRows = CountRows();
if(numberOfRows >= ServerStartupConfig.MaxAlarmsRows)
{
dbCtx.Database.ExecuteSqlCommand("DELETE FROM alarm_occurrence LIMIT {0}", ServerStartupConfig.AlarmToDelete);
}
}
public int CountRows()
{
return dbCtx.AlarmOccurrences.Count();
}
public void EmptyAlarms()
{
int numberOfRows = CountRows();
dbCtx.Database.ExecuteSqlCommand("DELETE FROM alarm_occurrence LIMIT {0}", numberOfRows);
}
#region NOTES
public List<DTOAlarmNoteModel> GetNotesByAlarmDescId(int alarmDescriptionId, ALARM_SOURCE source)
{
return dbCtx
.AlarmsNotes
.Where(x => x.AlarmId == alarmDescriptionId && x.Source == source) // Filter by id
.Select(x => new DTOAlarmNoteModel() // Convert to return model
{
Id = x.NoteId,
DateTime = x.DateTime,
Message = x.Message,
User = new DTOMessageUserModel()
{
Id = x.User.UserId,
FirstName = x.User.FirstName,
LastName = x.User.LastName,
Username = x.User.Username
}
})
.ToList();
}
public AlarmNoteModel FindNoteById(int noteId)
{
return dbCtx
.AlarmsNotes
.Where(x => x.NoteId == noteId)
.Include("User")
.FirstOrDefault();
}
public DTOAlarmNoteModel CreateNote(int userId, int alarmId, ALARM_SOURCE source, DTONewAlarmNoteModel newNote)
{
// Create model
AlarmNoteModel note = new AlarmNoteModel()
{
Message = newNote.Message,
DateTime = DateTime.Now,
AlarmId = alarmId,
UserId = userId,
Source = source
};
// Add & save into database
dbCtx.AlarmsNotes.Add(note);
dbCtx.SaveChanges();
// Populate user data
dbCtx.Entry(note).Reference(x => x.User).Load();
dbCtx.Users.Attach(note.User);
return (DTOAlarmNoteModel)note;
}
public DTOAlarmNoteModel UpdateNote(AlarmNoteModel note, DTONewAlarmNoteModel newNote)
{
note.Message = newNote.Message;
dbCtx.SaveChanges();
return (DTOAlarmNoteModel)note;
}
public void DeleteNote(int noteId)
{
AlarmNoteModel note = FindNoteById(noteId);
dbCtx.AlarmsNotes.Remove(note);
dbCtx.SaveChanges();
}
#endregion NOTES
#region ATTACHMENT
public List<AlarmFileModel> FindAttachmentByAlarmDescId(int alarmId, ALARM_SOURCE source)
{
return dbCtx
.AlarmFiles
.Where(x => x.AlarmId == alarmId && x.Source == source)
.ToList();
}
public AlarmFileModel FindAttachmentById(int attachmentId)
{
return dbCtx
.AlarmFiles
.Where(x => x.AttachmentId == attachmentId)
.FirstOrDefault();
}
public AlarmFileModel AddAttachment(string fileName, string localFileName, int alarmId, int userId, ALARM_SOURCE source)
{
// Create obj
AlarmFileModel file = new AlarmFileModel()
{
FileName = fileName,
LocalFileName = localFileName,
AlarmId = alarmId,
UserId = userId,
Source = source
};
// Add to db
dbCtx.AlarmFiles.Add(file);
dbCtx.SaveChanges();
return file;
}
public void DeleteAttachment(int attachmentId)
{
// Get attachmentRow
AlarmFileModel file = dbCtx
.AlarmFiles
.Where(x => x.AttachmentId == attachmentId)
.FirstOrDefault();
if (file != null)
{
dbCtx.AlarmFiles.Remove(file);
dbCtx.SaveChanges();
}
}
public void DeleteAttachment(AlarmFileModel attachment)
{
dbCtx.AlarmFiles.Remove(attachment);
dbCtx.SaveChanges();
if (File.Exists(ALARM_ATTACHMENT_PATH + attachment.LocalFileName))
File.Delete(ALARM_ATTACHMENT_PATH + attachment.LocalFileName);
}
#endregion ATTACHMENT
}
}