epasmed/src/main/java/it/cnr/isti/epasmed/sync/SyncService.java

1907 lines
62 KiB
Java
Executable File

package it.cnr.isti.epasmed.sync;
import java.sql.Timestamp;
import java.text.Normalizer;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.domain.Leaves;
import it.cnr.isti.epasmed.domain.PersOrario;
import it.cnr.isti.epasmed.domain.TabsSI;
import it.cnr.isti.epasmed.domain.TimeCardsReporting;
import it.cnr.isti.epasmed.epas.dto.EPASAffiliationsDTO;
import it.cnr.isti.epasmed.epas.dto.EPASGroupsDTO;
import it.cnr.isti.epasmed.epas.dto.EPASPersonWorkingTimeDTO;
import it.cnr.isti.epasmed.epas.dto.EPASPersonsDTO;
import it.cnr.isti.epasmed.epas.mapper.EPASAffiliationsMapper;
import it.cnr.isti.epasmed.epas.mapper.EPASGroupsMapper;
import it.cnr.isti.epasmed.epas.mapper.EPASPersonsMapper;
import it.cnr.isti.epasmed.epas.model.EPASAbsenceTypes;
import it.cnr.isti.epasmed.epas.model.EPASAbsences;
import it.cnr.isti.epasmed.epas.model.EPASAffiliations;
import it.cnr.isti.epasmed.epas.model.EPASGroups;
import it.cnr.isti.epasmed.epas.model.EPASLeaves;
import it.cnr.isti.epasmed.epas.model.EPASOffSiteWorks;
import it.cnr.isti.epasmed.epas.model.EPASPersonDays;
import it.cnr.isti.epasmed.epas.model.EPASPersons;
import it.cnr.isti.epasmed.epas.model.EPASStampings;
import it.cnr.isti.epasmed.epas.model.EPASTimeCards;
import it.cnr.isti.epasmed.epas.model.EPASValidates;
import it.cnr.isti.epasmed.epas.model.EPASWorkingTimeTypes;
import it.cnr.isti.epasmed.epas.service.EPASAbsenceTypesService;
import it.cnr.isti.epasmed.epas.service.EPASAffiliationsService;
import it.cnr.isti.epasmed.epas.service.EPASGroupsService;
import it.cnr.isti.epasmed.epas.service.EPASLeavesService;
import it.cnr.isti.epasmed.epas.service.EPASOffSiteWorksService;
import it.cnr.isti.epasmed.epas.service.EPASPersonWorkingTimeService;
import it.cnr.isti.epasmed.epas.service.EPASPersonsService;
import it.cnr.isti.epasmed.epas.service.EPASTimeCardsService;
import it.cnr.isti.epasmed.epas.service.EPASValidatesService;
import it.cnr.isti.epasmed.epas.service.EPASWorkingTimeTypesService;
import it.cnr.isti.epasmed.service.LeavesService;
import it.cnr.isti.epasmed.service.PersOrarioService;
import it.cnr.isti.epasmed.service.TabsSIService;
import it.cnr.isti.epasmed.service.TimeCardsReportingService;
import it.cnr.isti.epasmed.service.mapper.LeavesMapper;
import it.cnr.isti.epasmed.service.mapper.PersOrarioMapper;
import it.cnr.isti.epasmed.sistemainformativo.model.SIAnagrafico;
import it.cnr.isti.epasmed.sistemainformativo.model.SIAspettative;
import it.cnr.isti.epasmed.sistemainformativo.model.SICartellini;
import it.cnr.isti.epasmed.sistemainformativo.model.SICartelliniRendicontazioni;
import it.cnr.isti.epasmed.sistemainformativo.model.SIEmail;
import it.cnr.isti.epasmed.sistemainformativo.model.SIGruppi;
import it.cnr.isti.epasmed.sistemainformativo.model.SIGruppiPers;
import it.cnr.isti.epasmed.sistemainformativo.model.SILavoroFuoriSede;
import it.cnr.isti.epasmed.sistemainformativo.model.SIOrario;
import it.cnr.isti.epasmed.sistemainformativo.model.SIPersOrario;
import it.cnr.isti.epasmed.sistemainformativo.model.SITelefoni;
import it.cnr.isti.epasmed.sistemainformativo.service.SIAnagraficoService;
import it.cnr.isti.epasmed.sistemainformativo.service.SIAspettativeService;
import it.cnr.isti.epasmed.sistemainformativo.service.SICartelliniRendicontazioniService;
import it.cnr.isti.epasmed.sistemainformativo.service.SICartelliniService;
import it.cnr.isti.epasmed.sistemainformativo.service.SIEmailService;
import it.cnr.isti.epasmed.sistemainformativo.service.SIGruppiPersService;
import it.cnr.isti.epasmed.sistemainformativo.service.SIGruppiService;
import it.cnr.isti.epasmed.sistemainformativo.service.SILavoroFuoriSedeService;
import it.cnr.isti.epasmed.sistemainformativo.service.SIMasterLogService;
import it.cnr.isti.epasmed.sistemainformativo.service.SIOrarioService;
import it.cnr.isti.epasmed.sistemainformativo.service.SIPersOrarioService;
import it.cnr.isti.epasmed.sistemainformativo.service.SITelefoniService;
@Service
public class SyncService {
private static final String ISTI_OFFICE_ID = "1";
private static final String ISTI_OFFICE_CODEID = "225200";
private static final String SI_FLAG_DEL_TRUE = "1";
private static final String SI_FLAG_DEL_FALSE = "0";
private static final String SI_RECAPITO_TELEFONICO_UFFICIO = "Ufficio";
@SuppressWarnings("unused")
private static final String SI_TIPO_EMAIL_ISTITUZIONALE = "Istituzionale";
private static final String SI_TIPO_EMAIL_CNR = "C.N.R.";
private static final String PERSON_DEFAULT_QUALIFICATION = "3";
private static final boolean EXPORT_ABSENCE_CODE_DESCRIPTION = true;
private static final Logger logger = LoggerFactory.getLogger(SyncService.class);
private final SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
@Autowired
TabsSIService tabsSIService;
@Autowired
TimeCardsReportingService timeCardsReportingService;
@Autowired
LeavesService leavesService;
@Autowired
LeavesMapper leavesMapper;
@Autowired
PersOrarioService persOrarioService;
@Autowired
PersOrarioMapper persOrarioMapper;
@Autowired
SIMasterLogService siMasterLogService;
@Autowired
SIAnagraficoService siAnagraficoService;
@Autowired
SITelefoniService siTelefoniService;
@Autowired
SIEmailService siEmailService;
@Autowired
SIGruppiService siGruppiService;
@Autowired
SIGruppiPersService siGruppiPersService;
@Autowired
SICartelliniService siCartelliniService;
@Autowired
SICartelliniRendicontazioniService siCartelliniRendicontazioniService;
@Autowired
SIOrarioService siOrarioService;
@Autowired
SILavoroFuoriSedeService siLavoroFuoriSedeService;
@Autowired
SIAspettativeService siAspettativeService;
@Autowired
SIPersOrarioService siPersOrarioService;
@Autowired
EPASPersonsService epasPersonsService;
@Autowired
EPASPersonsMapper epasPersonsMapper;
@Autowired
EPASGroupsService epasGroupsService;
@Autowired
EPASAffiliationsService epasAffiliationsService;
@Autowired
EPASWorkingTimeTypesService epasWorkingTimeTypesService;
@Autowired
EPASTimeCardsService epasTimeCardsService;
@Autowired
EPASValidatesService epasValidatesService;
@Autowired
EPASOffSiteWorksService epasOffSiteWorksService;
@Autowired
EPASAbsenceTypesService epasAbsenceTypeService;
@Autowired
EPASLeavesService epasLeavesService;
@Autowired
EPASPersonWorkingTimeService epasPersonWorkingTimeService;
private boolean banagrafico;
private boolean bemail;
private boolean btelefoni;
private boolean bgruppi;
private boolean bgruppo_pers;
// private boolean bposizioni;
// private boolean bproroghe;
private boolean borario;
private boolean bcartellini;
private boolean bcartellini_rendicontazioni;
private boolean bpers_orario;
private boolean blavoro_fuori_sede;
private boolean baspettative;
private void setBReadTables() {
banagrafico = false;
bemail = false;
btelefoni = false;
bgruppi = false;
bgruppo_pers = false;
}
private void setBWriteTables() {
bcartellini = false;
bcartellini_rendicontazioni = false;
borario = false;
bpers_orario = false;
blavoro_fuori_sede = false;
baspettative = false;
}
public void executeReads() throws Exception {
setBReadTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
siMasterLogService.startFluxReads();
readData(tabsSI);
siMasterLogService.closeFluxReads(readTabs());
}
public void executeWrites(String year, String month) throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writeData(fluxId, tabsSI, year, month);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
public void executeWritesScheduled(String year, String month) throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writeScheduledData(fluxId, tabsSI, year, month);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
public void executeWritesOrario() throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writeOrarioData(fluxId, tabsSI);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
public void executeWritesTimeCards(String year, String month) throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writeTimeCardsData(fluxId, tabsSI, year, month);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
public void executeWritesSingleTimeCards(String year, String month, String fc) throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writeSingleTimeCardsData(fluxId, tabsSI, year, month, fc);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
public void executeWritesOffSiteWorks(String year, String month) throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writeOffSiteWorksData(fluxId, tabsSI, year, month);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
public void executeWritesLeaves(String year, String month) throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writeLeavesData(fluxId, tabsSI, year, month);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
public void executeWritesPersonWorkingTime(String year, String month) throws Exception {
setBWriteTables();
List<TabsSI> tabsSI = tabsSIService.getAllTabsSI();
Long fluxId = siMasterLogService.startFluxWrites();
writePersonWorkingTimeData(fluxId, tabsSI, year, month);
siMasterLogService.closeFluxWrites(fluxId, writeTabs());
}
private void readData(List<TabsSI> tabsSI) {
// TabsSI posizioniTab = null;
// TabsSI prorogheTab = null;
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("R") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
case "anagrafico":
syncAnagrafico(tab);
break;
case "mail":
syncMail(tab);
break;
case "telefoni":
syncTelefoni(tab);
break;
case "gruppi":
syncGruppi(tab);
break;
case "gruppo_pers":
syncGruppoPers(tab);
break;
// case "posizioni":
// posizioniTab = tab;
// break;
// case "proroghe":
// prorogheTab = tab;
// break;
default:
break;
}
}
}
// if (posizioniTab != null || prorogheTab != null) {
// syncPosizioniAndProroghe(posizioniTab, prorogheTab);
// }
}
private void syncAnagrafico(TabsSI tab) {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
long maxIdFlusso = 0;
List<SIAnagrafico> sianList = siAnagraficoService.readNewFlux(tab.getIdFlusso());
for (SIAnagrafico sia : sianList) {
if (sia.getId_flusso() != null && sia.getId_flusso().longValue() > maxIdFlusso) {
maxIdFlusso = sia.getId_flusso();
}
if (sia.getCodicefiscale() != null && !sia.getCodicefiscale().isEmpty()) {
if (sia.getFlag_del() != null && !sia.getFlag_del().isEmpty()) {
if (sia.getFlag_del().compareTo(SI_FLAG_DEL_TRUE) != 0) {
EPASPersons epasPerson = null;
try {
epasPerson = epasPersonsService.getByFiscalCode(sia.getCodicefiscale());
} catch (Exception e) {
logger.error("Error retrieving person by fiscal code: {}", sia.getCodicefiscale());
logger.error(e.getLocalizedMessage(), e);
}
if (epasPerson == null) {
EPASPersonsDTO epasPersonsDTO = new EPASPersonsDTO();
epasPersonsDTO.setFiscalCode(sia.getCodicefiscale());
epasPersonsDTO.setName(sia.getNome());
epasPersonsDTO.setSurname(sia.getCognome());
epasPersonsDTO.setOfficeId(ISTI_OFFICE_ID);
String email = createCNREmail(sia);
epasPersonsDTO.setEmail(email);
epasPersonsDTO.setQualification(PERSON_DEFAULT_QUALIFICATION);
try {
epasPerson = epasPersonsService.create(epasPersonsDTO);
logger.info("EPAS Created Person: {}", epasPerson);
} catch (Exception e) {
logger.error("Error creating person: {}", epasPersonsDTO);
logger.error(e.getLocalizedMessage(), e);
}
} else {
EPASPersonsDTO epasPersonsDTO = epasPersonsMapper.epasPersonsToEPASPersonsDTO(epasPerson);
epasPersonsDTO.setName(sia.getNome());
epasPersonsDTO.setSurname(sia.getCognome());
epasPersonsService.updateByFiscalCode(epasPersonsDTO.getFiscalCode(), epasPersonsDTO);
logger.info("EPAS Updated Person: {}", epasPersonsDTO);
}
}
}
}
}
if (maxIdFlusso > 0) {
banagrafico = true;
tab.setIdFlusso(maxIdFlusso);
tab.setLastUpdate(LocalDateTime.now());
tabsSIService.updateTabsSI(tab);
}
}
private String createCNREmail(SIAnagrafico sia) {
StringBuilder cnrEmail = new StringBuilder();
if (sia.getNome() != null && !sia.getNome().isEmpty()) {
String nome = sia.getNome();
if (!Normalizer.isNormalized(sia.getNome(), Normalizer.Form.NFKD)) {
nome = Normalizer.normalize(sia.getNome(), Normalizer.Form.NFKD).replaceAll("\\p{M}", "");
}
cnrEmail.append(nome.toLowerCase());
if (sia.getCognome() != null && !sia.getCognome().isEmpty()) {
String cognome = sia.getCognome();
if (!Normalizer.isNormalized(sia.getCognome(), Normalizer.Form.NFKD)) {
cognome = Normalizer.normalize(sia.getCognome(), Normalizer.Form.NFKD).replaceAll("\\p{M}", "");
}
cnrEmail.append(".");
cnrEmail.append(cognome.toLowerCase().trim());
}
} else {
if (sia.getCognome() != null && !sia.getCognome().isEmpty()) {
String cognome = sia.getCognome();
if (!Normalizer.isNormalized(sia.getCognome(), Normalizer.Form.NFKD)) {
cognome = Normalizer.normalize(sia.getCognome(), Normalizer.Form.NFKD).replaceAll("\\p{M}", "");
}
cnrEmail.append(cognome.toLowerCase().trim());
} else {
cnrEmail.append("empty");
}
}
cnrEmail.append("@cnr.it");
try {
InternetAddress emailAddr = new InternetAddress(cnrEmail.toString());
emailAddr.validate();
} catch (AddressException ex) {
cnrEmail = new StringBuilder();
cnrEmail.append("empty@cnr.it");
}
logger.debug("Created CNR email: {}", cnrEmail.toString());
return cnrEmail.toString();
}
private void syncMail(TabsSI tab) {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
long maxIdFlusso = 0;
List<SIEmail> seList = siEmailService.readNewFlux(tab.getIdFlusso());
for (SIEmail se : seList) {
if (se.getId_flusso() != null && se.getId_flusso().longValue() > maxIdFlusso) {
maxIdFlusso = se.getId_flusso();
}
if (se.getCf() != null && !se.getCf().isEmpty()) {
if (se.getFlag_del() != null && !se.getFlag_del().isEmpty()) {
if (se.getFlag_del().compareTo(SI_FLAG_DEL_TRUE) != 0) {
if (se.getTipo() != null && !se.getTipo().isEmpty()) {
String emailTipo = se.getTipo().trim();
if (!emailTipo.isEmpty()) {
EPASPersons epasPerson = null;
try {
epasPerson = epasPersonsService.getByFiscalCode(se.getCf());
} catch (Exception e) {
logger.error("Error retrieving person by fiscal code: {}", se.getCf());
logger.error(e.getLocalizedMessage(), e);
}
if (epasPerson != null) {
EPASPersonsDTO epasPersonsDTO = epasPersonsMapper
.epasPersonsToEPASPersonsDTO(epasPerson);
switch (emailTipo) {
// case SI_TIPO_EMAIL_ISTITUZIONALE:
// epasPersonsDTO.setEmail(se.getEmail());
// epasPersonsService.updateByFiscalCode(epasPersonsDTO.getFiscalCode(),
// epasPersonsDTO);
// log.info("EPAS Updated Person: {}", epasPersonsDTO);
//
// break;
case SI_TIPO_EMAIL_CNR:
epasPersonsDTO.setEmail(se.getEmail());
epasPersonsDTO.setEppn(se.getEmail());
epasPersonsService.updateByFiscalCode(epasPersonsDTO.getFiscalCode(),
epasPersonsDTO);
logger.info("EPAS Updated Person: {}", epasPersonsDTO);
break;
default:
break;
}
}
}
}
}
}
}
}
if (maxIdFlusso > 0) {
bemail = true;
tab.setIdFlusso(maxIdFlusso);
tab.setLastUpdate(LocalDateTime.now());
tabsSIService.updateTabsSI(tab);
}
}
private void syncTelefoni(TabsSI tab) {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.info("Invalid Id Flusso for tab: {}", tab);
return;
}
long maxIdFlusso = 0;
List<SITelefoni> sitList = siTelefoniService.readNewFlux(tab.getIdFlusso());
for (SITelefoni sit : sitList) {
if (sit.getId_flusso() != null && sit.getId_flusso().longValue() > maxIdFlusso) {
maxIdFlusso = sit.getId_flusso();
}
if (sit.getCf() != null && !sit.getCf().isEmpty()) {
if (sit.getFlag_del() != null && !sit.getFlag_del().isEmpty()) {
if (sit.getFlag_del().compareTo(SI_FLAG_DEL_TRUE) != 0) {
if (sit.getTiporecapitotelefonico() != null && !sit.getTiporecapitotelefonico().isEmpty()) {
String tipoRecapitoTelefonico = sit.getTiporecapitotelefonico().trim();
if (!tipoRecapitoTelefonico.isEmpty()) {
if (tipoRecapitoTelefonico.compareTo(SI_RECAPITO_TELEFONICO_UFFICIO) == 0) {
EPASPersons epasPerson = null;
try {
epasPerson = epasPersonsService.getByFiscalCode(sit.getCf());
} catch (Exception e) {
logger.error("Error retrieving person by fiscal code: {}", sit.getCf());
logger.error(e.getLocalizedMessage(), e);
}
if (epasPerson != null) {
EPASPersonsDTO epasPersonsDTO = epasPersonsMapper
.epasPersonsToEPASPersonsDTO(epasPerson);
epasPersonsDTO.setTelephone(sit.getRecapitotelefonico());
epasPersonsService.updateByFiscalCode(epasPersonsDTO.getFiscalCode(),
epasPersonsDTO);
logger.info("EPAS Updated Person: {}", epasPersonsDTO);
}
}
}
}
}
}
}
}
if (maxIdFlusso > 0) {
btelefoni = true;
tab.setIdFlusso(maxIdFlusso);
tab.setLastUpdate(LocalDateTime.now());
tabsSIService.updateTabsSI(tab);
}
}
private void syncGruppi(TabsSI tab) {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.info("Invalid Id Flusso for tab: {}", tab);
return;
}
long maxIdFlusso = 0;
List<SIGruppi> sigList = siGruppiService.readNewFlux(tab.getIdFlusso());
for (SIGruppi sig : sigList) {
if (sig.getId_flusso() != null && sig.getId_flusso().longValue() > maxIdFlusso) {
maxIdFlusso = sig.getId_flusso();
}
if (sig.getId() != null && sig.getId() != 0) {
if (sig.getFlag_del() != null && !sig.getFlag_del().isEmpty()) {
if (sig.getFlag_del().compareTo(SI_FLAG_DEL_TRUE) != 0) {
List<EPASGroups> epasGroups = epasGroupsService.getList(ISTI_OFFICE_ID);
if (epasGroups != null) {
EPASGroups groupPresent = null;
for (EPASGroups g : epasGroups) {
if (g.getExternalId() != null && !g.getExternalId().isEmpty()) {
Integer gExternalId=null;
try {
gExternalId=Integer.valueOf(g.getExternalId());
} catch (NumberFormatException e) {
logger.error("EPAS Group has invalid External Id: {}", g);
}
if (gExternalId!=null&&gExternalId.compareTo(sig.getId()) == 0) {
groupPresent = g;
break;
}
}
}
if (groupPresent == null) {
EPASGroupsDTO epasGroupsDTO = new EPASGroupsDTO(sig.getDescrizione(), null,
String.valueOf(sig.getId()), null, null, sig.getSigla(), ISTI_OFFICE_ID);
EPASGroups epasGroup = epasGroupsService.create(epasGroupsDTO);
logger.info("EPAS Created Group: {}", epasGroup);
} else {
EPASGroupsMapper epasGroupsMapper = new EPASGroupsMapper();
EPASGroupsDTO epasGroupsDTO = epasGroupsMapper.epasGroupsToEPASGroupsDTO(groupPresent);
epasGroupsDTO.setDescription(sig.getDescrizione());
epasGroupsDTO.setName(sig.getSigla());
if (epasGroupsDTO.getOfficeId() == null || epasGroupsDTO.getOfficeId().isEmpty()) {
epasGroupsDTO.setOfficeId(ISTI_OFFICE_ID);
}
epasGroupsService.updateById(groupPresent.getId(), epasGroupsDTO);
logger.info("EPAS Updated Group: {}", epasGroupsDTO);
}
} else {
EPASGroupsDTO epasGroupsDTO = new EPASGroupsDTO(sig.getDescrizione(), null,
String.valueOf(sig.getId()), null, null, sig.getSigla(), ISTI_OFFICE_ID);
EPASGroups epasGroup = epasGroupsService.create(epasGroupsDTO);
logger.info("EPAS Created Group: {}", epasGroup);
}
} else {
List<EPASGroups> epasGroups = epasGroupsService.getList(ISTI_OFFICE_ID);
if (epasGroups != null) {
EPASGroups groupPresent = null;
for (EPASGroups g : epasGroups) {
if (Integer.valueOf(g.getExternalId()).compareTo(sig.getId()) == 0) {
groupPresent = g;
break;
}
}
if (groupPresent != null) {
Date endDate = new Date();
if (sig.getData_mod() != null) {
endDate.setTime(sig.getData_mod().getTime());
groupPresent.setEndDate(sdfDate.format(endDate));
EPASGroupsMapper epasGroupsMapper = new EPASGroupsMapper();
EPASGroupsDTO epasGroupsDTO = epasGroupsMapper
.epasGroupsToEPASGroupsDTO(groupPresent);
if (epasGroupsDTO.getOfficeId() == null || epasGroupsDTO.getOfficeId().isEmpty()) {
epasGroupsDTO.setOfficeId(ISTI_OFFICE_ID);
}
epasGroupsService.updateById(groupPresent.getId(), epasGroupsDTO);
logger.info("EPAS Delete Group: {}", epasGroupsDTO);
}
}
}
}
}
}
}
if (maxIdFlusso > 0) {
bgruppi = true;
tab.setIdFlusso(maxIdFlusso);
tab.setLastUpdate(LocalDateTime.now());
tabsSIService.updateTabsSI(tab);
}
}
private void syncGruppoPers(TabsSI tab) {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.info("Invalid Id Flusso for tab: {}", tab);
return;
}
long maxIdFlusso = 0;
List<SIGruppiPers> sigList = siGruppiPersService.readNewFlux(tab.getIdFlusso());
for (SIGruppiPers sigp : sigList) {
if (sigp.getId_flusso() != null && sigp.getId_flusso().longValue() > maxIdFlusso) {
maxIdFlusso = sigp.getId_flusso();
}
if (sigp.getId() != null && sigp.getId() != 0) {
if (sigp.getFlag_del() != null && !sigp.getFlag_del().isEmpty()) {
if (sigp.getFlag_del().compareTo(SI_FLAG_DEL_TRUE) != 0) {
List<EPASAffiliations> epasAffiliations = null;
try {
epasAffiliations = epasAffiliationsService.getByPersonFiscalcode(sigp.getCf());
} catch (Exception e) {
logger.error("Error retrieving Affiliations for fiscalcode: {}", sigp.getCf());
logger.error(e.getLocalizedMessage(), e);
}
if (epasAffiliations != null) {
gestisciDipendenteGiaAffiliato(sigp, epasAffiliations);
} else {
gestisciDipendenteNonAffiliato(sigp);
}
} else {
rimuoviAffiliazione(sigp);
}
}
}
}
if (maxIdFlusso > 0) {
bgruppo_pers = true;
tab.setIdFlusso(maxIdFlusso);
tab.setLastUpdate(LocalDateTime.now());
tabsSIService.updateTabsSI(tab);
}
}
private void rimuoviAffiliazione(SIGruppiPers sigp) {
logger.debug("Rimuovi Affiliazione");
List<EPASAffiliations> epasAffiliations = null;
try {
epasAffiliations = epasAffiliationsService.getByPersonFiscalcode(sigp.getCf());
} catch (Exception e) {
logger.error("Error retrieving Affiliations for fiscal code: {}", sigp.getCf());
logger.error(e.getLocalizedMessage(), e);
}
if (epasAffiliations != null) {
EPASAffiliations affPresent = null;
for (EPASAffiliations aff : epasAffiliations) {
if (aff.getExternalId() != null && !aff.getExternalId().isEmpty()) {
Integer affId = 0;
try {
affId = Integer.valueOf(aff.getExternalId());
} catch (NumberFormatException e) {
logger.error("Invalid aff external id: {} ", aff.getExternalId());
}
if (affId.compareTo(sigp.getId()) == 0) {
affPresent = aff;
break;
}
}
}
if (affPresent != null) {
EPASAffiliationsMapper epasAffiliationsMapper = new EPASAffiliationsMapper();
EPASAffiliationsDTO epasAffiliationsDTO = epasAffiliationsMapper
.epasAffiliationsToEPASAffiliationsDTO(affPresent);
epasAffiliationsDTO.setEndDate(sdfDate.format(sigp.getAl()));
epasAffiliationsService.updateById(affPresent.getId(), epasAffiliationsDTO);
logger.info("EPAS Delete Affilation: {}", epasAffiliationsDTO);
}
}
}
private void gestisciDipendenteNonAffiliato(SIGruppiPers sigp) {
logger.debug("Aggiungi dipendente non affiliato");
List<EPASGroups> epasGroups = epasGroupsService.getList(ISTI_OFFICE_ID);
EPASGroups groupPresent = null;
if (epasGroups != null) {
for (EPASGroups g : epasGroups) {
if (g.getExternalId() != null && !g.getExternalId().isEmpty()) {
Integer gId = 0;
try {
gId = Integer.valueOf(g.getExternalId());
} catch (NumberFormatException e) {
logger.error("Invalid external id: {} ", g.getExternalId());
}
if (gId.compareTo(sigp.getId()) == 0) {
groupPresent = g;
break;
}
}
}
if (groupPresent != null) {
EPASPersons epasPerson = null;
try {
epasPerson = epasPersonsService.getByFiscalCode(sigp.getCf());
} catch (Exception e) {
logger.error("Error retrieving person by fiscal code: {}", sigp.getCf());
logger.error(e.getLocalizedMessage(), e);
}
if (epasPerson != null) {
EPASAffiliationsDTO epasAffiliationsDTO = new EPASAffiliationsDTO(sdfDate.format(sigp.getDal()),
sdfDate.format(sigp.getAl()), groupPresent.getId(), null,
String.valueOf(sigp.getPercentuale()), epasPerson.getId(), String.valueOf(sigp.getId()));
EPASAffiliations epasAffiliationNew = epasAffiliationsService.create(epasAffiliationsDTO);
logger.info("EPAS Created Affilation: {}", epasAffiliationNew);
}
}
}
}
private void gestisciDipendenteGiaAffiliato(SIGruppiPers sigp, List<EPASAffiliations> epasAffiliations) {
logger.debug("Aggiungi dipendente già affiliato");
EPASAffiliations affPresent = null;
for (EPASAffiliations aff : epasAffiliations) {
if (aff.getExternalId() != null && !aff.getExternalId().isEmpty()) {
Integer affId = 0;
try {
affId = Integer.valueOf(aff.getExternalId());
} catch (NumberFormatException e) {
logger.error("Invalid aff external id: {} ", aff.getExternalId());
}
if (affId.compareTo(sigp.getId()) == 0) {
affPresent = aff;
break;
}
}
}
if (affPresent != null) {
List<EPASGroups> epasGroups = epasGroupsService.getList(ISTI_OFFICE_ID);
EPASGroups groupPresent = null;
if (epasGroups != null) {
for (EPASGroups g : epasGroups) {
if (g.getExternalId() != null && !g.getExternalId().isEmpty()) {
Integer gId = 0;
try {
gId = Integer.valueOf(g.getExternalId());
} catch (NumberFormatException e) {
logger.error("Invalid external id: {} ", g.getExternalId());
}
if (gId.compareTo(sigp.getId()) == 0) {
groupPresent = g;
break;
}
}
}
if (groupPresent != null) {
EPASPersons epasPerson = null;
try {
epasPerson = epasPersonsService.getByFiscalCode(sigp.getCf());
} catch (Exception e) {
logger.error("Error retrieving person by fiscal code: {}", sigp.getCf());
logger.error(e.getLocalizedMessage(), e);
}
if (epasPerson != null) {
EPASAffiliationsDTO epasAffiliationsDTO = new EPASAffiliationsDTO(sdfDate.format(sigp.getDal()),
sdfDate.format(sigp.getAl()), groupPresent.getId(), null,
String.valueOf(sigp.getPercentuale()), epasPerson.getId(),
String.valueOf(sigp.getId()));
epasAffiliationsService.updateById(affPresent.getId(), epasAffiliationsDTO);
logger.info("EPAS Updated Affilation: {}", epasAffiliationsDTO);
}
}
}
} else {
gestisciDipendenteNonAffiliato(sigp);
}
}
private String readTabs() {
String readTabs = "";
if (banagrafico) {
if (readTabs == null || readTabs.isEmpty()) {
readTabs = "anagrafico";
} else {
readTabs = readTabs + ",anagrafico";
}
}
if (bemail) {
if (readTabs == null || readTabs.isEmpty()) {
readTabs = "mail";
} else {
readTabs = readTabs + ",mail";
}
}
if (btelefoni) {
if (readTabs == null || readTabs.isEmpty()) {
readTabs = "telefoni";
} else {
readTabs = readTabs + ",telefoni";
}
}
if (bgruppi) {
if (readTabs == null || readTabs.isEmpty()) {
readTabs = "gruppi";
} else {
readTabs = readTabs + ",gruppi";
}
}
if (bgruppo_pers) {
if (readTabs == null || readTabs.isEmpty()) {
readTabs = "gruppo_pers";
} else {
readTabs = readTabs + ",gruppo_pers";
}
}
/*
* if (bposizioni) { if (tabelle_lette == null || tabelle_lette.isEmpty()) {
* tabelle_lette = "posizioni"; } else { tabelle_lette = tabelle_lette +
* ",posizioni"; } }
*
* if (bproroghe) { if (tabelle_lette == null || tabelle_lette.isEmpty()) {
* tabelle_lette = "proroghe"; } else { tabelle_lette = tabelle_lette +
* ",proroghe"; } }
*/
return readTabs;
}
private String writeTabs() {
String writeTabs = "";
if (borario) {
if (writeTabs == null || writeTabs.isEmpty()) {
writeTabs = "epas_orario";
} else {
writeTabs = writeTabs + ",epas_orario";
}
}
if (bcartellini) {
if (writeTabs == null || writeTabs.isEmpty()) {
writeTabs = "epas_cartellini";
} else {
writeTabs = writeTabs + ",epas_cartellini";
}
}
if (bcartellini_rendicontazioni) {
if (writeTabs == null || writeTabs.isEmpty()) {
writeTabs = "epas_cartellini_rendicontazioni";
} else {
writeTabs = writeTabs + ",epas_cartellini_rendicontazioni";
}
}
if (bpers_orario) {
if (writeTabs == null || writeTabs.isEmpty()) {
writeTabs = "epas_pers_orario";
} else {
writeTabs = writeTabs + ",epas_pers_orario";
}
}
if (blavoro_fuori_sede) {
if (writeTabs == null || writeTabs.isEmpty()) {
writeTabs = "epas_lavoro_fuori_sede";
} else {
writeTabs = writeTabs + ",epas_lavoro_fuori_sede";
}
}
if (baspettative) {
if (writeTabs == null || writeTabs.isEmpty()) {
writeTabs = "epas_aspettative";
} else {
writeTabs = writeTabs + ",epas_aspettative";
}
}
return writeTabs;
}
private void writeScheduledData(Long fluxId, List<TabsSI> tabsSI, String year, String month) throws Exception {
logger.info("Report {}-{}", year, month);
LocalDateTime now = LocalDateTime.now();
// checkValidMonthToSend(year, month);
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
case "aspettative":
syncAspettative(fluxId, tab, year, month, now);
break;
case "orario":
syncOrario(fluxId, tab);
break;
case "pers_orario":
syncPersOrario(fluxId, tab, year, month, now);
break;
default:
break;
}
}
}
}
private void writeOrarioData(Long fluxId, List<TabsSI> tabsSI) {
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
case "orario":
syncOrario(fluxId, tab);
break;
default:
break;
}
}
}
}
private void writeData(Long fluxId, List<TabsSI> tabsSI, String year, String month) throws Exception {
logger.info("Report {}-{}", year, month);
LocalDateTime now = LocalDateTime.now();
checkValidMonthToSend(year, month);
TimeCardsReporting timeCardsReporting = createTimeCardReporting(fluxId, year, month, now);
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
// case "orario":
// syncOrario(fluxId, tab);
// break;
// case "pers_orario":
// syncPersOrario(fluxId,tab);
// break;
case "cartellini":
break;
case "cartellini_rendicontazioni":
syncCartelliniRendicontazioni(fluxId, tab, year, month, now, timeCardsReporting);
break;
case "lavoro_fuori_sede":
syncLavoroFuoriSede(fluxId, tab, year, month, now);
break;
// case "aspettative":
// syncAspettative(fluxId,tab);
// break;
default:
break;
}
}
}
}
private void writeTimeCardsData(Long fluxId, List<TabsSI> tabsSI, String year, String month) throws Exception {
logger.info("Report {}-{}", year, month);
LocalDateTime now = LocalDateTime.now();
checkValidMonthToSend(year, month);
TimeCardsReporting timeCardsReporting = createTimeCardReporting(fluxId, year, month, now);
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
// case "orario":
// syncOrario(fluxId, tab);
// break;
// case "pers_orario":
// syncPersOrario(fluxId,tab);
// break;
case "cartellini":
break;
case "cartellini_rendicontazioni":
syncCartelliniRendicontazioni(fluxId, tab, year, month, now, timeCardsReporting);
break;
// case "lavoro_fuori_sede":
// syncLavoroFuoriSede(fluxId,tab);
// break;
// case "aspettative":
// syncAspettative(fluxId,tab);
// break;
default:
break;
}
}
}
}
private void writeSingleTimeCardsData(Long fluxId, List<TabsSI> tabsSI, String year, String month, String fc)
throws Exception {
logger.info("Report {}-{}", year, month);
logger.info("FiscalCode: {}", fc);
LocalDateTime now = LocalDateTime.now();
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
case "cartellini":
syncSingleCartellino(fluxId, tab, year, month, now, fc);
break;
default:
break;
}
}
}
}
private void writeOffSiteWorksData(Long fluxId, List<TabsSI> tabsSI, String year, String month) throws Exception {
logger.info("Report {}-{}", year, month);
LocalDateTime now = LocalDateTime.now();
// checkValidMonthToSend(year, month);
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
case "lavoro_fuori_sede":
syncLavoroFuoriSede(fluxId, tab, year, month, now);
break;
default:
break;
}
}
}
}
private void writeLeavesData(Long fluxId, List<TabsSI> tabsSI, String year, String month) throws Exception {
logger.info("Report {}-{}", year, month);
LocalDateTime now = LocalDateTime.now();
// checkValidMonthToSend(year, month);
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
case "aspettative":
syncAspettative(fluxId, tab, year, month, now);
break;
default:
break;
}
}
}
}
private void writePersonWorkingTimeData(Long fluxId, List<TabsSI> tabsSI, String year, String month)
throws Exception {
logger.info("Report {}-{}", year, month);
LocalDateTime now = LocalDateTime.now();
for (TabsSI tab : tabsSI) {
logger.info("TabSI: {}", tab);
if (tab.getOperazioni() != null && !tab.getOperazioni().isEmpty()
&& tab.getOperazioni().compareTo("W") == 0) {
if (tab.getNome() == null || tab.getNome().isEmpty()) {
continue;
}
switch (tab.getNome()) {
case "pers_orario":
syncPersOrario(fluxId, tab, year, month, now);
break;
default:
break;
}
}
}
}
private void syncOrario(Long fluxId, TabsSI tab) {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
LocalDateTime lastUpdate = tab.getLastUpdate();
LocalDateTime maxLastUpdate = null;
List<EPASWorkingTimeTypes> eWTTs = epasWorkingTimeTypesService.getListByOfficeCodeId(ISTI_OFFICE_CODEID);
for (EPASWorkingTimeTypes eWTT : eWTTs) {
// "2021-02-03T09:49:05.231072"
DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME).optionalStart().appendPattern(".SSSSSS")
.optionalEnd().optionalStart().appendZoneOrOffsetId().optionalEnd().toFormatter();
if (eWTT.getUpdatedAt() != null && !eWTT.getUpdatedAt().isEmpty()) {
LocalDateTime updatedAt = LocalDateTime.parse(eWTT.getUpdatedAt(), formatter);
if (lastUpdate.compareTo(updatedAt) < 0) {
LocalDateTime dMod = updatedAt.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
SIOrario siOrario = new SIOrario(Long.valueOf(eWTT.getId()), eWTT.getDescription(),
Boolean.valueOf(eWTT.getHorizontal()), Boolean.valueOf(eWTT.getDisabled()), dataMod,
SI_FLAG_DEL_FALSE, fluxId);
siOrarioService.writeNewFlux(fluxId, siOrario);
if (maxLastUpdate == null) {
maxLastUpdate = updatedAt;
} else {
if (maxLastUpdate.compareTo(updatedAt) < 0) {
maxLastUpdate = updatedAt;
}
}
}
}
}
if (maxLastUpdate != null) {
borario = true;
tab.setIdFlusso(fluxId);
tab.setLastUpdate(maxLastUpdate);
tabsSIService.updateTabsSI(tab);
}
}
private void syncLavoroFuoriSede(Long fluxId, TabsSI tab, String year, String month, LocalDateTime now)
throws Exception {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
logger.info("Reference: {}-{}", year, month);
List<EPASOffSiteWorks> epasOffSiteWorksList = epasOffSiteWorksService.getListByOfficeCodeId(ISTI_OFFICE_CODEID,
year, month);
if (epasOffSiteWorksList == null || epasOffSiteWorksList.isEmpty()) {
logger.info("OffSiteWorks not found for: {} - {} ", year, month);
return;
}
// "2021-02-03T09:49:05.231072"
DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME).optionalStart().appendPattern(".SSSSSS").optionalEnd()
.optionalStart().appendZoneOrOffsetId().optionalEnd().toFormatter();
// SI
for (EPASOffSiteWorks offSiteWorks : epasOffSiteWorksList) {
logger.info("Writing OffSiteWorks: {}", offSiteWorks);
if (offSiteWorks == null || offSiteWorks.getPerson() == null) {
logger.error("Invalid Off Site Works: {}", offSiteWorks);
continue;
}
if (offSiteWorks.getPerson().getFiscalCode() == null
|| offSiteWorks.getPerson().getFiscalCode().isEmpty()) {
logger.error("Invalid FiscalCode: {}", offSiteWorks.getPerson().getFiscalCode());
continue;
} else {
logger.debug("FiscalCode: {}", offSiteWorks.getPerson().getFiscalCode());
}
Integer idPersona = 0;
try {
idPersona = Integer.valueOf(offSiteWorks.getPerson().getId());
} catch (NumberFormatException e) {
logger.error("Invalid Person Id: {}", offSiteWorks.getPerson().getId());
continue;
}
logger.debug("Date: {}", offSiteWorks.getDate());
java.sql.Date date = null;
try {
date = java.sql.Date.valueOf(offSiteWorks.getDate());
} catch (Exception e) {
logger.error("Invalid date format: {}", offSiteWorks.getDate());
continue;
}
for (EPASStampings epasStamping : offSiteWorks.getStampings()) {
if (epasStamping == null) {
logger.error("Invalid Stamping: {}", epasStamping);
continue;
}
if (epasStamping.getStampType() != null && !epasStamping.getStampType().isEmpty()
&& epasStamping.getStampType().compareTo("lavoroFuoriSede") == 0) {
logger.debug("Stamping Type: {}", epasStamping.getStampType());
Long id = 0L;
try {
id = Long.valueOf(epasStamping.getId());
} catch (NumberFormatException e) {
logger.error("Invalid id for stamping: {}", e.getLocalizedMessage(), e);
continue;
}
logger.debug("Stamping Data: {}", epasStamping.getDate());
Timestamp dataMod;
try {
LocalDateTime dMod = LocalDateTime.parse(epasStamping.getDate(), formatter);
dMod = dMod.truncatedTo(ChronoUnit.SECONDS);
dataMod = Timestamp.valueOf(dMod);
} catch (IllegalArgumentException | DateTimeParseException e) {
logger.error("Invalid stamping data format: {}", e.getLocalizedMessage(), e);
continue;
}
logger.debug("DataMod: {}", dataMod);
SILavoroFuoriSede siLavoroFuoriSede = new SILavoroFuoriSede(id, idPersona,
offSiteWorks.getPerson().getFiscalCode(), date, epasStamping.getPlace(),
epasStamping.getReason(), epasStamping.getWay(), dataMod, SI_FLAG_DEL_FALSE, fluxId);
siLavoroFuoriSedeService.writeNewFlux(fluxId, siLavoroFuoriSede);
}
}
}
logger.info("SILavoroFuoriSede Updated");
blavoro_fuori_sede = true;
tab.setIdFlusso(fluxId);
tab.setLastUpdate(now);
tabsSIService.updateTabsSI(tab);
}
private void syncAspettative(Long fluxId, TabsSI tab, String year, String month, LocalDateTime now)
throws Exception {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
logger.info("Reference: {}-{}", year, month);
Integer nextYear = 0;
try {
nextYear = Integer.parseInt(year);
} catch (Exception e) {
logger.error("Invalid year parameter: {}", year);
return;
}
nextYear = nextYear + 1;
logger.debug("Next Year: {}", nextYear.toString());
List<EPASLeaves> epasLeavesList = epasLeavesService.getLeavesByOfficeId(ISTI_OFFICE_ID, year, "true");
logger.debug("Current Year Leaves: {}", epasLeavesList);
List<EPASLeaves> epasLeavesNextList = epasLeavesService.getLeavesByOfficeId(ISTI_OFFICE_ID, nextYear.toString(),
"true");
logger.debug("Next Year Leaves: {}", epasLeavesNextList);
if (epasLeavesList == null || epasLeavesList.isEmpty()) {
logger.debug("Leaves not found for: {}", year);
epasLeavesList = new LinkedList<>();
}
if (epasLeavesNextList == null || epasLeavesNextList.isEmpty()) {
logger.debug("Leaves not found for: {}", nextYear);
epasLeavesNextList = new LinkedList<>();
}
epasLeavesList.addAll(epasLeavesNextList);
if (epasLeavesList.isEmpty()) {
logger.info("Leaves not found");
return;
}
LinkedHashMap<String, EPASAbsenceTypes> epasAbsenceTypeMap = epasAbsenceTypeService.getAbsenceTypesMapFull();
if (epasAbsenceTypeMap == null || epasAbsenceTypeMap.isEmpty()) {
logger.error("Absence Type Map not found");
return;
}
writeAspettativeOnSI(fluxId, now, epasLeavesList, epasAbsenceTypeMap);
logger.info("SIAspettative Updated");
baspettative = true;
tab.setIdFlusso(fluxId);
tab.setLastUpdate(now);
tabsSIService.updateTabsSI(tab);
}
private void writeAspettativeOnSI(Long fluxId, LocalDateTime now, List<EPASLeaves> epasLeavesList,
LinkedHashMap<String, EPASAbsenceTypes> epasAbsenceTypeMap) {
int count = 0;
// SI
for (EPASLeaves leave : epasLeavesList) {
logger.debug("Writing Leave: {}", leave);
if (leave == null || leave.getPerson() == null) {
logger.error("Invalid Leave: {}", leave);
continue;
}
if (leave.getPerson().getFiscalCode() == null || leave.getPerson().getFiscalCode().isEmpty()) {
logger.error("Invalid FiscalCode: {}", leave.getPerson().getFiscalCode());
continue;
} else {
logger.debug("FiscalCode: {}", leave.getPerson().getFiscalCode());
}
Integer idPersona = 0;
try {
idPersona = Integer.valueOf(leave.getPerson().getId());
} catch (NumberFormatException e) {
logger.error("Invalid Person Id: {}", leave.getPerson().getId());
continue;
}
if (leave.getCode() == null || leave.getCode().isEmpty()) {
logger.error("Invalid absence code: {}", leave.getCode());
continue;
}
EPASAbsenceTypes epasAbsenceType = epasAbsenceTypeMap.get(leave.getCode());
if (epasAbsenceType == null) {
logger.error("Not found absence type: {}", leave.getCode());
continue;
}
Integer absenceId = 0;
try {
absenceId = Integer.parseInt(epasAbsenceType.getId());
} catch (NumberFormatException e) {
logger.error("Not found absence id for absence: {}", leave.getCode());
continue;
}
logger.debug("Start Date: {}", leave.getStart());
java.sql.Date startDate = null;
if (leave.getStart() == null || leave.getStart().isEmpty()) {
logger.error("Invalid start date: {}", leave.getStart());
continue;
}
try {
startDate = java.sql.Date.valueOf(leave.getStart());
} catch (Exception e) {
logger.error("Invalid start date format: {}", leave.getStart());
continue;
}
logger.debug("End Date: {}", leave.getEnd());
java.sql.Date endDate = null;
if (leave.getEnd() != null && !leave.getEnd().isEmpty()) {
try {
endDate = java.sql.Date.valueOf(leave.getEnd());
} catch (Exception e) {
logger.error("Invalid end date format: {}", leave.getEnd());
}
}
LocalDateTime dMod = now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
Integer durata = 0;
if (startDate != null && endDate != null) {
LocalDate startD = LocalDate.parse(leave.getStart());
LocalDate endD = LocalDate.parse(leave.getEnd());
durata = new Long(ChronoUnit.DAYS.between(startD, endD) + 1).intValue();
}
int id = 0;
if (leave.getAbsences() != null && leave.getAbsences().length > 0) {
EPASAbsences firstAbsence = leave.getAbsences()[0];
try {
id = Integer.parseInt(firstAbsence.getId());
} catch (NumberFormatException e) {
logger.error("Invalid id for first absence: {}", firstAbsence);
}
}
SIAspettative siAspettative = new SIAspettative(leave.getPerson().getFiscalCode(),
epasAbsenceType.getDescription(), startDate, endDate, dataMod, SI_FLAG_DEL_FALSE, fluxId, id,
idPersona, absenceId, epasAbsenceType.getCode(), durata);
if (checkSIAspettativeIsUpgradeable(siAspettative)) {
logger.info("Write SIAspettativa: {}", siAspettative);
count = count + 1;
siAspettativeService.writeNewFlux(fluxId, siAspettative);
}
}
logger.info("Aspettative scritte su SI: {}", count);
}
private boolean checkSIAspettativeIsUpgradeable(SIAspettative siAspettative) {
boolean upgradeable = false;
try {
Optional<Leaves> leaves = leavesService.getLeavesById(siAspettative.getId());
if (leaves.isPresent()) {
Leaves found = leaves.get();
Leaves leavesDTO = leavesMapper.siAspettativeToLeaves(siAspettative);
if (!found.same(leavesDTO)) {
upgradeable = true;
leavesService.updateLeaves(leavesDTO);
}
} else {
upgradeable = true;
Leaves leavesDTO = leavesMapper.siAspettativeToLeaves(siAspettative);
leavesService.createLeaves(leavesDTO);
}
} catch (Exception e) {
logger.error("Error in check SI Aspettative: {}", e.getLocalizedMessage(), e);
}
return upgradeable;
}
private void syncPersOrario(Long fluxId, TabsSI tab, String year, String month, LocalDateTime now)
throws Exception {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
logger.info("Reference: {}-{}", year, month);
List<EPASPersonWorkingTimeDTO> epasPersonWorkingTimeDTOList = epasPersonWorkingTimeService
.getList(ISTI_OFFICE_ID);
if (epasPersonWorkingTimeDTOList == null || epasPersonWorkingTimeDTOList.isEmpty()) {
logger.error("PersonWorkingTimeDTOList not found");
return;
} else {
logger.info("PersonWorkingTimeDTOList size: {}", epasPersonWorkingTimeDTOList.size());
}
int count = 0;
// SI
for (EPASPersonWorkingTimeDTO pwtDTO : epasPersonWorkingTimeDTOList) {
logger.info("Writing Person Working Time: {}", pwtDTO);
if (pwtDTO == null) {
logger.error("Invalid Person Working Time: {}", pwtDTO);
continue;
}
Integer id = 0;
if (pwtDTO.getId() == null || pwtDTO.getId().isEmpty()) {
logger.error("Invalid Id: {}", pwtDTO.getId());
continue;
} else {
logger.debug("Id: {}", pwtDTO.getId());
try {
id = Integer.parseInt(pwtDTO.getId());
} catch (NumberFormatException e) {
logger.error("Invalid Id: {}", pwtDTO.getId());
continue;
}
}
Integer idPersona = 0;
if (pwtDTO.getIdPersona() == null || pwtDTO.getIdPersona().isEmpty()) {
logger.error("Invalid Id Persona: {}", pwtDTO.getIdPersona());
continue;
} else {
logger.debug("Id Persona: {}", pwtDTO.getIdPersona());
try {
idPersona = Integer.parseInt(pwtDTO.getIdPersona());
} catch (NumberFormatException e) {
logger.error("Invalid Id Persona: {}", pwtDTO.getIdPersona());
continue;
}
}
if (pwtDTO.getCf() == null || pwtDTO.getCf().isEmpty()) {
logger.error("Invalid FiscalCode: {}", pwtDTO.getCf());
continue;
} else {
logger.debug("FiscalCode: {}", pwtDTO.getCf());
}
logger.debug("Dal: {}", pwtDTO.getDal());
if (pwtDTO.getDal() == null || pwtDTO.getDal().isEmpty()) {
logger.error("Invalid dal date: {}", pwtDTO.getDal());
continue;
}
java.sql.Date startDate = null;
try {
startDate = java.sql.Date.valueOf(pwtDTO.getDal());
} catch (Exception e) {
logger.error("Invalid dal date format: {}", pwtDTO.getDal());
continue;
}
logger.debug("Al: {}", pwtDTO.getAl());
java.sql.Date endDate = null;
if (pwtDTO.getAl() != null && !pwtDTO.getAl().isEmpty()) {
try {
endDate = java.sql.Date.valueOf(pwtDTO.getAl());
} catch (Exception e) {
logger.error("Invalid al date format: {}", pwtDTO.getAl());
}
}
LocalDateTime dMod = now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
SIPersOrario siPersOrario = new SIPersOrario(id, idPersona, pwtDTO.getCf(), startDate, endDate,
pwtDTO.getDescrizione(), pwtDTO.getLun(), pwtDTO.getMar(), pwtDTO.getMer(), pwtDTO.getGio(),
pwtDTO.getVen(), pwtDTO.getSab(), pwtDTO.getPercentuale(), pwtDTO.getTurno(), pwtDTO.getOre_turno(),
pwtDTO.getFestivo(), pwtDTO.getNotturno(), dataMod, SI_FLAG_DEL_FALSE, fluxId);
if (checkSIPersOrarioIsUpgradeable(siPersOrario)) {
logger.info("Write SIPersOrario: {}", siPersOrario);
count = count + 1;
siPersOrarioService.writeNewFlux(fluxId, siPersOrario);
}
}
logger.info("Personale Orario scritto su SI: {}", count);
logger.info("SIPersOrario Updated");
bpers_orario = true;
tab.setIdFlusso(fluxId);
tab.setLastUpdate(now);
tabsSIService.updateTabsSI(tab);
}
private boolean checkSIPersOrarioIsUpgradeable(SIPersOrario siPersOrario) {
boolean upgradeable = false;
try {
Optional<PersOrario> persOrario = persOrarioService.getPersOrarioById(siPersOrario.getId());
if (persOrario.isPresent()) {
PersOrario found = persOrario.get();
logger.debug("Found: {}", found);
PersOrario persOrarioDTO = persOrarioMapper.siPersOrarioToPersOrario(siPersOrario);
logger.debug("PersOrarioDTO: {}", persOrarioDTO);
if (!found.same(persOrarioDTO)) {
upgradeable = true;
persOrarioService.updatePersOrario(persOrarioDTO);
}
} else {
logger.debug("Not found PersOrario by id: {}", siPersOrario.getId());
upgradeable = true;
PersOrario persOrarioDTO = persOrarioMapper.siPersOrarioToPersOrario(siPersOrario);
persOrarioService.createPersOrario(persOrarioDTO);
}
} catch (Exception e) {
logger.error("Error in check SI Per Orario: {}", e.getLocalizedMessage(), e);
}
return upgradeable;
}
private void syncCartelliniRendicontazioni(Long fluxId, TabsSI tab, String year, String month, LocalDateTime now,
TimeCardsReporting timeCardsReporting) throws Exception {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
logger.info("Reference: {}-{}", year, month);
EPASValidates epasValidates = epasValidatesService.getValidatesByOfficeCodeId(ISTI_OFFICE_CODEID, year, month);
// if (!epasValidates.getAllCertificationsValidated()) {
// logger.info("No month closed on EPAS: {}", nextMonthToSent);
// return;
// }
// Set Update DateTime
LocalDateTime dMod = now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
logger.info("Persons Validated: {}", epasValidates.getValidatedPersons().length);
checkFiscalCode(epasValidates.getValidatedPersons());
// SI
for (EPASPersons person : epasValidates.getValidatedPersons()) {
logger.info("Writing TimeCard for Person: {}", person);
if (person.getFiscalCode() == null || person.getFiscalCode().isEmpty()) {
logger.error("Invalid FiscalCode: {}", person.getFiscalCode());
continue;
} else {
logger.info("FiscalCode: {}", person.getFiscalCode());
}
EPASTimeCards epasTimeCards = epasTimeCardsService.getTimeCardByPersonFiscalCode(person.getFiscalCode(),
year, month);
LinkedHashMap<String, String> epasAbsenceTypeMap = null;
if (EXPORT_ABSENCE_CODE_DESCRIPTION) {
epasAbsenceTypeMap = epasAbsenceTypeService.getAbsenceTypesMap();
}
EPASPersons epasPerson = epasTimeCards.getPerson();
Integer personId = Integer.valueOf(epasPerson.getId());
for (EPASPersonDays epasPersonDay : epasTimeCards.getPersonDays()) {
Long id = Long.valueOf(epasPersonDay.getId());
StringBuilder motivo = new StringBuilder();
extractMotivoInfo(epasPersonDay, epasAbsenceTypeMap, motivo);
java.sql.Date date = null;
try {
date = java.sql.Date.valueOf(epasPersonDay.getDate());
} catch (Exception e) {
logger.error("Invalid date format: {}", epasPersonDay.getDate());
break;
}
SICartellini siCartellini = new SICartellini(id, personId, epasPerson.getFiscalCode(), date,
motivo.toString(), epasPersonDay.getTimeAtWork(), epasPersonDay.getDifference(), dataMod, "0",
fluxId);
siCartelliniService.writeNewFlux(fluxId, siCartellini);
}
}
logger.info("SICartellini Updated");
SICartelliniRendicontazioni siCartelliniRendicontazioni = new SICartelliniRendicontazioni(
timeCardsReporting.getId(), timeCardsReporting.getYear(), timeCardsReporting.getMonth(), dataMod,
SI_FLAG_DEL_FALSE, fluxId);
siCartelliniRendicontazioniService.writeNewFlux(fluxId, siCartelliniRendicontazioni);
logger.info("SICartelliniRendicontazioni Updated");
bcartellini = true;
bcartellini_rendicontazioni = true;
tab.setIdFlusso(fluxId);
tab.setLastUpdate(now);
tabsSIService.updateTabsSI(tab);
}
private void syncSingleCartellino(Long fluxId, TabsSI tab, String year, String month, LocalDateTime now, String fc)
throws Exception {
if (tab.getIdFlusso() == null || tab.getIdFlusso().longValue() == 0) {
logger.error("Invalid Id Flusso for tab: {}", tab);
return;
}
logger.info("Reference: {}-{}", year, month);
// Set Update DateTime
LocalDateTime dMod = now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
// logger.info("Persons Validated: {}",
// epasValidates.getValidatedPersons().length);
// checkFiscalCode(epasValidates.getValidatedPersons());
EPASPersons person = epasPersonsService.getByFiscalCode(fc);
if (person == null) {
logger.error("Error retrieving person by fiscal code: {}", fc);
String error = "Error retrieving person by fiscal code: " + fc;
throw new Exception(error);
}
logger.info("Writing TimeCard for Person: {}", person);
if (person.getFiscalCode() == null || person.getFiscalCode().isEmpty()) {
logger.error("Invalid FiscalCode: {}", person.getFiscalCode());
String error = "Invalid FiscalCode: " + person.getFiscalCode();
throw new Exception(error);
} else {
logger.info("FiscalCode: {}", person.getFiscalCode());
}
EPASTimeCards epasTimeCards = epasTimeCardsService.getTimeCardByPersonFiscalCode(person.getFiscalCode(), year,
month);
LinkedHashMap<String, String> epasAbsenceTypeMap = null;
if (EXPORT_ABSENCE_CODE_DESCRIPTION) {
epasAbsenceTypeMap = epasAbsenceTypeService.getAbsenceTypesMap();
}
EPASPersons epasPerson = epasTimeCards.getPerson();
Integer personId = Integer.valueOf(epasPerson.getId());
for (EPASPersonDays epasPersonDay : epasTimeCards.getPersonDays()) {
Long id = Long.valueOf(epasPersonDay.getId());
StringBuilder motivo = new StringBuilder();
extractMotivoInfo(epasPersonDay, epasAbsenceTypeMap, motivo);
java.sql.Date date = null;
try {
date = java.sql.Date.valueOf(epasPersonDay.getDate());
} catch (Exception e) {
logger.error("Invalid date format: {}", epasPersonDay.getDate());
break;
}
SICartellini siCartellini = new SICartellini(id, personId, epasPerson.getFiscalCode(), date,
motivo.toString(), epasPersonDay.getTimeAtWork(), epasPersonDay.getDifference(), dataMod, "0",
fluxId);
siCartelliniService.writeNewFlux(fluxId, siCartellini);
}
logger.info("SICartellino Updated");
bcartellini = true;
tab.setIdFlusso(fluxId);
tab.setLastUpdate(now);
tabsSIService.updateTabsSI(tab);
}
private TimeCardsReporting createTimeCardReporting(Long fluxId, String year, String month, LocalDateTime now) {
Integer iYear = Integer.parseInt(year);
Integer iMonth = Integer.parseInt(month);
// EPASMed
TimeCardsReporting timeCardsReporting = new TimeCardsReporting();
timeCardsReporting.setYear(iYear);
timeCardsReporting.setMonth(iMonth);
timeCardsReporting.setIdFlusso(fluxId);
timeCardsReporting.setLastUpdate(now);
timeCardsReporting = timeCardsReportingService.createTimeCardsReporting(timeCardsReporting);
return timeCardsReporting;
}
private void checkValidMonthToSend(String year, String month) throws Exception {
Integer iYear = Integer.valueOf(year);
Integer iMonth = Integer.valueOf(month);
YearMonth selectedMonth = YearMonth.of(iYear, iMonth);
YearMonth nextMonthToSent = nextMonthToSend();
if (selectedMonth.compareTo(nextMonthToSent) != 0) {
String error = "Attenzione il mese richiesto non è valido per la rendicontazione.";
logger.error(error);
throw new Exception(error);
}
}
private YearMonth nextMonthToSend() throws Exception {
Optional<TimeCardsReporting> lastTcR = timeCardsReportingService.getLastTimeCardsReporting();
if (!lastTcR.isPresent()) {
String error = "Invalid TimeCardsReporting start point, no value found.";
logger.error(error);
throw new Exception(error);
}
Integer latestY = lastTcR.get().getYear();
Integer latestM = lastTcR.get().getMonth();
YearMonth nextMonthToSent = YearMonth.of(latestY, latestM);
nextMonthToSent = nextMonthToSent.plusMonths(1);
return nextMonthToSent;
}
private void checkFiscalCode(EPASPersons[] validatedPersons) throws Exception {
if (validatedPersons != null && validatedPersons.length > 0) {
ArrayList<String> personsWithInvalidFiscalCode = new ArrayList<>();
for (EPASPersons epasPerson : validatedPersons) {
if (epasPerson != null) {
if (epasPerson.getFiscalCode() == null || epasPerson.getFiscalCode().isEmpty()) {
if (epasPerson.getFullname() != null && !epasPerson.getFullname().isEmpty()) {
personsWithInvalidFiscalCode.add(epasPerson.getFullname());
} else {
String error = "Dipendente non inizializzato correttamente: " + epasPerson;
logger.error(error);
throw new Exception(error);
}
}
}
}
if (!personsWithInvalidFiscalCode.isEmpty()) {
StringBuilder errore = new StringBuilder();
String invalids = personsWithInvalidFiscalCode.stream().collect(Collectors.joining(",", "[", "]"));
errore.append("Alcuni dipenenti non hanno il codice fiscale corretto ");
errore.append(invalids);
logger.error(errore.toString());
throw new Exception(errore.toString());
}
}
}
private void extractMotivoInfo(EPASPersonDays epasPersonDay, LinkedHashMap<String, String> epasAbsenceTypeMap,
StringBuilder motivo) {
if (epasPersonDay.getIsHoliday()) {
motivo.append("[Festivo]");
}
if (epasPersonDay.getStampings() != null && epasPersonDay.getStampings().length > 0) {
boolean foundLavoroFuoriSede = false;
boolean foundMotiviDiServizio = false;
for (EPASStampings epasStamping : epasPersonDay.getStampings()) {
if (epasStamping.getStampType() != null && !epasStamping.getStampType().isEmpty()) {
switch (epasStamping.getStampType()) {
case "lavoroFuoriSede":
foundLavoroFuoriSede = true;
break;
case "motiviDiServizio":
foundMotiviDiServizio = true;
break;
default:
break;
}
}
}
if (foundLavoroFuoriSede) {
motivo.append("[Lavoro Fuori Sede]");
}
if (foundMotiviDiServizio) {
motivo.append("[Servizio]");
}
}
if (epasPersonDay.getAbsences() != null && epasPersonDay.getAbsences().length > 0) {
for (EPASAbsences epasAbsences : epasPersonDay.getAbsences()) {
motivo.append("[");
motivo.append(epasAbsences.getCode());
if (epasAbsenceTypeMap != null && !epasAbsenceTypeMap.isEmpty()) {
String description = epasAbsenceTypeMap.get(epasAbsences.getCode());
if (description != null && !description.isEmpty()) {
motivo.append("-");
motivo.append(description);
}
}
if (epasAbsences.getNote() != null && !epasAbsences.getNote().isEmpty()) {
motivo.append("-");
motivo.append(epasAbsences.getNote());
}
motivo.append("]");
}
}
}
}