diff --git a/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/component/DbmsChangeTracker.java b/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/component/DbmsChangeTracker.java index a9d0d1a6eb..7466142960 100644 --- a/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/component/DbmsChangeTracker.java +++ b/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/component/DbmsChangeTracker.java @@ -12,6 +12,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.sql.SQLException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; @@ -174,16 +175,26 @@ public class DbmsChangeTracker { return result.stream() .map(x -> { DetectedChangeDataDTO detectedChangeDataDTO = new DetectedChangeDataDTO() - .setTableName(tableName) - .setSysChangeVersion(UtilityHashMap.getValueIfExists(x, "SYS_CHANGE_VERSION")) - .setSysChangeCreationVersion(UtilityHashMap.getValueIfExists(x, "SYS_CHANGE_CREATION_VERSION")) - .setSysChangeOperation(DetectedChangeDataDTO.Operation.from(UtilityHashMap.getValueIfExists(x, "SYS_CHANGE_OPERATION"))); + .setTableName(tableName); - x.remove("SYS_CHANGE_VERSION"); - x.remove("SYS_CHANGE_CREATION_VERSION"); - x.remove("SYS_CHANGE_OPERATION"); - x.remove("SYS_CHANGE_COLUMNS"); - x.remove("SYS_CHANGE_CONTEXT"); + Long sysChangeVersion = UtilityHashMap.getValueIfExists(x, "SYS_CHANGE_VERSION"); + detectedChangeDataDTO.setSysChangeVersion(sysChangeVersion); + + + Long sysChangeCreationVersion = UtilityHashMap.getValueIfExists(x, "SYS_CHANGE_CREATION_VERSION"); + detectedChangeDataDTO.setSysChangeCreationVersion(sysChangeCreationVersion); + + detectedChangeDataDTO.setSysChangeOperation(DetectedChangeDataDTO.Operation.from(UtilityHashMap.getValueIfExists(x, "SYS_CHANGE_OPERATION"))); + + List keysToRemove = new ArrayList<>(); + for (String colName : x.keySet()) { + if (colName.startsWith("SYS_")) + keysToRemove.add(colName); + } + + for (String colName : keysToRemove) { + x.remove(colName); + } detectedChangeDataDTO.setPrimaryKey(x); diff --git a/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/model/DetectedChangeDataDTO.java b/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/model/DetectedChangeDataDTO.java index 359a085ee0..98231bb6ac 100644 --- a/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/model/DetectedChangeDataDTO.java +++ b/ems-core/src/main/java/it/integry/ems/dbms_change_tracker/model/DetectedChangeDataDTO.java @@ -8,7 +8,7 @@ import java.util.HashMap; public class DetectedChangeDataDTO { private long sysChangeVersion; - private long sysChangeCreationVersion; + private Long sysChangeCreationVersion; private Operation sysChangeOperation; private String tableName; @@ -24,11 +24,11 @@ public class DetectedChangeDataDTO { return this; } - public long getSysChangeCreationVersion() { + public Long getSysChangeCreationVersion() { return sysChangeCreationVersion; } - public DetectedChangeDataDTO setSysChangeCreationVersion(long sysChangeCreationVersion) { + public DetectedChangeDataDTO setSysChangeCreationVersion(Long sysChangeCreationVersion) { this.sysChangeCreationVersion = sysChangeCreationVersion; return this; } diff --git a/ems-core/src/main/java/it/integry/ems/dynamic_cache/EntityCacheComponent.java b/ems-core/src/main/java/it/integry/ems/dynamic_cache/EntityCacheComponent.java index e1d884a5e2..2c8600ffe9 100644 --- a/ems-core/src/main/java/it/integry/ems/dynamic_cache/EntityCacheComponent.java +++ b/ems-core/src/main/java/it/integry/ems/dynamic_cache/EntityCacheComponent.java @@ -19,6 +19,8 @@ import it.integry.ems_model.entity.WtbGestSetupUser; import it.integry.ems_model.exception.DataConverterNotFoundException; import it.integry.ems_model.utility.UtilityDB; import it.integry.ems_model.utility.UtilityQuery; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @@ -34,6 +36,8 @@ import java.util.stream.Collectors; @Component public class EntityCacheComponent implements ApplicationListener { + private final Logger logger = LogManager.getLogger(); + private final DbmsChangeTrackerComponent dbmsChangeTrackerComponent; private final EntityPropertyHolder entityPropertyHolder; @@ -67,6 +71,11 @@ public class EntityCacheComponent implements ApplicationListener { ConcurrentHashMap, EntityBase> entities = retrieveEntityList(conn, tableName, clazz); entityCache.get(customerDB).put(tableName, entities); + + logger.trace(String.format("[%s] Cached %d records for entity %s", + customerDB.getValue(), + entities.size(), + clazz.getSimpleName())); } } } diff --git a/ems-core/src/main/java/it/integry/ems/rules/completing/CommonRules.java b/ems-core/src/main/java/it/integry/ems/rules/completing/CommonRules.java index 7c6fd97b39..913296f3fe 100644 --- a/ems-core/src/main/java/it/integry/ems/rules/completing/CommonRules.java +++ b/ems-core/src/main/java/it/integry/ems/rules/completing/CommonRules.java @@ -1,1351 +1,1359 @@ -package it.integry.ems.rules.completing; - -import com.annimon.stream.ComparatorCompat; -import com.annimon.stream.Optional; -import com.annimon.stream.Stream; -import it.integry.common.var.CommonConstants; -import it.integry.ems.json.ResponseJSONObjectMapper; -import it.integry.ems.sync.MultiDBTransaction.Connection; -import it.integry.ems_model.annotation.ReloadRow; -import it.integry.ems_model.annotation.SqlField; -import it.integry.ems_model.base.EntityBase; -import it.integry.ems_model.config.EmsRestConstants; -import it.integry.ems_model.db.ResultSetMapper; -import it.integry.ems_model.entity.*; -import it.integry.ems_model.entity.common.DtbDocOrdR; -import it.integry.ems_model.resolver.SqlFieldHolder; -import it.integry.ems_model.rules.util.DroolsUtil; -import it.integry.ems_model.rulescompleting.DroolsDataCompleting; -import it.integry.ems_model.types.ApplicationName; -import it.integry.ems_model.types.OperationType; -import it.integry.ems_model.utility.*; -import org.springframework.expression.Expression; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.util.ReflectionUtils; -import org.springframework.web.context.ContextLoader; - -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.*; -import java.util.concurrent.atomic.AtomicReference; - -public class CommonRules extends QueryRules { - - public static Boolean chk(Object arg0, String comparator, Object arg1) { - return validateCheck(arg0, arg1, comparator); - } - - public static MtbAart completeDatiMtbAart(Connection connection, String codMart) throws Exception { - String sql = "SELECT * FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); - - if (codMart == null || codMart.isEmpty()) - throw new Exception("Impossibile trovare l'articolo"); - - final MtbAart mtbAart = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(connection, sql, MtbAart.class); - - if (mtbAart == null) - throw new Exception("Codice articolo non trovato (" + codMart + ")"); - - return mtbAart; - } - - public static MtbPartitaMag completeDatiMtbPartitaMag(Connection connection, String codMart, String partitaMag) throws Exception { - String sql = "SELECT * FROM mtb_partita_mag WHERE cod_mart = " + UtilityDB.valueToString(codMart) + " AND partita_mag = " + UtilityDB.valueToString(partitaMag); - PreparedStatement ps = connection.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - - MtbPartitaMag mtbPartitaMag = new ResultSetMapper().mapResultSetToObject(rs, MtbPartitaMag.class); - rs.close(); - ps.close(); - return mtbPartitaMag; - } - - public static BigDecimal getPercAliq(Connection conn, String codAliq) throws SQLException { - BigDecimal percAliq = BigDecimal.ZERO; - String sql = "SELECT perc_aliq FROM gtb_aliq WHERE cod_aliq = " + UtilityDB.valueToString(codAliq); - PreparedStatement ps = conn.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - percAliq = rs.getBigDecimal(1); - } - rs.close(); - ps.close(); - - return percAliq; - } - - public static BigDecimal scorporoIva(Connection conn, BigDecimal importo, String codAliq) throws SQLException { - BigDecimal imponibile = BigDecimal.ZERO; - if (importo.compareTo(BigDecimal.ZERO) != 0) { - BigDecimal percAliq = getPercAliq(conn, codAliq); - imponibile = scorporoIva(importo, percAliq); - } - - return imponibile; - } - - public static BigDecimal scorporoIva(BigDecimal importo, BigDecimal percAliq) { - percAliq = percAliq.divide(new BigDecimal("100")); - percAliq = BigDecimal.ONE.add(percAliq); - importo = importo.divide(percAliq, EmsRestConstants.cifreDecMax, RoundingMode.HALF_UP); - importo = IntegerUtility.round(importo, 5); - return importo; - } - - public static BigDecimal calcImposta(BigDecimal importo, BigDecimal percAliq) { - percAliq = percAliq.divide(new BigDecimal("100")); - percAliq = BigDecimal.ONE.add(percAliq); - importo = importo.divide(percAliq, EmsRestConstants.cifreDecMax, RoundingMode.HALF_UP); - importo = IntegerUtility.round(importo, 2); - return importo; - } - - private static Boolean validateCheck(Object arg0, Object arg1, String comparator) { - - if (arg0 == null || arg0.equals(EmsRestConstants.NULL)) - arg0 = "null"; - if (arg1 == null || arg0.equals(EmsRestConstants.NULL)) - arg1 = "null"; - - if (arg0 instanceof String) - arg0 = UtilityDB.valueToString(arg0.toString()); - if (arg1 instanceof String) - arg1 = UtilityDB.valueToString(arg1.toString()); - - ExpressionParser parser = new SpelExpressionParser(); - Expression exp = parser.parseExpression(arg0.toString() + comparator + arg1.toString()); - return (Boolean) exp.getValue(); - } - - public static String completeFlagKitArt(Connection conn, String codMart) throws SQLException { - String flagKit = "N"; - - String sql = "SELECT flag_kit FROM mvw_kit WHERE cod_mart = " + UtilityDB.valueToString(codMart); - List> list = execQuery(conn, sql); - if (!list.isEmpty()) { - flagKit = list.get(0).get("flag_kit").toString(); - } - - return flagKit; - } - - public static Integer completeIdRilPrz(Connection conn, Date dataRil) throws Exception { - Integer anno = UtilityDate.getYear(dataRil); - String sql = - "SELECT isNull(max(id_ril), 0) as id_ril " + - " FROM vtb_ril_przt " + - " WHERE year(vtb_ril_przt.data_ril) = " + anno + "AND " + - "vtb_ril_przt.id_ril like '" + anno + "%' "; - - Integer idRil = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - if (idRil == 0) { - idRil = anno * 10000 + 1; - } else { - Integer idRilTemp = new Integer(UtilityString.mid(idRil.toString(), 5)); - idRilTemp += 1; - idRil = new Integer(anno + UtilityString.leftPad(idRilTemp.toString(), 4, '0')); - } - return idRil; - } - - public static String getFullName(Connection connection, String username) throws Exception { - String sql = "SELECT full_name FROM stb_user WHERE user_name = '" + username + "'"; - String value = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - - if (!UtilityString.isNullOrEmpty(value)) return value; - - return username; - } - - public static String getUserNameFromFullName(Connection connection, String fullName) throws Exception { - if (!UtilityString.isNullOrEmpty(fullName)) { - String sql = Query.format("SELECT user_name FROM stb_user WHERE full_name = %s", - fullName); - return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - } - return null; - } - - public static List calcPercAliq(Connection conn, List list) throws Exception { - for (WdtbOrdr row : list) { - if (row.getPercAliq() == null && row.getCodAliq() != null) - row.setPercAliq(CommonRules.completePercAliq(conn, row.getCodAliq())); - } - return list; - } - - @SuppressWarnings("unchecked") - - public static List reloadRow(Connection conn, EntityBase testata) throws Exception { - List finalList = new ArrayList<>(); - List fields = testata.getEntityHolder().getEntityChildField(testata.getClass()); - - for (Field field : fields) { - finalList = new ArrayList<>(); - field.setAccessible(true); - Object object = field.get(testata); - if (object != null && field.getType().isAssignableFrom(List.class) && (field.getAnnotation(ReloadRow.class) != null || testata.getOperation() == OperationType.SUBSTITUTE)) { - List rows = (ArrayList) object; - List list = null; - if (testata.getOperation() != OperationType.DELETE_THEN_INSERT && - testata.getOperation() != OperationType.INSERT) { - list = UtilityDB.reloadOnlyDbRow(conn, testata, rows, field); - } - - if (list != null && !list.isEmpty()) { - for (EntityBase entityDB : list) { - entityDB.setLoadedFromDb(true); - DroolsDataCompleting dataCompleting = testata.getCompletingManager(); - entityDB.setParentPKAndImportFromParent(testata, true); - if (testata.getOperation() == OperationType.SUBSTITUTE) { - entityDB.setOperation(OperationType.INSERT); - } - entityDB.setCompletingManager(dataCompleting); - entityDB.setParent(testata); - - // completing dell'entity presa da database. - dataCompleting.complete(entityDB, conn, testata.getUsername()); - dataCompleting.invokeCheckRules(entityDB, conn, testata.getUsername()); - } - finalList.addAll(list); - finalList.addAll(rows); - } else { - finalList.addAll(rows); - } - - field.set(testata, finalList); - } - } - //FIX ENTITY HOLDER SULLE RIGHE - for (EntityBase entity : finalList) { - if (entity.getEntityHolder() == null) - entity.setEntityHolder(testata.getEntityHolder()); - } - return finalList; - } - - public static void updateDescrDistintaBase(Connection conn, MtbAart mtbAart) throws Exception { - String sql = - "SELECT descrizione, descrizione_estesa " + - " FROM mtb_aart " + - " WHERE cod_mart = " + UtilityDB.valueToString(mtbAart.getCodMart()); - - HashMap dati = UtilityDB.executeSimpleQueryOnlyFirstRow(conn, sql); - - if (dati != null) { - String descrizioneOld = (String) dati.get("descrizione"); - String descrizioneEstesaOld = (String) dati.get("descrizione_estesa"); - - if (!UtilityString.equalsIgnoreCase(mtbAart.getDescrizione(), descrizioneOld) || !UtilityString.equalsIgnoreCase(mtbAart.getDescrizioneEstesa(), descrizioneEstesaOld)) { - sql = - "SELECT cod_prod, " + - "CASE WHEN cod_prod = " + UtilityDB.valueToString(mtbAart.getCodMart()) + " AND descrizione_prod = " + UtilityDB.valueToString(descrizioneOld) + " THEN " + - UtilityDB.valueToString(mtbAart.getDescrizione()) + " ELSE descrizione_prod END as descrizione_prod, " + - "CASE WHEN cod_prod = " + UtilityDB.valueToString(mtbAart.getCodMart()) + " AND descrizione_estesa = " + UtilityDB.valueToString(descrizioneEstesaOld) + " THEN " + - UtilityDB.valueToString(mtbAart.getDescrizioneEstesa()) + " ELSE descrizione_estesa END as descrizione_estesa " + - " FROM jtb_cicl " + - " WHERE ( jtb_cicl.cod_prod = " + UtilityDB.valueToString(mtbAart.getCodMart()) + " OR " + - "jtb_cicl.cod_prod in (SELECT cod_prod from jtb_dist_mate WHERE cod_mart = " + UtilityDB.valueToString(mtbAart.getCodMart()) + ")) "; - - List jtbCicl = new ResultSetMapper() - .mapQuerySetToList(conn, sql, JtbCicl.class); - - for (JtbCicl dist : jtbCicl) { - if (dist.getCodProd().equalsIgnoreCase(mtbAart.getCodMart())) { - dist.setOperation(OperationType.UPDATE); - } else { - dist.setOperation(OperationType.NO_OP); - sql = "SELECT cod_mart, " + - "id_riga," + - "case when descrizione = " + UtilityDB.valueToString(descrizioneOld) + " THEN " + UtilityDB.valueToString(mtbAart.getDescrizione()) + " ELSE descrizione END as descrizione, " + - "case when descrizione_estesa = " + UtilityDB.valueToString(descrizioneEstesaOld) + " THEN " + UtilityDB.valueToString(mtbAart.getDescrizioneEstesa()) + " ELSE descrizione_estesa END as descrizione_estesa " + - "FROM jtb_dist_mate " + - "WHERE jtb_dist_mate.cod_prod = " + UtilityDB.valueToString(dist.getCodProd()) + " AND " + - "jtb_dist_mate.cod_mart = " + UtilityDB.valueToString(mtbAart.getCodMart()); - - List jtbDistMate = new ResultSetMapper() - .mapQuerySetToList(conn, sql, JtbDistMate.class, OperationType.UPDATE); - - dist.setJtbDistMate(jtbDistMate); - } - } - - mtbAart.setJtbCicl(jtbCicl); - } - } - } - - public static void completeIdRigaEntity(Connection conn, List rows, EntityBase testata) - throws Exception { - - if (!rows.isEmpty()) { - String wherePK = testata.getEntityHolder().getWherePK(testata); - Field rigaField = testata.getEntityHolder().getRigaField(rows.get(0).getClass()); - if (rigaField != null) { - rigaField.setAccessible(true); - if (rigaField != null && rigaField.getAnnotation(SqlField.class) != null) { - Integer startRiga = 0; - if (testata.getOperation() != OperationType.INSERT) { - Integer maxIdRiga = 0; - Optional maxRiga = - Stream.of(rows) - .filter(x -> x.getIdRigaEntity(x, rigaField) != null) - .max(Comparator.comparingInt(o -> o.getIdRigaEntity(o, rigaField))); - - if (maxRiga.isPresent()) { - EntityBase entityBase = maxRiga.get(); - if (entityBase.getEntityHolder() == null) { - entityBase.setEntityHolder(testata.getEntityHolder()); - } - maxIdRiga = (Integer) DroolsUtil.getEntityFieldValue(entityBase, rigaField.getName()); - } - - String rigaSqlName = SqlFieldHolder.getSqlValue(rigaField.getAnnotation(SqlField.class).value(), - rigaField); - - String sql = "SELECT IsNull(max(" + rigaSqlName + "), 0) as riga " + " FROM " - + rows.get(0).getTableName() + " WHERE " + wherePK; - startRiga = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - if (startRiga == null || startRiga == 0) { - startRiga = 0; - } - - if (maxIdRiga > startRiga) { - startRiga = maxIdRiga; - } - } else { - startRiga = 0; - } - - for (EntityBase row : rows) { - if (rigaField.get(row) == null || testata.getOperation() == OperationType.INSERT) { - startRiga++; - rigaField.set(row, startRiga); - } - } - } - } - } - } - - - public static void completeIdRigaDocuLog(Connection conn, DtbDocuLog testata) - throws Exception { - - Field rigaField = testata.getEntityHolder().getRigaField(testata.getClass()); - if (rigaField != null) { - String wherePK = "dtb_docu_log.date_time_log = " + UtilityDB.valueDateToString(testata.getDateTimeLog(), CommonConstants.DATETIME_FORMAT_YMD) + " AND " + - "dtb_docu_log.flag_type = " + UtilityDB.valueToString(testata.getFlagType()) + " AND " + - "dtb_docu_log.type = " + UtilityDB.valueToString(testata.getDocType()) + " AND " + - "dtb_docu_log.format_file = " + UtilityDB.valueToString(testata.getFormatFile()); - rigaField.setAccessible(true); - if (rigaField != null && rigaField.getAnnotation(SqlField.class) != null) { - String rigaSqlName = SqlFieldHolder.getSqlValue(rigaField.getAnnotation(SqlField.class).value(), - rigaField); - - Integer startRiga = 0; - String sql = "SELECT IsNull(max(" + rigaSqlName + "), 0) as riga " + " FROM " - + testata.getTableName() + " WHERE " + wherePK; - List> list = execQuery(conn, sql); - if (list.isEmpty()) { - startRiga = 1; - } else { - startRiga = new Integer(list.get(0).get("riga").toString()) + 1; - } - - rigaField.set(testata, startRiga); - - } - } - - } - - public static void completePosRigaEntity(Connection conn, DtbOrdt testata) throws Exception { - List rows = Stream.of(testata.getDtbOrdr()).filter(x -> x.getOperation() != OperationType.DELETE).toList(); - if (!rows.isEmpty()) { - if (testata.getExecuteRecalc()) { - ComparatorCompat c = - new ComparatorCompat(Comparator.comparingInt(a -> UtilityInteger.isNull(a.getPosRiga(), Integer.MAX_VALUE))) - .thenComparing(Comparator.comparingInt(DtbOrdr::getRigaOrd)); - - rows = Stream.of(rows).sorted(c).toList(); - } else { - Integer posRigaLista = - Stream.of(rows) - .filter(x -> x.getPosRiga() != null).max(Comparator.comparingInt(DtbOrdr::getPosRiga)).map(x -> x.getPosRiga()).orElse(1); - String sql = - "SELECT ISNULL(max(pos_riga), 0) as pos_riga " + - " FROM dtb_ordr "; - - sql = UtilityDB.addwhereCond(sql, testata.getPkWhereCond(), false); - - Integer posRigaDb = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - - if (posRigaDb.intValue() > posRigaLista.intValue()) { - posRigaLista = posRigaDb; - } - AtomicReference i = new AtomicReference<>(posRigaLista); - Stream.of(rows).filter(x -> x.getPosRiga() == null).forEach(x -> x.setPosRiga(i.getAndSet(i.get() + 1))); - } - - Integer rigaPrec = 0; - for (DtbOrdr row : rows) { - if (row.getPosRiga() == null || rigaPrec.equals(row.getPosRiga())) { - rigaPrec++; - row.setPosRiga(rigaPrec); - } else { - rigaPrec = row.getPosRiga(); - } - } - - } - } - - public static void completeRigaCtbMovr(EntityBase testata) { - //questo campo definisce anche l'ordinemanto delle righe quindi viene sempre riassegnato. - Integer startRiga = 0; - - List rows = - Stream.of(((CtbMovt) testata).getCtbMovr()) - .filter(x -> x.getOperation() != OperationType.DELETE) - .toList(); - - for (CtbMovr row : rows) { - startRiga++; - row.setRiga(startRiga); - } - } - - public static void completeIdRigaCtbMovrCoan(Connection conn, List rows, EntityBase testata) throws Exception { - - if (!rows.isEmpty()) { - String wherePK = "ctb_movr_coan.num_cmov = " + UtilityDB.valueToString(((CtbMovr) testata).getNumCmov()) + " AND " - + "ctb_movr_coan.id_riga = " + UtilityDB.valueToString(((CtbMovr) testata).getIdRiga()); - Field rigaField = testata.getEntityHolder().getRigaField(rows.get(0).getClass()); - if (rigaField != null) { - rigaField.setAccessible(true); - if (rigaField != null && rigaField.getAnnotation(SqlField.class) != null) { - - String rigaSqlName = SqlFieldHolder.getSqlValue(rigaField.getAnnotation(SqlField.class).value(), - rigaField); - - Integer startRiga = 0; - String sql = "SELECT IsNull(max(" + rigaSqlName + "), 0) as riga " + " FROM " - + rows.get(0).getTableName() + " WHERE " + wherePK; - List> list = execQuery(conn, sql); - if (list.isEmpty()) { - startRiga = 1; - } else { - startRiga = new Integer(list.get(0).get("riga").toString()) + 1; - } - - for (EntityBase row : rows) { - if (rigaField.get(row) == null) { - rigaField.set(row, startRiga); - startRiga++; - } - } - } - } - } - } - - public static void completeIdRigaJtbSchedaCq(Connection conn, String codCq, List rows) - throws Exception { - - Integer startRiga = 0; - String sql = "SELECT IsNull(max(id_riga), 0) as riga " + " FROM jtb_scheda_cqr " + " WHERE cod_cq = " - + UtilityDB.valueToString(codCq); - List> list = execQuery(conn, sql); - if (list.isEmpty()) { - startRiga = 1; - } else { - startRiga = new Integer(list.get(0).get("riga").toString()) + 1; - } - - for (JtbSchedaCqr row : rows) { - if (row.getOperation() == OperationType.INSERT) { - row.setIdRiga(startRiga); - startRiga++; - } - } - } - - public static BigDecimal completeRapConv(Connection conn, EntityBase entity) throws Exception { - String fieldUntMis = null; - - String codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_mart"); - if (entity instanceof MtbLisa) { - fieldUntMis = "unt_mis_acq"; - } else if (entity instanceof DtbOrdr || entity instanceof WdtbOrdr) { - fieldUntMis = "unt_ord"; - } else if (entity instanceof DtbDocr || entity instanceof WdtbDocr) { - fieldUntMis = "unt_doc"; - } - String untMis = (String) DroolsUtil.getEntityFieldValue(entity, fieldUntMis); - - BigDecimal value = BigDecimal.ONE; - - - String query = "SELECT CASE " + UtilityDB.valueToString(untMis) + " WHEN unt_mis THEN 1 " - + " WHEN unt_mis2 THEN rap_conv2 " + " WHEN unt_mis3 THEN rap_conv3 " + " ELSE 1 END as rap_conv " - + " FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); - PreparedStatement info = conn.prepareStatement(query); - ResultSet res = info.executeQuery(); - if (res.next()) { - value = res.getBigDecimal("rap_conv"); - } - res.close(); - info.close(); - - return value; - } - - public static BigDecimal completePrzVend(Connection conn, EntityBase entity) throws SQLException { - String codVlis = null, codMart = null; - BigDecimal przBase = BigDecimal.ZERO, ricarico = BigDecimal.ZERO, maggPrzVend = BigDecimal.ZERO; - BigDecimal przVend = BigDecimal.ZERO; - - if (entity instanceof MtbLisvData) { - MtbLisvData mtbLisvData = (MtbLisvData) entity; - codVlis = mtbLisvData.getCodVlis(); - codMart = mtbLisvData.getCodMart(); - przBase = mtbLisvData.getPrzBase(); - ricarico = mtbLisvData.getRicarica(); - maggPrzVend = mtbLisvData.getMaggPrzVend(); - } - - String query = "SELECT dbo.f_calcPrzVend(" + UtilityDB.valueToString(codVlis) + ", " - + UtilityDB.valueToString(codMart) + ", " + UtilityDB.valueToString(przBase) + ", " - + UtilityDB.valueToString(ricarico) + ", " + "mtb_aart.perc_sfrido, " - + UtilityDB.valueToString(maggPrzVend) + ") " + "FROM mtb_aart " + "WHERE mtb_aart.cod_mart = " - + UtilityDB.valueToString(codMart); - PreparedStatement info = conn.prepareStatement(query); - ResultSet res = info.executeQuery(); - if (res.next()) { - przVend = res.getBigDecimal(1); - } - res.close(); - info.close(); - - return przVend; - } - - public static BigDecimal completePrzVendIva(Connection conn, EntityBase entity) throws SQLException { - String codMart = null, codVlis = null; - BigDecimal przVend = BigDecimal.ZERO; - BigDecimal przVendIVA = BigDecimal.ZERO; - - if (entity instanceof MtbLisvData) { - MtbLisvData mtbLisvData = (MtbLisvData) entity; - codMart = mtbLisvData.getCodMart(); - codVlis = mtbLisvData.getCodVlis(); - przVend = mtbLisvData.getPrzVend(); - } - - String query = "SELECT dbo.f_calcPrzVendIva(" + UtilityDB.valueToString(codVlis) + ", " - + UtilityDB.valueToString(codMart) + ", " + UtilityDB.valueToString(przVend) + ") "; - PreparedStatement info = conn.prepareStatement(query); - ResultSet res = info.executeQuery(); - if (res.next()) { - przVendIVA = res.getBigDecimal(1); - } - res.close(); - info.close(); - - return przVendIVA; - } - - @Deprecated - public static Double getCostoUltimo(Connection conn, String applicationName, String codMart, String codMdep, - Date dataValidita) throws SQLException { - String sql = ""; - Double costoUltimo = 0d; - - /* - * if(StringUtility.isNotNull(codMdep) && "S".equals(flagCostoDepo)){ - * - * } - */ - - if (ApplicationName.WINGEST.toString().equals(applicationName)) { - sql = "SELECT cod_comp, qta_std FROM mtb_comp WHERE cod_mart = '" + codMart + "'"; - List> list = execQuery(conn, sql); - for (HashMap map : list) { - - sql = "SELECT flag_caprz_acq FROM mtb_aart WHERE cod_mart = '" + codMart + "'"; - HashMap flagCalcMap = execSingleQuery(conn, sql); - String flagCalcPrzAcq = flagCalcMap.get("flag_caprz_acq").toString(); - - if ("K".equals(flagCalcPrzAcq)) { - List> ultimoAcqList = getUltimoAcquisto(conn, codMart, dataValidita, codMdep); - - String codDivi = ""; - if (ultimoAcqList.size() == 1) { - codDivi = ultimoAcqList.get(0).get("cod_divi").toString(); - } - // ULTIMO COSTO DEL COMPOSTO VIENE DA ULTIMO DOC. DI - // ACQUISTO DEL COMPOSTO - // VA CONVERTITO IN EURO - Double cambioEuro = 0d; - sql = "SELECT gtb_divi.cambio_euro FROM gtb_divi WHERE gtb_divi.cod_divi = '" + codDivi + "'"; - - HashMap cambioEuroMap = execSingleQuery(conn, sql); - cambioEuro = Double.valueOf(cambioEuroMap.get("cambio_euro").toString()); - if (cambioEuro != 0) { - // SE IL CAMBIO HA UN VALORE ERRATO, NON FACCIO LA - // CONVERSIONE - costoUltimo = costoUltimo / cambioEuro; - } - } - if ("C".equals(flagCalcPrzAcq) || costoUltimo == 0) { - // ULTIMO COSTO = SOMMA DEI COSTI ULTIMI DEI COMPONENTI - // String codComp = map.get("cod_comp"); - Double qtaStdComp = Double.valueOf(map.get("qta_std").toString()); - Double costoComp = 0d;// getCostoUltimo(profileDB, codComp, - // dataValidita, codMdep); - costoUltimo += costoComp * qtaStdComp; - } - } - - } else { - sql = "SELECT val_ult_car FROM mtb_aart WHERE cod_mart = '" + codMart + "'"; - HashMap ultValCarMap = execSingleQuery(conn, sql); - return Double.valueOf(ultValCarMap.get("val_ult_car").toString()); - } - - return null; - - } - - @Deprecated - public static List> getUltimoAcquisto(Connection conn, - String codMart, Date dataMax, String codMdep) throws SQLException { - - String sql; - - if ("".equals(codMdep)) { - sql = "SELECT top 1 dtb_doct.data_doc, dtb_doct.cod_anag, " - + " gtb_anag.rag_soc, dtb_doct.cod_divi, " - + " ((dtb_docr.val_unt / dtb_docr.rap_conv) * (1 - sconto1/100) * (1 - sconto2/100) * (1 - sconto3/100) * (1 - sconto4/100) * (1 - sconto5/100) * (1 - sconto6/100) * (1 - sconto7/100) * (1 - sconto8/100))" - + " FROM dtb_doct, dtb_docr, dtb_tipi, gtb_anag " - + " WHERE dtb_doct.cod_anag = dtb_docr.cod_anag and " - + " dtb_doct.cod_dtip = dtb_docr.cod_dtip and " - + " dtb_doct.data_doc = dtb_docr.data_doc and " + " dtb_doct.ser_doc = dtb_docr.ser_doc and " - + " dtb_doct.num_doc = dtb_docr.num_doc and " - + " dtb_doct.cod_anag = gtb_anag.cod_anag and " - + " dtb_doct.cod_dtip = dtb_tipi.cod_dtip and " + " dtb_tipi.segno_val_car = 1 and " - + " dtb_tipi.gestione <> 'V' and " + " dtb_tipi.flag_costo = 'S' and " - + " dtb_doct.data_doc <= '" + new SimpleDateFormat("yyyy-MM-dd").format(dataMax) + "'" - + " and " + " dtb_docr.cod_mart = '" + codMart + "' and " - + " dtb_docr.importo_riga > 0 " + " ORDER BY dtb_doct.data_doc DESC "; - } else { - sql = "SELECT top 1 dtb_doct.data_doc, " + " dtb_doct.cod_anag, " + " gtb_anag.rag_soc, " - + " dtb_doct.cod_divi, " - + " ((dtb_docr.val_unt / dtb_docr.rap_conv) * (1 - sconto1/100) * (1 - sconto2/100) * (1 - sconto3/100) * (1 - sconto4/100) * (1 - sconto5/100) * (1 - sconto6/100) * (1 - sconto7/100) * (1 - sconto8/100))" - + " FROM dtb_doct, dtb_docr, dtb_tipi, gtb_anag " - + " WHERE dtb_doct.cod_anag = dtb_docr.cod_anag and " - + " dtb_doct.cod_dtip = dtb_docr.cod_dtip and " - + " dtb_doct.data_doc = dtb_docr.data_doc and " - + " dtb_doct.ser_doc = dtb_docr.ser_doc and " - + " dtb_doct.num_doc = dtb_docr.num_doc and " - + " dtb_doct.cod_anag = gtb_anag.cod_anag and " - + " dtb_doct.cod_dtip = dtb_tipi.cod_dtip and " + " dtb_tipi.segno_val_car = 1 and " - + " dtb_tipi.gestione <> 'V' and " + " dtb_tipi.flag_costo = 'S' and " - + " dtb_doct.data_doc <= '" + new SimpleDateFormat("yyyy-MM-dd").format(dataMax) + "'" - + " and " + " dtb_docr.cod_mart = '" + codMart + "' and " - + " dtb_docr.importo_riga > 0 and " + " dtb_doct.cod_mdep = '" + codMdep + "' " - + " ORDER BY dtb_doct.data_doc DESC "; - } - return execQuery(conn, sql); - } - - public static String completeCodBarre(Connection connection, String codMart) - throws SQLException { - String sql = "SELECT mvw_barcode_det.cod_barre " + "FROM mvw_barcode_det " - + "WHERE mvw_barcode_det.cod_mart = '" + codMart + "'"; - List> result = execQuery(connection, sql); - - String barcode = null; - - if (result != null && !result.isEmpty() && result.get(0).containsKey("cod_barre")) - barcode = result.get(0).get("cod_barre").toString(); - - return barcode; - } - - public static String completeCodBarreScontrini(Connection connection, String codMart) - throws Exception { - String sql = "SELECT TOP 1 mvw_barcode_det.cod_barre " + "FROM mvw_barcode_det " - + "WHERE mvw_barcode_det.cod_mart = '" + codMart + "' and len(mvw_barcode_det.cod_barre) <= 13"; - String barcode = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - return barcode; - } - - public static String completeFlagQtaCnfFissa(Connection connection, String codMart) throws Exception { - String sql = "select flag_qta_cnf_fissa from mtb_aart WHERE cod_mart = '" + codMart + "'"; - String flagQtaCnfFissa = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - return flagQtaCnfFissa; - } - - public static String getApplicationName(Connection connection) throws Exception { - String sql = "select application_name from azienda"; - return (String) getSingleValue(connection, sql); - - } - - public static String completeCodDiviCont(Connection connection) throws Exception { - String sql = "select cod_divi_contab from azienda"; - String codDivi = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - return codDivi; - } - -/* - public static Double completeCambioDiviCont(Connection connection) throws SQLException { - String sql = "select gtb_divi.cambio FROM azienda LEFT OUTER JOIN gtb_divi ON azienda.cod_divi_contab = gtb_divi.cod_divi"; - List> list = execQuery(connection, sql); - if (list.isEmpty()) { - return new Double("1"); - } else { - return new Double(list.get(0).get("cambio").toString()); - } - } - */ - - public static BigDecimal completeCambio(Connection conn, EntityBase testata) throws Exception { - String codDivi = (String) DroolsUtil.getEntityFieldValue(testata, "cod_divi_cont"); - return completeCambio(conn, codDivi); - } - - public static BigDecimal completeCambio(Connection conn, String codDivi) throws SQLException { - String sql = "select gtb_divi.cambio FROM gtb_divi WHERE gtb_divi.cod_divi = " + UtilityDB.valueToString(codDivi); - return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - } - - public static HashMap completeCodDivi(Connection connection) throws SQLException { - return completeCodDivi(connection, new Date()); - } - - public static HashMap completeCodDivi(Connection connection, Date data) throws SQLException { - Integer anno = UtilityDate.datePart(Calendar.YEAR, data); - return completeCodDivi(connection, anno); - } - - public static HashMap completeCodDivi(Connection connection, LocalDate data) throws SQLException { - Integer anno = data.getYear(); - return completeCodDivi(connection, anno); - } - - public static HashMap completeCodDivi(Connection connection, Integer anno) throws SQLException { - String sql = "SELECT gtb_anni_divi.cod_divi_cont_prima AS cod_divi_contab, gtb_divi.cifre_dec, gtb_divi.cambio\n" + - "FROM gtb_anni_divi\n" + - " INNER JOIN gtb_divi ON gtb_anni_divi.cod_divi_cont_prima = gtb_divi.cod_divi\n" + - "WHERE anno = " + UtilityDB.valueToString(anno); - return execSingleQuery(connection, sql); - } - - public static Integer completeCifreDecDiviCont(Connection connection, String codDivi) throws SQLException { - String sql = "SELECT cifre_dec FROM gtb_divi" + " WHERE cod_divi = " + UtilityDB.valueToString(codDivi); - PreparedStatement ps = connection.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - Integer cifreDec = null; - if (rs.next()) { - cifreDec = rs.getInt(1); - } - rs.close(); - ps.close(); - return cifreDec; - } - - public static BigDecimal roundValue(BigDecimal value, Integer cifreDec) throws Exception { - if (cifreDec == null) - cifreDec = EmsRestConstants.cifreDecMax; - return IntegerUtility.round(value, cifreDec); - } - - public static String completeUntMis(Connection connection, String codMart) throws Exception { - String sql = - "SELECT mtb_aart.unt_mis " + - " FROM mtb_aart " + - " WHERE mtb_aart.cod_mart = " + UtilityDB.valueToString(codMart); - String untMis = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - - if (UtilityString.isNullOrEmpty(untMis)) { - throw new Exception("Codice articolo " + codMart + " inesitente"); - } - return untMis; - } - - public static Object completeWithDefault(Class clazz, String fieldName) throws Exception { - - - Object value = null; - Field f = ReflectionUtils.findField(clazz, fieldName); - if (f != null) { - SqlField sql; - if ((sql = f.getAnnotation(SqlField.class)) != null) { - value = SqlFieldHolder.applyConvert(sql.defaultObjectValue(), f.getType()); - } - } - return value; - } - - public static BigDecimal completeQtaCnfOffA(Connection connection, AtbOffr atbOffr) throws Exception { - AtbOfft atbOfft = (AtbOfft) atbOffr.getParent(); - String sql = null; - BigDecimal qtaCnf = null; - if (atbOfft.getCodAlis() != null) { - sql = - Query.format( - "SELECT qta_cnf\n" + - " FROM dbo.getListinoAcquisto(%s,%s,%s,%s, 'N', null) lisa\n" + - " WHERE IsNull(lisa.tipo_variazione, 'I') <> 'D' AND\n" + - "lisa.flag_attivo = 'S' ", - atbOfft.getDataIniz(), - atbOfft.getCodAlis(), - atbOffr.getCodArtForn(), - atbOffr.getCodMart()); - qtaCnf = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - } - - if (UtilityBigDecimal.isNullOrZero(qtaCnf)) { - sql = - Query.format("SELECT qta_cnf FROM mtb_aart WHERE cod_mart = %s", atbOffr.getCodMart()); - qtaCnf = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - } - - if (!UtilityBigDecimal.isNullOrZero(atbOffr.getRapConv()) && atbOffr.getRapConv().compareTo(BigDecimal.ONE) != 0) { - qtaCnf = qtaCnf.divide(atbOffr.getRapConv(), RoundingMode.HALF_UP); - } - return qtaCnf; - } - - public static String completeCodAliqSimple(Connection connection, String codMart) - throws Exception { - - String sql = - "SELECT mtb_aart.cod_aliq" - + " FROM mtb_aart " - + " WHERE mtb_aart.cod_mart = '" + codMart + "'"; - - return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - } - - public static BigDecimal completePercAliq(Connection connection, EntityBase entity) throws Exception { - String codAliq = (String) DroolsUtil.getEntityFieldValue(entity, "cod_aliq"); - - return completePercAliq(connection, codAliq); - } - - public static BigDecimal completePercAliq(Connection connection, String codAliq) throws SQLException { - String sql = "SELECT perc_aliq FROM gtb_aliq WHERE cod_aliq = " + UtilityDB.valueToString(codAliq); - HashMap map = execSingleQuery(connection, sql); - if (map.get("perc_aliq") != null) - return new BigDecimal(map.get("perc_aliq").toString()); - else - return BigDecimal.ZERO; - } - - public static BigDecimal completeQtaCnf(Connection connection, EntityBase entityBase) throws Exception { - BigDecimal qtaCnf = null; - if (entityBase instanceof MtbColr) { - MtbColr mtbColr = ((MtbColr) entityBase); - String sql = "SELECT * FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(mtbColr.getCodMart()); - MtbAart mtbAart = new ResultSetMapper() - .mapQueryToObject(connection, sql, MtbAart.class); - - if (mtbAart == null) - throw new Exception(String.format("Codice Articolo %s non trovato", mtbColr.getCodMart())); - - qtaCnf = DocOrdUntMisRules.calcQtaCnf(connection, mtbColr.getCodMart(), mtbColr.getPartitaMag(), mtbAart, mtbColr.getNumCnf(), BigDecimal.ONE, mtbColr.getQtaCol(), mtbColr.getQtaCnf()); - } - - if (qtaCnf == null) { - String codMart = (String) DroolsUtil.getEntityFieldValue(entityBase, "cod_mart"); - String sql = "SELECT qta_cnf FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); - - qtaCnf = (BigDecimal) getSingleValue(connection, sql); - if (qtaCnf == null) { - qtaCnf = BigDecimal.ONE; - } - } - return qtaCnf; - } - - public static HashMap completeDescrizione(Connection connection, EntityBase entity) throws Exception { - String codMart; - if (entity instanceof JtbCicl) { - codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_prod"); - } else { - codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_mart"); - } - - String sql = "SELECT mtb_aart.descrizione, descrizione_estesa " + "FROM mtb_aart " - + "WHERE mtb_aart.cod_mart = " + UtilityDB.valueToString(codMart); - return execSingleQuery(connection, sql); - } - - public static BigDecimal completeValUntUltPrezzo(Connection conn, EntityBase entity) throws Exception { - String codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_mart"); - BigDecimal rapConv = (BigDecimal) DroolsUtil.getEntityFieldValue(entity, "rap_conv"); - - String sql = "SELECT val_ult_scar FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); - BigDecimal valUltScar = (BigDecimal) getSingleValue(conn, sql); - return valUltScar; - } - - public static BigDecimal completeValUntULTC(Connection conn, DtbDocOrdR entity) throws Exception { - String codMart = entity.getCodMart(); - String codMdep = entity.getCodMdep(); - BigDecimal rapConv = entity.getRapConv(); - - - Date dataValidita = null; - if (entity instanceof DtbOrdr || entity instanceof WdtbOrdr) { - dataValidita = entity.getDataOrd(); - } else if (entity instanceof DtbDocr || entity instanceof WdtbDocr) { - if (entity instanceof DtbDocr) { - dataValidita = ((DtbDocr) entity).getDataDoc(); - } else { - dataValidita = ((WdtbDocr) entity).getDataDoc(); - } - } - BigDecimal valUnt = completeValUntULTC(conn, codMdep, codMart, dataValidita, rapConv); - return valUnt; - } - - public static BigDecimal completeValUntULTC(Connection conn, String codMdep, String codMart, Date dataValidita, BigDecimal rapConv) throws Exception { - if (rapConv.compareTo(BigDecimal.ZERO) == 0) rapConv = BigDecimal.ONE; - String sql = "SELECT Round(isNull(dbo.f_GetCostoUltArt_depo(" - + UtilityDB.valueDateToString(dataValidita, CommonConstants.DATE_FORMAT_YMD) + "," - + UtilityDB.valueToString(codMdep) + "," + UtilityDB.valueToString(codMart) + "), 0)*" + UtilityDB.valueToString(rapConv) + ", 5) as costo_ult"; - BigDecimal valUnt = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - return valUnt; - } - - - public static BigDecimal completeValUntDIST(Connection conn, EntityBase entity) throws SQLException { - String codMart = null, codMdep = null; - Date dataValidita = null; - if (entity instanceof DtbOrdr) { - codMart = ((DtbOrdr) entity).getCodMart(); - codMdep = ((DtbOrdr) entity).getCodMdep(); - dataValidita = ((DtbOrdr) entity).getDataOrd(); - } else if (entity instanceof DtbDocr) { - codMart = ((DtbDocr) entity).getCodMart(); - codMdep = ((DtbDocr) entity).getCodMdep(); - dataValidita = ((DtbDocr) entity).getDataDoc(); - } else if (entity instanceof MtbInvenr) { - codMart = ((MtbInvenr) entity).getCodMart(); - codMdep = ((MtbInvenr) entity).getCodMdep(); - dataValidita = ((MtbInvenr) entity).getDataInventario(); - } - String sql = "SELECT dbo.f_GetCostoDist_depo('', " - + UtilityDB.valueToString(codMart) + "," - + "1, " - + "0, " - + UtilityDB.valueDateToString(dataValidita, CommonConstants.DATE_FORMAT_YMD) + "," - + UtilityDB.valueToString(codMdep) + ") as costo_dist"; - BigDecimal valUnt = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - if (valUnt == null) - return BigDecimal.ZERO; - else - return valUnt; - } - - public static BigDecimal completeValUntCMED(Connection conn, EntityBase entity) throws SQLException { - String codMart = null; - Date dataValidita = null; - if (entity instanceof DtbOrdr) { - codMart = ((DtbOrdr) entity).getCodMart(); - dataValidita = ((DtbOrdr) entity).getDataOrd(); - } else if (entity instanceof MtbInvenr) { - codMart = ((MtbInvenr) entity).getCodMart(); - dataValidita = ((MtbInvenr) entity).getDataInventario(); - } - String sql = "SELECT dbo.f_GetCostoMedArt(" - + UtilityDB.valueDateToString(dataValidita, CommonConstants.DATE_FORMAT_YMD) + "," - + UtilityDB.valueToString(codMart) + ") as costo_med"; - List> list = execQuery(conn, sql); - if (list.isEmpty()) { - return BigDecimal.ZERO; - } else { - return new BigDecimal(list.get(0).get("costo_med").toString()); - } - } - - public static void completeActivityIdChild(StbActivity activity) { - for (StbActivityFile stbActivityFile : activity.getStbActivityFile()) { - stbActivityFile.setId(activity.getActivityId()); - } - } - - public static String completeDescrizionePaga(Connection conn, String codPaga) throws SQLException { - String sql = "SELECT descrizione FROM gtb_paga WHERE gtb_paga.cod_paga = " + UtilityDB.valueToString(codPaga); - HashMap map = execSingleQuery(conn, sql); - if (map.get("descrizione") == null) - return null; - else - return map.get("descrizione").toString(); - } - - public static MtbAartMarchio insMarchio(Connection conn, MtbAart entity) throws Exception { - String sql = "SELECT cast(count(*) as bit) FROM mtb_aart_marchio WHERE marchio = " + UtilityDB.valueToString(entity.getMarchio()); - Boolean existMarchio = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - MtbAartMarchio mtbAartMarchio = null; - - if (existMarchio) { - mtbAartMarchio = new MtbAartMarchio(); - mtbAartMarchio.setMarchio(entity.getMarchio()); - mtbAartMarchio.setOperation(OperationType.INSERT); - } - return mtbAartMarchio; - } - - public static void setIdArtEqui(Connection conn, MtbAart entity) throws Exception { - if (!UtilityString.isNullOrEmpty(entity.getIdArtEqui())) return; - boolean setSetIdArtEqui = setupGest.getSetupBoolean(conn, "MTB_AART", "ID_ART_EQUI", "INSERT_AUTO"); - if (!setSetIdArtEqui) return; - - // Convertire in JSON - entity.setOnlyPkMaster(false); - ResponseJSONObjectMapper objectMapper = ContextLoader.getCurrentWebApplicationContext().getBean(ResponseJSONObjectMapper.class); - String jsonParm = objectMapper.writeValueAsString(entity); - String sql = - String.format( - "SELECT * FROM dbo.suggestMtbArtEqui('%s') ", - jsonParm); - MtbAartEqui mtbAartEqui = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(conn, sql, MtbAartEqui.class); - if (mtbAartEqui != null) { - String idArtEqui = mtbAartEqui.getIdArtEqui(); - if (UtilityString.isNullOrEmpty(mtbAartEqui.getIdArtEqui())) { - idArtEqui = entity.getCodMart(); - mtbAartEqui.setIdArtEqui(idArtEqui) - .setFlagEquiPrezzo("T"); - mtbAartEqui.setOperation(OperationType.INSERT_OR_UPDATE); - } - entity.setIdArtEqui(idArtEqui); - } - } - - public static MtbAartEqui insEqui(Connection conn, MtbAart entity) throws Exception { - String sql = "SELECT id_art_equi FROM mtb_aart_equi WHERE id_art_equi = " + UtilityDB.valueToString(entity.getIdArtEqui()); - HashMap map = execSingleQuery(conn, sql); - MtbAartEqui mtbAartEqui = null; - if (map == null || map.isEmpty() || map.get("id_art_equi") == null) { - mtbAartEqui = new MtbAartEqui(); - mtbAartEqui.setIdArtEqui(entity.getIdArtEqui()); - mtbAartEqui.setDescrizione(entity.getMtbAartEqui_descrizione()); - mtbAartEqui.setOperation(OperationType.INSERT); - } - return mtbAartEqui; - } - - public static List insUntMis(Connection conn, MtbAart mtbAart) throws Exception { - List mtbUntMisList = new ArrayList<>(); - List untMisList = new ArrayList<>(); - - if (!UtilityString.isNullOrEmpty(mtbAart.getUntMis())) { - untMisList.add(mtbAart.getUntMis()); - } - if (!UtilityString.isNullOrEmpty(mtbAart.getUntMis2())) { - untMisList.add(mtbAart.getUntMis2()); - } - if (!UtilityString.isNullOrEmpty(mtbAart.getUntMis3())) { - untMisList.add(mtbAart.getUntMis3()); - } - - for (String untMis : untMisList) { - String sql = "SELECT count(*) FROM mtb_unt_mis WHERE unt_mis = " + UtilityDB.valueToString(untMis); - Integer countUM = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - if (countUM == null || countUM == 0) { - MtbUntMis mtbUntMis = new MtbUntMis(); - mtbUntMis.setUntMis(untMis); - mtbUntMis.setOperation(OperationType.INSERT); - mtbUntMisList.add(mtbUntMis); - } - } - - - return mtbUntMisList; - } - - public static Integer completeNumDist(Connection conn, VtbDistIncat vtbDistIncat) throws Exception { - String sql = - "SELECT max(num_dist) " + - "FROM vtb_dist_incat " + - "WHERE DatePart(Year, data_dist) = DatePart(Year, " + UtilityDB.valueToString(vtbDistIncat.getDataDist()) + ") "; - - Integer numDist = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - if (numDist == null) numDist = 0; - numDist++; - return numDist; - } - - public static String completeFlagRegAcc(Connection conn, VtbDistIncar vtbDistIncar) throws Exception { - String flagRegAcc = "S"; - String sql = - "SELECT prevista_fat FROM dtb_tipi WHERE cod_dtip = " + UtilityDB.valueToString(vtbDistIncar.getCodDtip()); - String previstaFat = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - - if (previstaFat.equalsIgnoreCase("N")) { - flagRegAcc = "N"; - } else if (!UtilityString.isNullOrEmpty(vtbDistIncar.getFlagTipoFatturazione())) { - LocalDate dataFattura = null; - int year = UtilityDate.getYear(vtbDistIncar.getDataDoc()); - int month = UtilityDate.datePart(Calendar.MONTH, vtbDistIncar.getDataDoc()); - switch (vtbDistIncar.getFlagTipoFatturazione()) { - case "M": - dataFattura = UtilityLocalDate.getLastDayOfMonth(year, month); - break; - case "Q": - dataFattura = UtilityLocalDate.dateFromPart(year, month, 15); - break; - } - - LocalDate dataDoc = UtilityLocalDate.localDateFromDate(vtbDistIncar.getDataDoc()); - LocalDate dataDist = UtilityLocalDate.localDateFromDate(vtbDistIncar.getDataDist()); - - if ((dataDoc.equals(dataFattura) || dataDoc.isBefore(dataFattura)) && - (dataDist.equals(dataFattura) || dataDist.isAfter(dataFattura))) { - flagRegAcc = "N"; - } - } - return flagRegAcc; - } - - public static String completeFlagElaboratoDocWebA(Connection conn, WdtbDoct entity) throws Exception { - String sql = - "SELECT flag_elaborato " + - " FROM wdtb_doct " + - " WHERE wdtb_doct.cod_anag = " + UtilityDB.valueToString(entity.getCodAnag()) + " AND " + - " wdtb_doct.cod_dtip = " + UtilityDB.valueToString(entity.getCodDtip()) + " AND " + - " wdtb_doct.data_doc = " + UtilityDB.valueDateToString(entity.getDataDoc(), CommonConstants.DATE_FORMAT_YMD) + " AND " + - " wdtb_doct.ser_doc = " + UtilityDB.valueToString(entity.getSerDoc()) + " AND " + - " wdtb_doct.num_doc = " + UtilityDB.valueToString(entity.getNumDoc()); - - PreparedStatement ps = conn.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - String flagElaborato = "I"; - if (rs.next()) { - flagElaborato = rs.getString(1); - } - rs.close(); - ps.close(); - - return flagElaborato; - } - - public static boolean checkCodMart(Connection conn, String codMart) throws Exception { - boolean ret = false; - String sql = "SELECT cod_mart from mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); - HashMap mapCodMart = UtilityDB.executeSimpleQueryOnlyFirstRow(conn, sql); - if (mapCodMart == null) { - ret = true; - throw new Exception("Codice Articolo " + codMart + " inesistente."); - } - - return ret; - } - - public static void updateStbGestSetupDepo(Connection conn, StbGestSetup entity) throws Exception { - String sql = - "UPDATE stb_gest_setup_depo " + - " SET stb_gest_setup_depo.flag_sync = " + UtilityDB.valueToString(entity.getFlagSync()) + - " WHERE stb_gest_setup_depo.gest_name = " + UtilityDB.valueToString(entity.getGestName()) + " AND " + - " stb_gest_setup_depo.section = " + UtilityDB.valueToString(entity.getSection()) + " AND " + - " stb_gest_setup_depo.key_section = " + UtilityDB.valueToString(entity.getKeySection()); - Statement cmd = conn.createStatement(); - cmd.executeUpdate(sql); - cmd.close(); - - - } - - public static void completeRowIdEquiLog(Connection conn, MtbAartEquiLog mtbAartEquiLog) throws Exception { - String sql = - "SELECT griglia.cod_alis, " + - "griglia.cod_mdep, " + - "lisa.prz_acq_netto as prz_acq " + - " FROM dbo.getGrigliaAcquisto(null, null, null, null, " + UtilityDB.valueToString(mtbAartEquiLog.getCodMart()) + ") griglia " + - "LEFT OUTER JOIN dbo.getListinoAcquisto(null, null, null, " + UtilityDB.valueToString(mtbAartEquiLog.getCodMart()) + ", 'S', null ) lisa on griglia.cod_alis = lisa.cod_alis " + - " WHERE griglia.tipo_variazione <> 'D' AND lisa.tipo_variazione <> 'D' "; - - List mtbAartEquiLogDets = new ResultSetMapper() - .mapQuerySetToList(conn, sql, MtbAartEquiLogDet.class, OperationType.INSERT); - - mtbAartEquiLog.setMtbAartEquiLogDet(mtbAartEquiLogDets); - - } - - public static StbGestSetupQuery completeStbGestSetupQuery(Connection conn, StbGestSetup stbGestSetup) throws Exception { - StbGestSetupQuery stbGestSetupQuery = new StbGestSetupQuery(); - OperationType op = OperationType.NO_OP; - String queryDefault = stbGestSetup.getQueryDefault(); - String codQuery = stbGestSetup.getCodQuery(); - if (UtilityString.isNullOrEmpty(codQuery) && UtilityString.isNullOrEmpty(queryDefault)) { - return stbGestSetupQuery; - } - - if (UtilityString.isNullOrEmpty(codQuery)) { - String sql = - "SELECT cod_query " + - "FROM stb_gest_setup_query " + - "WHERE query_default = " + UtilityDB.valueToString(queryDefault) + " OR " + - " cod_query = " + UtilityDB.valueToString(queryDefault); - codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - - if (UtilityString.isNullOrEmpty(codQuery)) { - stbGestSetupQuery.setCodQuery(getCodQuery(conn)); - op = OperationType.INSERT; - } else { - stbGestSetupQuery.setCodQuery(codQuery); - } - - } else { - stbGestSetupQuery.setCodQuery(codQuery); - } - - stbGestSetupQuery.setQueryDefault(queryDefault); - stbGestSetupQuery.setOperation(op); - return stbGestSetupQuery; - } - - public static String getCodQuery(Connection conn) throws Exception { - String sql = "SELECT MAX(CAST(cod_query AS INT)) + 1 FROM stb_gest_setup_query WHERE IsNumeric(cod_query) = 1"; - return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql).toString(); - } - - - public static boolean barCodeCheck(Connection conn, String barCode) throws Exception { - String sql; - HashMap map; - int check = 0; - - sql = " SELECT COUNT(cod_barre) as num_check " + - " FROM mvw_barcode " + - " WHERE cod_barre = " + UtilityDB.valueToString(barCode); - map = execSingleQuery(conn, sql); - if (!map.isEmpty()) { - check = new Integer(map.get("num_check").toString()); - if (check == 0) { - String applName = CommonRules.getApplicationName(conn); - if (ApplicationName.TEXTILES.toString().equals(applName)) { - map.clear(); - sql = " SELECT COUNT(cod_barre) as num_check " + - " FROM ttb_bar_code " + - " WHERE cod_barre = " + UtilityDB.valueToString(barCode); - map = execSingleQuery(conn, sql); - if (!map.isEmpty()) - check = new Integer(map.get("num_check").toString()); - } - } - } - if (check == 0) {//CODICE A BARRE NON TROVATO. - return true; - } else { - return false; - } - } - - - public static int retrieveNextProgressivoUl(Connection conn, String gestione, LocalDate dataOrd, int numOrd, int segno) throws SQLException { - String sql = Query.format("SELECT ISNULL(MAX(progressivo_ul), 0) AS progressivo_ul" + - " FROM " + MtbColt.ENTITY + - " WHERE data_ord = {} AND " + - " num_ord = {} AND " + - " gestione = {} AND " + - " segno = {}", dataOrd, numOrd, gestione, segno); - - int maxProgressivoUl = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - return maxProgressivoUl + 1; - } - - public static int retrieveNextProgressivoUlRG(Connection conn, String gestione, LocalDate dataOrd, int numOrd, int segno) throws SQLException { - String sql = Query.format( - "WITH partite AS (SELECT dot.cod_prod AS cod_mart, mpm.partita_mag_prod, dot.cod_jfas\n" + - " FROM dtb_ordt dot\n" + - " INNER JOIN mtb_partita_mag mpm\n" + - " ON dot.cod_prod = mpm.cod_mart AND dot.partita_mag = mpm.partita_mag\n" + - " WHERE dot.data_ord = %s\n" + - " AND dot.num_ord = %s\n" + - " AND dot.gestione = [gestione])\n" + - "SELECT ISNULL(MAX(progressivo_ul), 0) AS progressivo_ul\n" + - "FROM mtb_colt\n" + - " INNER JOIN mtb_colr mcr ON mtb_colt.gestione = mcr.gestione AND mtb_colt.data_collo = mcr.data_collo AND\n" + - " mtb_colt.ser_collo = mcr.ser_collo AND mtb_colt.num_collo = mcr.num_collo\n" + - " INNER JOIN mtb_partita_mag mpm ON mcr.cod_mart = mpm.cod_mart AND mcr.partita_mag = mpm.partita_mag\n" + - " INNER JOIN partite ON mcr.cod_mart = partite.cod_mart AND mpm.partita_mag_prod = partite.partita_mag_prod\n" + - " AND mtb_colt.cod_jfas = partite.cod_jfas\n" + - "WHERE mtb_colt.gestione = [gestione]\n" + - " AND segno = %s", - dataOrd, - numOrd, - segno - ).replace("[gestione]", UtilityDB.valueToString(gestione)); - - int maxProgressivoUl = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); - return maxProgressivoUl + 1; - } - - public static void updateDatiInv(Connection conn, DtbDoct entity) throws Exception { - String codAnagOld = null, serDocOld = null, codDtipOld = null; - Integer numDocOld = null; - Date dataDocOld = null; - - HashMap oldPk = entity.getOldPk(); - if (oldPk != null && !oldPk.isEmpty()) { - - if (oldPk.containsKey("codAnag")) codAnagOld = (String) oldPk.get("codAnag"); - else codAnagOld = entity.getCodAnag(); - if (oldPk.containsKey("codDtip")) codDtipOld = (String) oldPk.get("codDtip"); - else codDtipOld = entity.getCodDtip(); - if (oldPk.containsKey("dataDoc")) dataDocOld = UtilityString.parseDate((String) oldPk.get("dataDoc")); - else dataDocOld = entity.getDataDoc(); - if (oldPk.containsKey("serDoc")) serDocOld = (String) oldPk.get("serDoc"); - else serDocOld = entity.getSerDoc(); - if (oldPk.containsKey("numDoc")) numDocOld = (Integer) oldPk.get("numDoc"); - else numDocOld = entity.getNumDoc(); - - if (!entity.getCodDtip().equals(codDtipOld) || - !entity.getCodAnag().equals(codAnagOld) || - !entity.getDataDoc().equals(dataDocOld) || - entity.getSerDoc().equals(serDocOld) || - !entity.getNumDoc().equals(numDocOld)) { - String sql = - "UPDATE mtb_invent " + - "SET cod_anag = " + UtilityDB.valueToString(entity.getCodAnag()) + ", " + - "cod_dtip = " + UtilityDB.valueToString(entity.getCodDtip()) + ", " + - "data_doc = " + UtilityDB.valueDateToString(entity.getDataDoc(), CommonConstants.DATE_FORMAT_YMD) + ", " + - "ser_doc = " + UtilityDB.valueToString(entity.getSerDoc()) + ", " + - "num_doc = " + UtilityDB.valueToString(entity.getNumDoc()); - sql = UtilityDB.addwhereCond(sql, entity.getWhereCondOldPk(null), false); - conn.createStatement().executeUpdate(sql); - } - } - } - - public static boolean getChkCompatibilitaCarat(Connection connection, String codMart, String carat) throws SQLException { - String sql = - Query.format("SELECT chk_compatibilita\n" + - "FROM mtb_aart\n" + - " INNER JOIN mtb_tipi_carat ON mtb_aart.cod_mtip = mtb_tipi_carat.cod_mtip AND\n" + - " mtb_aart.cod_mstp = mtb_tipi_carat.cod_mstp\n" + - "WHERE mtb_aart.cod_mart = %s\n" + - " AND mtb_tipi_carat.carat = %s\n" , - codMart, carat); - - Boolean chkCompatibilita = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); - if (chkCompatibilita == null) chkCompatibilita = false; - return chkCompatibilita; - - } +package it.integry.ems.rules.completing; + +import com.annimon.stream.ComparatorCompat; +import com.annimon.stream.Optional; +import com.annimon.stream.Stream; +import it.integry.common.var.CommonConstants; +import it.integry.ems._context.ApplicationContextProvider; +import it.integry.ems.dynamic_cache.EntityCacheComponent; +import it.integry.ems.json.ResponseJSONObjectMapper; +import it.integry.ems.migration._base.IntegryCustomerDB; +import it.integry.ems.sync.MultiDBTransaction.Connection; +import it.integry.ems_model.annotation.ReloadRow; +import it.integry.ems_model.annotation.SqlField; +import it.integry.ems_model.base.EntityBase; +import it.integry.ems_model.config.EmsRestConstants; +import it.integry.ems_model.db.ResultSetMapper; +import it.integry.ems_model.entity.*; +import it.integry.ems_model.entity.common.DtbDocOrdR; +import it.integry.ems_model.resolver.SqlFieldHolder; +import it.integry.ems_model.rules.util.DroolsUtil; +import it.integry.ems_model.rulescompleting.DroolsDataCompleting; +import it.integry.ems_model.types.ApplicationName; +import it.integry.ems_model.types.OperationType; +import it.integry.ems_model.utility.*; +import org.springframework.expression.Expression; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.util.ReflectionUtils; +import org.springframework.web.context.ContextLoader; + +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.*; +import java.util.concurrent.atomic.AtomicReference; + +public class CommonRules extends QueryRules { + + public static Boolean chk(Object arg0, String comparator, Object arg1) { + return validateCheck(arg0, arg1, comparator); + } + + public static MtbAart completeDatiMtbAart(Connection connection, String codMart) throws Exception { + String sql = "SELECT * FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); + + if (codMart == null || codMart.isEmpty()) + throw new Exception("Impossibile trovare l'articolo"); + + final MtbAart mtbAart = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(connection, sql, MtbAart.class); + + if (mtbAart == null) + throw new Exception("Codice articolo non trovato (" + codMart + ")"); + + return mtbAart; + } + + public static MtbPartitaMag completeDatiMtbPartitaMag(Connection connection, String codMart, String partitaMag) throws Exception { + String sql = "SELECT * FROM mtb_partita_mag WHERE cod_mart = " + UtilityDB.valueToString(codMart) + " AND partita_mag = " + UtilityDB.valueToString(partitaMag); + PreparedStatement ps = connection.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + + MtbPartitaMag mtbPartitaMag = new ResultSetMapper().mapResultSetToObject(rs, MtbPartitaMag.class); + rs.close(); + ps.close(); + return mtbPartitaMag; + } + + public static BigDecimal getPercAliq(Connection conn, String codAliq) throws SQLException { + BigDecimal percAliq = BigDecimal.ZERO; + String sql = "SELECT perc_aliq FROM gtb_aliq WHERE cod_aliq = " + UtilityDB.valueToString(codAliq); + PreparedStatement ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + percAliq = rs.getBigDecimal(1); + } + rs.close(); + ps.close(); + + return percAliq; + } + + public static BigDecimal scorporoIva(Connection conn, BigDecimal importo, String codAliq) throws SQLException { + BigDecimal imponibile = BigDecimal.ZERO; + if (importo.compareTo(BigDecimal.ZERO) != 0) { + BigDecimal percAliq = getPercAliq(conn, codAliq); + imponibile = scorporoIva(importo, percAliq); + } + + return imponibile; + } + + public static BigDecimal scorporoIva(BigDecimal importo, BigDecimal percAliq) { + percAliq = percAliq.divide(new BigDecimal("100")); + percAliq = BigDecimal.ONE.add(percAliq); + importo = importo.divide(percAliq, EmsRestConstants.cifreDecMax, RoundingMode.HALF_UP); + importo = IntegerUtility.round(importo, 5); + return importo; + } + + public static BigDecimal calcImposta(BigDecimal importo, BigDecimal percAliq) { + percAliq = percAliq.divide(new BigDecimal("100")); + percAliq = BigDecimal.ONE.add(percAliq); + importo = importo.divide(percAliq, EmsRestConstants.cifreDecMax, RoundingMode.HALF_UP); + importo = IntegerUtility.round(importo, 2); + return importo; + } + + private static Boolean validateCheck(Object arg0, Object arg1, String comparator) { + + if (arg0 == null || arg0.equals(EmsRestConstants.NULL)) + arg0 = "null"; + if (arg1 == null || arg0.equals(EmsRestConstants.NULL)) + arg1 = "null"; + + if (arg0 instanceof String) + arg0 = UtilityDB.valueToString(arg0.toString()); + if (arg1 instanceof String) + arg1 = UtilityDB.valueToString(arg1.toString()); + + ExpressionParser parser = new SpelExpressionParser(); + Expression exp = parser.parseExpression(arg0.toString() + comparator + arg1.toString()); + return (Boolean) exp.getValue(); + } + + public static String completeFlagKitArt(Connection conn, String codMart) throws SQLException { + String flagKit = "N"; + + String sql = "SELECT flag_kit FROM mvw_kit WHERE cod_mart = " + UtilityDB.valueToString(codMart); + List> list = execQuery(conn, sql); + if (!list.isEmpty()) { + flagKit = list.get(0).get("flag_kit").toString(); + } + + return flagKit; + } + + public static Integer completeIdRilPrz(Connection conn, Date dataRil) throws Exception { + Integer anno = UtilityDate.getYear(dataRil); + String sql = + "SELECT isNull(max(id_ril), 0) as id_ril " + + " FROM vtb_ril_przt " + + " WHERE year(vtb_ril_przt.data_ril) = " + anno + "AND " + + "vtb_ril_przt.id_ril like '" + anno + "%' "; + + Integer idRil = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + if (idRil == 0) { + idRil = anno * 10000 + 1; + } else { + Integer idRilTemp = new Integer(UtilityString.mid(idRil.toString(), 5)); + idRilTemp += 1; + idRil = new Integer(anno + UtilityString.leftPad(idRilTemp.toString(), 4, '0')); + } + return idRil; + } + + public static String getFullName(Connection connection, String username) throws Exception { + String sql = "SELECT full_name FROM stb_user WHERE user_name = '" + username + "'"; + String value = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + + if (!UtilityString.isNullOrEmpty(value)) return value; + + return username; + } + + public static String getUserNameFromFullName(Connection connection, String fullName) throws Exception { + if (!UtilityString.isNullOrEmpty(fullName)) { + String sql = Query.format("SELECT user_name FROM stb_user WHERE full_name = %s", + fullName); + return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + } + return null; + } + + public static List calcPercAliq(Connection conn, List list) throws Exception { + for (WdtbOrdr row : list) { + if (row.getPercAliq() == null && row.getCodAliq() != null) + row.setPercAliq(CommonRules.completePercAliq(conn, row.getCodAliq())); + } + return list; + } + + @SuppressWarnings("unchecked") + + public static List reloadRow(Connection conn, EntityBase testata) throws Exception { + List finalList = new ArrayList<>(); + List fields = testata.getEntityHolder().getEntityChildField(testata.getClass()); + + for (Field field : fields) { + finalList = new ArrayList<>(); + field.setAccessible(true); + Object object = field.get(testata); + if (object != null && field.getType().isAssignableFrom(List.class) && (field.getAnnotation(ReloadRow.class) != null || testata.getOperation() == OperationType.SUBSTITUTE)) { + List rows = (ArrayList) object; + List list = null; + if (testata.getOperation() != OperationType.DELETE_THEN_INSERT && + testata.getOperation() != OperationType.INSERT) { + list = UtilityDB.reloadOnlyDbRow(conn, testata, rows, field); + } + + if (list != null && !list.isEmpty()) { + for (EntityBase entityDB : list) { + entityDB.setLoadedFromDb(true); + DroolsDataCompleting dataCompleting = testata.getCompletingManager(); + entityDB.setParentPKAndImportFromParent(testata, true); + if (testata.getOperation() == OperationType.SUBSTITUTE) { + entityDB.setOperation(OperationType.INSERT); + } + entityDB.setCompletingManager(dataCompleting); + entityDB.setParent(testata); + + // completing dell'entity presa da database. + dataCompleting.complete(entityDB, conn, testata.getUsername()); + dataCompleting.invokeCheckRules(entityDB, conn, testata.getUsername()); + } + finalList.addAll(list); + finalList.addAll(rows); + } else { + finalList.addAll(rows); + } + + field.set(testata, finalList); + } + } + //FIX ENTITY HOLDER SULLE RIGHE + for (EntityBase entity : finalList) { + if (entity.getEntityHolder() == null) + entity.setEntityHolder(testata.getEntityHolder()); + } + return finalList; + } + + public static void updateDescrDistintaBase(Connection conn, MtbAart mtbAart) throws Exception { + String sql = + "SELECT descrizione, descrizione_estesa " + + " FROM mtb_aart " + + " WHERE cod_mart = " + UtilityDB.valueToString(mtbAart.getCodMart()); + + HashMap dati = UtilityDB.executeSimpleQueryOnlyFirstRow(conn, sql); + + if (dati != null) { + String descrizioneOld = (String) dati.get("descrizione"); + String descrizioneEstesaOld = (String) dati.get("descrizione_estesa"); + + if (!UtilityString.equalsIgnoreCase(mtbAart.getDescrizione(), descrizioneOld) || !UtilityString.equalsIgnoreCase(mtbAart.getDescrizioneEstesa(), descrizioneEstesaOld)) { + sql = + "SELECT cod_prod, " + + "CASE WHEN cod_prod = " + UtilityDB.valueToString(mtbAart.getCodMart()) + " AND descrizione_prod = " + UtilityDB.valueToString(descrizioneOld) + " THEN " + + UtilityDB.valueToString(mtbAart.getDescrizione()) + " ELSE descrizione_prod END as descrizione_prod, " + + "CASE WHEN cod_prod = " + UtilityDB.valueToString(mtbAart.getCodMart()) + " AND descrizione_estesa = " + UtilityDB.valueToString(descrizioneEstesaOld) + " THEN " + + UtilityDB.valueToString(mtbAart.getDescrizioneEstesa()) + " ELSE descrizione_estesa END as descrizione_estesa " + + " FROM jtb_cicl " + + " WHERE ( jtb_cicl.cod_prod = " + UtilityDB.valueToString(mtbAart.getCodMart()) + " OR " + + "jtb_cicl.cod_prod in (SELECT cod_prod from jtb_dist_mate WHERE cod_mart = " + UtilityDB.valueToString(mtbAart.getCodMart()) + ")) "; + + List jtbCicl = new ResultSetMapper() + .mapQuerySetToList(conn, sql, JtbCicl.class); + + for (JtbCicl dist : jtbCicl) { + if (dist.getCodProd().equalsIgnoreCase(mtbAart.getCodMart())) { + dist.setOperation(OperationType.UPDATE); + } else { + dist.setOperation(OperationType.NO_OP); + sql = "SELECT cod_mart, " + + "id_riga," + + "case when descrizione = " + UtilityDB.valueToString(descrizioneOld) + " THEN " + UtilityDB.valueToString(mtbAart.getDescrizione()) + " ELSE descrizione END as descrizione, " + + "case when descrizione_estesa = " + UtilityDB.valueToString(descrizioneEstesaOld) + " THEN " + UtilityDB.valueToString(mtbAart.getDescrizioneEstesa()) + " ELSE descrizione_estesa END as descrizione_estesa " + + "FROM jtb_dist_mate " + + "WHERE jtb_dist_mate.cod_prod = " + UtilityDB.valueToString(dist.getCodProd()) + " AND " + + "jtb_dist_mate.cod_mart = " + UtilityDB.valueToString(mtbAart.getCodMart()); + + List jtbDistMate = new ResultSetMapper() + .mapQuerySetToList(conn, sql, JtbDistMate.class, OperationType.UPDATE); + + dist.setJtbDistMate(jtbDistMate); + } + } + + mtbAart.setJtbCicl(jtbCicl); + } + } + } + + public static void completeIdRigaEntity(Connection conn, List rows, EntityBase testata) + throws Exception { + + if (!rows.isEmpty()) { + String wherePK = testata.getEntityHolder().getWherePK(testata); + Field rigaField = testata.getEntityHolder().getRigaField(rows.get(0).getClass()); + if (rigaField != null) { + rigaField.setAccessible(true); + if (rigaField != null && rigaField.getAnnotation(SqlField.class) != null) { + Integer startRiga = 0; + if (testata.getOperation() != OperationType.INSERT) { + Integer maxIdRiga = 0; + Optional maxRiga = + Stream.of(rows) + .filter(x -> x.getIdRigaEntity(x, rigaField) != null) + .max(Comparator.comparingInt(o -> o.getIdRigaEntity(o, rigaField))); + + if (maxRiga.isPresent()) { + EntityBase entityBase = maxRiga.get(); + if (entityBase.getEntityHolder() == null) { + entityBase.setEntityHolder(testata.getEntityHolder()); + } + maxIdRiga = (Integer) DroolsUtil.getEntityFieldValue(entityBase, rigaField.getName()); + } + + String rigaSqlName = SqlFieldHolder.getSqlValue(rigaField.getAnnotation(SqlField.class).value(), + rigaField); + + String sql = "SELECT IsNull(max(" + rigaSqlName + "), 0) as riga " + " FROM " + + rows.get(0).getTableName() + " WHERE " + wherePK; + startRiga = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + if (startRiga == null || startRiga == 0) { + startRiga = 0; + } + + if (maxIdRiga > startRiga) { + startRiga = maxIdRiga; + } + } else { + startRiga = 0; + } + + for (EntityBase row : rows) { + if (rigaField.get(row) == null || testata.getOperation() == OperationType.INSERT) { + startRiga++; + rigaField.set(row, startRiga); + } + } + } + } + } + } + + + public static void completeIdRigaDocuLog(Connection conn, DtbDocuLog testata) + throws Exception { + + Field rigaField = testata.getEntityHolder().getRigaField(testata.getClass()); + if (rigaField != null) { + String wherePK = "dtb_docu_log.date_time_log = " + UtilityDB.valueDateToString(testata.getDateTimeLog(), CommonConstants.DATETIME_FORMAT_YMD) + " AND " + + "dtb_docu_log.flag_type = " + UtilityDB.valueToString(testata.getFlagType()) + " AND " + + "dtb_docu_log.type = " + UtilityDB.valueToString(testata.getDocType()) + " AND " + + "dtb_docu_log.format_file = " + UtilityDB.valueToString(testata.getFormatFile()); + rigaField.setAccessible(true); + if (rigaField != null && rigaField.getAnnotation(SqlField.class) != null) { + String rigaSqlName = SqlFieldHolder.getSqlValue(rigaField.getAnnotation(SqlField.class).value(), + rigaField); + + Integer startRiga = 0; + String sql = "SELECT IsNull(max(" + rigaSqlName + "), 0) as riga " + " FROM " + + testata.getTableName() + " WHERE " + wherePK; + List> list = execQuery(conn, sql); + if (list.isEmpty()) { + startRiga = 1; + } else { + startRiga = new Integer(list.get(0).get("riga").toString()) + 1; + } + + rigaField.set(testata, startRiga); + + } + } + + } + + public static void completePosRigaEntity(Connection conn, DtbOrdt testata) throws Exception { + List rows = Stream.of(testata.getDtbOrdr()).filter(x -> x.getOperation() != OperationType.DELETE).toList(); + if (!rows.isEmpty()) { + if (testata.getExecuteRecalc()) { + ComparatorCompat c = + new ComparatorCompat(Comparator.comparingInt(a -> UtilityInteger.isNull(a.getPosRiga(), Integer.MAX_VALUE))) + .thenComparing(Comparator.comparingInt(DtbOrdr::getRigaOrd)); + + rows = Stream.of(rows).sorted(c).toList(); + } else { + Integer posRigaLista = + Stream.of(rows) + .filter(x -> x.getPosRiga() != null).max(Comparator.comparingInt(DtbOrdr::getPosRiga)).map(x -> x.getPosRiga()).orElse(1); + String sql = + "SELECT ISNULL(max(pos_riga), 0) as pos_riga " + + " FROM dtb_ordr "; + + sql = UtilityDB.addwhereCond(sql, testata.getPkWhereCond(), false); + + Integer posRigaDb = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + + if (posRigaDb.intValue() > posRigaLista.intValue()) { + posRigaLista = posRigaDb; + } + AtomicReference i = new AtomicReference<>(posRigaLista); + Stream.of(rows).filter(x -> x.getPosRiga() == null).forEach(x -> x.setPosRiga(i.getAndSet(i.get() + 1))); + } + + Integer rigaPrec = 0; + for (DtbOrdr row : rows) { + if (row.getPosRiga() == null || rigaPrec.equals(row.getPosRiga())) { + rigaPrec++; + row.setPosRiga(rigaPrec); + } else { + rigaPrec = row.getPosRiga(); + } + } + + } + } + + public static void completeRigaCtbMovr(EntityBase testata) { + //questo campo definisce anche l'ordinemanto delle righe quindi viene sempre riassegnato. + Integer startRiga = 0; + + List rows = + Stream.of(((CtbMovt) testata).getCtbMovr()) + .filter(x -> x.getOperation() != OperationType.DELETE) + .toList(); + + for (CtbMovr row : rows) { + startRiga++; + row.setRiga(startRiga); + } + } + + public static void completeIdRigaCtbMovrCoan(Connection conn, List rows, EntityBase testata) throws Exception { + + if (!rows.isEmpty()) { + String wherePK = "ctb_movr_coan.num_cmov = " + UtilityDB.valueToString(((CtbMovr) testata).getNumCmov()) + " AND " + + "ctb_movr_coan.id_riga = " + UtilityDB.valueToString(((CtbMovr) testata).getIdRiga()); + Field rigaField = testata.getEntityHolder().getRigaField(rows.get(0).getClass()); + if (rigaField != null) { + rigaField.setAccessible(true); + if (rigaField != null && rigaField.getAnnotation(SqlField.class) != null) { + + String rigaSqlName = SqlFieldHolder.getSqlValue(rigaField.getAnnotation(SqlField.class).value(), + rigaField); + + Integer startRiga = 0; + String sql = "SELECT IsNull(max(" + rigaSqlName + "), 0) as riga " + " FROM " + + rows.get(0).getTableName() + " WHERE " + wherePK; + List> list = execQuery(conn, sql); + if (list.isEmpty()) { + startRiga = 1; + } else { + startRiga = new Integer(list.get(0).get("riga").toString()) + 1; + } + + for (EntityBase row : rows) { + if (rigaField.get(row) == null) { + rigaField.set(row, startRiga); + startRiga++; + } + } + } + } + } + } + + public static void completeIdRigaJtbSchedaCq(Connection conn, String codCq, List rows) + throws Exception { + + Integer startRiga = 0; + String sql = "SELECT IsNull(max(id_riga), 0) as riga " + " FROM jtb_scheda_cqr " + " WHERE cod_cq = " + + UtilityDB.valueToString(codCq); + List> list = execQuery(conn, sql); + if (list.isEmpty()) { + startRiga = 1; + } else { + startRiga = new Integer(list.get(0).get("riga").toString()) + 1; + } + + for (JtbSchedaCqr row : rows) { + if (row.getOperation() == OperationType.INSERT) { + row.setIdRiga(startRiga); + startRiga++; + } + } + } + + public static BigDecimal completeRapConv(Connection conn, EntityBase entity) throws Exception { + String fieldUntMis = null; + + String codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_mart"); + if (entity instanceof MtbLisa) { + fieldUntMis = "unt_mis_acq"; + } else if (entity instanceof DtbOrdr || entity instanceof WdtbOrdr) { + fieldUntMis = "unt_ord"; + } else if (entity instanceof DtbDocr || entity instanceof WdtbDocr) { + fieldUntMis = "unt_doc"; + } + String untMis = (String) DroolsUtil.getEntityFieldValue(entity, fieldUntMis); + + BigDecimal value = BigDecimal.ONE; + + + String query = "SELECT CASE " + UtilityDB.valueToString(untMis) + " WHEN unt_mis THEN 1 " + + " WHEN unt_mis2 THEN rap_conv2 " + " WHEN unt_mis3 THEN rap_conv3 " + " ELSE 1 END as rap_conv " + + " FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); + PreparedStatement info = conn.prepareStatement(query); + ResultSet res = info.executeQuery(); + if (res.next()) { + value = res.getBigDecimal("rap_conv"); + } + res.close(); + info.close(); + + return value; + } + + public static BigDecimal completePrzVend(Connection conn, EntityBase entity) throws SQLException { + String codVlis = null, codMart = null; + BigDecimal przBase = BigDecimal.ZERO, ricarico = BigDecimal.ZERO, maggPrzVend = BigDecimal.ZERO; + BigDecimal przVend = BigDecimal.ZERO; + + if (entity instanceof MtbLisvData) { + MtbLisvData mtbLisvData = (MtbLisvData) entity; + codVlis = mtbLisvData.getCodVlis(); + codMart = mtbLisvData.getCodMart(); + przBase = mtbLisvData.getPrzBase(); + ricarico = mtbLisvData.getRicarica(); + maggPrzVend = mtbLisvData.getMaggPrzVend(); + } + + String query = "SELECT dbo.f_calcPrzVend(" + UtilityDB.valueToString(codVlis) + ", " + + UtilityDB.valueToString(codMart) + ", " + UtilityDB.valueToString(przBase) + ", " + + UtilityDB.valueToString(ricarico) + ", " + "mtb_aart.perc_sfrido, " + + UtilityDB.valueToString(maggPrzVend) + ") " + "FROM mtb_aart " + "WHERE mtb_aart.cod_mart = " + + UtilityDB.valueToString(codMart); + PreparedStatement info = conn.prepareStatement(query); + ResultSet res = info.executeQuery(); + if (res.next()) { + przVend = res.getBigDecimal(1); + } + res.close(); + info.close(); + + return przVend; + } + + public static BigDecimal completePrzVendIva(Connection conn, EntityBase entity) throws SQLException { + String codMart = null, codVlis = null; + BigDecimal przVend = BigDecimal.ZERO; + BigDecimal przVendIVA = BigDecimal.ZERO; + + if (entity instanceof MtbLisvData) { + MtbLisvData mtbLisvData = (MtbLisvData) entity; + codMart = mtbLisvData.getCodMart(); + codVlis = mtbLisvData.getCodVlis(); + przVend = mtbLisvData.getPrzVend(); + } + + String query = "SELECT dbo.f_calcPrzVendIva(" + UtilityDB.valueToString(codVlis) + ", " + + UtilityDB.valueToString(codMart) + ", " + UtilityDB.valueToString(przVend) + ") "; + PreparedStatement info = conn.prepareStatement(query); + ResultSet res = info.executeQuery(); + if (res.next()) { + przVendIVA = res.getBigDecimal(1); + } + res.close(); + info.close(); + + return przVendIVA; + } + + @Deprecated + public static Double getCostoUltimo(Connection conn, String applicationName, String codMart, String codMdep, + Date dataValidita) throws SQLException { + String sql = ""; + Double costoUltimo = 0d; + + /* + * if(StringUtility.isNotNull(codMdep) && "S".equals(flagCostoDepo)){ + * + * } + */ + + if (ApplicationName.WINGEST.toString().equals(applicationName)) { + sql = "SELECT cod_comp, qta_std FROM mtb_comp WHERE cod_mart = '" + codMart + "'"; + List> list = execQuery(conn, sql); + for (HashMap map : list) { + + sql = "SELECT flag_caprz_acq FROM mtb_aart WHERE cod_mart = '" + codMart + "'"; + HashMap flagCalcMap = execSingleQuery(conn, sql); + String flagCalcPrzAcq = flagCalcMap.get("flag_caprz_acq").toString(); + + if ("K".equals(flagCalcPrzAcq)) { + List> ultimoAcqList = getUltimoAcquisto(conn, codMart, dataValidita, codMdep); + + String codDivi = ""; + if (ultimoAcqList.size() == 1) { + codDivi = ultimoAcqList.get(0).get("cod_divi").toString(); + } + // ULTIMO COSTO DEL COMPOSTO VIENE DA ULTIMO DOC. DI + // ACQUISTO DEL COMPOSTO + // VA CONVERTITO IN EURO + Double cambioEuro = 0d; + sql = "SELECT gtb_divi.cambio_euro FROM gtb_divi WHERE gtb_divi.cod_divi = '" + codDivi + "'"; + + HashMap cambioEuroMap = execSingleQuery(conn, sql); + cambioEuro = Double.valueOf(cambioEuroMap.get("cambio_euro").toString()); + if (cambioEuro != 0) { + // SE IL CAMBIO HA UN VALORE ERRATO, NON FACCIO LA + // CONVERSIONE + costoUltimo = costoUltimo / cambioEuro; + } + } + if ("C".equals(flagCalcPrzAcq) || costoUltimo == 0) { + // ULTIMO COSTO = SOMMA DEI COSTI ULTIMI DEI COMPONENTI + // String codComp = map.get("cod_comp"); + Double qtaStdComp = Double.valueOf(map.get("qta_std").toString()); + Double costoComp = 0d;// getCostoUltimo(profileDB, codComp, + // dataValidita, codMdep); + costoUltimo += costoComp * qtaStdComp; + } + } + + } else { + sql = "SELECT val_ult_car FROM mtb_aart WHERE cod_mart = '" + codMart + "'"; + HashMap ultValCarMap = execSingleQuery(conn, sql); + return Double.valueOf(ultValCarMap.get("val_ult_car").toString()); + } + + return null; + + } + + @Deprecated + public static List> getUltimoAcquisto(Connection conn, + String codMart, Date dataMax, String codMdep) throws SQLException { + + String sql; + + if ("".equals(codMdep)) { + sql = "SELECT top 1 dtb_doct.data_doc, dtb_doct.cod_anag, " + + " gtb_anag.rag_soc, dtb_doct.cod_divi, " + + " ((dtb_docr.val_unt / dtb_docr.rap_conv) * (1 - sconto1/100) * (1 - sconto2/100) * (1 - sconto3/100) * (1 - sconto4/100) * (1 - sconto5/100) * (1 - sconto6/100) * (1 - sconto7/100) * (1 - sconto8/100))" + + " FROM dtb_doct, dtb_docr, dtb_tipi, gtb_anag " + + " WHERE dtb_doct.cod_anag = dtb_docr.cod_anag and " + + " dtb_doct.cod_dtip = dtb_docr.cod_dtip and " + + " dtb_doct.data_doc = dtb_docr.data_doc and " + " dtb_doct.ser_doc = dtb_docr.ser_doc and " + + " dtb_doct.num_doc = dtb_docr.num_doc and " + + " dtb_doct.cod_anag = gtb_anag.cod_anag and " + + " dtb_doct.cod_dtip = dtb_tipi.cod_dtip and " + " dtb_tipi.segno_val_car = 1 and " + + " dtb_tipi.gestione <> 'V' and " + " dtb_tipi.flag_costo = 'S' and " + + " dtb_doct.data_doc <= '" + new SimpleDateFormat("yyyy-MM-dd").format(dataMax) + "'" + + " and " + " dtb_docr.cod_mart = '" + codMart + "' and " + + " dtb_docr.importo_riga > 0 " + " ORDER BY dtb_doct.data_doc DESC "; + } else { + sql = "SELECT top 1 dtb_doct.data_doc, " + " dtb_doct.cod_anag, " + " gtb_anag.rag_soc, " + + " dtb_doct.cod_divi, " + + " ((dtb_docr.val_unt / dtb_docr.rap_conv) * (1 - sconto1/100) * (1 - sconto2/100) * (1 - sconto3/100) * (1 - sconto4/100) * (1 - sconto5/100) * (1 - sconto6/100) * (1 - sconto7/100) * (1 - sconto8/100))" + + " FROM dtb_doct, dtb_docr, dtb_tipi, gtb_anag " + + " WHERE dtb_doct.cod_anag = dtb_docr.cod_anag and " + + " dtb_doct.cod_dtip = dtb_docr.cod_dtip and " + + " dtb_doct.data_doc = dtb_docr.data_doc and " + + " dtb_doct.ser_doc = dtb_docr.ser_doc and " + + " dtb_doct.num_doc = dtb_docr.num_doc and " + + " dtb_doct.cod_anag = gtb_anag.cod_anag and " + + " dtb_doct.cod_dtip = dtb_tipi.cod_dtip and " + " dtb_tipi.segno_val_car = 1 and " + + " dtb_tipi.gestione <> 'V' and " + " dtb_tipi.flag_costo = 'S' and " + + " dtb_doct.data_doc <= '" + new SimpleDateFormat("yyyy-MM-dd").format(dataMax) + "'" + + " and " + " dtb_docr.cod_mart = '" + codMart + "' and " + + " dtb_docr.importo_riga > 0 and " + " dtb_doct.cod_mdep = '" + codMdep + "' " + + " ORDER BY dtb_doct.data_doc DESC "; + } + return execQuery(conn, sql); + } + + public static String completeCodBarre(Connection connection, String codMart) + throws SQLException { + String sql = "SELECT mvw_barcode_det.cod_barre " + "FROM mvw_barcode_det " + + "WHERE mvw_barcode_det.cod_mart = '" + codMart + "'"; + List> result = execQuery(connection, sql); + + String barcode = null; + + if (result != null && !result.isEmpty() && result.get(0).containsKey("cod_barre")) + barcode = result.get(0).get("cod_barre").toString(); + + return barcode; + } + + public static String completeCodBarreScontrini(Connection connection, String codMart) + throws Exception { + String sql = "SELECT TOP 1 mvw_barcode_det.cod_barre " + "FROM mvw_barcode_det " + + "WHERE mvw_barcode_det.cod_mart = '" + codMart + "' and len(mvw_barcode_det.cod_barre) <= 13"; + String barcode = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + return barcode; + } + + public static String completeFlagQtaCnfFissa(Connection connection, IntegryCustomerDB customerDB, String codMart) { + final EntityCacheComponent entityCacheComponent = ApplicationContextProvider.getApplicationContext().getBean(EntityCacheComponent.class); + + final List cachedMtbAarts = entityCacheComponent.getCachedEntitiesList(customerDB, MtbAart.ENTITY, x -> x.getCodMart().equals(codMart)); + + if (cachedMtbAarts == null || cachedMtbAarts.isEmpty()) + return null; + + return cachedMtbAarts.get(0).getFlagQtaCnfFissa(); + } + + public static String getApplicationName(Connection connection) throws Exception { + String sql = "select application_name from azienda"; + return (String) getSingleValue(connection, sql); + + } + + public static String completeCodDiviCont(Connection connection) throws Exception { + String sql = "select cod_divi_contab from azienda"; + String codDivi = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + return codDivi; + } + +/* + public static Double completeCambioDiviCont(Connection connection) throws SQLException { + String sql = "select gtb_divi.cambio FROM azienda LEFT OUTER JOIN gtb_divi ON azienda.cod_divi_contab = gtb_divi.cod_divi"; + List> list = execQuery(connection, sql); + if (list.isEmpty()) { + return new Double("1"); + } else { + return new Double(list.get(0).get("cambio").toString()); + } + } + */ + + public static BigDecimal completeCambio(Connection conn, EntityBase testata) throws Exception { + String codDivi = (String) DroolsUtil.getEntityFieldValue(testata, "cod_divi_cont"); + return completeCambio(conn, codDivi); + } + + public static BigDecimal completeCambio(Connection conn, String codDivi) throws SQLException { + String sql = "select gtb_divi.cambio FROM gtb_divi WHERE gtb_divi.cod_divi = " + UtilityDB.valueToString(codDivi); + return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + } + + public static HashMap completeCodDivi(Connection connection) throws SQLException { + return completeCodDivi(connection, new Date()); + } + + public static HashMap completeCodDivi(Connection connection, Date data) throws SQLException { + Integer anno = UtilityDate.datePart(Calendar.YEAR, data); + return completeCodDivi(connection, anno); + } + + public static HashMap completeCodDivi(Connection connection, LocalDate data) throws SQLException { + Integer anno = data.getYear(); + return completeCodDivi(connection, anno); + } + + public static HashMap completeCodDivi(Connection connection, Integer anno) throws SQLException { + String sql = "SELECT gtb_anni_divi.cod_divi_cont_prima AS cod_divi_contab, gtb_divi.cifre_dec, gtb_divi.cambio\n" + + "FROM gtb_anni_divi\n" + + " INNER JOIN gtb_divi ON gtb_anni_divi.cod_divi_cont_prima = gtb_divi.cod_divi\n" + + "WHERE anno = " + UtilityDB.valueToString(anno); + return execSingleQuery(connection, sql); + } + + public static Integer completeCifreDecDiviCont(Connection connection, String codDivi) throws SQLException { + String sql = "SELECT cifre_dec FROM gtb_divi" + " WHERE cod_divi = " + UtilityDB.valueToString(codDivi); + PreparedStatement ps = connection.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + Integer cifreDec = null; + if (rs.next()) { + cifreDec = rs.getInt(1); + } + rs.close(); + ps.close(); + return cifreDec; + } + + public static BigDecimal roundValue(BigDecimal value, Integer cifreDec) throws Exception { + if (cifreDec == null) + cifreDec = EmsRestConstants.cifreDecMax; + return IntegerUtility.round(value, cifreDec); + } + + public static String completeUntMis(Connection connection, String codMart) throws Exception { + String sql = + "SELECT mtb_aart.unt_mis " + + " FROM mtb_aart " + + " WHERE mtb_aart.cod_mart = " + UtilityDB.valueToString(codMart); + String untMis = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + + if (UtilityString.isNullOrEmpty(untMis)) { + throw new Exception("Codice articolo " + codMart + " inesitente"); + } + return untMis; + } + + public static Object completeWithDefault(Class clazz, String fieldName) throws Exception { + + + Object value = null; + Field f = ReflectionUtils.findField(clazz, fieldName); + if (f != null) { + SqlField sql; + if ((sql = f.getAnnotation(SqlField.class)) != null) { + value = SqlFieldHolder.applyConvert(sql.defaultObjectValue(), f.getType()); + } + } + return value; + } + + public static BigDecimal completeQtaCnfOffA(Connection connection, AtbOffr atbOffr) throws Exception { + AtbOfft atbOfft = (AtbOfft) atbOffr.getParent(); + String sql = null; + BigDecimal qtaCnf = null; + if (atbOfft.getCodAlis() != null) { + sql = + Query.format( + "SELECT qta_cnf\n" + + " FROM dbo.getListinoAcquisto(%s,%s,%s,%s, 'N', null) lisa\n" + + " WHERE IsNull(lisa.tipo_variazione, 'I') <> 'D' AND\n" + + "lisa.flag_attivo = 'S' ", + atbOfft.getDataIniz(), + atbOfft.getCodAlis(), + atbOffr.getCodArtForn(), + atbOffr.getCodMart()); + qtaCnf = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + } + + if (UtilityBigDecimal.isNullOrZero(qtaCnf)) { + sql = + Query.format("SELECT qta_cnf FROM mtb_aart WHERE cod_mart = %s", atbOffr.getCodMart()); + qtaCnf = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + } + + if (!UtilityBigDecimal.isNullOrZero(atbOffr.getRapConv()) && atbOffr.getRapConv().compareTo(BigDecimal.ONE) != 0) { + qtaCnf = qtaCnf.divide(atbOffr.getRapConv(), RoundingMode.HALF_UP); + } + return qtaCnf; + } + + public static String completeCodAliqSimple(Connection connection, String codMart) + throws Exception { + + String sql = + "SELECT mtb_aart.cod_aliq" + + " FROM mtb_aart " + + " WHERE mtb_aart.cod_mart = '" + codMart + "'"; + + return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + } + + public static BigDecimal completePercAliq(Connection connection, EntityBase entity) throws Exception { + String codAliq = (String) DroolsUtil.getEntityFieldValue(entity, "cod_aliq"); + + return completePercAliq(connection, codAliq); + } + + public static BigDecimal completePercAliq(Connection connection, String codAliq) throws SQLException { + String sql = "SELECT perc_aliq FROM gtb_aliq WHERE cod_aliq = " + UtilityDB.valueToString(codAliq); + HashMap map = execSingleQuery(connection, sql); + if (map.get("perc_aliq") != null) + return new BigDecimal(map.get("perc_aliq").toString()); + else + return BigDecimal.ZERO; + } + + public static BigDecimal completeQtaCnf(Connection connection, EntityBase entityBase) throws Exception { + BigDecimal qtaCnf = null; + if (entityBase instanceof MtbColr) { + MtbColr mtbColr = ((MtbColr) entityBase); + String sql = "SELECT * FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(mtbColr.getCodMart()); + MtbAart mtbAart = new ResultSetMapper() + .mapQueryToObject(connection, sql, MtbAart.class); + + if (mtbAart == null) + throw new Exception(String.format("Codice Articolo %s non trovato", mtbColr.getCodMart())); + + qtaCnf = DocOrdUntMisRules.calcQtaCnf(connection, mtbColr.getCodMart(), mtbColr.getPartitaMag(), mtbAart, mtbColr.getNumCnf(), BigDecimal.ONE, mtbColr.getQtaCol(), mtbColr.getQtaCnf()); + } + + if (qtaCnf == null) { + String codMart = (String) DroolsUtil.getEntityFieldValue(entityBase, "cod_mart"); + String sql = "SELECT qta_cnf FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); + + qtaCnf = (BigDecimal) getSingleValue(connection, sql); + if (qtaCnf == null) { + qtaCnf = BigDecimal.ONE; + } + } + return qtaCnf; + } + + public static HashMap completeDescrizione(Connection connection, EntityBase entity) throws Exception { + String codMart; + if (entity instanceof JtbCicl) { + codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_prod"); + } else { + codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_mart"); + } + + String sql = "SELECT mtb_aart.descrizione, descrizione_estesa " + "FROM mtb_aart " + + "WHERE mtb_aart.cod_mart = " + UtilityDB.valueToString(codMart); + return execSingleQuery(connection, sql); + } + + public static BigDecimal completeValUntUltPrezzo(Connection conn, EntityBase entity) throws Exception { + String codMart = (String) DroolsUtil.getEntityFieldValue(entity, "cod_mart"); + BigDecimal rapConv = (BigDecimal) DroolsUtil.getEntityFieldValue(entity, "rap_conv"); + + String sql = "SELECT val_ult_scar FROM mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); + BigDecimal valUltScar = (BigDecimal) getSingleValue(conn, sql); + return valUltScar; + } + + public static BigDecimal completeValUntULTC(Connection conn, DtbDocOrdR entity) throws Exception { + String codMart = entity.getCodMart(); + String codMdep = entity.getCodMdep(); + BigDecimal rapConv = entity.getRapConv(); + + + Date dataValidita = null; + if (entity instanceof DtbOrdr || entity instanceof WdtbOrdr) { + dataValidita = entity.getDataOrd(); + } else if (entity instanceof DtbDocr || entity instanceof WdtbDocr) { + if (entity instanceof DtbDocr) { + dataValidita = ((DtbDocr) entity).getDataDoc(); + } else { + dataValidita = ((WdtbDocr) entity).getDataDoc(); + } + } + BigDecimal valUnt = completeValUntULTC(conn, codMdep, codMart, dataValidita, rapConv); + return valUnt; + } + + public static BigDecimal completeValUntULTC(Connection conn, String codMdep, String codMart, Date dataValidita, BigDecimal rapConv) throws Exception { + if (rapConv.compareTo(BigDecimal.ZERO) == 0) rapConv = BigDecimal.ONE; + String sql = "SELECT Round(isNull(dbo.f_GetCostoUltArt_depo(" + + UtilityDB.valueDateToString(dataValidita, CommonConstants.DATE_FORMAT_YMD) + "," + + UtilityDB.valueToString(codMdep) + "," + UtilityDB.valueToString(codMart) + "), 0)*" + UtilityDB.valueToString(rapConv) + ", 5) as costo_ult"; + BigDecimal valUnt = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + return valUnt; + } + + + public static BigDecimal completeValUntDIST(Connection conn, EntityBase entity) throws SQLException { + String codMart = null, codMdep = null; + Date dataValidita = null; + if (entity instanceof DtbOrdr) { + codMart = ((DtbOrdr) entity).getCodMart(); + codMdep = ((DtbOrdr) entity).getCodMdep(); + dataValidita = ((DtbOrdr) entity).getDataOrd(); + } else if (entity instanceof DtbDocr) { + codMart = ((DtbDocr) entity).getCodMart(); + codMdep = ((DtbDocr) entity).getCodMdep(); + dataValidita = ((DtbDocr) entity).getDataDoc(); + } else if (entity instanceof MtbInvenr) { + codMart = ((MtbInvenr) entity).getCodMart(); + codMdep = ((MtbInvenr) entity).getCodMdep(); + dataValidita = ((MtbInvenr) entity).getDataInventario(); + } + String sql = "SELECT dbo.f_GetCostoDist_depo('', " + + UtilityDB.valueToString(codMart) + "," + + "1, " + + "0, " + + UtilityDB.valueDateToString(dataValidita, CommonConstants.DATE_FORMAT_YMD) + "," + + UtilityDB.valueToString(codMdep) + ") as costo_dist"; + BigDecimal valUnt = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + if (valUnt == null) + return BigDecimal.ZERO; + else + return valUnt; + } + + public static BigDecimal completeValUntCMED(Connection conn, EntityBase entity) throws SQLException { + String codMart = null; + Date dataValidita = null; + if (entity instanceof DtbOrdr) { + codMart = ((DtbOrdr) entity).getCodMart(); + dataValidita = ((DtbOrdr) entity).getDataOrd(); + } else if (entity instanceof MtbInvenr) { + codMart = ((MtbInvenr) entity).getCodMart(); + dataValidita = ((MtbInvenr) entity).getDataInventario(); + } + String sql = "SELECT dbo.f_GetCostoMedArt(" + + UtilityDB.valueDateToString(dataValidita, CommonConstants.DATE_FORMAT_YMD) + "," + + UtilityDB.valueToString(codMart) + ") as costo_med"; + List> list = execQuery(conn, sql); + if (list.isEmpty()) { + return BigDecimal.ZERO; + } else { + return new BigDecimal(list.get(0).get("costo_med").toString()); + } + } + + public static void completeActivityIdChild(StbActivity activity) { + for (StbActivityFile stbActivityFile : activity.getStbActivityFile()) { + stbActivityFile.setId(activity.getActivityId()); + } + } + + public static String completeDescrizionePaga(Connection conn, String codPaga) throws SQLException { + String sql = "SELECT descrizione FROM gtb_paga WHERE gtb_paga.cod_paga = " + UtilityDB.valueToString(codPaga); + HashMap map = execSingleQuery(conn, sql); + if (map.get("descrizione") == null) + return null; + else + return map.get("descrizione").toString(); + } + + public static MtbAartMarchio insMarchio(Connection conn, MtbAart entity) throws Exception { + String sql = "SELECT cast(count(*) as bit) FROM mtb_aart_marchio WHERE marchio = " + UtilityDB.valueToString(entity.getMarchio()); + Boolean existMarchio = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + MtbAartMarchio mtbAartMarchio = null; + + if (existMarchio) { + mtbAartMarchio = new MtbAartMarchio(); + mtbAartMarchio.setMarchio(entity.getMarchio()); + mtbAartMarchio.setOperation(OperationType.INSERT); + } + return mtbAartMarchio; + } + + public static void setIdArtEqui(Connection conn, MtbAart entity) throws Exception { + if (!UtilityString.isNullOrEmpty(entity.getIdArtEqui())) return; + boolean setSetIdArtEqui = setupGest.getSetupBoolean(conn, "MTB_AART", "ID_ART_EQUI", "INSERT_AUTO"); + if (!setSetIdArtEqui) return; + + // Convertire in JSON + entity.setOnlyPkMaster(false); + ResponseJSONObjectMapper objectMapper = ContextLoader.getCurrentWebApplicationContext().getBean(ResponseJSONObjectMapper.class); + String jsonParm = objectMapper.writeValueAsString(entity); + String sql = + String.format( + "SELECT * FROM dbo.suggestMtbArtEqui('%s') ", + jsonParm); + MtbAartEqui mtbAartEqui = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(conn, sql, MtbAartEqui.class); + if (mtbAartEqui != null) { + String idArtEqui = mtbAartEqui.getIdArtEqui(); + if (UtilityString.isNullOrEmpty(mtbAartEqui.getIdArtEqui())) { + idArtEqui = entity.getCodMart(); + mtbAartEqui.setIdArtEqui(idArtEqui) + .setFlagEquiPrezzo("T"); + mtbAartEqui.setOperation(OperationType.INSERT_OR_UPDATE); + } + entity.setIdArtEqui(idArtEqui); + } + } + + public static MtbAartEqui insEqui(Connection conn, MtbAart entity) throws Exception { + String sql = "SELECT id_art_equi FROM mtb_aart_equi WHERE id_art_equi = " + UtilityDB.valueToString(entity.getIdArtEqui()); + HashMap map = execSingleQuery(conn, sql); + MtbAartEqui mtbAartEqui = null; + if (map == null || map.isEmpty() || map.get("id_art_equi") == null) { + mtbAartEqui = new MtbAartEqui(); + mtbAartEqui.setIdArtEqui(entity.getIdArtEqui()); + mtbAartEqui.setDescrizione(entity.getMtbAartEqui_descrizione()); + mtbAartEqui.setOperation(OperationType.INSERT); + } + return mtbAartEqui; + } + + public static List insUntMis(Connection conn, MtbAart mtbAart) throws Exception { + List mtbUntMisList = new ArrayList<>(); + List untMisList = new ArrayList<>(); + + if (!UtilityString.isNullOrEmpty(mtbAart.getUntMis())) { + untMisList.add(mtbAart.getUntMis()); + } + if (!UtilityString.isNullOrEmpty(mtbAart.getUntMis2())) { + untMisList.add(mtbAart.getUntMis2()); + } + if (!UtilityString.isNullOrEmpty(mtbAart.getUntMis3())) { + untMisList.add(mtbAart.getUntMis3()); + } + + for (String untMis : untMisList) { + String sql = "SELECT count(*) FROM mtb_unt_mis WHERE unt_mis = " + UtilityDB.valueToString(untMis); + Integer countUM = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + if (countUM == null || countUM == 0) { + MtbUntMis mtbUntMis = new MtbUntMis(); + mtbUntMis.setUntMis(untMis); + mtbUntMis.setOperation(OperationType.INSERT); + mtbUntMisList.add(mtbUntMis); + } + } + + + return mtbUntMisList; + } + + public static Integer completeNumDist(Connection conn, VtbDistIncat vtbDistIncat) throws Exception { + String sql = + "SELECT max(num_dist) " + + "FROM vtb_dist_incat " + + "WHERE DatePart(Year, data_dist) = DatePart(Year, " + UtilityDB.valueToString(vtbDistIncat.getDataDist()) + ") "; + + Integer numDist = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + if (numDist == null) numDist = 0; + numDist++; + return numDist; + } + + public static String completeFlagRegAcc(Connection conn, VtbDistIncar vtbDistIncar) throws Exception { + String flagRegAcc = "S"; + String sql = + "SELECT prevista_fat FROM dtb_tipi WHERE cod_dtip = " + UtilityDB.valueToString(vtbDistIncar.getCodDtip()); + String previstaFat = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + + if (previstaFat.equalsIgnoreCase("N")) { + flagRegAcc = "N"; + } else if (!UtilityString.isNullOrEmpty(vtbDistIncar.getFlagTipoFatturazione())) { + LocalDate dataFattura = null; + int year = UtilityDate.getYear(vtbDistIncar.getDataDoc()); + int month = UtilityDate.datePart(Calendar.MONTH, vtbDistIncar.getDataDoc()); + switch (vtbDistIncar.getFlagTipoFatturazione()) { + case "M": + dataFattura = UtilityLocalDate.getLastDayOfMonth(year, month); + break; + case "Q": + dataFattura = UtilityLocalDate.dateFromPart(year, month, 15); + break; + } + + LocalDate dataDoc = UtilityLocalDate.localDateFromDate(vtbDistIncar.getDataDoc()); + LocalDate dataDist = UtilityLocalDate.localDateFromDate(vtbDistIncar.getDataDist()); + + if ((dataDoc.equals(dataFattura) || dataDoc.isBefore(dataFattura)) && + (dataDist.equals(dataFattura) || dataDist.isAfter(dataFattura))) { + flagRegAcc = "N"; + } + } + return flagRegAcc; + } + + public static String completeFlagElaboratoDocWebA(Connection conn, WdtbDoct entity) throws Exception { + String sql = + "SELECT flag_elaborato " + + " FROM wdtb_doct " + + " WHERE wdtb_doct.cod_anag = " + UtilityDB.valueToString(entity.getCodAnag()) + " AND " + + " wdtb_doct.cod_dtip = " + UtilityDB.valueToString(entity.getCodDtip()) + " AND " + + " wdtb_doct.data_doc = " + UtilityDB.valueDateToString(entity.getDataDoc(), CommonConstants.DATE_FORMAT_YMD) + " AND " + + " wdtb_doct.ser_doc = " + UtilityDB.valueToString(entity.getSerDoc()) + " AND " + + " wdtb_doct.num_doc = " + UtilityDB.valueToString(entity.getNumDoc()); + + PreparedStatement ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + String flagElaborato = "I"; + if (rs.next()) { + flagElaborato = rs.getString(1); + } + rs.close(); + ps.close(); + + return flagElaborato; + } + + public static boolean checkCodMart(Connection conn, String codMart) throws Exception { + boolean ret = false; + String sql = "SELECT cod_mart from mtb_aart WHERE cod_mart = " + UtilityDB.valueToString(codMart); + HashMap mapCodMart = UtilityDB.executeSimpleQueryOnlyFirstRow(conn, sql); + if (mapCodMart == null) { + ret = true; + throw new Exception("Codice Articolo " + codMart + " inesistente."); + } + + return ret; + } + + public static void updateStbGestSetupDepo(Connection conn, StbGestSetup entity) throws Exception { + String sql = + "UPDATE stb_gest_setup_depo " + + " SET stb_gest_setup_depo.flag_sync = " + UtilityDB.valueToString(entity.getFlagSync()) + + " WHERE stb_gest_setup_depo.gest_name = " + UtilityDB.valueToString(entity.getGestName()) + " AND " + + " stb_gest_setup_depo.section = " + UtilityDB.valueToString(entity.getSection()) + " AND " + + " stb_gest_setup_depo.key_section = " + UtilityDB.valueToString(entity.getKeySection()); + Statement cmd = conn.createStatement(); + cmd.executeUpdate(sql); + cmd.close(); + + + } + + public static void completeRowIdEquiLog(Connection conn, MtbAartEquiLog mtbAartEquiLog) throws Exception { + String sql = + "SELECT griglia.cod_alis, " + + "griglia.cod_mdep, " + + "lisa.prz_acq_netto as prz_acq " + + " FROM dbo.getGrigliaAcquisto(null, null, null, null, " + UtilityDB.valueToString(mtbAartEquiLog.getCodMart()) + ") griglia " + + "LEFT OUTER JOIN dbo.getListinoAcquisto(null, null, null, " + UtilityDB.valueToString(mtbAartEquiLog.getCodMart()) + ", 'S', null ) lisa on griglia.cod_alis = lisa.cod_alis " + + " WHERE griglia.tipo_variazione <> 'D' AND lisa.tipo_variazione <> 'D' "; + + List mtbAartEquiLogDets = new ResultSetMapper() + .mapQuerySetToList(conn, sql, MtbAartEquiLogDet.class, OperationType.INSERT); + + mtbAartEquiLog.setMtbAartEquiLogDet(mtbAartEquiLogDets); + + } + + public static StbGestSetupQuery completeStbGestSetupQuery(Connection conn, StbGestSetup stbGestSetup) throws Exception { + StbGestSetupQuery stbGestSetupQuery = new StbGestSetupQuery(); + OperationType op = OperationType.NO_OP; + String queryDefault = stbGestSetup.getQueryDefault(); + String codQuery = stbGestSetup.getCodQuery(); + if (UtilityString.isNullOrEmpty(codQuery) && UtilityString.isNullOrEmpty(queryDefault)) { + return stbGestSetupQuery; + } + + if (UtilityString.isNullOrEmpty(codQuery)) { + String sql = + "SELECT cod_query " + + "FROM stb_gest_setup_query " + + "WHERE query_default = " + UtilityDB.valueToString(queryDefault) + " OR " + + " cod_query = " + UtilityDB.valueToString(queryDefault); + codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + + if (UtilityString.isNullOrEmpty(codQuery)) { + stbGestSetupQuery.setCodQuery(getCodQuery(conn)); + op = OperationType.INSERT; + } else { + stbGestSetupQuery.setCodQuery(codQuery); + } + + } else { + stbGestSetupQuery.setCodQuery(codQuery); + } + + stbGestSetupQuery.setQueryDefault(queryDefault); + stbGestSetupQuery.setOperation(op); + return stbGestSetupQuery; + } + + public static String getCodQuery(Connection conn) throws Exception { + String sql = "SELECT MAX(CAST(cod_query AS INT)) + 1 FROM stb_gest_setup_query WHERE IsNumeric(cod_query) = 1"; + return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql).toString(); + } + + + public static boolean barCodeCheck(Connection conn, String barCode) throws Exception { + String sql; + HashMap map; + int check = 0; + + sql = " SELECT COUNT(cod_barre) as num_check " + + " FROM mvw_barcode " + + " WHERE cod_barre = " + UtilityDB.valueToString(barCode); + map = execSingleQuery(conn, sql); + if (!map.isEmpty()) { + check = new Integer(map.get("num_check").toString()); + if (check == 0) { + String applName = CommonRules.getApplicationName(conn); + if (ApplicationName.TEXTILES.toString().equals(applName)) { + map.clear(); + sql = " SELECT COUNT(cod_barre) as num_check " + + " FROM ttb_bar_code " + + " WHERE cod_barre = " + UtilityDB.valueToString(barCode); + map = execSingleQuery(conn, sql); + if (!map.isEmpty()) + check = new Integer(map.get("num_check").toString()); + } + } + } + if (check == 0) {//CODICE A BARRE NON TROVATO. + return true; + } else { + return false; + } + } + + + public static int retrieveNextProgressivoUl(Connection conn, String gestione, LocalDate dataOrd, int numOrd, int segno) throws SQLException { + String sql = Query.format("SELECT ISNULL(MAX(progressivo_ul), 0) AS progressivo_ul" + + " FROM " + MtbColt.ENTITY + + " WHERE data_ord = {} AND " + + " num_ord = {} AND " + + " gestione = {} AND " + + " segno = {}", dataOrd, numOrd, gestione, segno); + + int maxProgressivoUl = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + return maxProgressivoUl + 1; + } + + public static int retrieveNextProgressivoUlRG(Connection conn, String gestione, LocalDate dataOrd, int numOrd, int segno) throws SQLException { + String sql = Query.format( + "WITH partite AS (SELECT dot.cod_prod AS cod_mart, mpm.partita_mag_prod, dot.cod_jfas\n" + + " FROM dtb_ordt dot\n" + + " INNER JOIN mtb_partita_mag mpm\n" + + " ON dot.cod_prod = mpm.cod_mart AND dot.partita_mag = mpm.partita_mag\n" + + " WHERE dot.data_ord = %s\n" + + " AND dot.num_ord = %s\n" + + " AND dot.gestione = [gestione])\n" + + "SELECT ISNULL(MAX(progressivo_ul), 0) AS progressivo_ul\n" + + "FROM mtb_colt\n" + + " INNER JOIN mtb_colr mcr ON mtb_colt.gestione = mcr.gestione AND mtb_colt.data_collo = mcr.data_collo AND\n" + + " mtb_colt.ser_collo = mcr.ser_collo AND mtb_colt.num_collo = mcr.num_collo\n" + + " INNER JOIN mtb_partita_mag mpm ON mcr.cod_mart = mpm.cod_mart AND mcr.partita_mag = mpm.partita_mag\n" + + " INNER JOIN partite ON mcr.cod_mart = partite.cod_mart AND mpm.partita_mag_prod = partite.partita_mag_prod\n" + + " AND mtb_colt.cod_jfas = partite.cod_jfas\n" + + "WHERE mtb_colt.gestione = [gestione]\n" + + " AND segno = %s", + dataOrd, + numOrd, + segno + ).replace("[gestione]", UtilityDB.valueToString(gestione)); + + int maxProgressivoUl = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql); + return maxProgressivoUl + 1; + } + + public static void updateDatiInv(Connection conn, DtbDoct entity) throws Exception { + String codAnagOld = null, serDocOld = null, codDtipOld = null; + Integer numDocOld = null; + Date dataDocOld = null; + + HashMap oldPk = entity.getOldPk(); + if (oldPk != null && !oldPk.isEmpty()) { + + if (oldPk.containsKey("codAnag")) codAnagOld = (String) oldPk.get("codAnag"); + else codAnagOld = entity.getCodAnag(); + if (oldPk.containsKey("codDtip")) codDtipOld = (String) oldPk.get("codDtip"); + else codDtipOld = entity.getCodDtip(); + if (oldPk.containsKey("dataDoc")) dataDocOld = UtilityString.parseDate((String) oldPk.get("dataDoc")); + else dataDocOld = entity.getDataDoc(); + if (oldPk.containsKey("serDoc")) serDocOld = (String) oldPk.get("serDoc"); + else serDocOld = entity.getSerDoc(); + if (oldPk.containsKey("numDoc")) numDocOld = (Integer) oldPk.get("numDoc"); + else numDocOld = entity.getNumDoc(); + + if (!entity.getCodDtip().equals(codDtipOld) || + !entity.getCodAnag().equals(codAnagOld) || + !entity.getDataDoc().equals(dataDocOld) || + entity.getSerDoc().equals(serDocOld) || + !entity.getNumDoc().equals(numDocOld)) { + String sql = + "UPDATE mtb_invent " + + "SET cod_anag = " + UtilityDB.valueToString(entity.getCodAnag()) + ", " + + "cod_dtip = " + UtilityDB.valueToString(entity.getCodDtip()) + ", " + + "data_doc = " + UtilityDB.valueDateToString(entity.getDataDoc(), CommonConstants.DATE_FORMAT_YMD) + ", " + + "ser_doc = " + UtilityDB.valueToString(entity.getSerDoc()) + ", " + + "num_doc = " + UtilityDB.valueToString(entity.getNumDoc()); + sql = UtilityDB.addwhereCond(sql, entity.getWhereCondOldPk(null), false); + conn.createStatement().executeUpdate(sql); + } + } + } + + public static boolean getChkCompatibilitaCarat(Connection connection, String codMart, String carat) throws SQLException { + String sql = + Query.format("SELECT chk_compatibilita\n" + + "FROM mtb_aart\n" + + " INNER JOIN mtb_tipi_carat ON mtb_aart.cod_mtip = mtb_tipi_carat.cod_mtip AND\n" + + " mtb_aart.cod_mstp = mtb_tipi_carat.cod_mstp\n" + + "WHERE mtb_aart.cod_mart = %s\n" + + " AND mtb_tipi_carat.carat = %s\n" , + codMart, carat); + + Boolean chkCompatibilita = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql); + if (chkCompatibilita == null) chkCompatibilita = false; + return chkCompatibilita; + + } } \ No newline at end of file