using EgtBEAMWALL.DataLayer.DatabaseModels; using EgwProxy.MagMan.DTO; using NLog; using System; using System.Collections.Generic; using System.Linq; using static EgtBEAMWALL.DataLayer.Controllers.MaterialsController.SearchResult; namespace EgtBEAMWALL.DataLayer.Controllers { /// /// Gestione Materiali su DB (= magazzino locale) /// public class MaterialsController : IDisposable { #region Public Constructors public MaterialsController() { } #endregion Public Constructors #region Public Methods /// /// Conversion of DB model class to base class /// /// /// public static Core.MaterialM ConvToCore(MaterialModel dbRec) { Core.MaterialM answ = new Core.MaterialM(dbRec.MatId, (double)dbRec.WMm, (double)dbRec.HMm, (double)dbRec.LMm, "", dbRec.MatCode); return answ; } /// /// Helper conversione a DTO /// /// /// public static MaterialDTO ConvToDto(MaterialModel currRec) { MaterialDTO answ = new MaterialDTO() { MatCloudId = currRec.MatCloudId, MatLocalId = currRec.MatId, MatCode = currRec.MatCode, MatDesc = currRec.MatDesc, HMm = currRec.HMm, LMm = currRec.LMm, WMm = currRec.WMm }; return answ; } /// /// Helper conversione da DTO /// /// /// public static MaterialModel ConvToModel(MaterialDTO currRec) { MaterialModel answ = new MaterialModel() { MatCloudId = currRec.MatCloudId, MatId = currRec.MatLocalId, MatCode = currRec.MatCode, MatDesc = currRec.MatDesc, HMm = currRec.HMm, LMm = currRec.LMm, WMm = currRec.WMm }; return answ; } /// /// Conversion of base class to DB model class /// /// /// public static MaterialModel ConvToModel(Core.MaterialM coreRec) { MaterialModel answ = new MaterialModel(); if (coreRec != null) { answ = new MaterialModel() { MatId = coreRec.nId, MatCode = coreRec.sWarehouseMaterial, HMm = (decimal)coreRec.dH, LMm = (decimal)coreRec.dL, WMm = (decimal)coreRec.dW, }; } return answ; } /// /// Delete by key /// /// /// public bool DeleteByKey(int MatId) { bool done = false; using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { var items2del = localDbCtx .MaterialsList .Where(x => x.MatId == MatId); try { // Add to database localDbCtx.MaterialsList.RemoveRange(items2del); // Commit changes localDbCtx.SaveChanges(); done = true; } catch (Exception exc) { Log.Error($"EXCEPTION on Materials.DeleteByKey: {Environment.NewLine}{exc}"); } } return done; } public void Dispose() { } /// /// Get record by Key /// /// /// public Core.MaterialM FindByDbId(int MatId) { Core.MaterialM result = new Core.MaterialM(0, 0, 0, "", ""); var rawData = FindByDbIdModel(MatId); if (rawData != null) { result = ConvToCore(rawData); } return result; } /// /// Get record by Key in formato Model /// /// /// public MaterialModel FindByDbIdModel(int MatId) { MaterialModel result = new MaterialModel(); using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { result = localDbCtx .MaterialsList .Where(x => x.MatId == MatId) .SingleOrDefault(); } return result; } /// /// Get Material (filtro x MatId) in formato Core /// /// se "" restituisce tutti /// public List GetFilt(string MatCode) { // recupero e converto List result = new List(); var rawData = GetFiltModel(MatCode); if (rawData != null) { result = rawData.Select(x => ConvToCore(x)).ToList(); } return result; } /// /// Get Material (filtro x MatId) in formato Model /// /// se "" restituisce tutti /// public List GetFiltModel(string MatCode) { List result = new List(); // retrieve using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { result = localDbCtx .MaterialsList .Where(x => string.IsNullOrEmpty(MatCode) || x.MatCode == MatCode) .OrderBy(x => x.MatDesc) .ToList(); } return result; } /// /// Insert Material record from CoreM if missing or return existing (for Id) /// /// /// MatId (existing or new) public int Insert(Core.MaterialM coreItem) { int newIdx = 0; // converto MaterialModel updItem = ConvToModel(coreItem); newIdx = Insert(updItem); return newIdx; } /// /// Insert Material record /// /// /// MatId (existing or new) public int Insert(MaterialModel updItem) { int newIdx = 0; using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { try { var item2update = localDbCtx .MaterialsList .Where(x => (updItem.MatId > 0 && x.MatId == updItem.MatId) || (updItem.MatCloudId > 0 && x.MatCloudId == updItem.MatCloudId) || (x.MatCode == updItem.MatCode && x.WMm == updItem.WMm && x.HMm == updItem.HMm && x.LMm == updItem.LMm)) .SingleOrDefault(); if (item2update != null) { newIdx = item2update.MatId; } else { localDbCtx.MaterialsList.Add(updItem); // verifico se c'è già "alias original" var aliasOrig = localDbCtx .AliasList .Where(x => x.ValueOriginal == updItem.MatCode) .FirstOrDefault(); if (aliasOrig == null || string.IsNullOrEmpty(aliasOrig.ValueOriginal) || aliasOrig.ValueOriginal != updItem.MatCode) { // inserisco alias! localDbCtx.AliasList.Add(new AliasModel() { Family = "MatCode", ValueOriginal = updItem.MatCode, ValueAlias = updItem.MatCode }); } // Commit changes localDbCtx.SaveChanges(); newIdx = updItem.MatId; } } catch (Exception exc) { Log.Error($"EXCEPTION on Materials.Insert: {Environment.NewLine}{exc}"); } } return newIdx; } /// /// Get Last RawItem used for Material /// /// /// Returns 0 if not found public int LastRawItemGet(int MatId) { int RawItemIdLast = 0; using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { try { var item2update = localDbCtx .MaterialsList .Where(x => (MatId > 0 && x.MatId == MatId)) .SingleOrDefault(); if (item2update != null) { RawItemIdLast = item2update.RawItemIdLast; } } catch (Exception exc) { Log.Error($"EXCEPTION on Materials.LastRawItemGet: {Environment.NewLine}{exc}"); } } return RawItemIdLast; } /// /// Update Last RawItem used for Material record /// /// Id locale materiale /// Id del RawItem /// Returns true if updated public bool LastRawItemSet(int MatId, int RawItemIdLast) { bool done = false; using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { try { var item2update = localDbCtx .MaterialsList .Where(x => (MatId > 0 && x.MatId == MatId)) .SingleOrDefault(); if (item2update != null) { item2update.RawItemIdLast = RawItemIdLast; localDbCtx.Entry(item2update).State = System.Data.Entity.EntityState.Modified; // Commit changes localDbCtx.SaveChanges(); done = true; } } catch (Exception exc) { Log.Error($"EXCEPTION on Materials.LastRawItemSet: {Environment.NewLine}{exc}"); } } return done; } /// /// Restituisce il primo materiale (se esiste) per MatCode (diretto o tramite Alias) /// /// Non accetta "" /// public SearchResult SearchFilt(string MatCode) { // init valori esito ricerca + risultato TypeFound esito = string.IsNullOrEmpty(MatCode) ? TypeFound.MISSING_CODE : TypeFound.NOT_FOUND; List result = new List(); // solo se ho una VERA ricerca x MatCode if (!string.IsNullOrEmpty(MatCode)) { // cerco nei materiali var rawData = GetFiltModel(MatCode); if (rawData != null && rawData.Count > 0) { // ...e converto result = rawData.Select(x => ConvToCore(x)).ToList(); esito = TypeFound.MATERIAL; } else { // cerco negli alias... using (AliasController aliasDbContr = new AliasController()) { var aliasRec = aliasDbContr.FindByDbId(MatCode); if (aliasRec != null) { rawData = GetFiltModel(aliasRec.ValueAlias); if (rawData != null && rawData.Count > 0) { // ...e converto result = rawData.Select(x => ConvToCore(x)).ToList(); esito = TypeFound.ALIAS; } } } } } // compongo risposta! SearchResult answ = new SearchResult() { Tipo = esito, Result = result }; return answ; } /// /// Update Material record from CoreM /// /// /// Returns 0 if not found public int Update(Core.MaterialM coreItem) { int newIdx = 0; // converto MaterialModel updItem = ConvToModel(coreItem); newIdx = Update(updItem); return newIdx; } /// /// Update Material record /// /// /// Returns 0 if not found public int Update(MaterialModel updItem) { int newIdx = 0; using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { try { var item2update = localDbCtx .MaterialsList .Where(x => (updItem.MatId > 0 && x.MatId == updItem.MatId) || (updItem.MatCloudId > 0 && x.MatCloudId == updItem.MatCloudId) || (x.MatCode == updItem.MatCode && x.WMm == updItem.WMm && x.HMm == updItem.HMm && x.LMm == updItem.LMm)) .SingleOrDefault(); if (item2update != null) { //// update, vers 1... //localDbCtx.Entry(item2update).CurrentValues.SetValues(updItem); item2update.MatCloudId = updItem.MatCloudId; item2update.MatDesc = updItem.MatDesc; localDbCtx.Entry(item2update).State = System.Data.Entity.EntityState.Modified; // Commit changes localDbCtx.SaveChanges(); newIdx = item2update.MatId; } } catch (Exception exc) { Log.Error($"EXCEPTION on Materials.Update: {Environment.NewLine}{exc}"); } } return newIdx; } /// /// Upsert Material record /// /// /// MatId (existing or new) public int Upsert(MaterialModel updItem) { int newIdx = 0; using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { try { var item2update = localDbCtx .MaterialsList .Where(x => (updItem.MatId > 0 && x.MatId == updItem.MatId) || (updItem.MatCloudId > 0 && x.MatCloudId == updItem.MatCloudId) || (x.MatCode == updItem.MatCode && x.WMm == updItem.WMm && x.HMm == updItem.HMm && x.LMm == updItem.LMm)) .SingleOrDefault(); if (item2update != null) { //// update, vers 1... //localDbCtx.Entry(item2update).CurrentValues.SetValues(updItem); item2update.MatCloudId = updItem.MatCloudId; item2update.MatDesc = updItem.MatDesc; localDbCtx.Entry(item2update).State = System.Data.Entity.EntityState.Modified; // Commit changes localDbCtx.SaveChanges(); newIdx = item2update.MatId; } else { localDbCtx.MaterialsList.Add(updItem); // Commit changes localDbCtx.SaveChanges(); newIdx = updItem.MatId; } } catch (Exception exc) { Log.Error($"EXCEPTION on Materials.Insert: {Environment.NewLine}{exc}"); } } return newIdx; } #endregion Public Methods #region Public Classes /// /// Risultato ricerca materiali /// public class SearchResult { #region Public Enums /// /// Enum del risultato della ricerca materiali /// public enum TypeFound { MISSING_CODE = 0, NOT_FOUND, ALIAS, MATERIAL } #endregion Public Enums #region Public Properties /// /// Materiali trovati /// public List Result { get; set; } = new List(); /// /// Tipologia oggetto trovato /// public TypeFound Tipo { get; set; } = TypeFound.MISSING_CODE; #endregion Public Properties } #endregion Public Classes #region Private Fields /// /// Istanza logger /// private NLog.Logger Log = LogManager.GetCurrentClassLogger(); #endregion Private Fields } }