kreta/Kreta.Job.Tasks/SapJob.cs
2024-03-13 00:33:46 +01:00

369 lines
16 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Kreta.Core;
using Kreta.Core.Exceptions;
using Kreta.Core.SAP;
using Kreta.DataAccessManual;
using Kreta.DataAccessManual.Interfaces;
using Kreta.DataAccessManual.ParameterClasses;
using Kreta.Enums.ManualEnums;
using Kreta.Job.Tasks.Core;
using Kreta.Job.Tasks.Core.Models;
using Kreta.Job.Tasks.Models;
using Kreta.Resources;
namespace Kreta.Job.Tasks
{
public class SapJob : ISapJob
{
private ISAPService SapServiceClient { get; }
private ISAPConfiguration SapConfiguration { get; }
public SapJob(ISAPService sapService, ISAPConfiguration sapConfiguration)
{
SapServiceClient = sapService ?? throw new ArgumentNullException(nameof(sapService));
SapConfiguration = sapConfiguration ?? throw new ArgumentNullException(nameof(sapService));
}
public void SyncJobKeretEsTavollet()
{
var exceptions = new List<Exception>();
var now = DateTime.Now;
foreach (var azonosito in KretaServer.KretaServer.Instance.GetOsszesIntezmeny())
{
Dal.OrganizationConnection.Run(azonosito, h =>
{
try
{
var icDal = h.IntezmenyConfigDAL();
var dal = h.IntezmenyDal();
var intezmenyId = dal.GetIntezmenyIdByAzonosito(azonosito);
if (!bool.Parse(icDal.GetIntezmenyConfig(intezmenyId.Value, IntezmenyConfigModulEnum.HRModul.ToString(), IntezmenyConfigTipusEnum.IsEnabled.ToString())))
return;
var ds = dal.GetIntezmenyIdAktivTanevIdByAzonosito(azonosito);
if (ds.Tables[0].Rows.Count > 0)
{
var pco = new TavolletSearchPco
{
TanevId = ds.Tables[0].Rows[0].Field<int>("AktivTanevId"),
IntezmenyId = ds.Tables[0].Rows[0].Field<int>("IntezmenyId"),
IntezmenyAzonosito = azonosito,
NaptariEv = new int[] { now.Year },
};
SyncSzabadsagKeret(h, null, pco);
SyncTavollet(h, null, pco);
}
}
catch (BlException ex)
{
exceptions.Add(ex);
//TODO: Üzleti logika által dobott hiba egyéb kezelése! Ha kell a job-nál ezzel valamit kezdeni, akkor...
}
catch (Exception ex)
{
exceptions.Add(ex);
}
});
}
if (exceptions.Any())
{
var blExceptions = exceptions.FindAll(e => e is BlException).Cast<BlException>();
if (blExceptions.Any())
{
//UzenetekHelper.cs ??
SendNotificationEmail(blExceptions);
}
var aggregateException = new AggregateException(exceptions);
throw aggregateException.Flatten();
}
}
private void SendNotificationEmail(IEnumerable<BlException> blExceptions)
{
var aggregateBlException = new AggregateException(blExceptions).ToString();
var emailModel = new EmailModel
{
Message = aggregateBlException,
Subject = $"{EmailResource.SapSyncJob}",
Bcc = SapConfiguration.NotificationEmailsBussinessLogic
};
Hangfire.BackgroundJob.Enqueue<IEmailJob>(email => email.SendMailAsync(emailModel));
}
private int SyncSzabadsagKeret(IDalHandler dalHandler, int? alkalmazottId, TavolletSearchPco pco)
{
int missingSzTSz = 0;
var aDal = dalHandler.Alkalmazott();
DataSet ds = aDal.GetAlkalmazottakSapAzonositoi(alkalmazottId, pco.TanevId, pco.IntezmenyId);
if (ds.Tables[0].Rows.Count > 0)
{
var funkcioTeruletek = new HashSet<string>();
var keretek = new Dictionary<string, (int alkalmazottId, int keret)>();
var requestQ = new List<TavolletRequestModel>();
var now = DateTime.Now;
foreach (DataRow row in ds.Tables[0].Rows)
{
string intezmenySapAzonosito = row["IntezmenySAPKod"].ToString();
string szTSzAzonosito = row["SzTSzKod"].ToString();
if (string.IsNullOrWhiteSpace(intezmenySapAzonosito))
{
throw new BlException(string.Format(HRModulResource.IntezmenySapAzonositoHiany, pco.IntezmenyAzonosito));
}
if (string.IsNullOrWhiteSpace(szTSzAzonosito))
{
missingSzTSz++;
continue;
}
if (!keretek.ContainsKey(szTSzAzonosito))
{
keretek.Add(szTSzAzonosito, (row.Field<int>("AlkalmazottId"), row.Field<int>("SzabadsagKeret")));
}
if (!funkcioTeruletek.Contains(intezmenySapAzonosito))
{
funkcioTeruletek.Add(intezmenySapAzonosito);
for (int i = 0; i < pco.NaptariEv.Length; i++)
{
// Időszak: január 1 - ma
DateTime kezdet = new DateTime(pco.NaptariEv[i], 1, 1);
DateTime vege = pco.NaptariEv[i] == now.Year ? now : new DateTime(pco.NaptariEv[i], 1, 1);
requestQ.Add(new TavolletRequestModel
{
IntezmenyAzonosito = intezmenySapAzonosito,
SzTSzAzonosito = alkalmazottId.HasValue ? szTSzAzonosito : null,
Kezdet = kezdet,
Vege = vege
});
}
}
}
var response = SapServiceClient.LekerdezesKeret(requestQ.ToArray());
if (response != null && response.Any())
{
var updateKeretDict = new Dictionary<int, int>();
var sapErrorList = new List<string>();
foreach (var item in response)
{
if (ResultCode.Success == item.ErrCode)
{
if (keretek.TryGetValue(item.SzTSzAzonosito, out (int alkalmazottId, int keret) value) && value.keret != item.SzabadKeret)
{
updateKeretDict.Add(value.alkalmazottId, item.SzabadKeret);
}
}
else
{
// Ha hiba van, akkor egy listában gyűjtjük az üzeneteket.
sapErrorList.Add(item.ErrText);
}
}
if (sapErrorList != null && sapErrorList.Count > 0)
{
throw new BlException(HRModulResource.ASzinkronizacioNemSikerult, new BlException(string.Join(Environment.NewLine, sapErrorList)));
}
aDal.UpdateAlkalmazottSzabadsagKeret(updateKeretDict);
}
}
return missingSzTSz;
}
private int SyncTavollet(IDalHandler dalHandler, int? alkalmazottId, TavolletSearchPco pco)
{
int missingSzTSz = 0;
IAlkalmazottDal alkalmazaottDal = dalHandler.Alkalmazott();
DataSet ds = alkalmazaottDal.GetAlkalmazottakSapAzonositoi(alkalmazottId, pco.TanevId, pco.IntezmenyId);
if (ds.Tables[0].Rows.Count > 0)
{
var sztszError = new HashSet<string>(); //Adathibák!!!
var sapAzonositok = ds.Tables[0].Rows.OfType<DataRow>();
var requestQ = new List<TavolletRequestModel>();
foreach (DataRow row in sapAzonositok)
{
string intezmenySapAzonosito = row["IntezmenySAPKod"].ToString();
string szTSzAzonosito = row["SzTSzKod"].ToString();
if (string.IsNullOrWhiteSpace(intezmenySapAzonosito))
{
throw new BlException(string.Format(HRModulResource.IntezmenySapAzonositoHiany, pco.IntezmenyAzonosito));
}
if (string.IsNullOrWhiteSpace(szTSzAzonosito))
{
missingSzTSz++;
continue;
}
// Időszak: január 1 - december 31
for (int i = 0; i < pco.NaptariEv.Length; i++)
{
DateTime kezdet = new DateTime(pco.NaptariEv[i], 1, 1);
DateTime vege = kezdet.AddYears(1).AddSeconds(-1);
requestQ.Add(new TavolletRequestModel
{
IntezmenyAzonosito = intezmenySapAzonosito,
SzTSzAzonosito = szTSzAzonosito,
Kezdet = kezdet,
Vege = vege
});
}
}
var response = SapServiceClient.Lekerdezes(requestQ.ToArray());
if (response != null && response.Any())
{
ISapTavolletDal sapTavolletDal = dalHandler.SapTavolletDal();
var tavolletTipusDict = new Dictionary<string, int>();
foreach (DataRow row in sapTavolletDal.GetTavolletTipusDataSet(pco.TanevId, pco.IntezmenyId).Tables[0].Rows)
{
tavolletTipusDict.Add(row.Field<string>("SapCode"), row.Field<int>("ID"));
}
// 'Na' érték SAP kódja
string naTavollettipus = "0000";
var tavolletListDict = new Dictionary<string, List<TavolletModel>>();
var sapErrorList = new List<string>();
foreach (var item in response)
{
if (ResultCode.Success == item.ErrCode)
{
DataRow sapAzonosito;
try
{
sapAzonosito = sapAzonositok.Single(d => d.Field<string>("SzTSzKod") == item.SzTSzAzonosito);
}
catch (Exception)
{
if (!sztszError.Contains(item.SzTSzAzonosito))
{
sztszError.Add(item.SzTSzAzonosito);
}
continue;
}
TavolletModel e = new TavolletModel
{
AlkalmazottId = sapAzonosito.Field<int>("AlkalmazottId"),
ElozoTaneviAlkalmazottId = sapAzonosito.Field<int?>("ElozoTaneviAlkalmazottId"),
TanevId = pco.TanevId,
IntezmenyId = pco.IntezmenyId,
TavolletKezdete = item.Kezdet,
TavolletVege = item.Vege,
TavolletIdotartamNap = item.TavolletIdotartamNap,
TavolletIdotartamOra = item.TavolletIdotartamOra,
TavolletTipusId = tavolletTipusDict.TryGetValue(item.TavolletKod.WithLeadZeros(), out int value)
? value
: tavolletTipusDict[naTavollettipus]
};
if (!tavolletListDict.ContainsKey(item.SzTSzAzonosito))
{
tavolletListDict.Add(item.SzTSzAzonosito, new List<TavolletModel>());
}
tavolletListDict[item.SzTSzAzonosito].Add(e);
}
else
{
// Ha hiba van, akkor egy listában gyűjtjük az üzeneteket.
sapErrorList.Add(item.ErrText);
}
}
if (sapErrorList != null && sapErrorList.Count > 0)
{
throw new BlException(HRModulResource.ASzinkronizacioNemSikerult, new BlException(string.Join(Environment.NewLine, sapErrorList)));
}
var checklistTavolletDict = new Dictionary<string, List<TavolletModel>>();
foreach (DataRow row in sapTavolletDal.GetSAPTavolletDataSet(alkalmazottId, pco).Tables[0].Rows)
{
TavolletModel c = new TavolletModel
{
AlkalmazottId = row.Field<int>("AlkalmazottId"),
IntezmenyId = row.Field<int>("IntezmenyId"),
TavolletKezdete = row.Field<DateTime>("TavolletKezdete"),
TavolletVege = row.Field<DateTime>("TavolletVege"),
TavolletIdotartamNap = row.Field<int?>("TavolletIdotartamNap"),
TavolletIdotartamOra = row.Field<int?>("TavolletIdotartamOra"),
TavolletTipusId = row.Field<int>("TavolletTipusId")
};
if (!checklistTavolletDict.ContainsKey(row.Field<string>("SzTSzKod")))
{
checklistTavolletDict.Add(row.Field<string>("SzTSzKod"), new List<TavolletModel>());
}
checklistTavolletDict[row.Field<string>("SzTSzKod")].Add(c);
}
var syncKeys = new List<string>();
foreach (var key in tavolletListDict.Keys)
{
int th = tavolletListDict[key].AsReadOnly().GetSequenceHashCode();
int ch = checklistTavolletDict.TryGetValue(key, out List<TavolletModel> list) ? list.AsReadOnly().GetSequenceHashCode() : 0;
if (th != ch)
{
syncKeys.Add(key);
}
}
if (syncKeys.Count > 0)
{
sapTavolletDal.SyncSapTavollet(ConvertModelToPco(tavolletListDict.Where(d => syncKeys.Contains(d.Key))), pco);
}
}
}
return missingSzTSz;
}
private Dictionary<string, List<SAPTavolletPco>> ConvertModelToPco(IEnumerable<KeyValuePair<string, List<TavolletModel>>> coList)
{
var result = new Dictionary<string, List<SAPTavolletPco>>();
foreach (var co in coList)
{
result.Add(co.Key, new List<SAPTavolletPco>());
foreach (var item in co.Value)
{
result[co.Key].Add(new SAPTavolletPco
{
AlkalmazottId = item.AlkalmazottId,
ElozoTaneviAlkalmazottId = item.ElozoTaneviAlkalmazottId,
TanevId = item.TanevId,
IntezmenyId = item.IntezmenyId,
TavolletKezdete = item.TavolletKezdete,
TavolletVege = item.TavolletVege,
TavolletIdotartamNap = item.TavolletIdotartamNap,
TavolletIdotartamOra = item.TavolletIdotartamOra,
TavolletTipusId = item.TavolletTipusId
});
}
}
return result;
}
}
}