diff --git a/MP-TAB3/MP-TAB3.csproj b/MP-TAB3/MP-TAB3.csproj
index f073261a..9bdd0469 100644
--- a/MP-TAB3/MP-TAB3.csproj
+++ b/MP-TAB3/MP-TAB3.csproj
@@ -3,7 +3,7 @@
net8.0
enable
- 8.16.2606.408
+ 8.16.2606.1117
enable
MP_TAB3
diff --git a/MP-TAB3/Resources/ChangeLog.html b/MP-TAB3/Resources/ChangeLog.html
index 6e774415..a7abc269 100644
--- a/MP-TAB3/Resources/ChangeLog.html
+++ b/MP-TAB3/Resources/ChangeLog.html
@@ -1,6 +1,6 @@
Modulo MAPOSPEC
- Versione: 8.16.2606.408
+ Versione: 8.16.2606.1117
Note di rilascio:
-
diff --git a/MP-TAB3/Resources/VersNum.txt b/MP-TAB3/Resources/VersNum.txt
index 988a0006..cb037420 100644
--- a/MP-TAB3/Resources/VersNum.txt
+++ b/MP-TAB3/Resources/VersNum.txt
@@ -1 +1 @@
-8.16.2606.408
+8.16.2606.1117
diff --git a/MP-TAB3/Resources/manifest.xml b/MP-TAB3/Resources/manifest.xml
index 1c9cc682..bdbc08e1 100644
--- a/MP-TAB3/Resources/manifest.xml
+++ b/MP-TAB3/Resources/manifest.xml
@@ -1,6 +1,6 @@
-
- 8.16.2606.408
+ 8.16.2606.1117
https://nexus.steamware.net/repository/SWS/MP-TAB3/stable/LAST/MP-TAB3.zip
https://nexus.steamware.net/repository/SWS/MP-TAB3/stable/LAST/ChangeLog.html
false
diff --git a/MP.Data/Controllers/MpIocController.cs b/MP.Data/Controllers/MpIocController.cs
index 6502ccf6..f2520dfa 100644
--- a/MP.Data/Controllers/MpIocController.cs
+++ b/MP.Data/Controllers/MpIocController.cs
@@ -15,8 +15,6 @@ namespace MP.Data.Controllers
{
public class MpIocController
{
- protected readonly IDbContextFactory _ctxFactory;
- protected readonly IDbContextFactory _ctxFactoryFL;
#region Public Constructors
public MpIocController(
@@ -24,21 +22,8 @@ namespace MP.Data.Controllers
IDbContextFactory ctxFactory,
IDbContextFactory ctxFactoryFL)
{
-#if false
- _configuration = configuration;
-#endif
_ctxFactory = ctxFactory;
_ctxFactoryFL = ctxFactoryFL;
-#if false
- string connStr = configuration.GetConnectionString("MP.Data");
- options = new DbContextOptionsBuilder()
- .UseSqlServer(connStr)
- .Options;
- string connStrFlux = configuration.GetConnectionString("MP.Flux");
- optionsFlux = new DbContextOptionsBuilder()
- .UseSqlServer(connStrFlux)
- .Options;
-#endif
Log.Info("Avviata classe MpIocController");
}
@@ -500,9 +485,6 @@ namespace MP.Data.Controllers
// Update() allega l'entità e segna tutti i campi come Modified
dbCtx.DbSetMicroStatoMacc.Update(actRec);
-#if false
- dbCtx.Entry(actRec).State = EntityState.Modified;
-#endif
}
// ora record EVList
@@ -540,28 +522,6 @@ namespace MP.Data.Controllers
.ToListAsync();
}
- ///
- /// Elenco ultimi n record flux log dato macchina e flusso (ordinato x data registrazione)
- ///
- /// Data massima x eventi
- /// Data minima x eventi
- /// * = tutte, altrimenti solo x una data macchina
- /// *=tutti, altrimenti solo selezionato
- /// numero massimo record da restituire
- ///
- public async Task
> FluxLogGetLastFiltAsync(DateTime DtMax, DateTime DtMin, string IdxMacchina, string CodFlux, int MaxRec)
- {
- using var dbCtx = await _ctxFactoryFL.CreateDbContextAsync();
-
- return await dbCtx
- .DbSetFluxLog
- .AsNoTracking()
- .Where(x => (x.dtEvento >= DtMin && x.dtEvento <= DtMax) && (IdxMacchina == "*" || x.IdxMacchina == IdxMacchina) && (CodFlux == "*" || x.CodFlux == CodFlux))
- .OrderByDescending(x => x.dtEvento)
- .Take(MaxRec)
- .ToListAsync();
- }
-
///
/// Aggiunta record FluxLog
///
@@ -574,8 +534,7 @@ namespace MP.Data.Controllers
var currRec = dbCtx
.DbSetFluxLog
.Add(newRec);
- return await dbCtx.SaveChangesAsync()>0;
-
+ return await dbCtx.SaveChangesAsync() > 0;
}
///
@@ -597,266 +556,6 @@ namespace MP.Data.Controllers
return result > 0;
}
- ///
- /// Upsert record keepalive
- ///
- ///
- ///
- ///
- ///
- public async Task KeepAliveUpsertAsync(string IdxMacc, DateTime OraServer, DateTime OraMacc)
- {
- bool fatto = false;
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var currRec = await dbCtx
- .DbSetKeepAlive
- .Where(x => x.IdxMacchina == IdxMacc)
- .FirstOrDefaultAsync();
- if (currRec != null)
- {
- currRec.DataOraServer = OraServer;
- currRec.DataOraMacchina = OraMacc;
- dbCtx.Entry(currRec).State = EntityState.Modified;
- }
- else
- {
- KeepAliveModel newRec = new KeepAliveModel()
- {
- IdxMacchina = IdxMacc,
- DataOraMacchina = OraMacc,
- DataOraServer = OraServer,
- DataOraStart = DateTime.Now
- };
- dbCtx
- .DbSetKeepAlive
- .Add(newRec);
- }
- fatto = await dbCtx.SaveChangesAsync() > 0;
-
- return fatto;
- }
-
- public async Task> ListLinkFiltAsync(string tipoLink)
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- dbResult = await dbCtx
- .DbSetLinkMenu
- .Where(x => x.TipoLink == tipoLink)
- .AsNoTracking()
- .OrderBy(x => x.Ordine)
- .ToListAsync();
- return dbResult;
- }
-
- ///
- /// Elenco valori ammessi x tabella/colonna con filtro parametrico
- ///
- /// Filtro tabella (se "" tutto)
- /// Filtro colonna (se "" tutto)
- ///
- public async Task> ListValuesFiltAsync(string tabName, string fieldName)
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var query = dbCtx
- .DbSetListValues
- .AsNoTracking()
- .AsQueryable();
-
- if (!string.IsNullOrEmpty(tabName))
- query = query.Where(x => x.TableName == tabName);
- if (!string.IsNullOrEmpty(fieldName))
- query = query.Where(x => x.FieldName == fieldName);
-
- dbResult = await query.ToListAsync();
-
- return dbResult;
- }
-
- ///
- /// Intera tabella relazione master/slave in machine (gestione setup master - slave)
- ///
- ///
- public async Task> Macchine2SlaveAsync()
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- dbResult = await dbCtx
- .DbSetM2S
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToListAsync();
-
- return dbResult;
- }
-
- ///
- /// Elenco Record Macchine
- ///
- ///
- public async Task> MacchineGetAllAsync()
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- dbResult = await dbCtx
- .DbSetMacchine
- .ToListAsync();
-
- return dbResult;
- }
-
- public async Task MacchineGetByIdxAsync(string IdxMacchina)
- {
- MacchineModel dbResult = null;
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- dbResult = await dbCtx
- .DbSetMacchine
- .FirstOrDefaultAsync(x => x.IdxMacchina == IdxMacchina);
-
- return dbResult;
- }
-
- ///
- /// Elenco da tabella Macchine
- ///
- ///
- ///
- public async Task> MacchineGetFiltAsync(string codGruppo)
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- if (codGruppo == "*")
- {
- dbResult = await dbCtx
- .DbSetMacchine
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToListAsync();
- }
- else
- {
- dbResult = await dbCtx
- .DbSetGrp2Macc
- .Where(g => g.CodGruppo == codGruppo)
- .Join(dbCtx.DbSetMacchine,
- g => g.IdxMacchina,
- m => m.IdxMacchina,
- (g, m) => m
- )
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToListAsync();
- }
-
- return dbResult;
- }
-
- ///
- /// Upsert Record Macchine ASYNC
- ///
- ///
- public async Task MacchineUpsertAsync(MacchineModel entity)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- // Recuperiamo l'entità tracciata dal context
- var trackedEntity = await dbCtx
- .DbSetMacchine
- .FirstOrDefaultAsync(x => x.IdxMacchina == entity.IdxMacchina);
-
- if (trackedEntity != null)
- {
- // Aggiorna i valori dell'entità tracciata con quelli della nuova
- dbCtx.Entry(trackedEntity).CurrentValues.SetValues(entity);
- }
- else
- {
- dbCtx.DbSetMacchine.Update(entity);
- }
- bool fatto = await dbCtx.SaveChangesAsync() > 0;
- return fatto;
- }
-
- ///
- /// Elenco da tabella Macchine
- ///
- ///
- ///
- public async Task> MicroStatoMacchinaGetByIdxMaccAsync(string IdxMacc)
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- dbResult = await dbCtx
- .DbSetMicroStatoMacc
- .Where(x => x.IdxMacchina == IdxMacc)
- .AsNoTracking()
- .ToListAsync();
- return dbResult;
- }
-
- ///
- /// Aggiornamento record Microstato macchina
- ///
- ///
- ///
- public async Task MicroStatoMacchinaUpsertAsync(MicroStatoMacchinaModel newRec)
- {
- bool fatto = false;
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var actRec = await dbCtx
- .DbSetMicroStatoMacc
- .Where(x => x.IdxMacchina == newRec.IdxMacchina)
- .AsNoTracking()
- .FirstOrDefaultAsync();
- if (actRec == null)
- {
- dbCtx
- .DbSetMicroStatoMacc
- .Add(newRec);
- }
- else
- {
- actRec.IdxMicroStato = newRec.IdxMicroStato;
- actRec.InizioStato = newRec.InizioStato;
- actRec.Value = newRec.Value;
-
- dbCtx.Entry(actRec).State = EntityState.Modified;
- }
- fatto = await dbCtx.SaveChangesAsync() > 0;
-
- return fatto;
- }
-
- ///
- /// Elenco da tabella MappaStatoExplModel
- ///
- ///
- public async Task> MseGetAllAsync(int maxAge = 2000)
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge);
-
- dbResult = await dbCtx
- .DbSetMSE
- .FromSqlRaw("EXEC stp_MSE_getData @maxAgeSec", maxAgeSec)
- .AsNoTracking()
- .ToListAsync();
-
- return dbResult;
- }
-
///
/// Generazione automatica ODL
///
@@ -929,28 +628,6 @@ namespace MP.Data.Controllers
return answ;
}
- ///
- /// Fix ODL per macchine SLAVE
- ///
- ///
- ///
- ///
- ///
- public async Task OdlFixMachineSlave(string idxMacchina, int numDayPrev, int doInsert)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var idxMaccParam = new SqlParameter("@IdxMacchina", idxMacchina ?? "");
- var numDayPrevParam = new SqlParameter("@NumDayPrev", numDayPrev);
- var doInsertParam = new SqlParameter("@DoInsert", doInsert);
-
- var result = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC stp_ODL_fixMachineSlave @IdxMacchina, @NumDayPrev, @DoInsert", idxMaccParam, numDayPrevParam, doInsertParam);
-
- return result != -1;
- }
-
///
/// Fix ODL per macchine SLAVE Async
///
@@ -993,30 +670,6 @@ namespace MP.Data.Controllers
return answ;
}
- ///
- /// Elenco ODL data macchina e periodo
- ///
- ///
- ///
- ///
- ///
- public async Task> OdlListByMaccPeriodoAsync(string idxMacchina, DateTime dtStart, DateTime dtEnd)
- {
- List dbResult = new List();
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina);
- var DataFrom = new SqlParameter("@dataFrom", dtStart);
- var DataTo = new SqlParameter("@dataTo", dtEnd);
- dbResult = await dbCtx
- .DbSetODLExp
- .FromSqlRaw("EXEC stp_ODL_getByMacchinaPeriodo @IdxMacchina, @dataFrom, @dataTo", IdxMacchina, DataFrom, DataTo)
- .AsNoTracking()
- .ToListAsync();
-
- return dbResult;
- }
-
///
/// Conteggio PzProd Macchina Async
///
@@ -1131,27 +784,6 @@ namespace MP.Data.Controllers
return result != 0;
}
- ///
- /// Update record Registro Dichiarazioni
- ///
- ///
- ///
- public async Task RegDichiarUpdateAsync(RegistroDichiarazioniModel newRec)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var Original_IdxDich = new SqlParameter("@Original_IdxDich", newRec.IdxDich);
- var DtRec = new SqlParameter("@DtRec", newRec.DtRec);
- var TagCode = new SqlParameter("@TagCode", newRec.TagCode);
- var ValString = new SqlParameter("@ValString", newRec.ValString);
- var MatrOpr = new SqlParameter("@MatrOpr", newRec.MatrOpr);
- var result = await dbCtx
- .Database
- .ExecuteSqlRawAsync("exec dbo.stp_DD_updateQuery @Original_IdxDich, @DtRec, @TagCode, @ValString, @MatrOpr", Original_IdxDich, DtRec, TagCode, ValString, MatrOpr);
-
- return result != 0;
- }
-
///
/// Aggiunta record RegistroScarti
///
@@ -1222,160 +854,6 @@ namespace MP.Data.Controllers
return fatto;
}
- ///
- /// Aggiunta record RemoteRebootLog
- ///
- ///
- ///
- public async Task RemRebootLogAddAsync(RemoteRebootLogModel newRec)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var dbResult = dbCtx
- .DbSetRemRebLog
- .Add(newRec);
-
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Recupera tutti i record di RemoteRebootLog
- ///
- ///
- public async Task> RemRebootLogGetAllAsync()
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var dbResult = await dbCtx
- .DbSetRemRebLog
- .AsNoTracking()
- .OrderByDescending(x => x.IdxReboot)
- .ToListAsync();
- return dbResult;
- }
-
- ///
- /// Recupera ultimo record x ogni IdxMacchina x avere ultimo attivo
- ///
- ///
- public async Task> RemRebootLogGetLastAsync()
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
- var dbResult = await dbCtx
- .DbSetRemRebLog
- .FromSqlRaw("EXEC stp_RRL_getLast")
- .AsNoTracking()
- .ToListAsync();
- return dbResult;
- }
-
- ///
- /// Recupera ultimo record x ogni IdxMacchina x avere ultimo attivo
- ///
- ///
- public async Task RemRebootLogKeepLastAsync(int num2keep)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var pNum2Keep = new SqlParameter("@num2keep", num2keep);
- // La SP gestisce già la logica di soglia (1.5x), ma la specifico x sicurezza
- var pThresh = new SqlParameter("@threshMult", 1.5);
- var dbResult = await dbCtx.Database.ExecuteSqlRawAsync(
- "EXEC dbo.stp_RRL_KeepLatest @num2keep, @threshMult", pNum2Keep, pThresh);
-
- return dbResult != 0;
- }
-
- ///
- /// Aggiunta record SignalLog Async
- ///
- ///
- ///
- public async Task SignalLogInsertAsync(SignalLogModel newRec)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var currRec = dbCtx
- .DbSetSignalLog
- .Add(newRec);
-
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Tabella state machine eventi 2 stati data macchina e tipo evento
- ///
- ///
- ///
- public async Task> SMES_getHwTransitionsAsync(string idxMacchina, int idxTipo)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina);
- var IdxTipo = new SqlParameter("@IdxTipo", idxTipo);
- var dbResult = await dbCtx
- .DbSetSMES
- .FromSqlRaw("exec dbo.stp_TS_getByIdxMacchIdxTipoEv @IdxMacchina, @IdxTipo", IdxMacchina, IdxTipo)
- .AsNoTracking()
- .ToListAsync();
-
- return dbResult;
- }
-
- ///
- /// Tabella state machine eventi 2 stati data macchina e tipo evento
- ///
- ///
- ///
- public async Task> SMES_getUserForcedAsync(string idxMacchina, int idxTipo)
- {
- await using var dbCtx = _ctxFactory.CreateDbContext();
-
- var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina);
- var IdxTipo = new SqlParameter("@IdxTipo", idxTipo);
- var dbResult = await dbCtx
- .DbSetSMES
- .FromSqlRaw("exec dbo.stp_TS_getUserForcedTrans @IdxMacchina, @IdxTipo", IdxMacchina, IdxTipo)
- .AsNoTracking()
- .ToListAsync();
-
- return dbResult;
- }
-
- ///
- /// Intera tabella state machine ingressi 2 eventi
- ///
- ///
- public List StateMachineIngressi(int idxFam)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
- var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam);
- return dbCtx
- .DbSetSMI
- .FromSqlRaw("exec dbo.stp_TRI_getByIdxFamIng @IdxFamigliaIngresso", IdxFamIn)
- .AsNoTracking()
- .AsEnumerable()
- .ToList();
- }
-
- ///
- /// Intera tabella state machine ingressi 2 eventi
- ///
- ///
- public async Task> StateMachineIngressiAsync(int idxFam)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
-
- var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam);
- var dbResult = await dbCtx
- .DbSetSMI
- .FromSqlRaw("exec dbo.stp_TRI_getByIdxFamIng @IdxFamigliaIngresso", IdxFamIn)
- .AsNoTracking()
- .ToListAsync();
-
- return dbResult;
- }
-
///
/// Stato prod macchina (completo) Async
///
@@ -1457,24 +935,18 @@ namespace MP.Data.Controllers
#endregion Public Methods
+ #region Protected Fields
+
+ protected readonly IDbContextFactory _ctxFactory;
+ protected readonly IDbContextFactory _ctxFactoryFL;
+
+ #endregion Protected Fields
+
#region Private Fields
-#if false
- private static IConfiguration _configuration;
-#endif
private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
-#if false
- private DbContextOptions options;
-#endif
private DbContextOptions optionsFlux;
#endregion Private Fields
-
-#if false
- public void Dispose()
- {
- _configuration = null;
- }
-#endif
}
}
\ No newline at end of file
diff --git a/MP.Data/Controllers/MpSpecRepository.cs b/MP.Data/Controllers/MpSpecRepository.cs
deleted file mode 100644
index 27b70da3..00000000
--- a/MP.Data/Controllers/MpSpecRepository.cs
+++ /dev/null
@@ -1,2029 +0,0 @@
-using Microsoft.Data.SqlClient;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.Configuration;
-using MP.Data.DbModels;
-using NLog;
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace MP.Data.Controllers
-{
- public class MpSpecController
- {
- protected readonly IDbContextFactory _ctxFactory;
- protected readonly IDbContextFactory _ctxFactoryFL;
- #region Public Constructors
-
- public MpSpecController(
- IConfiguration configuration,
- IDbContextFactory ctxFactory,
- IDbContextFactory ctxFactoryFL)
- {
- _configuration = configuration;
- _ctxFactory = ctxFactory;
- _ctxFactoryFL = ctxFactoryFL;
-#if false
- string connStr = _configuration.GetConnectionString("MP.Data");
- options = new DbContextOptionsBuilder()
- .UseSqlServer(connStr)
- .Options;
-#endif
- Log.Info("Avviata classe MpSpecController");
- }
-
- #endregion Public Constructors
-
- #region Public Methods
-
-#if false
- ///
- /// Stacca un nuovo counter x il tipo richiesto
- ///
- ///
- public async Task AnagCountersGetNextAsync(string cntType)
- {
- AnagCountersModel answ = new AnagCountersModel();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- bool outTable = true;
- if (outTable)
- {
- var pCntType = new SqlParameter("@CntType", cntType);
- var pLastNum = new SqlParameter
- {
- ParameterName = "@LastNum",
- SqlDbType = SqlDbType.Int,
- Direction = ParameterDirection.Output
- };
-
- var dbResult = await dbCtx
- .DbSetAnagCount
- .FromSqlRaw("EXEC dbo.stp_getNextNumb @CntType, @LastNum OUTPUT", pCntType, pLastNum)
- .AsNoTracking()
- .FirstOrDefaultAsync();
- if (dbResult != null)
- {
- answ = dbResult;
- }
- }
- else
- {
- // se si volessero impiegare parametri OUTPUT (qui ne mancherebbe 1 nella stored x CntCode...)
- var pCntType = new SqlParameter("@CntType", cntType);
- var pLastNum = new SqlParameter
- {
- ParameterName = "@LastNum",
- SqlDbType = SqlDbType.Int,
- Direction = ParameterDirection.Output
- };
- var pCntCode = new SqlParameter
- {
- ParameterName = "@CntCode",
- SqlDbType = SqlDbType.NVarChar,
- Direction = ParameterDirection.Output
- };
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC dbo.stp_getNextNumb @CntType, @LastNum OUTPUT, @CntCode OUTPUT", pCntType, pLastNum, pCntCode);
- if (dbResult != 0)
- {
- answ.CntType = cntType;
- answ.CntCode = $"{pCntCode.Value}";
- int lNum = 0;
- int.TryParse($"{pLastNum.Value}", out lNum);
- answ.LastNum = lNum;
- }
- }
- return answ;
- }
-
- ///
- /// Restituisce l'anagrafica EVENTI generalmente disponibile per OGNI macchina
- ///
- /// Nome Table x filtro (std: EvList)
- /// Nome Field x filtro (std: Common)
- ///
- public async Task> AnagEventiGeneralAsync(string TableName = "EvList", string FieldName = "Common")
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var pTableName = new SqlParameter("@TableName", TableName);
- var pFieldName = new SqlParameter("@FieldName", FieldName);
- var dbResult = await dbCtx
- .DbSetVSEB
- .FromSqlRaw("exec dbo.stp_vseb_getGenerallyAvailable @TableName, @FieldName", pTableName, pFieldName)
- .AsNoTracking()
- .ToListAsync();
- return dbResult ?? new();
- }
-
-
- ///
- /// Elenco Gruppi tipo Azienda
- ///
- ///
- public Task> AnagGruppiAziendeAsync()
- {
- return AnagGruppiGetTipoAsync("AZIENDA");
- }
-
- ///
- /// Delete record AnagraficaGruppi
- ///
- ///
- public async Task AnagGruppiDeleteAsync(AnagGruppiModel updRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var dbRec = await dbCtx
- .DbSetAnagGruppi
- .AsNoTracking()
- .Where(x => x.CodGruppo == updRec.CodGruppo)
- .FirstOrDefaultAsync();
- // se trovato aggiorno descrizione (resto immutato x sicurezza!)
- if (dbRec != null)
- {
- dbCtx.DbSetAnagGruppi.Remove(dbRec);
- }
- var numRes = await dbCtx.SaveChangesAsync();
- return numRes != 0;
- }
-
- ///
- /// Elenco Gruppi tipo Fasi
- ///
- ///
- public Task> AnagGruppiFaseAsync()
- {
- return AnagGruppiGetTipoAsync("FASE");
- }
-
-
- ///
- /// Gruppi x tipo modalità Async
- ///
- ///
- ///
- public async Task> AnagGruppiGetTipoAsync(string tipoGruppo)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetAnagGruppi
- .Where(x => x.TipoGruppo == tipoGruppo)
- .AsNoTracking()
- .OrderBy(x => x.CodGruppo)
- .ToListAsync();
- }
-
- ///
- /// Elenco Gruppi tipo REPARTO (x associazione Macchine-Operatori) in formato DTO con conteggi del numero record trovati
- ///
- ///
- public async Task> AnagGruppiRepartoDtoAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- // in primis recupero i reparti...
- var listReparti = await AnagGruppiGetTipoAsync("REPARTO");
-
- // recupero TUTTE le macchine da DbSetGrp2Macc
- var listMacc = await dbCtx
- .DbSetGrp2Macc
- .AsNoTracking()
- .ToListAsync();
- // recupero TUTTI gli operatori da DbSetGrp2Oper
- var listOpr = await dbCtx
- .DbSetGrp2Oper
- .AsNoTracking()
- .ToListAsync();
-
- return listReparti
- .Select(x => new RepartiDTO()
- {
- CodGruppo = x.CodGruppo,
- TipoGruppo = x.TipoGruppo,
- DescrGruppo = x.DescrGruppo,
- SelEnabled = x.SelEnabled,
- CountMacc = listMacc.Where(y => y.CodGruppo == x.CodGruppo).Select(x => x.IdxMacchina).Distinct().Count(),
- CountOpr = listOpr.Where(y => y.CodGruppo == x.CodGruppo).Select(x => x.MatrOpr).Distinct().Count()
- })
- .ToList();
- }
-
- ///
- /// Upsert record AnagraficaGruppi (solo codice/descrizione)
- ///
- ///
- ///
- public async Task AnagGruppiUpsertAsync(AnagGruppiModel updRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var dbRec = await dbCtx
- .DbSetAnagGruppi
- .AsNoTracking()
- .Where(x => x.CodGruppo == updRec.CodGruppo)
- .FirstOrDefaultAsync();
- // se trovato aggiorno descrizione (resto immutato x sicurezza!)
- if (dbRec != null)
- {
- dbRec.DescrGruppo = updRec.DescrGruppo;
- dbCtx.Entry(dbRec).State = EntityState.Modified;
- }
- // altrimenti aggiungo
- else
- {
- await dbCtx.DbSetAnagGruppi.AddAsync(updRec);
- }
- var numRes = await dbCtx.SaveChangesAsync();
-
- return numRes != 0;
- }
-
-
- ///
- /// Elenco valori ammessi x Stati commessa (es Yacht Baglietto)
- ///
- ///
- public Task> AnagStatiCommAsync()
- {
- return ListValuesFiltAsync("PODL", "StatoComm");
- }
-
- ///
- /// Elenco valori ammessi x Tipo articoli
- ///
- ///
- public Task> AnagTipoArtLvAsync()
- {
- return ListValuesFiltAsync("AnagArticoli", "Tipo");
- }
-
-#endif
-
-#if false
- ///
- /// Elenco codice articoli che abbiano dati Dossier
- ///
- ///
- public async Task> ArticleWithDossierAsync()
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- return await dbCtx
- .DbSetDossiers
- .AsNoTracking()
- .Select(i => i.CodArticolo)
- .Distinct()
- .ToListAsync();
- }
-
-#endif
-
-#if false
- ///
- /// Conteggio num articoli Async
- ///
- ///
- public async Task ArticoliCountAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var result = await dbCtx
- .DbSetArticoli
- .CountAsync();
- return result;
- }
-
- ///
- /// Conteggio articoli data condizione ricerca
- ///
- ///
- ///
- ///
- ///
- public async Task ArticoliCountSearchAsync(string tipoArt = "*", string azienda = "*", string searchVal = "")
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- IQueryable query = dbCtx.DbSetArticoli.AsNoTracking();
-
- // filtro tipo articolo
- if (tipoArt != "*")
- {
- //query = query.Where(x => x.Tipo.ToLower() == tipoArt.ToLower());
- query = query.Where(x => EF.Functions.Like(x.Tipo, tipoArt));
- }
- // filtro azienda
- if (azienda != "*")
- {
- //query = query.Where(x => x.Azienda.ToLower() == azienda.ToLower());
- query = query.Where(x => EF.Functions.Like(x.Azienda, azienda));
- }
- // filtro ricerca
- if (!string.IsNullOrWhiteSpace(searchVal))
- {
- string pattern = $"%{searchVal}%";
- query = query.Where(x =>
- EF.Functions.Like(x.CodArticolo, pattern) ||
- EF.Functions.Like(x.DescArticolo, pattern) ||
- EF.Functions.Like(x.Disegno, pattern));
- }
-
- return await query
- .OrderBy(x => x.CodArticolo)
- .CountAsync();
- }
-
- ///
- /// Elenco tabella Articoli IMPIEGATI (da stored stp_ART_getUsed) Async
- ///
- ///
- public async Task ArticoliCountUsedAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var result = await dbCtx
- .DbSetCounter
- .FromSqlRaw("EXEC stp_ART_CountUsed")
- .AsNoTracking()
- .ToListAsync();
-
- return result.FirstOrDefault()?.NumCount ?? 0;
- }
-
- ///
- /// Eliminazione Record
- ///
- ///
- ///
- public async Task ArticoliDeleteRecordAsync(AnagArticoliModel currRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var currVal = dbCtx
- .DbSetArticoli
- .Where(x => x.CodArticolo == currRec.CodArticolo)
- .FirstOrDefault();
- dbCtx
- .DbSetArticoli
- .Remove(currVal);
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Restitusice elenco articoli dato tipo (es KIT)
- ///
- ///
- ///
- ///
- ///
- public async Task> ArticoliGetByTipoAsync(string tipo, string azienda = "*")
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetArticoli
- .AsNoTracking()
- .Where(x => x.Tipo.ToUpper() == tipo.ToUpper() && (azienda == "*" || x.Azienda.ToUpper() == azienda.ToUpper()))
- .OrderBy(x => x.CodArticolo)
- .ToListAsync();
- }
-
- ///
- /// Elenco tabella Articoli da filtro
- ///
- ///
- ///
- ///
- ///
- ///
- public async Task> ArticoliGetSearchAsync(int numRecord, string tipoArt = "*", string azienda = "*", string searchVal = "")
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- IQueryable query = dbCtx.DbSetArticoli
- .AsNoTracking();
-
- // filtro tipo articolo
- if (tipoArt != "*")
- {
- //query = query.Where(x => x.Tipo.ToLower() == tipoArt.ToLower());
- query = query.Where(x => EF.Functions.Like(x.Tipo, tipoArt));
- }
- // filtro azienda
- if (azienda != "*")
- {
- //query = query.Where(x => x.Azienda.ToLower() == azienda.ToLower());
- query = query.Where(x => EF.Functions.Like(x.Azienda, azienda));
- }
- // filtro ricerca
- if (!string.IsNullOrWhiteSpace(searchVal))
- {
- string pattern = $"%{searchVal}%";
- query = query.Where(x =>
- EF.Functions.Like(x.CodArticolo, pattern) ||
- EF.Functions.Like(x.DescArticolo, pattern) ||
- EF.Functions.Like(x.Disegno, pattern));
- }
-
- return await query
- .OrderBy(x => x.CodArticolo)
- .Take(numRecord)
- .ToListAsync();
- }
-
- ///
- /// Elenco tabella Articoli NON IMPIEGATI (da stored stp_ART_getUsed) Async
- ///
- ///
- public async Task> ArticoliGetUnusedAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetArticoli
- .FromSqlRaw("EXEC stp_ART_getNotUsed")
- .AsNoTracking()
- .ToListAsync();
- }
-
- ///
- /// Elenco tabella Articoli IMPIEGATI (da stored stp_ART_getUsed) Async
- ///
- ///
- public async Task> ArticoliGetUsedAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetArticoli
- .FromSqlRaw("EXEC stp_ART_getUsed")
- .AsNoTracking()
- .ToListAsync();
- }
-
- ///
- /// Elenco Articoli che sono in KIT Child
- ///
- ///
- public async Task> ArticoliInKitAsync()
- {
- List dbResult = new List();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- dbResult = await dbCtx
- .DbSetArticoli
- .FromSqlRaw("EXEC stp_TempKIT_getArtChild")
- .AsNoTracking()
- .ToListAsync();
- return dbResult;
- }
-
- ///
- /// Update Record
- ///
- ///
- ///
- public async Task ArticoliUpdateRecord(AnagArticoliModel editRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var currRec = dbCtx
- .DbSetArticoli
- .Where(x => x.CodArticolo == editRec.CodArticolo)
- .FirstOrDefault();
- if (currRec != null)
- {
- currRec.Disegno = editRec.Disegno;
- currRec.DescArticolo = editRec.DescArticolo;
- currRec.Tipo = editRec.Tipo;
- currRec.Azienda = editRec.Azienda;
- dbCtx.Entry(currRec).State = EntityState.Modified;
- }
- else
- {
- dbCtx
- .DbSetArticoli
- .Add(editRec);
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-#endif
-#if false
-
- ///
- /// Elenco da tabella Config Async
- ///
- ///
- public async Task> ConfigGetAllAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetConfig
- .AsNoTracking()
- .OrderBy(x => x.Chiave)
- .ToListAsync() ?? new();
- }
-
- ///
- /// Update record config
- ///
- ///
- public async Task ConfigUpdateAsync(ConfigModel updRec)
- {
- bool fatto = false;
- ConfigModel dbResult = new ConfigModel();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- dbResult = await dbCtx
- .DbSetConfig
- .Where(x => x.Chiave == updRec.Chiave)
- .FirstOrDefaultAsync();
- if (dbResult != null)
- {
- dbResult.Valore = updRec.Valore;
- fatto = await dbCtx.SaveChangesAsync() > 0;
- }
- return fatto;
- }
-
- ///
- /// Eliminazione di un dossier
- ///
- /// record dossier da eliminare
- ///
- public async Task DossiersDeleteRecordAsync(DossierModel currRec)
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- var currVal = await dbCtx
- .DbSetDossiers
- .Where(x => x.IdxDossier == currRec.IdxDossier)
- .FirstOrDefaultAsync();
- dbCtx
- .DbSetDossiers
- .Remove(currVal);
-
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Elenco ultimi n record DOssiers (che contengono ad esempio "salvataggi" di FLuxLog) dato
- /// macchina (ordinato x data registrazione)
- ///
- /// * = tutte, altrimenti solo x una data macchina
- /// * = tutti, altrimenti solo x un dato articolo
- /// Data minima per estrazione records
- /// Data Massima per estrazione records
- /// Num max record recuperati
- ///
- public async Task> DossiersGetLastFiltAsync(string IdxMacchina, string CodArticolo, DateTime DtStart, DateTime DtEnd, int MaxRec)
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- return await dbCtx
- .DbSetDossiers
- .AsNoTracking()
- .Where(x => (IdxMacchina == "*" || x.IdxMacchina == IdxMacchina) && (CodArticolo == "*" || x.CodArticolo == CodArticolo) && (x.DtRif >= DtStart && x.DtRif <= DtEnd))
- .Include(m => m.MachineNav)
- .Include(a => a.ArticoloNav)
- .OrderByDescending(x => x.DtRif)
- .Take(MaxRec)
- .ToListAsync();
- }
-
- ///
- /// insert di un record Dossier
- ///
- /// record dossier da modificare
- ///
- public async Task DossiersInsertAsync(DossierModel newRec)
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- dbCtx
- .DbSetDossiers
- .AddAsync(newRec);
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Effettua salvataggio snapshot parametri (con stored) + svuota eventuale cache _redisConn
- ///
- /// macchina
- /// Data min x selezione
- /// Data MAX x selezione
- public async Task DossiersTakeParamsSnapshotLastAsync(string idxMacchina, DateTime dtMin, DateTime dtMax)
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- var pIdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina);
- var pDtMin = new SqlParameter("@DtMin", dtMin);
- var pDtMax = new SqlParameter("@DtMax", dtMax);
-
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC stp_FL_TakeSnapshotLast @IdxMacchina,@DtMin,@DtMax", pIdxMacchina, pDtMin, pDtMax);
- return dbResult != 0;
- }
-
- ///
- /// Update del campo VALORE di un dossier (che contiene json flux log serializzati)
- ///
- /// record dossier da modificare
- ///
- public async Task DossiersUpdateValoreAsync(DossierModel editRec)
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- var currRec = await dbCtx
- .DbSetDossiers
- .Where(x => x.IdxDossier == editRec.IdxDossier)
- .FirstOrDefaultAsync();
- if (currRec != null)
- {
- currRec.Valore = editRec.Valore;
- dbCtx.Entry(currRec).State = EntityState.Modified;
- }
- else
- {
- await dbCtx
- .DbSetDossiers
- .AddAsync(editRec);
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Elenco valori link (x home e navMenu laterale)
- ///
- ///
- public Task> ElencoLinkAsync()
- {
- return ListLinkFiltAsync("SpecLink");
- }
-
- ///
- /// Aggiunta record EventList
- ///
- ///
- ///
- public async Task EvListInsertAsync(EventListModel newRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var currRec = await dbCtx
- .DbSetEvList
- .AddAsync(newRec);
-
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Funzione di Data Reduction x FluxLog
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- /// Restitusice list dei record statistiche raccolti (da integrare a quelli rpesenti in Redis...)
- ///
- public async Task> FluxLogDataReduxAsync(string idxMaccSel, List fluxList, Periodo currPeriodo, Enums.ValSelection valMode, Enums.DataInterval intReq, int maxItem)
- {
- List procStats = new List();
- Log.Info($"Inizio FluxLogDataReduxAsync | idxMaccSel: {idxMaccSel} | periodo: {currPeriodo.Inizio:yyyy-MM-dd} --> {currPeriodo.Fine:yyyy-MM-dd}");
- TimeSpan step = TimeSpan.FromHours(1);
- switch (intReq)
- {
- case Enums.DataInterval.minute:
- step = TimeSpan.FromMinutes(1.00 / maxItem);
- break;
-
- case Enums.DataInterval.hour:
- step = TimeSpan.FromHours(1.00 / maxItem);
- break;
-
- case Enums.DataInterval.day:
- step = TimeSpan.FromDays(1.00 / maxItem);
- break;
-
- default:
- break;
- }
-
- // setup parametri costanti x stored
- var pIdxMacchina = new SqlParameter("@IdxMacchina", idxMaccSel);
- var pOnlyTest = new SqlParameter("@OnlyTest", false);
-
- // dbContext condiviso
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- // opzionalmente timeout comandi a 2 minuti... NON usato x ora e da testare
- //dbCtx.Database.SetCommandTimeout(TimeSpan.FromMinutes(2));
- // processo 1:1 ogni flusso
- foreach (var item in fluxList)
- {
- Log.Info($"FluxLogDataReduxAsync | Flux: {item}");
- int numRecProc = 0;
- Stopwatch sw = new Stopwatch();
- sw.Start();
- // parametri x flusso
- var pCodFlux = new SqlParameter("@CodFlux", item);
- // inizializzo cursore timer
- DateTime dtCursStart = currPeriodo.Inizio;
- DateTime dtCursEnd = dtCursStart.Add(step);
- bool setCompleted = false;
- // li processo per intervallo richiesto, cercando dati nel periodo eselezionando VC
- while (!setCompleted)
- {
- // ora recupero TUTTI i dati della macchina
- var currFlux = await dbCtx
- .DbSetFluxLog
- .Where(x => (x.CodFlux == item) && (x.dtEvento >= dtCursStart && x.dtEvento < dtCursEnd) && (x.IdxMacchina == idxMaccSel))
- .ToListAsync();
-
- int numRec = currFlux.Count;
- numRecProc += numRec;
- if (numRec > maxItem)
- {
- List listPeriodi = new List();
-
- switch (valMode)
- {
- case Enums.ValSelection.First:
- // recupero 2° item
- var recStart = currFlux.Skip(1).FirstOrDefault();
- // salvo periodo!
- listPeriodi.Add(new Periodo(recStart.dtEvento, dtCursEnd));
- break;
-
- case Enums.ValSelection.Last:
- // recupero ultimo item
- var recEnd = currFlux.LastOrDefault();
- // salvo periodo!
- listPeriodi.Add(new Periodo(dtCursStart, recEnd.dtEvento));
- break;
-
- case Enums.ValSelection.Center:
- int idx = 1;
- // per iniziare mi metto a 1/(n+1) rec come step
- var recCent = currFlux.Skip(idx / (maxItem + 1)).FirstOrDefault();
- listPeriodi.Add(new Periodo(dtCursStart, recCent.dtEvento));
- // salvo restanti periodi (se > 1)!
- if (maxItem > 1)
- {
- for (int i = 2; i < maxItem; i++)
- {
- DateTime dtInizio = recCent.dtEvento;
- recCent = currFlux.Skip(i / (maxItem + 1)).FirstOrDefault();
- listPeriodi.Add(new Periodo(dtInizio, recCent.dtEvento));
- }
- }
- // aggiungo ultimo...
- listPeriodi.Add(new Periodo(recCent.dtEvento.AddSeconds(1), dtCursEnd));
- break;
-
- default:
- break;
- }
-
- // ciclo x tutti i periodi e chiamo stored...
- foreach (var slot in listPeriodi)
- {
- // parametri x periodo (base)
- var pDtStart = new SqlParameter("@DtStart", slot.Inizio);
- var pDtEnd = new SqlParameter("@DtEnd", slot.Fine);
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC man.stp_ReduceFluxLog @IdxMacchina, @CodFlux, @DtStart, @DtEnd, @OnlyTest", pIdxMacchina, pCodFlux, pDtStart, pDtEnd, pOnlyTest);
- }
- }
-
- // incremento dt fine periodo
- dtCursStart = dtCursEnd;
- dtCursEnd = dtCursStart.Add(step);
- setCompleted = dtCursStart >= currPeriodo.Fine;
- }
- // fermo cronometro e salvo su DB...
- sw.Stop();
- StatDedupDTO currStat = new StatDedupDTO()
- {
- IdxMacchina = idxMaccSel,
- CodFlux = item,
- Interval = intReq,
- Num4Int = maxItem,
- NumRec = numRecProc,
- ProcTime = sw.Elapsed.TotalSeconds
- };
- procStats.Add(currStat);
- }
- Log.Info($"FINE FluxLogDataReduxAsync | idxMaccSel: {idxMaccSel} | periodo: {currPeriodo.Inizio:yyyy-MM-dd} --> {currPeriodo.Fine:yyyy-MM-dd}");
- return procStats;
- }
-
- ///
- /// Elenco ultimi n record flux log dato macchina e flusso (ordinato x data registrazione)
- ///
- /// Data massima x eventi
- /// Data minima x eventi
- /// * = tutte, altrimenti solo x una data macchina
- /// *=tutti, altrimenti solo selezionato
- /// numero massimo record da restituire
- ///
- public async Task> FluxLogGetLastFiltAsync(DateTime DtMax, DateTime DtMin, string IdxMacchina, string CodFlux, int MaxRec)
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- return await dbCtx
- .DbSetFluxLog
- .AsNoTracking()
- .Where(x => (x.dtEvento >= DtMin && x.dtEvento <= DtMax) && (IdxMacchina == "*" || x.IdxMacchina == IdxMacchina) && (CodFlux == "*" || x.CodFlux == CodFlux))
- .OrderByDescending(x => x.dtEvento)
- .Take(MaxRec)
- .ToListAsync() ?? new();
- }
-
- ///
- /// Elenco Gruppi
- ///
- ///
- public async Task> FluxLogParetoAsync(string idxMacchina, DateTime dtFrom, DateTime dtTo)
- {
- using var dbCtx = new MoonPro_FluxContext(_configuration);
- return await dbCtx
- .DbSetFluxLog
- .Where(x => (string.IsNullOrEmpty(idxMacchina) || x.IdxMacchina == idxMacchina) && (dtFrom <= x.dtEvento && x.dtEvento <= dtTo))
- .AsNoTracking()
- .GroupBy(x => x.CodFlux)
- .Select(g => new ParetoFluxLogDTO() { IdxMacchina = idxMacchina, CodFlux = g.Key, Qty = g.Count() })
- .OrderByDescending(x => x.Qty)
- .ToListAsync() ?? new();
- }
-
- ///
- /// Stored manutenzione del DB
- ///
- /// Esegue realmente il task
- /// Aggiornamento statistiche
- /// Salvataggio
- /// def: 1000
- /// def: 10
- /// def: 50
- ///
- public async Task ForceDbMaintAsync(bool doExec, bool doUpdStat, bool doSave, int minPgCnt, int minAvgFrag, int maxAvgFragReb)
- {
- Log.Info($"Inizio ForceDbMaintAsync on MoonProAdminContext");
- // uso context admin x query lunghe
- using var dbCtx = new MoonProAdminContext(_configuration);
- var pFlgExec = new SqlParameter("@FlgExec", doExec ? "Y" : "N");
- var pFlgUpdStat = new SqlParameter("@FlgUpdStat", doUpdStat ? "Y" : "N");
- var pFlgSave = new SqlParameter("@FlgSave", doSave ? "Y" : "N");
- var pMinPgCnt = new SqlParameter("@min_page_count", minPgCnt);
- var pMinAvgFrag = new SqlParameter("@min_avg_fragmentation_in_percent", minAvgFrag);
- var pMaxAvgFrag = new SqlParameter("@max_avg_fragmentation_per_rebuild", maxAvgFragReb);
-
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC man.stp_Utility_Maintanance");
- //.ExecuteSqlRaw("EXEC man.stp_Utility_Maintanance @FlgExec, @FlgUpdStat, @FlgSave, @min_page_count, @min_avg_fragmentation_in_percent, @max_avg_fragmentation_per_rebuild", pFlgExec, pFlgUpdStat, pFlgSave, pMinPgCnt, pMinAvgFrag, pMaxAvgFrag);
- Log.Info($"FINE ForceDbMaintAsync on MoonProAdminContext");
- return dbResult != 0;
- }
-
- ///
- /// Eliminazione di un record macchina dal gruppo
- ///
- ///
- ///
- public async Task Grp2MaccDeleteAsync(Gruppi2MaccModel rec2del)
- {
- bool answ = false;
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var dbRec = await dbCtx
- .DbSetGrp2Macc
- .Where(x => x.CodGruppo == rec2del.CodGruppo && x.IdxMacchina == rec2del.IdxMacchina)
- .FirstOrDefaultAsync();
- if (dbRec != null)
- {
- dbCtx.DbSetGrp2Macc.Remove(dbRec);
- int numDone = await dbCtx.SaveChangesAsync();
- answ = numDone != 0;
- }
- return answ;
- }
-
- ///
- /// Insert di un record macchina
- ///
- ///
- ///
- public async Task Grp2MaccInsertAsync(Gruppi2MaccModel upsRec)
- {
- bool answ = false;
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var dbRec = await dbCtx
- .DbSetGrp2Macc
- .Where(x => x.CodGruppo == upsRec.CodGruppo && x.IdxMacchina == upsRec.IdxMacchina)
- .FirstOrDefaultAsync();
- if (dbRec == null)
- {
- await dbCtx.DbSetGrp2Macc.AddAsync(upsRec);
- // salvo
- int numDone = await dbCtx.SaveChangesAsync();
- answ = numDone != 0;
- }
- return answ;
- }
-
- ///
- /// Eliminazione di un record operatore dal gruppo
- ///
- ///
- ///
- public async Task Grp2OperDeleteAsync(Gruppi2OperModel rec2del)
- {
- bool answ = false;
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var dbRec = await dbCtx
- .DbSetGrp2Oper
- .Where(x => x.CodGruppo == rec2del.CodGruppo && x.MatrOpr == rec2del.MatrOpr)
- .FirstOrDefaultAsync();
- if (dbRec != null)
- {
- dbCtx.DbSetGrp2Oper.Remove(dbRec);
- int numDone = await dbCtx.SaveChangesAsync();
- answ = numDone != 0;
- }
- return answ;
- }
-
- ///
- /// Insert di un record operatore
- ///
- ///
- ///
- public async Task Grp2OperInsertAsync(Gruppi2OperModel upsRec)
- {
- bool answ = false;
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var dbRec = await dbCtx
- .DbSetGrp2Oper
- .Where(x => x.CodGruppo == upsRec.CodGruppo && x.MatrOpr == upsRec.MatrOpr)
- .FirstOrDefaultAsync();
- if (dbRec == null)
- {
- await dbCtx.DbSetGrp2Oper.AddAsync(upsRec);
- // salvo
- int numDone = await dbCtx.SaveChangesAsync();
- answ = numDone != 0;
- }
- return answ;
- }
-
- ///
- /// Elimina record
- ///
- ///
- public async Task IstKitDeleteAsync(IstanzeKitModel rec2del)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var actRec = await dbCtx
- .DbSetInstKit
- .Where(x => x.KeyKit == rec2del.KeyKit && x.KeyExtOrd == rec2del.KeyExtOrd)
- .FirstOrDefaultAsync();
- // se ci fosse aggiorno...
- if (actRec != null)
- {
- dbCtx
- .DbSetInstKit
- .Remove(actRec);
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Elenco istanze KIT da ricerca
- ///
- ///
- ///
- ///
- public async Task> IstKitFiltAsync(string keyKit, string keyExtOrd)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetInstKit
- .Where(x => (string.IsNullOrEmpty(keyKit) && string.IsNullOrEmpty(keyExtOrd)) || (x.KeyKit.Contains(keyKit) && !string.IsNullOrEmpty(keyKit)) || (x.KeyExtOrd.Contains(keyExtOrd) && !string.IsNullOrEmpty(keyExtOrd)))
- .AsNoTracking()
- .ToListAsync() ?? new();
- }
-
- ///
- /// Effettua creazione istanza KIT
- ///
- /// Articolo KIT (fittizio)
- /// Chiave x filtro conf su tab WKS
- public async Task IstKitInsertByWKSAsync(string CodArtParent, string KeyFilt)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
-
- var pCodArtParent = new SqlParameter("@CodArtParent", CodArtParent);
- var pKeyFilt = new SqlParameter("@KeyFilt", KeyFilt);
-
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC dbo.stp_IstKit_insertByWKS @CodArtParent,@KeyFilt", pCodArtParent, pKeyFilt);
- return dbResult != 0;
- }
-
- ///
- /// Esegue upsert record
- ///
- ///
- public async Task IstKitUpsertAsync(IstanzeKitModel editRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var actRec = await dbCtx
- .DbSetInstKit
- .Where(x => x.KeyKit == editRec.KeyKit && x.KeyExtOrd == editRec.KeyExtOrd)
- .FirstOrDefaultAsync();
-
- // se ci fosse aggiorno...
- if (actRec == null)
- {
- await dbCtx
- .DbSetInstKit
- .AddAsync(editRec);
- }
- else
- {
- actRec.CodArtParent = editRec.CodArtParent;
- actRec.CodArtChild = editRec.CodArtChild;
- actRec.QtyART = editRec.QtyART;
- actRec.QtyKIT = editRec.QtyKIT;
- dbCtx.Entry(actRec).State = EntityState.Modified;
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Elenco giacenze
- ///
- /// id odl da cercare
- ///
- public async Task> ListGiacenzeAsync(int IdxOdl)
- {
- List dbResult = new List();
- using var dbCtx = new MoonPro_InveContext(_configuration);
- dbResult = await dbCtx
- .DbGiacenzeData
- .Where(x => x.IdxOdl == IdxOdl)
- .AsNoTracking()
- .ToListAsync();
- return dbResult;
- }
-
- ///
- /// Elenco link JQM completo
- ///
- ///
- ///
- public async Task> ListLinkAllAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetLinkMenu
- .AsNoTracking()
- .OrderBy(x => x.Ordine)
- .ToListAsync();
- }
-
- ///
- /// Elenco link JQM dato filtro tipo, Async
- ///
- ///
- ///
- public async Task> ListLinkFiltAsync(string tipoLink)
- {
- List dbResult = new List();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetLinkMenu
- .Where(x => x.TipoLink == tipoLink)
- .AsNoTracking()
- .OrderBy(x => x.Ordine)
- .ToListAsync();
- }
-
-#endif
-
- ///
- /// Elenco ODL filtrati x stato, articolo, KeyRich (che contiene stato)
- ///
- /// Stato ODL: true=in corso/completato
- /// Cod articolo
- /// KeyRich (parziale) da cercare (es cod stato x yacht)
- /// Reparto selezionato
- /// Macchina selezionata
- /// Data inizio
- /// Data fine
- ///
- public async Task> ListODLFiltAsync(bool inCorso, string codArt, string keyRichPart, string Reparto, string IdxMacchina, DateTime startDate, DateTime endDate)
- {
- List dbResult = new List();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
-
- var InCorso = new SqlParameter("@InCorso", inCorso);
- var CodArt = new SqlParameter("@CodArt", codArt);
- var KeyRich = new SqlParameter("@KeyRich", keyRichPart);
- var CodGruppo = new SqlParameter("@CodGruppo", Reparto);
- var IdxMacc = new SqlParameter("@IdxMacchina", IdxMacchina);
- var DataFrom = new SqlParameter("@DataFrom", startDate);
- var DataTo = new SqlParameter("@DataTo", endDate);
-
- return await dbCtx
- .DbSetODLExp
- .FromSqlRaw("EXEC stp_ODL_getByFiltSpec @InCorso, @CodArt, @KeyRich, @CodGruppo, @IdxMacchina, @DataFrom, @DataTo", InCorso, CodArt, KeyRich, CodGruppo, IdxMacc, DataFrom, DataTo)
- .AsNoTracking()
- .ToListAsync();
- }
-
- ///
- /// Recupero elenco PODL EXPL filtrati
- ///
- ///
- /// True = aperti (=senza ODL)
- ///
- public async Task> ListPODL_ByCodArtAsync(string CodArticolo, bool OnlyAvail)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var pCodArticolo = new SqlParameter("@CodArticolo", CodArticolo);
- var pOnlyAvail = new SqlParameter("@onlyAvail", OnlyAvail);
-
- return await dbCtx
- .DbSetPODLExp
- .FromSqlRaw("EXEC stp_PODL_getByCodArt @CodArticolo, @onlyAvail", pCodArticolo, pOnlyAvail)
- .AsNoTracking()
- .ToListAsync();
- }
-
- ///
- /// Elenco PODL in un istanza KIT dall'ID del parent
- ///
- /// IDX PODL parent
- ///
- public async Task> ListPODL_ByKitParentAsync(int IdxPodlParent)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var pIdxPodlParent = new SqlParameter("@IdxPodlParent", IdxPodlParent);
-
- return await dbCtx
- .DbSetPODLExp
- .FromSqlRaw("EXEC stp_PODL_getByParentKitIdx @IdxPodlParent", pIdxPodlParent)
- .AsNoTracking()
- .ToListAsync();
- }
-
- ///
- /// Elenco PODL per composizione KIT non avviati filtrati x articolo, KeyRich (che contiene stato)
- ///
- /// Solo lanciati (1) o ancora disponibili (0)
- /// KeyRich (parziale) da cercare (es cod stato x yacht)
- /// Macchina
- /// Gruppo
- ///
- public async Task> ListPODL_KitFiltAsync(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var Lanc = new SqlParameter("@Lanciato", lanciato);
- var KeyRich = new SqlParameter("@KeyRich", keyRichPart);
- var CodGrp = new SqlParameter("@CodGruppo", codGruppo);
- var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina);
- var DateFrom = new SqlParameter("@DtInizio", startDate);
- var DateTo = new SqlParameter("@DtFine", endDate);
-
- return await dbCtx
- .DbSetPODLExp
- .FromSqlRaw("EXEC stp_PODL_getByFiltSpecKit @Lanciato, @KeyRich, @CodGruppo, @IdxMacchina, @DtInizio, @DtFine", Lanc, KeyRich, CodGrp, IdxMacc, DateFrom, DateTo)
- .AsNoTracking()
- .ToListAsync();
- }
-
- ///
- /// Elenco PODL non avviati filtrati x articolo, KeyRich (che contiene stato) - ASYNC
- ///
- /// Solo lanciati (1) o ancora disponibili (0)
- /// KeyRich (parziale) da cercare (es cod stato x yacht)
- /// Macchina
- /// Gruppo
- ///
- public async Task> ListPODLFiltAsync(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var Lanc = new SqlParameter("@Lanciato", lanciato);
- var KeyRich = new SqlParameter("@KeyRich", keyRichPart);
- var CodGrp = new SqlParameter("@CodGruppo", codGruppo);
- var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina);
- var DateFrom = new SqlParameter("@DtInizio", startDate);
- var DateTo = new SqlParameter("@DtFine", endDate);
-
- return await dbCtx
- .DbSetPODLExp
- .FromSqlRaw("EXEC stp_PODL_getByFiltSpec @Lanciato, @KeyRich, @CodGruppo, @IdxMacchina, @DtInizio, @DtFine", Lanc, KeyRich, CodGrp, IdxMacc, DateFrom, DateTo)
- .AsNoTracking()
- .ToListAsync();
- }
-
- ///
- /// Elenco valori ammessi x tabella/colonna Async
- ///
- ///
- ///
- ///
- public async Task> ListValuesFiltAsync(string tabName, string fieldName)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetListValues
- .Where(x => x.TableName == tabName && x.FieldName == fieldName)
- .AsNoTracking()
- .OrderBy(x => x.ordinal)
- .ToListAsync();
- }
-
- ///
- /// Elenco Macchine dato operatore secondo gruppi (macchine/operatore)
- ///
- ///
- ///
- public async Task> MacchineByMatrOperAsync(int MatrOpr)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- if (MatrOpr == 0)
- {
- return await dbCtx
- .DbSetMacchine
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToListAsync();
- }
- else
- {
- return await dbCtx
- .DbSetGrp2Oper
- .Where(g => g.MatrOpr == MatrOpr)
- .Join(dbCtx.DbSetGrp2Macc,
- g => g.CodGruppo,
- m => m.CodGruppo,
- (g, m) => m
- )
- .Distinct()
- .Join(dbCtx.DbSetMacchine,
- g => g.IdxMacchina,
- m => m.IdxMacchina,
- (g, m) => m
- )
- .Distinct()
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToListAsync();
- }
- }
-
- ///
- /// Elenco da tabella Macchine filtro x gruppo
- ///
- ///
- ///
- public async Task> MacchineGetFiltAsync(string codGruppo)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- if (codGruppo == "*")
- {
- return await dbCtx
- .DbSetMacchine
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToListAsync();
- }
- else
- {
- return await dbCtx
- .DbSetGrp2Macc
- .Where(g => g.CodGruppo == codGruppo)
- .Join(dbCtx.DbSetMacchine,
- g => g.IdxMacchina,
- m => m.IdxMacchina,
- (g, m) => m
- )
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToListAsync();
- }
- }
-
- ///
- /// Elenco id MacchineModel che abbiano dati FLuxLog, nel periodo indicato
- ///
- ///
- ///
- ///
- public async Task> MacchineWithFluxAsync(DateTime dtStart, DateTime dtEnd)
- {
- using var dbCtx = await _ctxFactoryFL.CreateDbContextAsync();
- return await dbCtx
- .DbSetFluxLog
- .AsNoTracking()
- .Where(x => x.dtEvento >= dtStart && x.dtEvento <= dtEnd)
- .Select(i => i.IdxMacchina)
- .Distinct()
- .ToListAsync() ?? new();
- }
-
- ///
- /// Elenco da tabella MappaStatoExplModel
- ///
- ///
- public async Task> MseGetAllAsync(int maxAge = 2000)
- {
- List dbResult = new List();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
-
- var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge);
-
- dbResult = await dbCtx
- .DbSetMSE
- .FromSqlRaw("EXEC stp_MSE_getData @maxAgeSec", maxAgeSec)
- .AsNoTracking()
- .ToListAsync();
-
- return dbResult;
- }
-
- ///
- /// Elenco ODL dato batch selezionato
- ///
- /// Batch richiesto
- ///
- public async Task> OdlByBatchAsync(string batchSel)
- {
- using var dbCtx = new MoonPro_InveContext(_configuration);
- return await dbCtx
- .DbGiacenzeData
- .AsNoTracking()
- .Where(x => x.IdentRG == batchSel)
- .Select(x => x.IdxOdl)
- .ToListAsync();
- }
-
- ///
- /// ODL da chiave
- ///
- ///
- public async Task OdlByKeyAsync(int IdxOdl)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetODLExp
- .AsNoTracking()
- .FirstOrDefaultAsync(x => x.IdxOdl == IdxOdl);
- }
-
- ///
- /// Chiusura ODL con eventuale conferma pezzi
- ///
- /// idx odl da chiudere
- /// idx macchina
- /// matricola operatore
- /// indica se confermare i pezzi prima di chiudere ODL
- /// Conferma con rettifica (ev 121) x pezzi lasciati in macchina
- /// Modo conferma produzione (0=periodo, 1=giorno, 2=turno)
- ///
- public async Task ODLCloseAsync(int idxOdl, string idxMacchina, int matrOpr, bool confPezzi, bool confRett, int modoConfProd)
- {
- bool fatto = false;
- if (idxOdl > 0)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- DateTime adesso = DateTime.Now;
- // preparo i parametri
- var IdxODL = new SqlParameter("@IdxODL", idxOdl);
- var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina);
-
- // se richiesto confermo produzione
- if (confPezzi)
- {
- var MatrApp = new SqlParameter("@MatrApp", idxMacchina);
-
- /* ----------------------------------
- * CONFERMA PEZZI
- *
- * condizioni da verificare:
- * - gestione rettifica (ev121) / pezzi da LASCIARE in macchina
- * - conferma a zero pezzi (setup) oppure con i pezzi fatti e non ancora confermati
- *
- *
- *
- * */
-
- // recupero i dati dei pezzi da confermare... con DbSetPzProd + exec
- // stp_PzProd_getByMacchina 'SIMUL_01'
-
- // stp_ConfermaProduzCompletaFull
- /*
- * @idxMacchina NVARCHAR(50),
- @MatrApp INT,
- @dataFrom DATETIME,
- @dataTo DATETIME,
- @pezziConf INT,
- @pezziLasciati INT, -- pezzi lasciati = evento 121 (-) pre conferma e (+) dopo --> da lasciare in macchina post conferma
- @pezziScar INT = 0, -- pezzi scartati (registrati da 2016.11.20) DA INDICARE COME VALORE > 0!!! sennò faccio ABS...
- @TipoConf INT = 0, -- Tipo intervallo conferma: 0 = periodo intero, 1 = per giorni, 2 = per turni
- @DataOraApp DATETIME = NULL, -- di norma GETDATE() nel programma - serve per ricalcolo
- @TestConferma BIT = 1 -- TestConferma : 1 = verifica conf. duplicata e inserisci in ElencoConfermeProd, 0 = nessuna verifica e inserimento ( per ricalcolo )
- */
- }
-
- // ora chiudo ODL con stored SENZA ritorno...
- try
- {
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC stp_ODL_fineProd @IdxODL, @IdxMacchina", IdxODL, IdxMacchina);
- fatto = dbResult != 0;
- }
- catch (Exception exc)
- {
- Log.Error($"Eccezione durante ODLCloseAsync{Environment.NewLine}{exc}");
- }
- }
- return fatto;
- }
-
- ///
- /// Recupero Odl CORRENTI
- ///
- ///
- public async Task> OdlGetCurrentAsync()
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetODL
- .Where(x => x.DataInizio != null && x.DataFine == null)
- .ToListAsync();
- }
-
- ///
- /// Statistiche ODL calcolate (da stored stp_STAT_ODL)
- ///
- ///
- public async Task> OdlGetStatAsync(int IdxOdl)
- {
- List dbResult = new List();
- if (IdxOdl > 0)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var IdxODL = new SqlParameter("@IdxODL", IdxOdl);
-
- dbResult = await dbCtx
- .DbSetStatOdl
- .FromSqlRaw("EXEC stp_STAT_ODL @IdxODL", IdxODL)
- .AsNoTracking()
- .ToListAsync();
- }
- return dbResult;
- }
-
- ///
- /// Elenco da tabella Operatori filtro x gruppo
- ///
- ///
- ///
- public async Task> OperatoriGetFiltAsync(string codGruppo)
- {
- List dbResult = new List();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- if (codGruppo == "*")
- {
- dbResult = await dbCtx
- .DbOperatori
- .AsNoTracking()
- .OrderBy(x => x.MatrOpr)
- .ToListAsync();
- }
- else
- {
- dbResult = await dbCtx
- .DbSetGrp2Oper
- .Where(g => g.CodGruppo == codGruppo)
- .Join(dbCtx.DbOperatori,
- g => g.MatrOpr,
- m => m.MatrOpr,
- (g, m) => m
- )
- .AsNoTracking()
- .OrderBy(x => x.MatrOpr)
- .ToListAsync();
- }
- return dbResult;
- }
-
- ///
- /// Elenco parametri validi x una data macchina
- ///
- ///
- ///
- public async Task> ParametriGetFiltAsync(string IdxMacchina)
- {
- using var dbCtx = await _ctxFactoryFL.CreateDbContextAsync();
- return await dbCtx
- .DbSetFluxLog
- .AsNoTracking()
- .Where(x => (IdxMacchina == "*" || x.IdxMacchina == IdxMacchina))
- .Take(1000)
- .Select(i => i.CodFlux)
- .Distinct()
- .OrderBy(x => x)
- .ToListAsync();
- }
-
- ///
- /// Recupero PODL da chiave
- ///
- ///
- ///
- public async Task PODL_getByKeyAsync(int idxPODL)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetPODL
- .AsNoTracking()
- .Where(x => x.IdxPromessa == idxPODL)
- .Include(a => a.ArticoloNav)
- .FirstOrDefaultAsync() ?? new();
- }
-
- ///
- /// Recupero PODL da IdxOdl
- ///
- ///
- ///
- public async Task PODL_getByOdlAsync(int idxODL)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetPODL
- .AsNoTracking()
- .Where(x => x.IdxOdl == idxODL)
- .FirstOrDefaultAsync() ?? new();
- }
-
- ///
- /// Dizionario associazione ODL/PODL
- ///
- ///
- ///
- public async Task> PODL_getDictOdlPodlAsync(List missingIds)
- {
- if (missingIds == null || !missingIds.Any())
- return new Dictionary();
-
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetPODL
- .AsNoTracking()
- .Where(x => missingIds.Contains(x.IdxOdl))
- .ToDictionaryAsync(x => x.IdxOdl, x => x.IdxPromessa);
- }
-
- ///
- /// Avvio setup ODL da PODL
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public async Task PODL_startSetup(PODLExpModel editRec, int matrOpr, double tcRich, int pzPallet, string note, DateTime dtEvent)
- {
- bool answ = false;
- PODLModel recPODL = new PODLModel()
- {
- IdxPromessa = editRec.IdxPromessa,
- KeyRichiesta = editRec.KeyRichiesta,
- KeyBCode = editRec.KeyBCode,
- IdxOdl = editRec.IdxOdl,
- CodArticolo = editRec.CodArticolo,
- CodGruppo = editRec.CodGruppo,
- IdxMacchina = editRec.IdxMacchina,
- NumPezzi = editRec.NumPezzi,
- Tcassegnato = editRec.Tcassegnato,
- DueDate = editRec.DueDate,
- Priorita = editRec.Priorita,
- PzPallet = editRec.PzPallet,
- Note = editRec.Note,
- CodCli = editRec.CodCli,
- InsertDate = editRec.InsertDate
- };
-
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var currRec = await dbCtx
- .DbSetPODL
- .AsNoTracking()
- .Where(x => x.IdxPromessa == recPODL.IdxPromessa)
- .FirstOrDefaultAsync();
-
- if (currRec != null)
- {
- // eseguo stored attrezzaggio
- var IdxPromessa = new SqlParameter("@idxPromessa", recPODL.IdxPromessa);
- var MatrOpr = new SqlParameter("@MatrOpr", matrOpr);
- var IdxMacchina = new SqlParameter("@IdxMacchina", recPODL.IdxMacchina);
- var TCRichAttr = new SqlParameter("@TCRichAttr", tcRich);
- var PzPallet = new SqlParameter("@PzPallet", pzPallet);
- var Note = new SqlParameter("@Note", note);
- var DtEvento = new SqlParameter("@dtEvento", dtEvent);
- var callResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC stp_ODL_inizioSetupPromessa @idxPromessa, @MatrOpr, @IdxMacchina, @TCRichAttr, @PzPallet, @Note, @dtEvento", IdxPromessa, MatrOpr, IdxMacchina, TCRichAttr, PzPallet, Note, DtEvento);
-
- answ = true;
- }
- return answ;
- }
-
- ///
- /// Chiamata salvataggio ricetta su DB
- ///
- ///
- ///
- ///
- public async Task PODL_updateRecipe(int idxPODL, string recipeName)
- {
- bool answ = false;
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var currRec = await dbCtx
- .DbSetPODL
- .Where(x => x.IdxPromessa == idxPODL)
- .FirstOrDefaultAsync();
-
- if (currRec != null)
- {
- currRec.Recipe = recipeName;
- dbCtx.Entry(currRec).State = EntityState.Modified;
- answ = await dbCtx.SaveChangesAsync() > 0;
- }
- return answ;
- }
-
- ///
- /// Eliminazione Record
- ///
- ///
- ///
- public async Task PODLDeleteRecordAsync(PODLExpModel currRec)
- {
- PODLModel recPODL = new PODLModel()
- {
- IdxPromessa = currRec.IdxPromessa,
- KeyRichiesta = currRec.KeyRichiesta,
- KeyBCode = currRec.KeyBCode,
- IdxOdl = currRec.IdxOdl,
- CodArticolo = currRec.CodArticolo,
- CodGruppo = currRec.CodGruppo,
- IdxMacchina = currRec.IdxMacchina,
- NumPezzi = currRec.NumPezzi,
- Tcassegnato = currRec.Tcassegnato,
- DueDate = currRec.DueDate,
- Priorita = currRec.Priorita,
- PzPallet = currRec.PzPallet,
- Note = currRec.Note,
- CodCli = currRec.CodCli,
- InsertDate = currRec.InsertDate
- };
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var currVal = await dbCtx
- .DbSetPODL
- .Where(x => x.IdxPromessa == recPODL.IdxPromessa)
- .FirstOrDefaultAsync();
- dbCtx
- .DbSetPODL
- .Remove(currVal);
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Effettua il task di eliminazione PODL KIT + istanze + riattivazione PODL originali disattivate tramite stored
- ///
- /// IdxPODL parent
- public async Task PodlIstKitDeleteAsync(int IdxPODL)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var pIdxPODL = new SqlParameter("@IdxPODL", IdxPODL);
-
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC dbo.stp_PodlIstKit_delete @IdxPODL", pIdxPODL);
- return dbResult != 0;
- }
-
- ///
- /// Update Record
- ///
- ///
- ///
- public async Task PODLUpdateRecordAsync(PODLModel editRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var currRec = await dbCtx
- .DbSetPODL
- .Where(x => x.IdxPromessa == editRec.IdxPromessa)
- .FirstOrDefaultAsync();
- if (currRec != null)
- {
- currRec.CodGruppo = editRec.CodGruppo;
- currRec.CodArticolo = editRec.CodArticolo;
- currRec.IdxMacchina = editRec.IdxMacchina;
- currRec.KeyBCode = editRec.KeyBCode;
- currRec.KeyRichiesta = editRec.KeyRichiesta;
- currRec.NumPezzi = editRec.NumPezzi;
- currRec.Tcassegnato = editRec.Tcassegnato;
- currRec.Attivabile = editRec.Attivabile;
- currRec.Note = editRec.Note;
- dbCtx.Entry(currRec).State = EntityState.Modified;
- }
- else
- {
- await dbCtx
- .DbSetPODL
- .AddAsync(editRec);
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Stato macchina (da key)
- ///
- ///
- ///
- public async Task StatoMacchinaAsync(string idxMacchina)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- return await dbCtx
- .DbSetStatoMacc
- .Where(x => x.IdxMacchina == idxMacchina)
- .AsNoTracking()
- .FirstOrDefaultAsync();
- }
-
- ///
- /// Elimina record
- ///
- ///
- public async Task TemplateKitDeleteAsync(TemplateKitModel rec2del)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var actRec = await dbCtx
- .DbSetTempKit
- .Where(x => x.CodArtParent == rec2del.CodArtParent && x.CodArtChild == rec2del.CodArtChild)
- .FirstOrDefaultAsync();
- // se ci fosse aggiorno...
- if (actRec != null)
- {
- dbCtx
- .DbSetTempKit
- .Remove(actRec);
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Elenco template KIT da ricerca
- ///
- ///
- ///
- ///
- public async Task> TemplateKitFiltAsync(string KitCode, string codChild)
- {
- List dbResult = new List();
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- dbResult = await dbCtx
- .DbSetTempKit
- .Where(x => (string.IsNullOrEmpty(KitCode) && string.IsNullOrEmpty(codChild)) || (x.CodArtParent.Contains(KitCode) && !string.IsNullOrEmpty(KitCode)) || (x.CodArtChild.Contains(codChild) && !string.IsNullOrEmpty(codChild)))
- .AsNoTracking()
- .ToListAsync();
- return dbResult;
- }
-
- ///
- /// Esegue upsert record
- ///
- ///
- ///
- public async Task TemplateKitUpsertAsync(TemplateKitModel editRec, string codAzienda)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- // verifico preliminarmente articolo...
- var recArt = dbCtx
- .DbSetArticoli
- .FirstOrDefault(x => x.CodArticolo == editRec.CodArtParent);
- // se mancasse...
- if (recArt == null)
- {
- // aggiungo!
- AnagArticoliModel newRecArt = new AnagArticoliModel()
- {
- CodArticolo = editRec.CodArtParent,
- Tipo = "KIT",
- DescArticolo = $"Articolo KIT - {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
- Disegno = "",
- Azienda = codAzienda,
- CurrRev = "",
- ProdRev = ""
- };
- dbCtx
- .DbSetArticoli
- .Add(newRecArt);
- }
-
- // proseguo col KIT
- var actRec = await dbCtx
- .DbSetTempKit
- .Where(x => x.CodArtParent == editRec.CodArtParent && x.CodArtChild == editRec.CodArtChild)
- .FirstOrDefaultAsync();
-
- // se NON ci fosse aggiungo...
- if (actRec == null)
- {
- await dbCtx
- .DbSetTempKit
- .AddAsync(editRec);
- }
- else
- {
- actRec.Qty = editRec.Qty;
- dbCtx.Entry(actRec).State = EntityState.Modified;
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Punteggio compatibilità KIT per KeyFilt indicato
- ///
- ///
- ///
- ///
- public async Task> TksScoreAsync(string KeyFilt, int MaxResult)
- {
- List dbResult = new List();
- if (!string.IsNullOrEmpty(KeyFilt))
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var pKeyFilt = new SqlParameter("@KeyFilt", KeyFilt);
- var pMaxRes = new SqlParameter("@maxResult", MaxResult);
- dbResult = await dbCtx
- .DbSetTksScore
- .FromSqlRaw("EXEC stp_TKS_Search @KeyFilt, @maxResult", pKeyFilt, pMaxRes)
- .AsNoTracking()
- .ToListAsync();
- }
- return dbResult;
- }
-
-#if false
- ///
- /// Elenco Vocabolario di una lingua
- ///
- ///
- public Dictionary VocabolarioGetLang(string lingua)
- {
- using var dbCtx = _ctxFactory.CreateDbContext();
- var rawList = dbCtx
- .DbSetVocabolario
- .AsNoTracking()
- .Where(x => x.Lingua.ToLower() == lingua.ToLower())
- .OrderBy(x => x.Lemma)
- .ToList();
- // Proietto in dizionario
- return rawList
- .DistinctBy(t => t.Lemma, StringComparer.OrdinalIgnoreCase)
- .ToDictionary(t => t.Lemma, t => t.Traduzione, StringComparer.OrdinalIgnoreCase);
- }
-
- ///
- /// Upsert record Vocabolario
- ///
- ///
- ///
- public async Task VocabolarioUpsertAsync(VocabolarioModel upsRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var actRec = await dbCtx
- .DbSetVocabolario
- .Where(x => x.Lingua == upsRec.Lingua && x.Lemma == upsRec.Lemma)
- .FirstOrDefaultAsync();
-
- // se ci fosse aggiorno...
- if (actRec == null)
- {
- dbCtx
- .DbSetVocabolario
- .Add(upsRec);
- }
- else
- {
- actRec.Traduzione = upsRec.Traduzione;
- dbCtx.Entry(actRec).State = EntityState.Modified;
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Elimina record
- ///
- ///
- public async Task WipKitDeleteAsync(WipSetupKitModel rec2del)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var actRec = await dbCtx
- .DbSetWipKit
- .Where(x => x.KeyFilt == rec2del.KeyFilt && x.CodOrd == rec2del.CodOrd)
- .FirstOrDefaultAsync();
- // se ci fosse aggiorno...
- if (actRec != null)
- {
- dbCtx
- .DbSetWipKit
- .Remove(actRec);
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-#endif
-
- ///
- /// Elimina record + vecchi della data-ora indicata
- ///
- ///
- ///
- public async Task WipKitDeleteOlderAsync(DateTime dateLimit)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var actRec = await dbCtx
- .DbSetWipKit
- .Where(x => x.DataIns < dateLimit)
- .ToListAsync();
- // se ci fosse aggiorno...
- if (actRec != null)
- {
- dbCtx
- .DbSetWipKit
- .RemoveRange(actRec);
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- ///
- /// Elenco record WipSetupKit da KeyFilt
- ///
- ///
- ///
- public async Task> WipKitFiltAsync(string KeyFilt)
- {
- List dbResult = new List();
- // solo se filtro valido...
- if (!string.IsNullOrEmpty(KeyFilt))
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- dbResult = await dbCtx
- .DbSetWipKit
- .Where(x => x.KeyFilt.Contains(KeyFilt))
- .AsNoTracking()
- .ToListAsync();
- }
- return dbResult;
- }
-
- ///
- /// Esegue upsert record
- ///
- ///
- public async Task WipKitUpsertAsync(WipSetupKitModel editRec)
- {
- using var dbCtx = await _ctxFactory.CreateDbContextAsync();
- var actRec = await dbCtx
- .DbSetWipKit
- .Where(x => x.KeyFilt == editRec.KeyFilt && x.CodOrd == editRec.CodOrd)
- .FirstOrDefaultAsync();
-
- // se ci fosse aggiorno...
- if (actRec == null)
- {
- dbCtx
- .DbSetWipKit
- .Add(editRec);
- }
- else
- {
- actRec.CodArt = editRec.CodArt;
- actRec.DescArt = editRec.DescArt;
- actRec.Qta = editRec.Qta;
- actRec.DataIns = editRec.DataIns;
- dbCtx.Entry(actRec).State = EntityState.Modified;
- }
- return await dbCtx.SaveChangesAsync() > 0;
- }
-
- #endregion Public Methods
-
- #region Private Fields
-
- private static IConfiguration _configuration;
- private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
-#if false
- private DbContextOptions options;
-#endif
-
- #endregion Private Fields
- }
-}
\ No newline at end of file
diff --git a/MP.Data/DataServiceCollectionExtensions.cs b/MP.Data/DataServiceCollectionExtensions.cs
index ddc1ef7c..03a1f181 100644
--- a/MP.Data/DataServiceCollectionExtensions.cs
+++ b/MP.Data/DataServiceCollectionExtensions.cs
@@ -35,9 +35,11 @@ namespace MP.Data
// Repository Singleton
services.TryAddSingleton();
services.TryAddSingleton();
+ services.TryAddSingleton();
+ services.TryAddSingleton();
+ services.TryAddSingleton();
- // Repository Scoped
- services.TryAddScoped();
+ // Repository Scoped (non usate da MpDataService)
services.TryAddScoped();
services.TryAddScoped();
diff --git a/MP.Data/Repository/Anag/AnagRepository.cs b/MP.Data/Repository/Anag/AnagRepository.cs
index 03721446..33d884a5 100644
--- a/MP.Data/Repository/Anag/AnagRepository.cs
+++ b/MP.Data/Repository/Anag/AnagRepository.cs
@@ -27,55 +27,25 @@ namespace MP.Data.Repository.Anag
{
AnagCountersModel answ = new AnagCountersModel();
await using var dbCtx = await CreateContextAsync();
- bool outTable = true;
- if (outTable)
- {
- var pCntType = new SqlParameter("@CntType", cntType);
- var pLastNum = new SqlParameter
- {
- ParameterName = "@LastNum",
- SqlDbType = SqlDbType.Int,
- Direction = ParameterDirection.Output
- };
- var dbResult = await dbCtx
- .DbSetAnagCount
- .FromSqlRaw("EXEC dbo.stp_getNextNumb @CntType, @LastNum OUTPUT", pCntType, pLastNum)
- .AsNoTracking()
- .FirstOrDefaultAsync();
- if (dbResult != null)
- {
- answ = dbResult;
- }
- }
- else
+ var pCntType = new SqlParameter("@CntType", cntType);
+ var pLastNum = new SqlParameter
{
- // se si volessero impiegare parametri OUTPUT (qui ne mancherebbe 1 nella stored x CntCode...)
- var pCntType = new SqlParameter("@CntType", cntType);
- var pLastNum = new SqlParameter
- {
- ParameterName = "@LastNum",
- SqlDbType = SqlDbType.Int,
- Direction = ParameterDirection.Output
- };
- var pCntCode = new SqlParameter
- {
- ParameterName = "@CntCode",
- SqlDbType = SqlDbType.NVarChar,
- Direction = ParameterDirection.Output
- };
- var dbResult = await dbCtx
- .Database
- .ExecuteSqlRawAsync("EXEC dbo.stp_getNextNumb @CntType, @LastNum OUTPUT, @CntCode OUTPUT", pCntType, pLastNum, pCntCode);
- if (dbResult != 0)
- {
- answ.CntType = cntType;
- answ.CntCode = $"{pCntCode.Value}";
- int lNum = 0;
- int.TryParse($"{pLastNum.Value}", out lNum);
- answ.LastNum = lNum;
- }
+ ParameterName = "@LastNum",
+ SqlDbType = SqlDbType.Int,
+ Direction = ParameterDirection.Output
+ };
+
+ var dbResult = (await dbCtx
+ .DbSetAnagCount
+ .FromSqlRaw("EXEC dbo.stp_getNextNumb @CntType, @LastNum OUTPUT", pCntType, pLastNum)
+ .AsNoTracking()
+ .ToListAsync()).FirstOrDefault();
+ if (dbResult != null)
+ {
+ answ = dbResult;
}
+
return answ;
}
@@ -352,7 +322,7 @@ namespace MP.Data.Repository.Anag
}
///
- public async Task ArticoliUpdateRecord(AnagArticoliModel editRec)
+ public async Task ArticoliUpsertAsync(AnagArticoliModel editRec)
{
await using var dbCtx = await CreateContextAsync();
var currRec = await dbCtx.DbSetArticoli.FirstOrDefaultAsync(x => x.CodArticolo == editRec.CodArticolo);
@@ -363,9 +333,12 @@ namespace MP.Data.Repository.Anag
currRec.Tipo = editRec.Tipo;
currRec.Azienda = editRec.Azienda;
dbCtx.Entry(currRec).State = EntityState.Modified;
- return await dbCtx.SaveChangesAsync() > 0;
}
- return false;
+ else
+ {
+ dbCtx.DbSetArticoli.Add(editRec);
+ }
+ return await dbCtx.SaveChangesAsync() > 0;
}
///
diff --git a/MP.Data/Repository/Anag/IAnagRepository.cs b/MP.Data/Repository/Anag/IAnagRepository.cs
index 728a4657..4028e102 100644
--- a/MP.Data/Repository/Anag/IAnagRepository.cs
+++ b/MP.Data/Repository/Anag/IAnagRepository.cs
@@ -140,11 +140,11 @@ namespace MP.Data.Repository.Anag
Task> ArticoliInKitAsync();
///
- /// Update Record Articolo
+ /// Upsert (add/update) Record Articolo
///
/// Record da aggiornare
/// True se aggiornato
- Task ArticoliUpdateRecord(AnagArticoliModel editRec);
+ Task ArticoliUpsertAsync(AnagArticoliModel editRec);
///
/// Elenco Gruppi tipo REPARTOin formato DTO con conteggi del numero record trovati filtrati per operatore
diff --git a/MP.Data/Repository/Production/IProductionRepository.cs b/MP.Data/Repository/Production/IProductionRepository.cs
index 7089a4de..daea39cd 100644
--- a/MP.Data/Repository/Production/IProductionRepository.cs
+++ b/MP.Data/Repository/Production/IProductionRepository.cs
@@ -31,7 +31,7 @@ namespace MP.Data.Repository.Production
Task> ListPODL_ByKitParentAsync(int IdxPodlParent);
- Task> ListPODL_KitFiltAsync(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate);
+ Task> ListPODL_KitFiltAsync(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate, bool flagAttive, bool flagKitChild);
Task PODL_getByKeyAsync(int idxPODL);
diff --git a/MP.Data/Repository/Production/ProductionRepository.cs b/MP.Data/Repository/Production/ProductionRepository.cs
index ec051504..9ac67318 100644
--- a/MP.Data/Repository/Production/ProductionRepository.cs
+++ b/MP.Data/Repository/Production/ProductionRepository.cs
@@ -187,7 +187,7 @@ namespace MP.Data.Repository.Production
}
///
- public async Task> ListPODL_KitFiltAsync(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate)
+ public async Task> ListPODL_KitFiltAsync(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate, bool flagAttive, bool flagKitChild)
{
await using var dbCtx = await GetMoonProContextAsync();
var Lanc = new SqlParameter("@Lanciato", lanciato);
@@ -196,10 +196,12 @@ namespace MP.Data.Repository.Production
var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina);
var DateFrom = new SqlParameter("@DtInizio", startDate);
var DateTo = new SqlParameter("@DtFine", endDate);
+ var pFlagAtt = new SqlParameter("@flgAttive", flagAttive);
+ var pFlagKChild = new SqlParameter("@flgPodChild", flagKitChild);
return await dbCtx
.DbSetPODLExp
- .FromSqlRaw("EXEC stp_PODL_getByFiltSpecKit @Lanciato, @KeyRich, @CodGruppo, @IdxMacchina, @DtInizio, @DtFine", Lanc, KeyRich, CodGrp, IdxMacc, DateFrom, DateTo)
+ .FromSqlRaw("EXEC stp_PODL_getByFiltSpecKit @Lanciato, @KeyRich, @CodGruppo, @IdxMacchina, @DtInizio, @DtFine, @flgAttive, @flgPodChild", Lanc, KeyRich, CodGrp, IdxMacc, DateFrom, DateTo, pFlagAtt, pFlagKChild)
.AsNoTracking()
.ToListAsync();
}
diff --git a/MP.Data/Services/BaseServ.cs b/MP.Data/Services/BaseServ.cs
index 0a6dbf7e..df5344c6 100644
--- a/MP.Data/Services/BaseServ.cs
+++ b/MP.Data/Services/BaseServ.cs
@@ -10,7 +10,6 @@ using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using ZiggyCreatures.Caching.Fusion;
-using static Org.BouncyCastle.Asn1.Cmp.Challenge;
namespace MP.Data.Services
{
@@ -54,6 +53,35 @@ namespace MP.Data.Services
GC.SuppressFinalize(this);
}
+ ///
+ /// Cancellazione FusionCache (totale) - wrapper public
+ ///
+ ///
+ public Task ForceFlushFusionCacheAsync()
+ {
+ return FlushFusionCacheAsync();
+ }
+
+ ///
+ /// Cancellazione Fusion Cache x tag (wrapper)
+ ///
+ ///
+ ///
+ public Task ForceFlushFusionCacheAsync(string tag)
+ {
+ return FlushFusionCacheAsync(tag);
+ }
+
+ ///
+ /// Cancellazione Fusion Cache x list tags (wrapper)
+ ///
+ ///
+ ///
+ public Task ForceFlushFusionCacheAsync(List listTags)
+ {
+ return FlushFusionCacheAsync(listTags);
+ }
+
///
/// Recupero info IOB x TAB (da info registrate IOB-WIN--> MP-IO)
///
@@ -525,5 +553,50 @@ namespace MP.Data.Services
private double slowLogThresh = 0;
#endregion Private Fields
+
+ #region Private Methods
+
+ ///
+ /// Cancellazione FusionCache (totale)
+ ///
+ ///
+ private async Task FlushFusionCacheAsync()
+ {
+ await _cache.ClearAsync(allowFailSafe: false);
+ return true;
+ }
+
+ ///
+ /// Cancellazione FusionCache dato singolo tag
+ ///
+ ///
+ ///
+ private async Task FlushFusionCacheAsync(string tag)
+ {
+ if (string.IsNullOrWhiteSpace(tag)) return false;
+
+ await _cache.RemoveByTagAsync(tag);
+ return true;
+ }
+
+ ///
+ /// Cancellazione FusionCache dato elenco tags
+ ///
+ ///
+ ///
+ private async Task FlushFusionCacheAsync(List listTags)
+ {
+ if (listTags == null || listTags.Count == 0) return false;
+
+ // Generiamo i Task di rimozione ed eseguiamoli in parallelo su Redis/L1
+ var tasks = listTags
+ .Where(tag => !string.IsNullOrWhiteSpace(tag))
+ .Select(tag => _cache.RemoveByTagAsync(tag).AsTask());
+
+ await Task.WhenAll(tasks);
+ return true;
+ }
+
+ #endregion Private Methods
}
}
\ No newline at end of file
diff --git a/MP.Data/Services/IOC/IIocService.cs b/MP.Data/Services/IOC/IIocService.cs
index 1eedf50d..5ccfb9f8 100644
--- a/MP.Data/Services/IOC/IIocService.cs
+++ b/MP.Data/Services/IOC/IIocService.cs
@@ -30,6 +30,20 @@ namespace MP.Data.Services.IOC
///
Task ClearFusionCache();
+ ///
+ /// Esegue flush della cache fusion dato tag
+ ///
+ ///
+ ///
+ Task ClearFusionCache(string tag);
+
+ ///
+ /// Esegue flush della cache fusion data list tags
+ ///
+ ///
+ ///
+ Task ClearFusionCache(List listTags);
+
///
/// Aggiunta record MicroStato + EventList
///
diff --git a/MP.Data/Services/IOC/IocService.cs b/MP.Data/Services/IOC/IocService.cs
index 0a709a30..f4901fb0 100644
--- a/MP.Data/Services/IOC/IocService.cs
+++ b/MP.Data/Services/IOC/IocService.cs
@@ -34,7 +34,7 @@ namespace MP.Data.Services.IOC
_repo = repo;
_scopeFactory = scopeFactory;
#if false
- _cache = cache;
+ _cache = cache;
#endif
}
@@ -58,6 +58,29 @@ namespace MP.Data.Services.IOC
return fatto;
}
+ ///
+ public async Task ClearFusionCache(string tag)
+ {
+ if (string.IsNullOrWhiteSpace(tag)) return false;
+
+ await _cache.RemoveByTagAsync(tag);
+ return true;
+ }
+
+ ///
+ public async Task ClearFusionCache(List listTags)
+ {
+ if (listTags == null || listTags.Count == 0) return false;
+
+ // Generiamo i Task di rimozione ed eseguiamoli in parallelo su Redis/L1
+ var tasks = listTags
+ .Where(tag => !string.IsNullOrWhiteSpace(tag))
+ .Select(tag => _cache.RemoveByTagAsync(tag).AsTask());
+
+ await Task.WhenAll(tasks);
+ return true;
+ }
+
///
public async Task EvListMicroStatoInsertAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv)
{
@@ -79,9 +102,7 @@ namespace MP.Data.Services.IOC
else
{
result = await GetCurrOdlByProdAsync(idxMacchina);
- // serializzo e salvo...
- rawData = JsonConvert.SerializeObject(result);
- _redisDb.StringSet(currKey, rawData, GetRandTOut(redisLongTimeCache));
+ _redisDb.StringSet(currKey, result, GetRandTOut(redisShortTimeCache));
}
return result;
}
@@ -96,12 +117,13 @@ namespace MP.Data.Services.IOC
///
public async Task IobInsEnabAsync(string idxMacchina)
{
+#if false
string cacheKey = $"IOC_IobInsEnab_{idxMacchina}";
return await GetOrFetchAsync(cacheKey, async () =>
{
- var key = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS);
+ var rKey = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS);
- string? val = await _redisDb.HashGetAsync(key, "insEnabled");
+ string? val = await _redisDb.HashGetAsync(rKey, "insEnabled");
if (val == null)
{
@@ -111,6 +133,23 @@ namespace MP.Data.Services.IOC
return val != null && (val == "1" || val.ToLower() == "true");
}, TimeSpan.FromSeconds(5));
+#endif
+
+ bool answ = false;
+ // ORA recupero da memoria redis...
+ var rKey = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS);
+ RedisValue rawData = await _redisDb.HashGetAsync(rKey, (RedisValue)"insEnabled");
+ // se è vuoto... leggo da DB e popolo!
+ if (!rawData.HasValue)
+ {
+ await ResetDatiMacchinaAsync(idxMacchina);
+ // riprovo
+ rawData = await _redisDb.HashGetAsync(rKey, (RedisValue)"insEnabled");
+ }
+
+ // provo conversione
+ bool.TryParse($"{rawData}", out answ);
+ return answ;
}
///
@@ -162,6 +201,7 @@ namespace MP.Data.Services.IOC
// gestisce i casi DB/REDIS secondo necessità
await CheckMicroStatoAsync(idxMacchina, valore, dataOraEvento, contatore, datiMacc);
}
+ await ClearFusionCache(idxMacchina);
// forzo RESET dati macchina...
await ResetDatiMacchinaAsync(idxMacchina);
// registro in risposta che è andato tutto bene...
@@ -181,8 +221,7 @@ namespace MP.Data.Services.IOC
public async Task PzCounterTcAsync(string idxMacchina)
{
int answ = -1;
- DateTime dataRif = DateTime.Now;
- var datiProd = await StatoProdMacchinaAsync(idxMacchina, dataRif);
+ var datiProd = await StatoProdMacchinaAsync(idxMacchina, DateTime.Now);
if (datiProd != null)
{
answ = datiProd.PzTotODL;
@@ -230,6 +269,7 @@ namespace MP.Data.Services.IOC
answ = currCount.ToString();
// salvo per meno tempo...
await _redisDb.StringSetAsync(currKey, answ);
+ await ClearFusionCache(idxMacchina);
}
}
}
@@ -261,8 +301,6 @@ namespace MP.Data.Services.IOC
#endregion Protected Fields
- #region Protected Methods
-
#if false
///
/// Restituisce un timeout dai minuti richiesti + tempo random 1..60 sec
@@ -273,17 +311,15 @@ namespace MP.Data.Services.IOC
{
double rndValue = stdMinutes + (double)rand.Next(1, 60) / 60;
return TimeSpan.FromMinutes(rndValue);
- }
+ }
#endif
- #endregion Protected Methods
-
#region Private Fields
private static Logger Log = LogManager.GetCurrentClassLogger();
#if false
- private readonly IFusionCache _cache;
+ private readonly IFusionCache _cache;
#endif
private readonly string _className;
@@ -301,14 +337,14 @@ namespace MP.Data.Services.IOC
///
private string dtFormat = "yyyyMMddHHmmssfff";
+ #endregion Private Fields
+
#if false
private int redisLongTimeCache = 5;
- private int redisShortTimeCache = 2;
+ private int redisShortTimeCache = 2;
#endif
- #endregion Private Fields
-
#region Private Methods
///
@@ -467,7 +503,7 @@ namespace MP.Data.Services.IOC
}
///
- /// Implementa gestione recupero cache da memoria o da obj esterno + cache memoria
+ /// Implementa gestione recupero cache da memoria o da obj esterno + cache memoria (versione semplificata)
///
///
///
@@ -493,25 +529,18 @@ namespace MP.Data.Services.IOC
{
bool answ = false;
// ORA recupero da memoria redis...
- try
+ var rKey = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS);
+ RedisValue rawData = await _redisDb.HashGetAsync(rKey, (RedisValue)"sLogEnabled");
+ // se è vuoto... leggo da DB e popolo!
+ if (!rawData.HasValue)
{
- var currHash = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS);
- RedisValue rawData = await _redisDb.HashGetAsync(currHash, (RedisValue)"sLogEnabled");
- // se è vuoto... leggo da DB e popolo!
- if (!rawData.HasValue)
- {
- await ResetDatiMacchinaAsync(idxMacchina);
- // riprovo
- rawData = await _redisDb.HashGetAsync(currHash, (RedisValue)"sLogEnabled");
- }
+ await ResetDatiMacchinaAsync(idxMacchina);
+ // riprovo
+ rawData = await _redisDb.HashGetAsync(rKey, (RedisValue)"sLogEnabled");
+ }
- // provo conversione
- bool.TryParse($"{rawData}", out answ);
- }
- catch (Exception exc)
- {
- Log.Error($"Errore IobSLogEnabAsync | idxMacchina {idxMacchina}:{Environment.NewLine}{exc}");
- }
+ // provo conversione
+ bool.TryParse($"{rawData}", out answ);
return answ;
}
@@ -832,7 +861,7 @@ namespace MP.Data.Services.IOC
result.Add("palletChange", $"{dbResult.PalletChange}");
// durata cache in secondi dal valOut insEnabled...
//double numSecCache = ((result["insEnabled"].ToLower() == "true") ? redisShortTimeCache : redisLongTimeCache);
- numSecCache = dbResult.InsEnabled ? redisShortTimeCache : redisLongTimeCache;
+ numSecCache = dbResult.InsEnabled ? redisShortTimeCache * 2 : redisLongTimeCache;
}
// dati master/slave
@@ -853,7 +882,7 @@ namespace MP.Data.Services.IOC
// 3. Inseriamo i nuovi valori
_ = transaction.HashSetAsync(redKey, entries);
// 4. Impostiamo l'expiration in un unico colpo
- _ = transaction.KeyExpireAsync(redKey, TimeSpan.FromSeconds(numSecCache));
+ _ = transaction.KeyExpireAsync(redKey, GetRandTOut(numSecCache));
// Eseguiamo tutto in un unico viaggio verso Redis
bool success = await transaction.ExecuteAsync();
@@ -1011,30 +1040,37 @@ namespace MP.Data.Services.IOC
///
private async Task StatoProdMacchinaAsync(string idxMacchina, DateTime dtReq, bool forceDb = false)
{
- string cacheKey = $"IOC_StatoProd_{idxMacchina}";
- return await GetOrFetchAsync(cacheKey, async () =>
- {
- StatoProdModel? result = new StatoProdModel();
- // cerco in _redisConn...
- string currKey = $"{MP.Data.Utils.redisStatoProd}:{idxMacchina}:{dtReq:HHmm}";
- RedisValue rawData = await _redisDb.StringGetAsync(currKey);
- if (rawData.HasValue && !forceDb)
+ string cKey = $"IOC_StatoProd_{idxMacchina}";
+ var stdTTL = TimeSpan.FromSeconds(30);
+ return await GetOrFetchAsync(
+ operationName: "StatoProdMacchinaAsync",
+ cacheKey: cKey,
+ fetchFunc: async () =>
{
- result = JsonConvert.DeserializeObject($"{rawData}");
- }
- else
- {
- result = await _repo.StatoProdMacchinaAsync(idxMacchina, dtReq);
- // serializzo e salvo...
- rawData = JsonConvert.SerializeObject(result);
- await _redisDb.StringSetAsync(currKey, rawData, TimeSpan.FromSeconds(30));
- }
- if (result == null)
- {
- result = new StatoProdModel();
- }
- return result;
- }, TimeSpan.FromSeconds(3));
+ StatoProdModel? result = new StatoProdModel();
+ // cerco in _redisConn...
+ string currKey = $"{MP.Data.Utils.redisStatoProd}:{idxMacchina}:{dtReq:HHmm}";
+ RedisValue rawData = await _redisDb.StringGetAsync(currKey);
+ if (rawData.HasValue && !forceDb)
+ {
+ result = JsonConvert.DeserializeObject($"{rawData}");
+ }
+ else
+ {
+ result = await _repo.StatoProdMacchinaAsync(idxMacchina, dtReq);
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ await _redisDb.StringSetAsync(currKey, rawData, stdTTL);
+ }
+ if (result == null)
+ {
+ result = new StatoProdModel();
+ }
+ return result;
+ },
+ expiration: stdTTL,
+ tagList: ["IOC_StatoProd", cKey, idxMacchina]
+ );
}
///
diff --git a/MP.INVE/MP.INVE.csproj b/MP.INVE/MP.INVE.csproj
index ef7907fa..37b17e7a 100644
--- a/MP.INVE/MP.INVE.csproj
+++ b/MP.INVE/MP.INVE.csproj
@@ -5,7 +5,7 @@
enable
enable
MP.INVE
- 8.16.2606.408
+ 8.16.2606.1117
diff --git a/MP.INVE/Resources/ChangeLog.html b/MP.INVE/Resources/ChangeLog.html
index 878755a2..e2bcff20 100644
--- a/MP.INVE/Resources/ChangeLog.html
+++ b/MP.INVE/Resources/ChangeLog.html
@@ -1,6 +1,6 @@
Modulo MAPOINVE
- Versione: 8.16.2606.408
+ Versione: 8.16.2606.1117
Note di rilascio:
-
diff --git a/MP.INVE/Resources/VersNum.txt b/MP.INVE/Resources/VersNum.txt
index 988a0006..cb037420 100644
--- a/MP.INVE/Resources/VersNum.txt
+++ b/MP.INVE/Resources/VersNum.txt
@@ -1 +1 @@
-8.16.2606.408
+8.16.2606.1117
diff --git a/MP.INVE/Resources/manifest.xml b/MP.INVE/Resources/manifest.xml
index e69c68e1..57ec3dc9 100644
--- a/MP.INVE/Resources/manifest.xml
+++ b/MP.INVE/Resources/manifest.xml
@@ -1,6 +1,6 @@
-
- 8.16.2606.408
+ 8.16.2606.1117
https://nexus.steamware.net/repository/SWS/MP-INVE/stable/LAST/MP.INVE.zip
https://nexus.steamware.net/repository/SWS/MP-INVE/stable/LAST/ChangeLog.html
false
diff --git a/MP.IOC/Controllers/BenchController.cs b/MP.IOC/Controllers/BenchController.cs
index 357ee5cb..b096bbb1 100644
--- a/MP.IOC/Controllers/BenchController.cs
+++ b/MP.IOC/Controllers/BenchController.cs
@@ -13,10 +13,9 @@ namespace MP.IOC.Controllers
{
#region Public Constructors
- public BenchController(IConfiguration configuration, MpDataService DataService)
+ public BenchController(MpDataService DataService)
{
Log.Info("Starting BenchController");
- _configuration = configuration;
DService = DataService;
Log.Info("Avviata BenchController");
}
@@ -378,8 +377,6 @@ namespace MP.IOC.Controllers
#region Private Fields
- private static IConfiguration _configuration = null!;
-
private static Logger Log = LogManager.GetCurrentClassLogger();
#endregion Private Fields
diff --git a/MP.IOC/Controllers/IOBController.cs b/MP.IOC/Controllers/IOBController.cs
index f0ebee6c..834d64bd 100644
--- a/MP.IOC/Controllers/IOBController.cs
+++ b/MP.IOC/Controllers/IOBController.cs
@@ -20,7 +20,6 @@ namespace MP.IOC.Controllers
public IOBController(IConfiguration configuration, MpDataService DataService, IIocService IService)
{
- _configuration = configuration;
DService = DataService;
IOCService = IService;
}
@@ -480,14 +479,12 @@ namespace MP.IOC.Controllers
try
{
var odl = await IOCService.GetCurrOdlAsync(id);
- //var odl = await DService.GetCurrOdlAsync(id);
return Ok($"{odl}");
}
catch (Exception exc)
{
Log.Error(exc, "Errore GetCurrODL | macchina {MachineId}", id);
return StatusCode(StatusCodes.Status500InternalServerError, "NO");
- //return StatusCode(StatusCodes.Status500InternalServerError, "Errore interno | GetCurrODL");
}
}
@@ -1089,6 +1086,7 @@ namespace MP.IOC.Controllers
try
{
answ = await DService.saveCaricoPezzi(id, qty);
+ await IOCService.ClearFusionCache();
return Ok(answ);
}
catch (Exception exc)
@@ -1451,8 +1449,6 @@ namespace MP.IOC.Controllers
#endregion Public Methods
#region Private Fields
-
- private static IConfiguration _configuration = null!;
private static Logger Log = LogManager.GetCurrentClassLogger();
private IIocService IOCService;
diff --git a/MP.IOC/Controllers/RecipeArchiveController.cs b/MP.IOC/Controllers/RecipeArchiveController.cs
index 48a65540..feba2568 100644
--- a/MP.IOC/Controllers/RecipeArchiveController.cs
+++ b/MP.IOC/Controllers/RecipeArchiveController.cs
@@ -10,10 +10,9 @@ namespace MP.IOC.Controllers
{
#region Public Constructors
- public RecipeArchiveController(IConfiguration configuration, MpDataService DataService)
+ public RecipeArchiveController(MpDataService DataService)
{
Log.Info("Starting RecipeArchiveController");
- _configuration = configuration;
DService = DataService;
Log.Info("Avviata classe RecipeArchiveController");
}
@@ -121,8 +120,6 @@ namespace MP.IOC.Controllers
#region Private Fields
- private static IConfiguration _configuration = null!;
-
private static Logger Log = LogManager.GetCurrentClassLogger();
#endregion Private Fields
diff --git a/MP.IOC/Controllers/RecipeController.cs b/MP.IOC/Controllers/RecipeController.cs
index 6ebf6944..50005b4f 100644
--- a/MP.IOC/Controllers/RecipeController.cs
+++ b/MP.IOC/Controllers/RecipeController.cs
@@ -12,10 +12,9 @@ namespace MP.IOC.Controllers
{
#region Public Constructors
- public RecipeController(IConfiguration configuration, MpDataService DataService)
+ public RecipeController(MpDataService DataService)
{
Log.Info("Starting RecipeController");
- _configuration = configuration;
DService = DataService;
Log.Info("Avviata RecipeController");
}
@@ -64,8 +63,6 @@ namespace MP.IOC.Controllers
#region Private Fields
- private static IConfiguration _configuration = null!;
-
private static Logger Log = LogManager.GetCurrentClassLogger();
#endregion Private Fields
diff --git a/MP.IOC/Data/IMpDataService.cs b/MP.IOC/Data/IMpDataService.cs
new file mode 100644
index 00000000..3864402b
--- /dev/null
+++ b/MP.IOC/Data/IMpDataService.cs
@@ -0,0 +1,620 @@
+using MP.Core.DTO;
+using MP.Core.Objects;
+using MP.Data.DbModels;
+using MP.Data.DbModels.Anag;
+using MP.Data.MgModels;
+using StackExchange.Redis;
+using static MP.Core.Objects.Enums;
+
+namespace MP.IOC.Data
+{
+ public interface IMpDataService
+ {
+ #region Public Methods
+
+ ///
+ /// Verifica se sia da reinviare un taskName alla macchina dall'elenco di quelli salvati (in
+ /// modalit\u00e0 upsert) se non scaduti
+ ///
+ /// idx macchina
+ /// tipo task
+ /// valore task
+ /// true se il task \u00e8 stato reinviato
+ bool AddCheckTask4Machine(string idxMacchina, taskType taskKey, string taskVal);
+
+ ///
+ /// Aggiunge un parametro opzionale all'elenco dei saved task (in modalit\u00e0 upsert)
+ ///
+ /// idx macchina
+ /// chiave del parametro
+ /// valore del parametro
+ /// true se inserito
+ bool AddOptPar4Machine(string idxMacchina, string taskKey, string taskVal);
+
+ ///
+ /// Aggiunge un task all'elenco di quelli salvati (in modalit\u00e0 upsert)
+ ///
+ /// idx macchina
+ /// tipo task
+ /// valore task
+ /// true se inserito
+ bool AddTask4Machine(string idxMacchina, taskType taskKey, string taskVal);
+
+ ///
+ /// Aggiunge un set di task per macchina all'elenco di quelli salvati (in modalit\u00e0 upsert)
+ ///
+ /// idx macchina
+ /// Dizionario di task tipo-valore da salvare
+ /// true se completato
+ Task AddTask4MacListAsync(string idxMacchina, Dictionary taskDict);
+
+ ///
+ /// Inserimento record allarme su DB
+ ///
+ /// Data evento
+ /// Nome macchina
+ /// Indirizzo memoria PLC
+ /// Indice memoria
+ /// Stato valOut
+ /// Valore decodificato
+ /// true se inserito
+ Task AlarmInsertAsync(DateTime dtRif, string idxMacchina, string memAddress, int memIndex, int statusVal, string valDecoded);
+
+ ///
+ /// Restituisce l'anagrafica STATI per intero con cache Fusion
+ ///
+ /// Lista di modelli AnagStatiModel
+ Task
> AnagStatiGetAllAsync();
+
+ ///
+ /// Restituisce i modelli di ultimo articolo per data macchina, con cache Fusion
+ ///
+ /// idx macchina
+ /// Lista di modelli AnagArticoliModel
+ Task> ArticoliGetLastByMaccAsync(string idxMacc);
+
+ ///
+ /// Effettua lo split dell'ODL corrente per la macchina, con eventuale conferma produzione e
+ /// gestione slave
+ ///
+ /// idx macchina
+ /// effettuare la conferma quantitativa
+ /// imposta la qty del prossimo ODL da quello che si chiude
+ /// matricola operatore
+ /// Step di arrotondamento quantit\u00e0
+ /// Chiave esterna da associare all'ODL
+ /// "OK" se successo, "KO" altrimenti
+ Task AutoStartOdlAsync(string idxMacchina, bool doConfirm, bool qtyFromLast, int matrOpr, int roundStep = 100, string keyRichiesta = "");
+
+ ///
+ /// Calcola la ricetta su MongoDB dato modello ricetta corrente
+ ///
+ /// Modello ricetta da calcolare
+ /// Risultato del calcolo ricetta
+ string CalcRecipe(RecipeModel currRecipe);
+
+ ///
+ /// Controlla se dal segnale di "microstato" deriva un evento da generare - modalit\u00e0 OFFLINE
+ ///
+ /// idx macchina
+ /// valore valOut ingresso
+ /// data-ora evento (server)
+ /// sequenza dati inviati
+ /// dati macchina in cache (opzionale, se null fa lookup)
+ /// Risultato del processing
+ Task CheckMicroStatoAsync(string idxMacchina, string valore, DateTime dtEve, string contatore, Dictionary? datiMaccCache = null);
+
+ ///
+ /// Restituisce l'elenco completo delle configurazioni da DB, con cache Fusion
+ ///
+ /// Lista di modelli ConfigModel
+ Task> ConfigGetAllAsync();
+
+ ///
+ /// Restituisce l'elenco delle decodifiche articoli filtrata per codice, con cache Fusion
+ ///
+ /// codice articolo (opzionale, se vuoto restituisce tutto)
+ /// Lista di modelli DecNumArticoliModel
+ Task> DecNumArtGetFiltAsync(string codArt = "");
+
+ ///
+ /// Restituisce le date dei dossier per una macchina, con cache Fusion
+ ///
+ /// idx macchina
+ /// Lista di modelli DossierModel
+ Task> DossierLastByMachAsync(string idxMacchina);
+
+ ///
+ /// Task completo per sistemazione dossier quotidiani mancanti
+ ///
+ /// idx macchina
+ /// "OK" se completato
+ Task FixDailyDossierAsync(string idxMacc);
+
+ ///
+ /// Restituisce il codice valOut dell'ODL corrente (con cache redis interna)
+ ///
+ /// idx macchina
+ /// codice valOut dell'ODL corrente
+ Task GetCurrOdlAsync(string idxMacchina);
+
+ ///
+ /// Restituisce il modello dell'ultimo ODL per macchina, con cache Fusion
+ ///
+ /// idx macchina
+ /// Modello ODLExpModel
+ Task GetLastOdlAsync(string idxMacchina);
+
+ ///
+ /// Effettua il calcolo della data-ora di riferimento per il server, correggendo il delta
+ /// tra orologio macchina e server
+ ///
+ /// data-oras dell'evento (macchina)
+ /// data-ora corrente (server)
+ /// Data-ora evento corretta
+ DateTime GetSrvDtEvent(string dtEve, string dtCurr);
+
+ ///
+ /// Restituisce se la macchina sia abilitata all'inserimento dati da IOB
+ ///
+ /// idx macchina
+ /// true se abilitato all'input
+ Task IobInsEnabAsync(string idxMacchina);
+
+ ///
+ /// Restituisce se la macchina sia abilitata come master di un impianto
+ ///
+ /// idx macchina
+ /// true se \u00e8 master
+ Task IobIsMasterAsync(string idxMacchina);
+
+ ///
+ /// Restituisce se la macchina sia abilitata all'inserimento nel Signal Log
+ ///
+ /// idx macchina
+ /// true se abilitato
+ Task IobSLogEnabAsync(string idxMacchina);
+
+ ///
+ /// Restituisce i valori ammessi per una tabella/colonna (con cache redis interna)
+ ///
+ /// nome tabella
+ /// nome campo
+ /// Lista di ListValuesModel
+ Task> ListValuesFilt(string tabName, string fieldName);
+
+ ///
+ /// Restituisce l'elenco completo delle relazioni macchine master-slave, con cache Fusion
+ ///
+ /// Lista di Macchine2SlaveModel
+ Task> Macchine2SlaveGetAllAsync();
+
+ ///
+ /// Restituisce le macchine filtrate per gruppo, con cache Fusion
+ ///
+ /// codice gruppo (o "*" per tutto)
+ /// Lista di MacchineModel
+ Task> MacchineGetFilt(string codGruppo);
+
+ ///
+ /// Restituisce il path delle ricette di una macchina, con cache Fusion
+ ///
+ /// idx macchina
+ /// Path delle ricette
+ Task MacchineRecipeArchive(string idxMacchina);
+
+ ///
+ /// Restituisce la lista parametri correnti (ObjItemDTO) della macchina da Redis
+ ///
+ /// idx macchina
+ /// Lista di ObjItemDTO
+ Task> MachineParamListAsync(string idxMacchina);
+
+ ///
+ /// Restituisce i parametri correnti della macchina che necessitano di write (writable + reqValue valorizzato)
+ ///
+ /// idx macchina
+ /// Lista di ObjItemDTO
+ Task> MachineParamListPendingWriteAsync(string idxMacchina);
+
+ ///
+ /// Imposta i parametri correnti (ObjItemDTO) nella cache Redis della macchina
+ ///
+ /// idx macchina
+ /// dati parametri da impostare
+ /// true se salvato
+ Task MachineParamListSetAsync(string idxMacchina, List currData);
+
+ ///
+ /// Effettua l'UPSERT degli elementi dei parametri macchina in Redis
+ ///
+ /// idx macchina
+ /// nuovi elementi da aggiungere/aggiornare
+ /// true se completato
+ Task MachineParamUpsertAsync(string idxMacchina, List innovations);
+
+ ///
+ /// Restituisce i campi DatiMacchine + StatoMacchine come dizionario (da Redis o DB)
+ ///
+ /// idx macchina
+ /// Dizionario KVP dei campi macchina
+ Task> mDatiMacchineAsync(string idxMacchina);
+
+ ///
+ /// Restituisce i parametri ottimizzati per la macchine (Redis hash sync)
+ ///
+ /// idx macchina
+ /// Dizionario KVP parametri
+ Dictionary mOptParMacchina(string idxMacchina);
+
+ ///
+ /// Restituisce i task salvati della macchina (Redis hash sync)
+ ///
+ /// idx macchina
+ /// Dizionario KVP dei task salvati
+ Dictionary mSavedTaskMacchina(string idxMacchina);
+
+ ///
+ /// Restituisce l'elenco dalla tabella MappaStatoExpl, con o senza cache
+ ///
+ /// se true forza lettura database senza cache
+ /// Lista di MappaStatoExplModel
+ Task> MseGetAllAsync(bool forceDb = false);
+
+ ///
+ /// Restituisce il dizionario KVP della tabella Multi State Machine Ingressi (da Redis)
+ ///
+ /// idx macchina
+ /// Array di KeyValuePair
+ Task[]> mTabMSMIAsync(string idxMacchina);
+
+ ///
+ /// Restituisce i task in esecuzione per la macchina (Redis hash sync)
+ ///
+ /// idx macchina
+ /// Dizionario KVP dei task
+ Dictionary mTaskMacchina(string idxMacchina);
+
+ ///
+ /// Restituisce i task in esecuzione per la macchina (Redis hash async)
+ ///
+ /// idx macchina
+ /// Dizionario KVP dei task
+ Task> mTaskMacchinaAsync(string idxMacchina);
+
+ ///
+ /// Generazione automatica ODL giornalieri per la macchina
+ ///
+ /// idx macchina
+ /// data di inizio generazione
+ /// data di fine generazione
+ /// codice articolo
+ /// true se generato con successo
+ Task OdlAutoDayGenAsync(string idxMacchina, DateTime dataInizio, DateTime dataFine, string codArticolo);
+
+ ///
+ /// Generazione automatica ODL giornalieri completa con tutti i parametri PO/TC
+ ///
+ /// idx macchina
+ /// data inizio
+ /// data fine
+ /// codice articolo
+ /// pezzi per PODL
+ /// pezzi per pallet
+ /// chiave richiesta
+ /// TC assegnato
+ /// codice gruppo
+ /// flag crea PODL
+ /// flag verifica TC
+ /// true se generato con successo
+ Task OdlAutoDayGenFullAsync(string idxMacchina, DateTime dataInizio, DateTime dataFine, string codArticolo, int? pzPODL, int? pzPallet, string? keyRichiesta, int? tcAssegnato, string? codGruppo, bool flgCreaPODL, bool flgCheckTC);
+
+ ///
+ /// Restituisce l'ODL corrente per macchina, con cache Fusion
+ ///
+ /// idx macchina
+ /// Modello ODLExpModel
+ Task OdlCurrByMaccAsync(string IdxMacchina);
+
+ ///
+ /// Restituisce il modello PODL dato il suo indice, con cache Fusion
+ ///
+ /// indice PODL
+ /// Modello PODLModel
+ Task POdlGetByKey(int idxPODL);
+
+ ///
+ /// Restituisce i PODL per macchina/articolo, con cache Fusion
+ ///
+ /// idx macchina
+ /// codice articolo
+ /// codice gruppo
+ /// solo PODL liberi
+ /// Lista di PODLExpModel
+ Task> POdlGetByMaccArtAsync(string idxMacchina, string codArticolo, string codGruppo, bool onlyFree);
+
+ ///
+ /// Processa la registrazione di un flusso (FL) da IOB
+ ///
+ /// idx macchina
+ /// codice flusso (es. Ingresso, Uscita)
+ /// valore valOut del flusso
+ /// data-ora dell'evento (macchina)
+ /// data-ora corrente (server)
+ /// contatore invio
+ /// se true disabilita la scrittura del keepalive
+ /// "OK" se completato
+ Task ProcessFluxLogAsync(string idxMacchina, string flux, string valore, string dtEve, string dtCurr, int contatore, bool disabKA);
+
+ ///
+ /// Processa un input completo da IOB (verifica parametri, log segnali, processing microstato)
+ ///
+ /// idx macchina
+ /// valore valOut
+ /// data-ora evento (macchina)
+ /// data-ora corrente (server)
+ /// contatore
+ /// "OK" se completato, error message in caso contrario
+ Task ProcessInputAsync(string idxMacchina, string valore, string dtEve, string dtCurr, string contatore);
+
+ ///
+ /// Processa un UserLog registrato da IOB (DI=dichiarazioni, RC=controlli, RS=scarti)
+ ///
+ /// idx macchina
+ /// tipo flusso: DI (Dichiarazione), RC (Controllo), RS (Scarto)
+ /// valore/testo
+ /// data-ora evento
+ /// data-ora corrente
+ /// contatore invio dati
+ /// matricola operatore
+ /// causale scarto o tagCode
+ /// esitoOk (0/1) o quantit\u00e0 scarto
+ /// "OK" se completato
+ Task ProcessUserLogAsync(string idxMacchina, string flux, string valore, string dtEve, string dtCurr, int contatore, int matrOpr, string label, int valNum);
+
+ ///
+ /// Restituisce il contapezzi salvato in Redis per la macchina
+ ///
+ /// idx macchina
+ /// Contatore pezzi (-1 se non trovato)
+ Task pzCounter(string idxMacchina);
+
+ ///
+ /// Restituisce il contapezzi come conteggio da TCRilevati (dal DB)
+ ///
+ /// idx macchina
+ /// Conteggio pezzi (-1 se non trovato)
+ Task PzCounterTcAsync(string idxMacchina);
+
+ ///
+ /// Ricerca la ricetta su MongoDB dato l'indice del PODL
+ ///
+ /// indice PODL di riferimento
+ /// Modello ricetta o null
+ Task RecipeGetByPODL(int idxPODL);
+
+ ///
+ /// Effettua il conteggio delle chiavi Redis che corrispondono a un pattern
+ ///
+ /// pattern di ricerca
+ /// Numero di chiavi trovate
+ int RedisCountKey(string keyPattern);
+
+ ///
+ /// Elimina una chiave dalla memoria Redis
+ ///
+ /// chiave da eliminare
+ /// true se eliminata
+ bool RedisDelKey(string keyVal);
+
+ ///
+ /// Elimina una chiave dalla memoria Redis (async)
+ ///
+ /// chiave da eliminare
+ /// true se eliminata
+ Task RedisDelKeyAsync(RedisKey keyVal);
+
+ ///
+ /// Esegue il flush di tutte le chiavi Redis che corrispondono a un pattern
+ ///
+ /// pattern di ricerca
+ /// true se completato
+ Task RedisFlushPatternAsync(RedisValue pattern);
+
+ ///
+ /// Leggo un hash Redis come array di KeyValuePair (sync)
+ ///
+ /// chiave Redis
+ /// Array di KeyValuePair
+ KeyValuePair[] RedisGetHash(RedisKey redKey);
+
+ ///
+ /// Leggo un hash Redis come array di KeyValuePair (async)
+ ///
+ /// chiave Redis
+ /// Array di KeyValuePair
+ Task[]> RedisGetHashAsync(RedisKey redKey);
+
+ ///
+ /// Leggo un hash Redis come dizionario (sync)
+ ///
+ /// chiave Redis
+ /// Dizionario KVP
+ Dictionary RedisGetHashDict(RedisKey hashKey);
+
+ ///
+ /// Leggo un hash Redis come dizionario (async)
+ ///
+ /// chiave Redis
+ /// Dizionario KVP
+ Task> RedisGetHashDictAsync(RedisKey hashKey);
+
+ ///
+ /// Leggo un singolo campo di un hash Redis (async)
+ ///
+ /// chiave Redis
+ /// nome campo hash
+ /// Valore del campo
+ Task RedisGetHashFieldAsync(RedisKey key, string hashField);
+
+ ///
+ /// Verifica se una chiave esista in Redis (sync)
+ ///
+ /// chiave Redis
+ /// true se la chiave esiste
+ bool RedisKeyPresent(RedisKey key);
+
+ ///
+ /// Verifica se una chiave esista in Redis (async)
+ ///
+ /// chiave Redis
+ /// true se la chiave esiste
+ Task RedisKeyPresentAsync(RedisKey key);
+
+ ///
+ /// Imposta un hash Redis con expiration opzionale (sync)
+ ///
+ /// chiave Redis
+ /// array di coppie chiave-valore da inserire
+ /// TTL in secondi (-1 = nessuna expiration)
+ void RedisSetHash(RedisKey redKey, KeyValuePair[] valori, double expireSeconds = -1.0);
+
+ ///
+ /// Imposta un hash Redis con expiration opzionale (async)
+ ///
+ /// chiave Redis
+ /// array di coppie chiave-valore da inserire
+ /// TTL in secondi (-1 = nessuna expiration)
+ Task RedisSetHashAsync(RedisKey redKey, KeyValuePair[] valori, double expireSeconds = -1.0);
+
+ ///
+ /// Imposta un hash Redis con expiration opzionale (sync) da dizionario
+ ///
+ /// chiave Redis
+ /// dizionario di coppie chiave-valore da inserire
+ /// TTL in secondi (-1 = nessuna expiration)
+ void RedisSetHashDict(RedisKey redKey, Dictionary valori, double expireSeconds = -1.0);
+
+ ///
+ /// Imposta un hash Redis con expiration opzionale (async) da dizionario
+ ///
+ /// chiave Redis
+ /// dizionario di coppie chiave-valore da inserire
+ /// TTL in secondi (-1 = nessuna expiration)
+ Task RedisSetHashDictAsync(RedisKey redKey, Dictionary valori, double expireSeconds = -1.0);
+
+ ///
+ /// Inserimento record RemoteRebootLog con eventuale pulizia dei record vecchi
+ ///
+ /// record da inserire
+ /// true se completato
+ Task RemRebootLogAddAsync(RemoteRebootLogModel newRec);
+
+ ///
+ /// Elimina un task da elenco Redis per l'impianto indicato
+ ///
+ /// idx macchina
+ /// nome task da eliminare
+ /// Dizionario KVP rimanente
+ Task> RemTask2ExeMacchinaAsync(string idxMacchina, taskType tName);
+
+ ///
+ /// Resetta la tabella Multi State Machine Ingressi per macchina rileggendola dal DB
+ ///
+ /// idx macchina
+ /// Array di KVP della State Machine Ingressi
+ Task[]> resetMSMIAsync(string idxMacchina);
+
+ ///
+ /// Registra la movimentazione di un carico pezzi su Redis
+ ///
+ /// idx macchina
+ /// quantit\u00e0 da registrare
+ /// "OK" se completato
+ Task saveCaricoPezzi(string idxMacchina, string qty);
+
+ ///
+ /// Salva un elenco di dati macchina in DB
+ ///
+ /// identificativo della serie dati
+ /// elenco di dati macchina da salvare
+ /// true se salvato
+ Task SaveDataItemsAsync(string id, List dataList);
+
+ ///
+ /// Salva i dati macchina-IOB (serializzazione JSON) su Redis
+ ///
+ /// idx macchina
+ /// dati JSON serializzati
+ /// true se salvato
+ Task SaveMachine2Iob(string idxMacchina, string serData);
+
+ ///
+ /// Salva la configurazione della macchina come dizionario su Redis
+ ///
+ /// idx macchina
+ /// dizionario di configurazione
+ /// true se salvato
+ Task SaveMachineIobConf(string idxMacchina, Dictionary currDict);
+
+ ///
+ /// Salva il segnale di "microstato" come record SignalLog su DB (async)
+ ///
+ /// idx macchina
+ /// valOut ingresso
+ /// data-ora evento (server)
+ /// contatore sequenza dati inviati
+ /// true se salvato
+ Task saveSigLogAsync(string idxMacchina, string valore, DateTime dtEve, int contatore);
+
+ ///
+ /// Scrive un evento di keepalive se non presente in Redis con TTL
+ ///
+ /// idx macchina
+ /// ora macchina
+ Task ScriviKeepAliveAsync(string IdxMacchina, DateTime oraMacchina);
+
+ ///
+ /// Salva la configurazione YAML completa dell'IOB su Redis
+ ///
+ /// idx macchina
+ /// configurazione YAML completa
+ /// true se salvata
+ Task SetIobConfYamlAsync(string idxMacchina, string iobConfFull);
+
+ ///
+ /// Salva la mappatura memoria PLC su Redis
+ ///
+ /// idx macchina
+ /// mappatura PLC da salvare
+ /// true se salvata
+ Task SetIobMemMap(string idxMacchina, PlcMemMapDto currMap);
+
+ ///
+ /// Restituisce la tabella key-value della State Machine Ingressi per famiglia,
+ /// rileggendola dal DB e salvandola in Redis
+ ///
+ /// idx famiglia ingressi
+ /// Array di KVP (currentMicroStato_nVal -> IdxTipoEv_nStato)
+ Task[]> StateMachInByKeyAsync(int idxFamIn);
+
+ ///
+ /// Effettua l'UPSERT degli oggetti corrente della macchina su Redis (legacy compatibilit\u00e0)
+ ///
+ /// idx macchina
+ /// dati da aggiornare/aggiungere
+ /// true se completato
+ Task UpsertCurrObjItemsAsync(string idxMacchina, List innovations);
+
+ ///
+ /// Restituisce il valore SPECIFICATO per la state machine ingressi in formato hash Redis
+ ///
+ /// idx famiglia ingressi
+ /// idx microstato
+ /// valore ingresso
+ /// valore (IdxFamIn_nValore) dalla tab SMI Redis
+ Task ValoreSmiAsync(int idxFamIn, int idxMicroStato, int valoreIn);
+
+ #endregion Public Methods
+ }
+}
\ No newline at end of file
diff --git a/MP.IOC/Data/MpDataService.cs b/MP.IOC/Data/MpDataService.cs
index 87ed22a2..59802944 100644
--- a/MP.IOC/Data/MpDataService.cs
+++ b/MP.IOC/Data/MpDataService.cs
@@ -7,7 +7,10 @@ using MP.Data.Controllers;
using MP.Data.DbModels;
using MP.Data.DbModels.Anag;
using MP.Data.MgModels;
+using MP.Data.Repository.Anag;
+using MP.Data.Repository.IOC;
using MP.Data.Repository.Production;
+using MP.Data.Repository.System;
using MP.Data.Services.IOC;
using MP.Data.Services.Mtc;
using Newtonsoft.Json;
@@ -16,28 +19,36 @@ using StackExchange.Redis;
using System.Data;
using System.Diagnostics;
using System.Globalization;
+using ZiggyCreatures.Caching.Fusion;
using static MP.Core.Objects.Enums;
namespace MP.IOC.Data
{
- public class MpDataService
+ public class MpDataService : IMpDataService
{
#region Public Constructors
- private readonly IProductionRepository _productionRepository;
public MpDataService(
IConfiguration configuration,
ILogger logger,
IServiceScopeFactory scopeFactory,
IProductionRepository productionRepository,
+ IFusionCache cache,
MpIocController mpIocCtr,
- IMtcSetupService mtcServ)
+ IMtcSetupService mtcServ,
+ IIocRepository iocRepository,
+ IAnagRepository anagRepository,
+ ISystemRepository systemRepository)
{
_logger = logger;
_logger.LogInformation("Starting MpDataService INIT");
_configuration = configuration;
_scopeFactory = scopeFactory;
_productionRepository = productionRepository;
+ _iocRepository = iocRepository;
+ _anagRepository = anagRepository;
+ _systemRepository = systemRepository;
+ _cache = cache;
IocDbController = mpIocCtr;
// setup compoenti REDIS
@@ -64,10 +75,6 @@ namespace MP.IOC.Data
}
else
{
-#if false
- SpecDbController = new MpSpecController(configuration);
- IocDbController = new MpIocController(configuration);
-#endif
Log.Info("DbControllers INIT OK");
}
@@ -84,37 +91,24 @@ namespace MP.IOC.Data
mongoController = new MpMongoController(configuration);
Log.Info("MongoController INIT OK");
}
-
}
#endregion Public Constructors
#region Public Properties
- public static MpMongoController mongoController { get; set; } = null!;
public static MpIocController IocDbController { get; set; } = null!;
-#if false
- public static MpSpecController SpecDbController { get; set; } = null!;
-#endif
+ public static MpMongoController mongoController { get; set; } = null!;
public MessagePipe BroadastMsgPipe { get; set; } = null!;
- ///
- /// Dizionario dei tag configurati per IOB
- ///
+ ///
public Dictionary> currTagConf { get; set; } = new Dictionary>();
#endregion Public Properties
#region Public Methods
- ///
- /// Verifica se sia da reinviare un tName alla macchina dall'elenco di quelli salvati (in
- /// modalità upsert) se non scaduti
- ///
- ///
- ///
- ///
- ///
+ ///
public bool AddCheckTask4Machine(string idxMacchina, taskType taskKey, string taskVal)
{
bool answ = false;
@@ -145,13 +139,7 @@ namespace MP.IOC.Data
return answ;
}
- ///
- /// Aggiunge un PARAMETRO OPZIONALE all'elenco di quelli salvati (in modalità upsert)
- ///
- ///
- ///
- ///
- ///
+ ///
public bool AddOptPar4Machine(string idxMacchina, string taskKey, string taskVal)
{
bool answ = false;
@@ -179,13 +167,7 @@ namespace MP.IOC.Data
return answ;
}
- ///
- /// Aggiunge un tName all'elenco di quelli salvati (in modalità upsert)
- ///
- ///
- ///
- ///
- ///
+ ///
public bool AddTask4Machine(string idxMacchina, Enums.taskType taskKey, string taskVal)
{
bool answ = false;
@@ -237,13 +219,7 @@ namespace MP.IOC.Data
return answ;
}
- ///
- /// Aggiunge un set di task x macchina all'elenco di quelli salvati (in modalità upsert)
- ///
- ///
- ///
- ///
- ///
+ ///
public async Task AddTask4MacListAsync(string idxMacchina, Dictionary taskDict)
{
bool answ = false;
@@ -302,16 +278,7 @@ namespace MP.IOC.Data
return answ;
}
- ///
- /// Insert record allarme
- ///
- /// Data evento
- /// Idx macchina
- /// area memoria
- /// indice memoria
- /// valOut status
- /// valOut decodificato
- ///
+ ///
public async Task AlarmInsertAsync(DateTime dtRif, string idxMacchina, string memAddress, int memIndex, int statusVal, string valDecoded)
{
// aggiorno record sul DB
@@ -320,76 +287,31 @@ namespace MP.IOC.Data
return answ;
}
- ///
- /// Restituisce l'anagrafica STATI per intero
- ///
- ///
+ ///
public async Task> AnagStatiGetAllAsync()
{
- List dbResult = new List();
- // cerco in redis...
- var currKey = Utils.redisAnagStati;
- RedisValue rawData = await redisDb.StringGetAsync(currKey);
- if (rawData.HasValue)
- {
- dbResult = JsonConvert.DeserializeObject>($"{rawData}") ?? new();
- }
- else
- {
- dbResult = await IocDbController.AnagStatiGetAllAsync();
- // serializzo e salvo...
- rawData = JsonConvert.SerializeObject(dbResult);
- await redisDb.StringSetAsync(currKey, rawData, getRandTOut(redisLongTimeCache));
- }
- return dbResult;
+ return await GetOrFetchAsync(
+ operationName: "AnagStatiGetAllAsync",
+ cacheKey: Utils.redisAnagStati,
+ expiration: getRandTOut(redisLongTimeCache),
+ fetchFunc: async () => await IocDbController.AnagStatiGetAllAsync() ?? new List(),
+ tagList: [Utils.redisAnagStati]
+ );
}
- ///
- /// Elenco ultimi articoli data amcchina
- ///
- ///
- ///
+ ///
public async Task> ArticoliGetLastByMaccAsync(string idxMacc)
{
- List? result = new List();
- Stopwatch stopWatch = new Stopwatch();
- stopWatch.Start();
- string readType = "DB";
- string currKey = $"{Utils.redisArtList}:Last:{idxMacc}";
- // cerco in redis dato valOut sel macchina...
- RedisValue rawData = redisDb.StringGet(currKey);
- if (rawData.HasValue)
- {
- result = JsonConvert.DeserializeObject>($"{rawData}");
- readType = "REDIS";
- }
- else
- {
- result = await IocDbController.ArticoliGetLastByMaccAsync(idxMacc);
- // serializzo e salvo...
- rawData = JsonConvert.SerializeObject(result);
- redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
- }
- if (result == null)
- {
- result = new List();
- }
- stopWatch.Stop();
- TimeSpan ts = stopWatch.Elapsed;
- Log.Debug($"ArticoliGetLastByMaccAsync | Read from {readType}: {ts.TotalMilliseconds}ms");
- return result;
+ return await GetOrFetchAsync(
+ operationName: "ArticoliGetLastByMaccAsync",
+ cacheKey: $"{Utils.redisArtList}:Last:{idxMacc}",
+ expiration: getRandTOut(redisLongTimeCache),
+ fetchFunc: async () => (await IocDbController.ArticoliGetLastByMaccAsync(idxMacc)) ?? new List(),
+ tagList: [Utils.redisArtList]
+ );
}
- ///
- /// Effettua split ODL
- ///
- /// macchina
- /// effettuare conferma qty
- /// imposta la qty prox ODL da ODL che si chiude
- /// matricola operatore
- /// Round Step quantità prox ODL (corrente come riferimento)
- /// Cod ext da associare all'ODL
- ///
+ ///
public async Task AutoStartOdlAsync(string idxMacchina, bool doConfirm, bool qtyFromLast, int matrOpr, int roundStep = 100, string keyRichiesta = "")
{
string answ = "KO";
@@ -467,7 +389,7 @@ namespace MP.IOC.Data
List slaveList = new();
if (isMachMaster)
{
- List allSlaveList = await IocDbController.Macchine2SlaveAsync();
+ List allSlaveList = await _iocRepository.Macchine2SlaveAsync();
slaveList = allSlaveList.Where(x => x.IdxMacchina == idxMacchina).ToList();
}
@@ -582,15 +504,6 @@ namespace MP.IOC.Data
updDict.Add(taskType.setArt, setArtVal);
updDict.Add(taskType.setComm, setCommVal);
updDict.Add(taskType.setPzComm, setPzCommVal);
-#if false
- addTask4Machine(idxMacchina, taskType.setArt, setArtVal);
- addTask4Machine(idxMacchina, taskType.setComm, setCommVal);
- addTask4Machine(idxMacchina, taskType.setPzComm, setPzCommVal);
-
- updateMachineParameter(idxMacchina, "setArt", setArtVal);
- updateMachineParameter(idxMacchina, "setComm", setCommVal);
- updateMachineParameter(idxMacchina, "setPzComm", setPzCommVal);
-#endif
// recupero set attuale parametri
var currMachPar = await MachineParamListAsync(idxMacchina);
List list2upd = new();
@@ -635,20 +548,6 @@ namespace MP.IOC.Data
updDict.Add(taskType.setArt, setArtVal);
updDict.Add(taskType.setComm, setCommVal);
updDict.Add(taskType.setPzComm, setPzCommVal);
-
-#if false
- addTask4Machine(machine.IdxMacchinaSlave, taskType.fixStopSetup, outData);
- addTask4Machine(machine.IdxMacchinaSlave, taskType.forceResetPzCount, outData);
- // invio task caricamento dati ODL
- addTask4Machine(machine.IdxMacchinaSlave, taskType.setArt, setArtVal);
- addTask4Machine(machine.IdxMacchinaSlave, taskType.setComm, setCommVal);
- addTask4Machine(machine.IdxMacchinaSlave, taskType.setPzComm, setPzCommVal);
-
- updateMachineParameter(machine.IdxMacchinaSlave, "setArt", setArtVal);
- updateMachineParameter(machine.IdxMacchinaSlave, "setComm", setCommVal);
- updateMachineParameter(machine.IdxMacchinaSlave, "setPzComm", setPzCommVal);
-#endif
-
// recupero set attuale parametri
var currMachPar = await MachineParamListAsync(machine.IdxMacchinaSlave);
List list2upd = new();
@@ -685,15 +584,7 @@ namespace MP.IOC.Data
return mongoController.CalcRecipe(currRecipe);
}
- ///
- /// controlla se da il segnale di "microstato" deriva un evento da generare - modalità OFFLINE
- ///
- /// idx macchina
- /// valOut ingresso
- /// data-ora evento (server)
- /// sequenza dati inviati
- /// dati macchina in cache (opzionale, se null fa lookup)
- ///
+ ///
public async Task CheckMicroStatoAsync(string idxMacchina, string valore, DateTime dtEve, string contatore, Dictionary? datiMaccCache = null)
{
// recupero SE IMPIEGATO REDIS i valori del Dictionary della macchina...
@@ -712,7 +603,7 @@ namespace MP.IOC.Data
string CodArticolo = datiMacc["CodArticolo"];
if (string.IsNullOrEmpty(CodArticolo))
{
- var allDatiMacch = await IocDbController.DatiMacchineGetAllAsync();
+ var allDatiMacch = await _iocRepository.DatiMacchineGetAllAsync();
var recMacc = allDatiMacch.FirstOrDefault(x => x.IdxMacchina == idxMacchina);
if (recMacc != null)
{
@@ -774,109 +665,47 @@ namespace MP.IOC.Data
}
else
{
- if (useFactory)
- {
- await using var scope = _scopeFactory.CreateAsyncScope();
- var iocService = scope.ServiceProvider.GetRequiredService();
- // solo microstato
- await iocService.MicroStatoMacchinaUpsertAsync(newRecMsm);
- }
- else
- {
- // solo microstato
- await IocDbController.MicroStatoMacchinaUpsertAsync(newRecMsm);
- }
+ // solo microstato → IIocRepository
+ await _iocRepository.MicroStatoMacchinaUpsertAsync(newRecMsm);
}
return answ;
}
public async Task> ConfigGetAllAsync()
{
- Stopwatch stopWatch = new Stopwatch();
- stopWatch.Start();
- List? result = new List