diff --git a/crov-prase-controller/src/main/java/com/arrebol/taxiservicios/controller/admin/ClosingDayController.java b/crov-prase-controller/src/main/java/com/arrebol/taxiservicios/controller/admin/ClosingDayController.java index cb69930..f1fee77 100644 --- a/crov-prase-controller/src/main/java/com/arrebol/taxiservicios/controller/admin/ClosingDayController.java +++ b/crov-prase-controller/src/main/java/com/arrebol/taxiservicios/controller/admin/ClosingDayController.java @@ -1,8 +1,8 @@ /* * Arrebol Consultancy copyright. - * + * * This code belongs to Arrebol Consultancy - * its use, redistribution or modification are prohibited + * its use, redistribution or modification are prohibited * without written authorization from Arrebol Consultancy. */ package com.arrebol.taxiservicios.controller.admin; @@ -46,999 +46,999 @@ import org.hibernate.query.Query; */ public class ClosingDayController extends ConnectionManager implements Serializable { - /** - * - * @param date - * @return - */ - public boolean existStableSmallBoxByCreatedOn(Date date) { - logger.info("existStableSmallBoxByCreatedOn"); - - boolean success = true; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - String query = "SELECT COUNT(ssb.id) " - + "FROM StableSmallBox ssb " - + "WHERE DATE(ssb.createdOn) = DATE(:date) " - + "AND ssb.activeStatus = 'ENEBLED'"; - - Long count = (Long) session.createQuery(query).setParameter("date", date).uniqueResult(); - - if (null != count && count == 0) { - success = false; - } - - transaction.commit(); - - logger.info("Total of closing day found: " + count); - } catch (HibernateException e) { - logger.error("Can not find stable small box by created on", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method existStableSmallBoxByCreatedOn()", e); - rollback(transaction); - } - - return success; - } - - /** - * - * @param date - * @return - */ - public boolean existNextPaidClosingDayByCreatedOn(Date date) { - logger.info("existNextPaidClosingDayByCreatedOn"); - - boolean success = true; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - String query = "SELECT cd.id " - + "FROM closing_day cd " - + "WHERE DATE(cd.created_on) >= DATE_ADD(DATE(:date), INTERVAL 1 DAY) " - + "AND cd.active_status = 'ENEBLED'"; - - List records = session.createSQLQuery(query).setParameter("date", date).getResultList(); - - if (records.isEmpty()) { - success = false; - } - - transaction.commit(); - - logger.info("Total of closing day found: " + records.size()); - } catch (HibernateException e) { - logger.error("Can not find next closing day by created on", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method existNextPaidClosingDayByCreatedOn()", e); - rollback(transaction); - } - - return success; - } - - /** - * - * @param location - * @return - */ - public List getAllActiveUsers(Location location) { - logger.info("getAllActiveUsers"); - - List users = new ArrayList<>(); - Transaction transaction = null; - - try { - List usersAlreadyClosedDay = getAllUsersWithClasingDay(); - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(User.class); - Root root = query.from(User.class); - - Path id = root.get("id"); - Path person = root.get("person"); - Predicate criterioLocation = builder.equal(root.get("location"), location); - - Predicate userStatusTypePredicate = builder.equal(root.get("userStatusType"), UserStatusType.ENABLED); - - query.select( - builder.construct(User.class, id, person) - ); - - if (usersAlreadyClosedDay.isEmpty()) { - query.where(userStatusTypePredicate, criterioLocation); - } else { - CriteriaBuilder.In ids = builder.in(root.get("id")); - usersAlreadyClosedDay.forEach(user -> { - ids.value(user.getId()); - }); - query.where(userStatusTypePredicate, criterioLocation, builder.not(ids)); - } - - query.orderBy(builder.asc(root.get("person"))); - - users = session.createQuery(query).getResultList(); - - transaction.commit(); - - logger.info("Employee list " + users.size()); - } catch (HibernateException e) { - logger.error("Can not find active users", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method getAllActiveUsers()", e); - rollback(transaction); - } - return users; - } - - /** - * Find Closing daily's list between Dates (Start date and End Date). - * - * @param startDate - * @param endDate - * @return - */ - public List findClosingDailyListBetweenDates(Date startDate, Date endDate, String idLocation) { - logger.info("findClosingDailyListBetweenDates"); - - List results = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(ClosingDay.class); - Root root = query.from(ClosingDay.class); - - LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - LocalDate localEndDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - - Path id = root.get("id"); - Path user = root.get("user"); - Path amountPaid = root.get("amountPaid"); - Path amountExpected = root.get("amountExpected"); - Path amountTransfer = root.get("amountTransfer"); - Path comments = root.get("comments"); - Path createdOn = root.get("createdOn"); - Path createdByPath = root.get("createdBy"); - Path locationPath = root.get("location"); - - Predicate activeStatusPredicate = builder.equal(root.get("activeStatus"), BasicType.ENEBLED); - Predicate startDatePredicate = builder.greaterThanOrEqualTo(root.get("createdOn").as(LocalDate.class), localStartDate); - Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("createdOn").as(LocalDate.class), localEndDate); - Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation)); - - query.select( - builder.construct( - ClosingDay.class, id, user, - amountPaid, amountExpected, comments, createdOn, createdByPath, locationPath, amountTransfer - ) - ); - query.where(builder.and(activeStatusPredicate, startDatePredicate, endDatePredicate, locationPredicate)); - query.orderBy(builder.asc(root.get("createdOn"))); - - results = session.createQuery(query).getResultList(); - - transaction.commit(); - - logger.info("Closing daily's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not find closing daily list between dates", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findClosingDailyListBetweenDates()", e); - rollback(transaction); - } - return results; - } - - public List findClosingDailyListBetweenDatesForCuadre(Date startDate, Date endDate, String idLocation) { - logger.info("findClosingDailyListBetweenDates"); - - List results = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(ClosingDay.class); - Root root = query.from(ClosingDay.class); - - LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - LocalDate localEndDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - - Path id = root.get("id"); - Path user = root.get("user"); - Path amountPaid = root.get("amountPaid"); - Path amountExpected = root.get("amountExpected"); - Path amountTransfer = root.get("amountTransfer"); - Path comments = root.get("comments"); - Path createdOn = root.get("createdOn"); - Path createdByPath = root.get("createdBy"); - Path locationPath = root.get("location"); - - Predicate activeStatusPredicate = builder.equal(root.get("activeStatus"), BasicType.ENEBLED); - Predicate startDatePredicate = builder.greaterThan(root.get("createdOn").as(LocalDate.class), localStartDate); - Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("createdOn").as(LocalDate.class), localEndDate); - Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation)); - - query.select( - builder.construct( - ClosingDay.class, id, user, - amountPaid, amountExpected, comments, createdOn, createdByPath, locationPath, amountTransfer - ) - ); - query.where(builder.and(activeStatusPredicate, startDatePredicate, endDatePredicate, locationPredicate)); - query.orderBy(builder.asc(root.get("createdOn"))); - - results = session.createQuery(query).getResultList(); - - transaction.commit(); - - logger.info("Closing daily's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not find closing daily list between dates", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findClosingDailyListBetweenDates()", e); - rollback(transaction); - } - return results; - } - - /** - * Find Closing daily's list between Dates (Start date and End Date). - * - * @param startDate - * @param idLocation - * @return - */ - public List FindDailyListClosingBeforeDateForCuadre(Date startDate, String idLocation) { - logger.info("findClosingDailyListBetweenDates"); - - List results = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(ClosingDay.class); - Root root = query.from(ClosingDay.class); - - LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - - Path id = root.get("id"); - Path user = root.get("user"); - Path amountPaid = root.get("amountPaid"); - Path amountExpected = root.get("amountExpected"); - Path amountTransfer = root.get("amountTransfer"); - Path comments = root.get("comments"); - Path createdOn = root.get("createdOn"); - Path createdByPath = root.get("createdBy"); - Path locationPath = root.get("location"); - - Predicate activeStatusPredicate = builder.equal(root.get("activeStatus"), BasicType.ENEBLED); - Predicate startDatePredicate = builder.lessThan(root.get("createdOn").as(LocalDate.class), localStartDate); - Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation)); - - query.select( - builder.construct( - ClosingDay.class, id, user, - amountPaid, amountExpected, comments, createdOn, createdByPath, locationPath, amountTransfer - ) - ); - - query.where(builder.and(activeStatusPredicate, startDatePredicate, locationPredicate)); - query.orderBy(builder.asc(root.get("createdOn"))); - - results = session.createQuery(query).getResultList(); - - transaction.commit(); - - logger.info("Closing daily's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not find closing daily list between dates", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findClosingDailyListBetweenDates()", e); - rollback(transaction); - } - return results; - } - - public List findClosingDailyListByStableSmallBox(StableSmallBox stableSmallBox, Date startDate, String idLocation) { - logger.info("findClosingDailyListBetweenDates"); - - logger.info("findDetailsFromClosingDayID"); - - List results = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - - transaction = session.beginTransaction(); - - results = session.createQuery("FROM ClosingDay c WHERE c.activeStatus = 'ENEBLED' AND c.location.id = :idLocation AND DATE(c.createdOn) > DATE(:fechaInicio) AND DATE(c.createdOn) <= DATE(:fechaFinal) ") - .setParameter("idLocation", idLocation) - .setParameter("fechaInicio", startDate) - .setParameter("fechaFinal", stableSmallBox.getCreatedOn()) - .getResultList(); - - transaction.commit(); - - logger.info("Closing daily detail's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not find closing daily details list", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findDetailsFromClosingDayID()", e); - rollback(transaction); - } - return results; - } - - public ClosingDay findLastClosingDay(String idLocation, String idUser) { - logger.info("findLastClosingDay"); - - ClosingDay result = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - - transaction = session.beginTransaction(); - - result = (ClosingDay) session.createQuery("FROM ClosingDay c WHERE c.activeStatus = 'ENEBLED' AND c.location.id = :idLocation AND c.createdBy.id = :idUser ORDER BY c.createdOn DESC") - .setParameter("idLocation", idLocation) - .setParameter("idUser", idUser) - .setMaxResults(1) - .uniqueResult(); - - transaction.commit(); - - logger.info("Last closing daily detail retrieved: " + result); - } catch (HibernateException e) { - logger.error("Can not find the last closing daily detail", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Error in findLastClosingDay()", e); - rollback(transaction); - } - return result; - } - - public Date lastStableSmallBoxBySmallBox(StableSmallBox stableSmallBox) { - logger.info("lastStableSmallBoxByDate"); - - Date success = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - String query = "SELECT cd.createdOn FROM StableSmallBox cd " - + "WHERE DATE(cd.createdOn) < DATE(:date) AND cd.location.id = :locationID AND cd.activeStatus = 'ENEBLED' " - + "order by cd.createdOn DESC"; - - success = (Date) session.createQuery(query) - .setParameter("date", stableSmallBox.getCreatedOn()) - .setParameter("locationID", stableSmallBox.getLocation().getId()).setMaxResults(1) - .uniqueResult(); - - transaction.commit(); - - logger.info("Total of closing day found: "); - } catch (HibernateException e) { - logger.error("Can not find stable small box by created on", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method lastStableSmallBoxByDate()", e); - rollback(transaction); - } - - return success; - } - - public List findClosingDailyCurdate(String idLocation) { - logger.info("findDetailsFromClosingDayID"); - - List results = null; - Transaction transaction = null; - - Date fecha = getLastDateStableSmallBox(idLocation); - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - - transaction = session.beginTransaction(); - - results = session.createQuery("FROM ClosingDay c WHERE c.activeStatus = 'ENEBLED' AND c.location.id = :idLocation AND DATE(c.createdOn) > :fecha ") - .setParameter("idLocation", idLocation) - .setParameter("fecha", fecha) - .getResultList(); - - transaction.commit(); - - logger.info("Closing daily detail's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not find closing daily details list", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findDetailsFromClosingDayID()", e); - rollback(transaction); - } - return results; - } - - public Date getLastDateStableSmallBox(String locationId) { - logger.info("getLastDateStableSmallBox"); - - Date total = new Date(); - Transaction transaction = null; - logger.info(locationId); - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - String sqlQuery = "SELECT DATE(sgb.created_on) FROM stable_small_box sgb WHERE DATE(sgb.created_on) < CURDATE() AND sgb.id_location = '" + locationId + "' AND sgb.active_status = 'ENEBLED' ORDER BY sgb.created_on DESC LIMIT 1"; - - NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); - - total = (Date) (nativeQuery.uniqueResult()); - - logger.info(total); - transaction.commit(); - } catch (HibernateException e) { - logger.error("Can not load the last date in stable small box", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method getLastDateStableSmallBox()", e); - rollback(transaction); - } - - return total; - } - - public List findDetailsFromClosingDayID(ClosingDay closingDay) { - logger.info("findDetailsFromClosingDayID"); - - List results = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - - transaction = session.beginTransaction(); - - results = session.createQuery("FROM ClosingDayDetail WHERE closingDay = :closingDay ORDER BY type, person") - .setParameter("closingDay", closingDay) - .getResultList(); - - transaction.commit(); - - logger.info("Closing daily detail's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not find closing daily details list", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findDetailsFromClosingDayID()", e); - rollback(transaction); - } - return results; - } - - /** - * Update active status (ENEBLED/DISABLED) of closing day table by ID. - * - * @param id Primary key to be updated. - * @param status Status to be updated (ENEBLED/DISABLED). - * @param lastUpdatedBy User to apply update. - * @return - */ - public boolean updateClosingDailyById(String id, BasicType status, User lastUpdatedBy) { - logger.info("updateClosingDailyById"); - - boolean success = false; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaUpdate query = builder.createCriteriaUpdate(ClosingDay.class); - Root root = query.from(ClosingDay.class); - - query.set(root.get("activeStatus"), status); - query.set(root.get("lastUpdatedBy"), lastUpdatedBy); - query.set(root.get("lastUpdatedOn"), new Date()); - - query.where(builder.equal(root.get("id"), id)); - - int total = session.createQuery(query).executeUpdate(); - - if (1 == total) { - transaction.commit(); - success = true; - logger.info("Update closing day status successfully"); - } else { - logger.info("CAN NOT update closing day"); - rollback(transaction); - } - } catch (HibernateException e) { - logger.info("CAN NOT update closing day", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method updateClosingDailyById()", e); - rollback(transaction); - } - return success; - } - - /** - * - * @param sqlQuery - * @param userID - * @return - */ - public Double findTotals(String sqlQuery, String userID) { - logger.info("findTotals"); - - Double total = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); - - nativeQuery.setParameter("userID", userID); - - total = (Double) (nativeQuery.uniqueResult()); - - transaction.commit(); - } catch (HibernateException e) { - logger.error("Can not execute sql native query", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findTotals()", e); - rollback(transaction); - } - - return total; - } - - public BigDecimal findTotalsBigDecimal(String sqlQuery, String userID) { - logger.info("findTotals"); - - BigDecimal total = null; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); - - nativeQuery.setParameter("userID", userID); - - total = (BigDecimal) (nativeQuery.uniqueResult()); - - transaction.commit(); - } catch (HibernateException e) { - logger.error("Can not execute sql native query", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findTotals()", e); - rollback(transaction); - } - - return total; - } - - /** - * - * @param closingDay - * @param details - * @return - */ - public boolean saveClosingDayAndDetails(ClosingDay closingDay, List details) { - logger.info("saveClosingDayAndDetails"); - - boolean success = false; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - session.save(closingDay); - - details.forEach(detail -> { - session.save(detail); + /** + * + * @param date + * @return + */ + public boolean existStableSmallBoxByCreatedOn(Date date) { + logger.info("existStableSmallBoxByCreatedOn"); + + boolean success = true; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + String query = "SELECT COUNT(ssb.id) " + + "FROM StableSmallBox ssb " + + "WHERE DATE(ssb.createdOn) = DATE(:date) " + + "AND ssb.activeStatus = 'ENEBLED'"; + + Long count = (Long) session.createQuery(query).setParameter("date", date).uniqueResult(); + + if (null != count && count == 0) { + success = false; + } + + transaction.commit(); + + logger.info("Total of closing day found: " + count); + } catch (HibernateException e) { + logger.error("Can not find stable small box by created on", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method existStableSmallBoxByCreatedOn()", e); + rollback(transaction); + } + + return success; + } + + /** + * + * @param date + * @return + */ + public boolean existNextPaidClosingDayByCreatedOn(Date date) { + logger.info("existNextPaidClosingDayByCreatedOn"); + + boolean success = true; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + String query = "SELECT cd.id " + + "FROM closing_day cd " + + "WHERE DATE(cd.created_on) >= DATE_ADD(DATE(:date), INTERVAL 1 DAY) " + + "AND cd.active_status = 'ENEBLED'"; + + List records = session.createSQLQuery(query).setParameter("date", date).getResultList(); + + if (records.isEmpty()) { + success = false; + } + + transaction.commit(); + + logger.info("Total of closing day found: " + records.size()); + } catch (HibernateException e) { + logger.error("Can not find next closing day by created on", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method existNextPaidClosingDayByCreatedOn()", e); + rollback(transaction); + } + + return success; + } + + /** + * + * @param location + * @return + */ + public List getAllActiveUsers(Location location) { + logger.info("getAllActiveUsers"); + + List users = new ArrayList<>(); + Transaction transaction = null; + + try { + List usersAlreadyClosedDay = getAllUsersWithClasingDay(); + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(User.class); + Root root = query.from(User.class); + + Path id = root.get("id"); + Path person = root.get("person"); + Predicate criterioLocation = builder.equal(root.get("location"), location); + + Predicate userStatusTypePredicate = builder.equal(root.get("userStatusType"), UserStatusType.ENABLED); + + query.select( + builder.construct(User.class, id, person) + ); + + if (usersAlreadyClosedDay.isEmpty()) { + query.where(userStatusTypePredicate, criterioLocation); + } else { + CriteriaBuilder.In ids = builder.in(root.get("id")); + usersAlreadyClosedDay.forEach(user -> { + ids.value(user.getId()); }); + query.where(userStatusTypePredicate, criterioLocation, builder.not(ids)); + } + query.orderBy(builder.asc(root.get("person"))); + + users = session.createQuery(query).getResultList(); + + transaction.commit(); + + logger.info("Employee list " + users.size()); + } catch (HibernateException e) { + logger.error("Can not find active users", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method getAllActiveUsers()", e); + rollback(transaction); + } + return users; + } + + /** + * Find Closing daily's list between Dates (Start date and End Date). + * + * @param startDate + * @param endDate + * @return + */ + public List findClosingDailyListBetweenDates(Date startDate, Date endDate, String idLocation) { + logger.info("findClosingDailyListBetweenDates"); + + List results = null; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(ClosingDay.class); + Root root = query.from(ClosingDay.class); + + LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + LocalDate localEndDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + + Path id = root.get("id"); + Path user = root.get("user"); + Path amountPaid = root.get("amountPaid"); + Path amountExpected = root.get("amountExpected"); + Path amountTransfer = root.get("amountTransfer"); + Path comments = root.get("comments"); + Path createdOn = root.get("createdOn"); + Path createdByPath = root.get("createdBy"); + Path locationPath = root.get("location"); + + Predicate activeStatusPredicate = builder.equal(root.get("activeStatus"), BasicType.ENEBLED); + Predicate startDatePredicate = builder.greaterThanOrEqualTo(root.get("createdOn").as(LocalDate.class), localStartDate); + Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("createdOn").as(LocalDate.class), localEndDate); + Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation)); + + query.select( + builder.construct( + ClosingDay.class, id, user, + amountPaid, amountExpected, comments, createdOn, createdByPath, locationPath, amountTransfer + ) + ); + query.where(builder.and(activeStatusPredicate, startDatePredicate, endDatePredicate, locationPredicate)); + query.orderBy(builder.asc(root.get("createdOn"))); + + results = session.createQuery(query).getResultList(); + + transaction.commit(); + + logger.info("Closing daily's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not find closing daily list between dates", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findClosingDailyListBetweenDates()", e); + rollback(transaction); + } + return results; + } + + public List findClosingDailyListBetweenDatesForCuadre(Date startDate, Date endDate, String idLocation) { + logger.info("findClosingDailyListBetweenDates"); + + List results = null; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(ClosingDay.class); + Root root = query.from(ClosingDay.class); + + LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + LocalDate localEndDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + + Path id = root.get("id"); + Path user = root.get("user"); + Path amountPaid = root.get("amountPaid"); + Path amountExpected = root.get("amountExpected"); + Path amountTransfer = root.get("amountTransfer"); + Path comments = root.get("comments"); + Path createdOn = root.get("createdOn"); + Path createdByPath = root.get("createdBy"); + Path locationPath = root.get("location"); + + Predicate activeStatusPredicate = builder.equal(root.get("activeStatus"), BasicType.ENEBLED); + Predicate startDatePredicate = builder.greaterThan(root.get("createdOn").as(LocalDate.class), localStartDate); + Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("createdOn").as(LocalDate.class), localEndDate); + Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation)); + + query.select( + builder.construct( + ClosingDay.class, id, user, + amountPaid, amountExpected, comments, createdOn, createdByPath, locationPath, amountTransfer + ) + ); + query.where(builder.and(activeStatusPredicate, startDatePredicate, endDatePredicate, locationPredicate)); + query.orderBy(builder.asc(root.get("createdOn"))); + + results = session.createQuery(query).getResultList(); + + transaction.commit(); + + logger.info("Closing daily's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not find closing daily list between dates", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findClosingDailyListBetweenDates()", e); + rollback(transaction); + } + return results; + } + + /** + * Find Closing daily's list between Dates (Start date and End Date). + * + * @param startDate + * @param idLocation + * @return + */ + public List FindDailyListClosingBeforeDateForCuadre(Date startDate, String idLocation) { + logger.info("findClosingDailyListBetweenDates"); + + List results = null; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(ClosingDay.class); + Root root = query.from(ClosingDay.class); + + LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + + Path id = root.get("id"); + Path user = root.get("user"); + Path amountPaid = root.get("amountPaid"); + Path amountExpected = root.get("amountExpected"); + Path amountTransfer = root.get("amountTransfer"); + Path comments = root.get("comments"); + Path createdOn = root.get("createdOn"); + Path createdByPath = root.get("createdBy"); + Path locationPath = root.get("location"); + + Predicate activeStatusPredicate = builder.equal(root.get("activeStatus"), BasicType.ENEBLED); + Predicate startDatePredicate = builder.lessThan(root.get("createdOn").as(LocalDate.class), localStartDate); + Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation)); + + query.select( + builder.construct( + ClosingDay.class, id, user, + amountPaid, amountExpected, comments, createdOn, createdByPath, locationPath, amountTransfer + ) + ); + + query.where(builder.and(activeStatusPredicate, startDatePredicate, locationPredicate)); + query.orderBy(builder.asc(root.get("createdOn"))); + + results = session.createQuery(query).getResultList(); + + transaction.commit(); + + logger.info("Closing daily's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not find closing daily list between dates", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findClosingDailyListBetweenDates()", e); + rollback(transaction); + } + return results; + } + + public List findClosingDailyListByStableSmallBox(StableSmallBox stableSmallBox, Date startDate, String idLocation) { + logger.info("findClosingDailyListBetweenDates"); + + logger.info("findDetailsFromClosingDayID"); + + List results = null; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + + transaction = session.beginTransaction(); + + results = session.createQuery("FROM ClosingDay c WHERE c.activeStatus = 'ENEBLED' AND c.location.id = :idLocation AND DATE(c.createdOn) > DATE(:fechaInicio) AND DATE(c.createdOn) <= DATE(:fechaFinal) ") + .setParameter("idLocation", idLocation) + .setParameter("fechaInicio", startDate) + .setParameter("fechaFinal", stableSmallBox.getCreatedOn()) + .getResultList(); + + transaction.commit(); + + logger.info("Closing daily detail's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not find closing daily details list", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findDetailsFromClosingDayID()", e); + rollback(transaction); + } + return results; + } + + public ClosingDay findLastClosingDay(String idLocation, String idUser) { + logger.info("findLastClosingDay"); + + ClosingDay result = null; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + + transaction = session.beginTransaction(); + + result = (ClosingDay) session.createQuery("FROM ClosingDay c WHERE c.activeStatus = 'ENEBLED' AND c.location.id = :idLocation AND c.createdBy.id = :idUser ORDER BY c.createdOn DESC") + .setParameter("idLocation", idLocation) + .setParameter("idUser", idUser) + .setMaxResults(1) + .uniqueResult(); + + transaction.commit(); + + logger.info("Last closing daily detail retrieved: " + result); + } catch (HibernateException e) { + logger.error("Can not find the last closing daily detail", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Error in findLastClosingDay()", e); + rollback(transaction); + } + return result; + } + + public Date lastStableSmallBoxBySmallBox(StableSmallBox stableSmallBox) { + logger.info("lastStableSmallBoxByDate"); + + Date success = null; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + String query = "SELECT cd.createdOn FROM StableSmallBox cd " + + "WHERE DATE(cd.createdOn) < DATE(:date) AND cd.location.id = :locationID AND cd.activeStatus = 'ENEBLED' " + + "order by cd.createdOn DESC"; + + success = (Date) session.createQuery(query) + .setParameter("date", stableSmallBox.getCreatedOn()) + .setParameter("locationID", stableSmallBox.getLocation().getId()).setMaxResults(1) + .uniqueResult(); + + transaction.commit(); + + logger.info("Total of closing day found: "); + } catch (HibernateException e) { + logger.error("Can not find stable small box by created on", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method lastStableSmallBoxByDate()", e); + rollback(transaction); + } + + return success; + } + + public List findClosingDailyCurdate(String idLocation) { + logger.info("findDetailsFromClosingDayID"); + + List results = null; + Transaction transaction = null; + + Date fecha = getLastDateStableSmallBox(idLocation); + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + + transaction = session.beginTransaction(); + + results = session.createQuery("FROM ClosingDay c WHERE c.activeStatus = 'ENEBLED' AND c.location.id = :idLocation AND DATE(c.createdOn) > :fecha ") + .setParameter("idLocation", idLocation) + .setParameter("fecha", fecha) + .getResultList(); + + transaction.commit(); + + logger.info("Closing daily detail's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not find closing daily details list", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findDetailsFromClosingDayID()", e); + rollback(transaction); + } + return results; + } + + public Date getLastDateStableSmallBox(String locationId) { + logger.info("getLastDateStableSmallBox"); + + Date total = new Date(); + Transaction transaction = null; + logger.info(locationId); + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + String sqlQuery = "SELECT DATE(sgb.created_on) FROM stable_small_box sgb WHERE DATE(sgb.created_on) < CURDATE() AND sgb.id_location = '" + locationId + "' AND sgb.active_status = 'ENEBLED' ORDER BY sgb.created_on DESC LIMIT 1"; + + NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); + + total = (Date) (nativeQuery.uniqueResult()); + + logger.info(total); + transaction.commit(); + } catch (HibernateException e) { + logger.error("Can not load the last date in stable small box", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method getLastDateStableSmallBox()", e); + rollback(transaction); + } + + return total; + } + + public List findDetailsFromClosingDayID(ClosingDay closingDay) { + logger.info("findDetailsFromClosingDayID"); + + List results = null; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + + transaction = session.beginTransaction(); + + results = session.createQuery("FROM ClosingDayDetail WHERE closingDay = :closingDay ORDER BY type, person") + .setParameter("closingDay", closingDay) + .getResultList(); + + transaction.commit(); + + logger.info("Closing daily detail's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not find closing daily details list", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findDetailsFromClosingDayID()", e); + rollback(transaction); + } + return results; + } + + /** + * Update active status (ENEBLED/DISABLED) of closing day table by ID. + * + * @param id Primary key to be updated. + * @param status Status to be updated (ENEBLED/DISABLED). + * @param lastUpdatedBy User to apply update. + * @return + */ + public boolean updateClosingDailyById(String id, BasicType status, User lastUpdatedBy) { + logger.info("updateClosingDailyById"); + + boolean success = false; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaUpdate query = builder.createCriteriaUpdate(ClosingDay.class); + Root root = query.from(ClosingDay.class); + + query.set(root.get("activeStatus"), status); + query.set(root.get("lastUpdatedBy"), lastUpdatedBy); + query.set(root.get("lastUpdatedOn"), new Date()); + + query.where(builder.equal(root.get("id"), id)); + + int total = session.createQuery(query).executeUpdate(); + + if (1 == total) { transaction.commit(); success = true; - } catch (HibernateException e) { - logger.error("Can not save Closing Day And Details", e); + logger.info("Update closing day status successfully"); + } else { + logger.info("CAN NOT update closing day"); rollback(transaction); - } catch (Exception e) { - logger.error("Method saveClosingDayAndDetails()", e); - rollback(transaction); - } - return success; - } + } + } catch (HibernateException e) { + logger.info("CAN NOT update closing day", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method updateClosingDailyById()", e); + rollback(transaction); + } + return success; + } - /** - * - * @param userID - * @return - */ - //Modificar para poder añadir las cosas - public List findClosingDayDetails(String userID) { - List details = new ArrayList<>(); - try { + /** + * + * @param sqlQuery + * @param userID + * @return + */ + public Double findTotals(String sqlQuery, String userID) { + logger.info("findTotals"); - details.addAll(buildDetailsList(4, executeNativeSQLQuery(query_details_expenses, userID))); - details.addAll(buildDetailsList(13, executeNativeSQLQuery(query_details_expenses_by_type, userID))); - details.addAll(buildDetailsList(13, executeNativeSQLQuery(query_details_expenses_by_type_earning, userID))); - details.addAll(buildDetailsList(25, executeNativeSQLQuery(query_poliza_prase, userID))); + Double total = null; + Transaction transaction = null; - } catch (Exception e) { - logger.error(e); - } - return details; - } + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - /** - * - * @return - */ - private List getAllUsersWithClasingDay() { - List users = new ArrayList<>(); - Transaction transaction = null; + NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); - try { - String hql = "SELECT c From ClosingDay c WHERE DATE(c.createdOn) = CURDATE() AND c.activeStatus = 'ENEBLED'"; - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + nativeQuery.setParameter("userID", userID); - Query query = session.createQuery(hql); - List results = query.getResultList(); + total = (Double) (nativeQuery.uniqueResult()); - results.forEach((ClosingDay closingDay) -> { - users.add(closingDay.getUser()); - }); + transaction.commit(); + } catch (HibernateException e) { + logger.error("Can not execute sql native query", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findTotals()", e); + rollback(transaction); + } - transaction.commit(); - } catch (HibernateException e) { - logger.error("Can not save Closing Day And Details", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method saveClosingDayAndDetails()", e); - rollback(transaction); - } - return users; - } + return total; + } - /** - * - * @param queryNumber 1: query_details_sales , 2: query_details_sanctions_in - * , 3: query_details_sanctions_out , 4: query_details_expenses , 5: - * query_details_invoices. - * @param results - * @return - */ - private List buildDetailsList(int queryNumber, Object results) { - List details = new ArrayList<>(); - try { - List list = new ArrayList<>(); - if (null != results) { - if (results.getClass().isArray()) { - list = Arrays.asList((Object[]) results); - } else if (results instanceof Collection) { - list = new ArrayList<>((Collection) results); - } + public BigDecimal findTotalsBigDecimal(String sqlQuery, String userID) { + logger.info("findTotals"); - for (Object object : list) { - Object[] array = (Object[]) object; + BigDecimal total = null; + Transaction transaction = null; - ClosingDayDetail closingDayDetail = new ClosingDayDetail(queryNumber, array); - details.add(closingDayDetail); - } - logger.info("execute sql native query's list " + queryNumber + " " + details.size()); - } - } catch (Exception e) { - logger.error(e); - } - return details; - } + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - /** - * - * @param sqlQuery - * @param userID - * @return - */ - private Object executeNativeSQLQuery(String sqlQuery, String userID) { - Object results = null; - Transaction transaction = null; + NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + nativeQuery.setParameter("userID", userID); - NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); + total = (BigDecimal) (nativeQuery.uniqueResult()); - nativeQuery.setParameter("userID", userID); + transaction.commit(); + } catch (HibernateException e) { + logger.error("Can not execute sql native query", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findTotals()", e); + rollback(transaction); + } - results = nativeQuery.getResultList(); + return total; + } - transaction.commit(); - } catch (HibernateException e) { - logger.error("Can not execute sql native query", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method executeNativeSQLQuery()", e); - rollback(transaction); - } + /** + * + * @param closingDay + * @param details + * @return + */ + public boolean saveClosingDayAndDetails(ClosingDay closingDay, List details) { + logger.info("saveClosingDayAndDetails"); - return results; - } + boolean success = false; + Transaction transaction = null; - public User getUserById(String userId) { - logger.info("getUserById"); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - User general = null; - Transaction transaction = null; - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + session.save(closingDay); - general = session.get(User.class, userId); + details.forEach(detail -> { + session.save(detail); + }); - transaction.commit(); - logger.info("User " + general); - } catch (HibernateException e) { - logger.error("User cannot be loaded " + userId, e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method getUserById(" + userId + ") ", e); - rollback(transaction); - } - return general; - } + transaction.commit(); + success = true; + } catch (HibernateException e) { + logger.error("Can not save Closing Day And Details", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method saveClosingDayAndDetails()", e); + rollback(transaction); + } + return success; + } - /** - * - * @param idLocation - * @return - */ - public boolean existSalesToPay(String idLocation) { - logger.info("existSalesToPay"); + /** + * + * @param userID + * @return + */ + //Modificar para poder añadir las cosas + public List findClosingDayDetails(String userID) { + List details = new ArrayList<>(); + try { - boolean existSalestoPay = true; - Transaction transaction = null; - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + details.addAll(buildDetailsList(4, executeNativeSQLQuery(query_details_expenses, userID))); + details.addAll(buildDetailsList(13, executeNativeSQLQuery(query_details_expenses_by_type, userID))); + details.addAll(buildDetailsList(13, executeNativeSQLQuery(query_details_expenses_by_type_earning, userID))); + details.addAll(buildDetailsList(25, executeNativeSQLQuery(query_poliza_prase, userID))); - String query = "SELECT COUNT(styleClass) " - + "FROM DashboardToCollectView " - + "WHERE styleClass = 'datatableRowEmpty'" - + "AND idLocation = :idLocation"; + } catch (Exception e) { + logger.error(e); + } + return details; + } - Long count = (Long) session.createQuery(query).setParameter("idLocation", idLocation).uniqueResult(); + /** + * + * @return + */ + private List getAllUsersWithClasingDay() { + List users = new ArrayList<>(); + Transaction transaction = null; - if (null != count && count == 0) { - existSalestoPay = false; + try { + String hql = "SELECT c From ClosingDay c WHERE DATE(c.createdOn) = CURDATE() AND c.activeStatus = 'ENEBLED'"; + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + Query query = session.createQuery(hql); + List results = query.getResultList(); + + results.forEach((ClosingDay closingDay) -> { + users.add(closingDay.getUser()); + }); + + transaction.commit(); + } catch (HibernateException e) { + logger.error("Can not save Closing Day And Details", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method saveClosingDayAndDetails()", e); + rollback(transaction); + } + return users; + } + + /** + * + * @param queryNumber 1: query_details_sales , 2: query_details_sanctions_in + * , 3: query_details_sanctions_out , 4: query_details_expenses , 5: + * query_details_invoices. + * @param results + * @return + */ + private List buildDetailsList(int queryNumber, Object results) { + List details = new ArrayList<>(); + try { + List list = new ArrayList<>(); + if (null != results) { + if (results.getClass().isArray()) { + list = Arrays.asList((Object[]) results); + } else if (results instanceof Collection) { + list = new ArrayList<>((Collection) results); } - transaction.commit(); + for (Object object : list) { + Object[] array = (Object[]) object; - logger.info("Total of existing sales to pay " + count); - } catch (HibernateException e) { - logger.error("Can not find existing sales to pay", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method existSalesToPay()", e); - rollback(transaction); - } - - return existSalestoPay; - } - - public boolean validateTransferInvoice(User createdBy) { - logger.info("validateTransferInvoice"); - - Transaction transaction = null; - boolean result = false; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - Query query = session.createQuery("SELECT COUNT(transfer) FROM Invoice transfer WHERE transfer.statusType = 'PENDING' AND transfer.createdBy = :createdBy") - .setParameter("createdBy", createdBy); - - Long count = (Long) query.uniqueResult(); - - if (count == 0) { - result = true; + ClosingDayDetail closingDayDetail = new ClosingDayDetail(queryNumber, array); + details.add(closingDayDetail); } + logger.info("execute sql native query's list " + queryNumber + " " + details.size()); + } + } catch (Exception e) { + logger.error(e); + } + return details; + } - transaction.commit(); - ; - } catch (HibernateException e) { - rollback(transaction); - logger.error("Can not load auto complete list of Transfers", e); - } catch (Exception e) { - rollback(transaction); - logger.error("Method findAllTransferPendingByUser", e); - } + /** + * + * @param sqlQuery + * @param userID + * @return + */ + private Object executeNativeSQLQuery(String sqlQuery, String userID) { + Object results = null; + Transaction transaction = null; - return result; - } + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - public boolean validateInvoice(User createdBy) { - logger.info("validateTransferInvoice"); + NativeQuery nativeQuery = session.createSQLQuery(sqlQuery); - Transaction transaction = null; - boolean result = false; + nativeQuery.setParameter("userID", userID); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + results = nativeQuery.getResultList(); - Query query = session.createQuery("SELECT COUNT(transfer) FROM Invoice transfer WHERE transfer.authorize = 'PENDING' AND transfer.createdBy = :createdBy") - .setParameter("createdBy", createdBy); + transaction.commit(); + } catch (HibernateException e) { + logger.error("Can not execute sql native query", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method executeNativeSQLQuery()", e); + rollback(transaction); + } - Long count = (Long) query.uniqueResult(); + return results; + } - if (count == 0) { - result = true; - } + public User getUserById(String userId) { + logger.info("getUserById"); - transaction.commit(); - ; - } catch (HibernateException e) { - rollback(transaction); - logger.error("Can not load auto complete list of Transfers", e); - } catch (Exception e) { - rollback(transaction); - logger.error("Method findAllTransferPendingByUser", e); - } + User general = null; + Transaction transaction = null; + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - return result; - } + general = session.get(User.class, userId); - public boolean validateTransferExpense(User createdBy) { - logger.info("validateTransferInvoice"); + transaction.commit(); + logger.info("User " + general); + } catch (HibernateException e) { + logger.error("User cannot be loaded " + userId, e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method getUserById(" + userId + ") ", e); + rollback(transaction); + } + return general; + } - Transaction transaction = null; - boolean result = false; + /** + * + * @param idLocation + * @return + */ + public boolean existSalesToPay(String idLocation) { + logger.info("existSalesToPay"); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + boolean existSalestoPay = true; + Transaction transaction = null; + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - Query query = session.createQuery("SELECT COUNT(transfer) FROM Expense transfer WHERE transfer.status = 'PENDING' AND transfer.createdBy = :createdBy") - .setParameter("createdBy", createdBy); + String query = "SELECT COUNT(styleClass) " + + "FROM DashboardToCollectView " + + "WHERE styleClass = 'datatableRowEmpty'" + + "AND idLocation = :idLocation"; - Long count = (Long) query.uniqueResult(); + Long count = (Long) session.createQuery(query).setParameter("idLocation", idLocation).uniqueResult(); - if (count == 0) { - result = true; - } + if (null != count && count == 0) { + existSalestoPay = false; + } - transaction.commit(); - ; - } catch (HibernateException e) { - rollback(transaction); - logger.error("Can not load auto complete list of Transfers", e); - } catch (Exception e) { - rollback(transaction); - logger.error("Method findAllTransferPendingByUser", e); - } + transaction.commit(); - return result; - } + logger.info("Total of existing sales to pay " + count); + } catch (HibernateException e) { + logger.error("Can not find existing sales to pay", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method existSalesToPay()", e); + rollback(transaction); + } - public boolean validateTransferPaymentToClient(User createdBy) { - logger.info("validateTransferInvoice"); + return existSalestoPay; + } - Transaction transaction = null; - boolean result = false; + public boolean validateTransferInvoice(User createdBy) { + logger.info("validateTransferInvoice"); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + Transaction transaction = null; + boolean result = false; - Query query = session.createQuery("SELECT COUNT(transfer) FROM PaymentClient transfer WHERE transfer.actionStatus = 'PENDING' AND transfer.createdBy = :createdBy") - .setParameter("createdBy", createdBy); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - Long count = (Long) query.uniqueResult(); + Query query = session.createQuery("SELECT COUNT(transfer) FROM Invoice transfer WHERE transfer.statusType = 'PENDING' AND transfer.createdBy = :createdBy") + .setParameter("createdBy", createdBy); - if (count == 0) { - result = true; - } + Long count = (Long) query.uniqueResult(); - transaction.commit(); - ; - } catch (HibernateException e) { - rollback(transaction); - logger.error("Can not load auto complete list of Transfers", e); - } catch (Exception e) { - rollback(transaction); - logger.error("Method findAllTransferPendingByUser", e); - } + if (count == 0) { + result = true; + } - return result; - } + transaction.commit(); + ; + } catch (HibernateException e) { + rollback(transaction); + logger.error("Can not load auto complete list of Transfers", e); + } catch (Exception e) { + rollback(transaction); + logger.error("Method findAllTransferPendingByUser", e); + } - private final String complete_name = "CONCAT(\n" - + " CASE\n" - + " WHEN p.first_name IS NOT NULL AND p.first_name != ''\n" - + " THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')\n" - + " ELSE ''\n" - + " END,\n" - + " CASE\n" - + " WHEN p.second_name IS NOT NULL AND p.second_name != ''\n" - + " THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')\n" - + " ELSE ''\n" - + " END, \n" - + " CASE\n" - + " WHEN p.last_name IS NOT NULL AND p.last_name != ''\n" - + " THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')\n" - + " ELSE ''\n" - + " END,\n" - + " CASE\n" - + " WHEN p.middle_name IS NOT NULL AND p.middle_name != ''\n" - + " THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))\n" - + " ELSE ''\n" - + " END\n" - + " ) AS person_name"; - private final String sub_query_to_find_previously_closing_day = "(SELECT DATE(cd.created_on) FROM closing_day cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = :userID AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)"; + return result; + } - private final String query_details_expenses = "SELECT e.payment, e.expense_type, t.customer_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN taxi t ON e.taxi_id = t.id INNER JOIN person p ON t.customer_id = p.id WHERE DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND expense_type NOT IN ('MANDADOS','APOYO_VIAL') AND expense_type IN ('INICIO','PAGO_ORDEN_SERVICIO','ABONO_FINANCIAMIENTO') AND e.created_by = :userID " - + "UNION " - + "SELECT e.payment, e.expense_type, e.driver_id, e.description, " + complete_name + ", e.id FROM expense e LEFT JOIN person p ON e.driver_id = p.id WHERE p.id IS NULL AND e.taxi_id is null AND DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND expense_type NOT IN ('MANDADOS','APOYO_VIAL') AND expense_type IN ('INICIO','PAGO_ORDEN_SERVICIO','ABONO_FINANCIAMIENTO') AND e.created_by = :userID"; + public boolean validateInvoice(User createdBy) { + logger.info("validateTransferInvoice"); - private final String query_details_expenses_by_type = "SELECT e.payment, eic.name, t.customer_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id INNER JOIN taxi t ON e.taxi_id = t.id INNER JOIN person p ON t.customer_id = p.id WHERE DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EXPENSE' AND e.created_by = :userID " - + "UNION " - + "SELECT e.payment, eic.name, e.driver_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id LEFT JOIN person p ON e.driver_id = p.id WHERE p.id IS NULL AND e.taxi_id is null AND DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EXPENSE' AND e.created_by = :userID "; + Transaction transaction = null; + boolean result = false; - private final String query_details_expenses_by_type_earning = "SELECT e.payment, eic.name, t.customer_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id INNER JOIN taxi t ON e.taxi_id = t.id INNER JOIN person p ON t.customer_id = p.id WHERE DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EARNING' AND e.created_by = :userID " - + "UNION " - + "SELECT e.payment, eic.name, e.driver_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id LEFT JOIN person p ON e.driver_id = p.id WHERE p.id IS NULL AND e.taxi_id is null AND DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EARNING' AND e.created_by = :userID "; + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - private final String query_poliza_prase = "SELECT e.pago, (CASE WHEN e.tipo_pago = 'ABONO' THEN CONCAT('PAGO - ', e.metodo_pago) WHEN e.tipo_pago = 'ANTICIPO' THEN CONCAT('ANTICIPO - ', e.metodo_pago) ELSE ' ' END) AS tipo_pago, p.id as person, CONCAT(e.folio, ' -> ', ve.folio), " + complete_name + ", e.id " - + "FROM pagos_poliza e " - + "INNER JOIN poliza_prase ve ON e.id_poliza = ve.id " - + "INNER JOIN person p ON ve.id_customer = p.id " - + "WHERE DATE(e.fecha_pago) > " + sub_query_to_find_previously_closing_day - + "AND e.pago_estatus = 'ENABLED' " - + "AND e.estatus_activo = 'ENABLED' " - + "AND e.cobro = :userID "; + Query query = session.createQuery("SELECT COUNT(transfer) FROM Invoice transfer WHERE transfer.authorize = 'PENDING' AND transfer.createdBy = :createdBy") + .setParameter("createdBy", createdBy); - final Logger logger = LogManager.getLogger(ClosingDayController.class); - private static final long serialVersionUID = -6732331411572526429L; + Long count = (Long) query.uniqueResult(); + + if (count == 0) { + result = true; + } + + transaction.commit(); + ; + } catch (HibernateException e) { + rollback(transaction); + logger.error("Can not load auto complete list of Transfers", e); + } catch (Exception e) { + rollback(transaction); + logger.error("Method findAllTransferPendingByUser", e); + } + + return result; + } + + public boolean validateTransferExpense(User createdBy) { + logger.info("validateTransferInvoice"); + + Transaction transaction = null; + boolean result = false; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + Query query = session.createQuery("SELECT COUNT(transfer) FROM Expense transfer WHERE transfer.status = 'PENDING' AND transfer.createdBy = :createdBy") + .setParameter("createdBy", createdBy); + + Long count = (Long) query.uniqueResult(); + + if (count == 0) { + result = true; + } + + transaction.commit(); + ; + } catch (HibernateException e) { + rollback(transaction); + logger.error("Can not load auto complete list of Transfers", e); + } catch (Exception e) { + rollback(transaction); + logger.error("Method findAllTransferPendingByUser", e); + } + + return result; + } + + public boolean validateTransferPaymentToClient(User createdBy) { + logger.info("validateTransferInvoice"); + + Transaction transaction = null; + boolean result = false; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + Query query = session.createQuery("SELECT COUNT(transfer) FROM PaymentClient transfer WHERE transfer.actionStatus = 'PENDING' AND transfer.createdBy = :createdBy") + .setParameter("createdBy", createdBy); + + Long count = (Long) query.uniqueResult(); + + if (count == 0) { + result = true; + } + + transaction.commit(); + ; + } catch (HibernateException e) { + rollback(transaction); + logger.error("Can not load auto complete list of Transfers", e); + } catch (Exception e) { + rollback(transaction); + logger.error("Method findAllTransferPendingByUser", e); + } + + return result; + } + + private final String complete_name = "CONCAT(\n" + + " CASE\n" + + " WHEN p.first_name IS NOT NULL AND p.first_name != ''\n" + + " THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')\n" + + " ELSE ''\n" + + " END,\n" + + " CASE\n" + + " WHEN p.second_name IS NOT NULL AND p.second_name != ''\n" + + " THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')\n" + + " ELSE ''\n" + + " END, \n" + + " CASE\n" + + " WHEN p.last_name IS NOT NULL AND p.last_name != ''\n" + + " THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')\n" + + " ELSE ''\n" + + " END,\n" + + " CASE\n" + + " WHEN p.middle_name IS NOT NULL AND p.middle_name != ''\n" + + " THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))\n" + + " ELSE ''\n" + + " END\n" + + " ) AS person_name"; + private final String sub_query_to_find_previously_closing_day = "(SELECT DATE(cd.created_on) FROM closing_day cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = :userID AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)"; + + private final String query_details_expenses = "SELECT e.payment, e.expense_type, t.customer_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN taxi t ON e.taxi_id = t.id INNER JOIN person p ON t.customer_id = p.id WHERE DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND expense_type NOT IN ('MANDADOS','APOYO_VIAL') AND expense_type IN ('INICIO','PAGO_ORDEN_SERVICIO','ABONO_FINANCIAMIENTO') AND e.created_by = :userID " + + "UNION " + + "SELECT e.payment, e.expense_type, e.driver_id, e.description, " + complete_name + ", e.id FROM expense e LEFT JOIN person p ON e.driver_id = p.id WHERE p.id IS NULL AND e.taxi_id is null AND DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND expense_type NOT IN ('MANDADOS','APOYO_VIAL') AND expense_type IN ('INICIO','PAGO_ORDEN_SERVICIO','ABONO_FINANCIAMIENTO') AND e.created_by = :userID"; + + private final String query_details_expenses_by_type = "SELECT e.payment, eic.name, t.customer_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id INNER JOIN taxi t ON e.taxi_id = t.id INNER JOIN person p ON t.customer_id = p.id WHERE DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EXPENSE' AND e.created_by = :userID " + + "UNION " + + "SELECT e.payment, eic.name, e.driver_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id LEFT JOIN person p ON e.driver_id = p.id WHERE p.id IS NULL AND e.taxi_id is null AND DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EXPENSE' AND e.created_by = :userID "; + + private final String query_details_expenses_by_type_earning = "SELECT e.payment, eic.name, t.customer_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id INNER JOIN taxi t ON e.taxi_id = t.id INNER JOIN person p ON t.customer_id = p.id WHERE DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EARNING' AND e.created_by = :userID " + + "UNION " + + "SELECT e.payment, eic.name, e.driver_id, e.description, " + complete_name + ", e.id FROM expense e INNER JOIN expense_income_catalog eic ON e.id_expense_type = eic.id LEFT JOIN person p ON e.driver_id = p.id WHERE p.id IS NULL AND e.taxi_id is null AND DATE(e.created_on) > " + sub_query_to_find_previously_closing_day + " AND e.expense_status_type = 'AUTHORIZED' AND eic.type = 'EARNING' AND e.created_by = :userID "; + + private final String query_poliza_prase = "SELECT e.cantidad_pagada, (CASE WHEN pa.tipo_pago = 'ABONO' THEN CONCAT('PAGO - ', e.metodo_pago) WHEN pa.tipo_pago = 'ANTICIPO' THEN CONCAT('ANTICIPO - ', e.metodo_pago) ELSE ' ' END) AS tipo_pago, p.id as person, CONCAT(e.folio, ' -> ', ve.folio), " + complete_name + ", e.id " + + "FROM detelle_pago_poliza e " + + "INNER JOIN pagos_poliza pa ON e.id_pago_poliza = pa.id " + + "INNER JOIN poliza_prase ve ON pa.id_poliza = ve.id " + + "INNER JOIN person p ON ve.id_customer = p.id " + + "WHERE DATE(e.fecha_pago) > " + sub_query_to_find_previously_closing_day + + "AND e.estatus_activo = 'ENABLED' " + + "AND e.cobro = :userID "; + + final Logger logger = LogManager.getLogger(ClosingDayController.class); + private static final long serialVersionUID = -6732331411572526429L; } diff --git a/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PagosPolizaController.java b/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PagosPolizaController.java index c933ca6..976537a 100644 --- a/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PagosPolizaController.java +++ b/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PagosPolizaController.java @@ -8,13 +8,19 @@ import com.arrebol.taxiservicios.controller.connection.ConnectionManager; import com.arrebol.taxiservicios.controller.util.HibernateUtil; import com.arrebol.taxiservicios.model.catalog.Location; import com.arrebol.taxiservicios.model.core.User; +import com.arrebol.taxiservicios.model.enums.EstatusPagoMultiple; import com.arrebol.taxiservicios.model.enums.GenericEnumType; +import com.arrebol.taxiservicios.model.enums.MetodoPago; +import com.arrebol.taxiservicios.model.enums.PolizaEstatus; import com.crov.prase.model.prase.DetellePagoPoliza; +import com.crov.prase.model.prase.HistorialAbonoMultiple; import com.crov.prase.model.prase.PagosPoliza; import com.crov.prase.model.prase.Poliza; import java.io.Serializable; +import java.math.BigDecimal; import java.time.LocalDate; import java.time.ZoneId; +import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -110,8 +116,8 @@ public class PagosPolizaController extends ConnectionManager implements Serializ return resultList; } - public PagosPoliza fillFoliosByPagos(String abreviacionFolio) { - PagosPoliza result = null; + public DetellePagoPoliza fillFoliosByPagos(String abreviacionFolio) { + DetellePagoPoliza result = null; Transaction transaction = null; try { logger.info("Search last generated folio.."); @@ -119,13 +125,13 @@ public class PagosPolizaController extends ConnectionManager implements Serializ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); transaction = session.beginTransaction(); - String query = "SELECT tap FROM PagosPoliza tap " + String query = "SELECT tap FROM DetellePagoPoliza tap " + "WHERE tap.folio LIKE '" + abreviacionFolio + "%' " + "ORDER BY " + "SUBSTRING_INDEX(tap.folio, '-', 1) DESC, " + "SUBSTRING_INDEX(SUBSTRING_INDEX(tap.folio, '-', -2), '-', -6) DESC "; - result = (PagosPoliza) session.createQuery(query).setMaxResults(1).uniqueResult(); + result = (DetellePagoPoliza) session.createQuery(query).setMaxResults(1).uniqueResult(); transaction.commit(); } catch (HibernateException e) { logger.error("Search for the last generated folio " + e); @@ -278,6 +284,229 @@ public class PagosPolizaController extends ConnectionManager implements Serializ return resultList; } + public String procesarPagoMultiple(Poliza polizaActual, Double montoTotal, String metodoPago, String comentario, User user) { + Session session = null; + Transaction transaction = null; + Date fechaActual = correcciónDeHr(new Date(), -7); + List foliosGenerados = new ArrayList<>(); + List detallesPagos = new ArrayList<>(); + try { + session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + // 1. Obtener pagos validos + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery criteria = builder.createQuery(PagosPoliza.class); + Root root = criteria.from(PagosPoliza.class); + + Predicate[] predicates = new Predicate[]{ + builder.equal(root.get("poliza"), polizaActual), + builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED), + root.get("pagoEstatus").in(GenericEnumType.DISABLED, GenericEnumType.INCOMPLETE) + }; + criteria.where(predicates).orderBy(builder.asc(root.get("fechaAPagar"))); + + List pagos = session.createQuery(criteria).getResultList(); + + if (pagos.isEmpty()) { + return "No existen pagos pendientes"; + } + + // 2. Deuda total + BigDecimal deudaTotal = pagos.stream().map(p -> BigDecimal.valueOf(p.getPago()).subtract(BigDecimal.valueOf(p.getCantidadPagada()))).reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal montoPagadoBD = BigDecimal.valueOf(montoTotal); + BigDecimal tolerancia = new BigDecimal("0.10"); + if (montoPagadoBD.subtract(deudaTotal).compareTo(tolerancia) > 0) { + return "Monto excede tolerancia permitida"; + } + + // 3. Procesar pagos + double montoRestante = montoTotal; + + // 5. Generar folio + // 5.1. Obtener el último consecutivo + Integer ultimoConsecutivo = obtenerUltimoConsecutivo("A-PRASE"); + if (ultimoConsecutivo == null) { + return "Error al generar los folios"; + } + // 5.2. Modificar el ciclo para usar incremento local + int currentConsecutivo = ultimoConsecutivo + 1; + + //4. Crear historial + HistorialAbonoMultiple historial = new HistorialAbonoMultiple(); + historial.setId(UUID.randomUUID().toString()); + historial.setLocation(polizaActual.getLocation()); + historial.setEstatus(EstatusPagoMultiple.PROCESANDO); + historial.setPoliza(polizaActual); + historial.setCobro(user); + historial.setFechaPago(fechaActual); + historial.setMetodoPago(MetodoPago.valueOf(metodoPago)); + historial.setTotalPago(montoTotal); + historial.setCometario(comentario); + historial.setCreatedOn(fechaActual); + historial.setCreatedBy(user); + session.save(historial); + + for (PagosPoliza pago : pagos) { + if (montoRestante <= 0) { + break; + } + + double saldoPendiente = pago.getPago() - pago.getCantidadPagada(); + if (saldoPendiente <= 0) { + continue; + } + + double montoAplicar = Math.min(saldoPendiente, montoRestante); + + // 5.3 Generar folio con incremento local + String folio = obtenerFolio("A-PRASE", currentConsecutivo); + currentConsecutivo++; + + // 6. Crear detalle de pago + DetellePagoPoliza detalle = new DetellePagoPoliza(); + detalle.setId(UUID.randomUUID().toString()); + detalle.setPagoPoliza(pago); + detalle.setEstatusActivo(GenericEnumType.ENABLED); + detalle.setFechaPago(fechaActual); + detalle.setCantidadPagada(montoAplicar); + detalle.setCobro(user); + detalle.setFolio(folio); + detalle.setMetodoPago(MetodoPago.valueOf(metodoPago)); + detalle.setCreatedOn(fechaActual); + detalle.setCreatedBy(user); + detalle.setHistorialAbonoMultiple(historial); + session.save(detalle); + + // 7. Actualizar pago + pago.setCantidadPagada(pago.getCantidadPagada() + montoAplicar); + pago.setDiferenciaPago(pago.getPago() - pago.getCantidadPagada()); + if (pago.getDiferenciaPago() < 0.01) { + pago.setPagoEstatus(GenericEnumType.ENABLED); + pago.setCantidadPagada(pago.getPago()); + } else { + pago.setPagoEstatus(GenericEnumType.INCOMPLETE); + } + pago.setLastUpdatedOn(fechaActual); + pago.setLastUpdatedBy(user); + session.update(pago); + + // 8. Actualizar la cantidad pagada de la poliza + polizaActual.setCantidadPagada(polizaActual.getCantidadPagada() + montoAplicar); + montoRestante -= montoAplicar; + + // 9. Se agrega el folio a la lista + foliosGenerados.add(folio); + + // 10. Se crear el detalle del folio + String detallePago = String.format( + "%s | ", + folio + ); + detallesPagos.add(detallePago); + } + + // 11. Validar liquidación completa de la poliza + if (Math.abs(polizaActual.getAmount() - polizaActual.getCantidadPagada()) < 0.10) { + polizaActual.setEstatus(PolizaEstatus.LIQUIDADO); + } + polizaActual.setLastUpdatedOn(fechaActual); + polizaActual.setLastUpdatedBy(user); + session.update(polizaActual); + + // 12. Se actualizar historial con los folios + historial.setFolios(String.join(", ", foliosGenerados)); + historial.setDetalle(String.join("\n", detallesPagos)); + historial.setEstatus(EstatusPagoMultiple.PAGADO); + session.update(historial); + + transaction.commit(); + return historial.getId(); + } catch (Exception e) { + if (transaction != null) { + transaction.rollback(); + } + return "Error interno: " + e.getMessage(); + } finally { + if (session != null) { + session.close(); + } + } + } + + private Integer obtenerUltimoConsecutivo(String ab) { + Session session = null; + try { + session = HibernateUtil.getSessionFactory().openSession(); + + String query = "SELECT tap FROM DetellePagoPoliza tap " + + "WHERE tap.folio LIKE '" + ab + "%' " + + "ORDER BY " + + "SUBSTRING_INDEX(tap.folio, '-', 1) DESC, " + + "SUBSTRING_INDEX(SUBSTRING_INDEX(tap.folio, '-', -2), '-', -6) DESC "; + + DetellePagoPoliza ultimoFolio = (DetellePagoPoliza) session.createQuery(query).setMaxResults(1).uniqueResult(); + + if (ultimoFolio == null || ultimoFolio.getFolio() == null) { + return 0; + } + + String[] partes = ultimoFolio.getFolio().split("-"); + if (partes.length < 4) { + throw new IllegalStateException("Formato inválido. Se esperaba: ABREV-CONSECUTIVO-AÑO"); + } + + try { + return Integer.valueOf(partes[2]); + } catch (NumberFormatException e) { + throw new IllegalStateException("Consecutivo no numérico: " + partes[2]); + } + + } catch (Exception e) { + logger.error("Error obteniendo consecutivo: ", e); + return null; + } finally { + if (session != null) { + session.close(); + } + } + } + + private String obtenerFolio(String ab, int consecutivo) { + try { + String numeroFormateado = String.format("%06d", consecutivo); + Calendar calendario = Calendar.getInstance(); + int ano = calendario.get(Calendar.YEAR); + return ab + "-" + numeroFormateado + "-" + ano; + } catch (Exception e) { + logger.error("Error generando folio", e); + return null; + } + } + + public HistorialAbonoMultiple getHistorialAbonoMultipleById(String userId) { + logger.info("getHistorialAbonoMultipleById"); + + HistorialAbonoMultiple general = null; + Transaction transaction = null; + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + general = session.get(HistorialAbonoMultiple.class, userId); + + transaction.commit(); + logger.info("HistorialAbonoMultiple " + general); + } catch (HibernateException e) { + logger.error("HistorialAbonoMultiple cannot be loaded " + userId, e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method getHistorialAbonoMultipleById(" + userId + ") ", e); + rollback(transaction); + } + return general; + } + private Date correcciónDeHr(Date fecha, int horas) { Calendar calendar = Calendar.getInstance(); calendar.setTime(fecha); diff --git a/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PolizaController.java b/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PolizaController.java index d6a217e..f9ad53a 100644 --- a/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PolizaController.java +++ b/crov-prase-controller/src/main/java/com/crov/prase/controller/prase/PolizaController.java @@ -1,8 +1,8 @@ /* * Arrebol Consultancy copyright. - * + * * This code belongs to Arrebol Consultancy - * its use, redistribution or modification are prohibited + * its use, redistribution or modification are prohibited * without written authorization from Arrebol Consultancy. */ package com.crov.prase.controller.prase; @@ -12,7 +12,7 @@ import com.arrebol.taxiservicios.controller.util.HibernateUtil; import com.arrebol.taxiservicios.model.catalog.Location; import com.arrebol.taxiservicios.model.core.Address; import com.arrebol.taxiservicios.model.core.User; -import com.crov.prase.model.prase.Incidence; +import com.crov.prase.model.prase.DetellePagoPoliza; import com.crov.prase.model.prase.PagosPoliza; import com.crov.prase.model.prase.Poliza; import java.io.Serializable; @@ -39,370 +39,387 @@ import org.hibernate.Transaction; */ public class PolizaController extends ConnectionManager implements Serializable { - public PolizaController() { - } + public PolizaController() { + } - public Poliza findPoliza(String idPoliza) { - logger.info("findPoliza"); - Poliza results = null; - Transaction transaction = null; - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); + public Poliza findPoliza(String idPoliza) { + logger.info("findPoliza"); + Poliza results = null; + Transaction transaction = null; + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(Poliza.class); - Root root = query.from(Poliza.class); + CriteriaQuery query = builder.createQuery(Poliza.class); + Root root = query.from(Poliza.class); - Predicate id = builder.equal(root.get("id"), idPoliza); - query.where(builder.and(id)); - results = session.createQuery(query).getSingleResult(); - transaction.commit(); + Predicate id = builder.equal(root.get("id"), idPoliza); + query.where(builder.and(id)); + results = session.createQuery(query).getSingleResult(); + transaction.commit(); - logger.info("Poliza" + results.getId()); - } catch (HibernateException e) { - logger.error("Can not load Poliza", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findPoliza() ", e); - rollback(transaction); - } - return results; - } + logger.info("Poliza" + results.getId()); + } catch (HibernateException e) { + logger.error("Can not load Poliza", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findPoliza() ", e); + rollback(transaction); + } + return results; + } - public Address findAddress(String idPerson) { - logger.info("findAddress"); - Address results = null; - Transaction transaction = null; - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); + public Address findAddress(String idPerson) { + logger.info("findAddress"); + Address results = null; + Transaction transaction = null; + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery
query = builder.createQuery(Address.class); - Root
root = query.from(Address.class); + CriteriaQuery
query = builder.createQuery(Address.class); + Root
root = query.from(Address.class); - Predicate id = builder.equal(root.get("person").get("id"), idPerson); - query.where(builder.and(id)); - results = session.createQuery(query).getSingleResult(); - transaction.commit(); + Predicate id = builder.equal(root.get("person").get("id"), idPerson); + query.where(builder.and(id)); + results = session.createQuery(query).getSingleResult(); + transaction.commit(); - logger.info("Address" + results.getId()); - } catch (NoResultException e) { - transaction.rollback(); - logger.error("No se encontro el address: "); - } catch (HibernateException e) { - rollback(transaction); - logger.error("Error al encontrar el address: ", e); - } catch (Exception e) { - rollback(transaction); - logger.error("Método findAddress: ", e); - } - return results; - } + logger.info("Address" + results.getId()); + } catch (NoResultException e) { + transaction.rollback(); + logger.error("No se encontro el address: "); + } catch (HibernateException e) { + rollback(transaction); + logger.error("Error al encontrar el address: ", e); + } catch (Exception e) { + rollback(transaction); + logger.error("Método findAddress: ", e); + } + return results; + } - /** - * @param location - * @return List of all Poliza. - */ - public List findActive(Location location) { - logger.info("findActive"); - List results = new ArrayList<>(); + /** + * @param location + * @return List of all Poliza. + */ + public List findActive(Location location) { + logger.info("findActive"); + List results = new ArrayList<>(); - Transaction transaction = null; + Transaction transaction = null; - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(Poliza.class); - Root root = query.from(Poliza.class); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(Poliza.class); + Root root = query.from(Poliza.class); - Predicate policyActives = builder.equal(root.get("active"), Boolean.TRUE); - Predicate locations = builder.equal(root.get("location"), location); + Predicate policyActives = builder.equal(root.get("active"), Boolean.TRUE); + Predicate locations = builder.equal(root.get("location"), location); - query.where(builder.and( - policyActives, locations - )); - query.orderBy(builder.asc(root.get("createdOn"))); + query.where(builder.and( + policyActives, locations + )); + query.orderBy(builder.asc(root.get("createdOn"))); - results = session.createQuery(query).getResultList(); + results = session.createQuery(query).getResultList(); - transaction.commit(); + transaction.commit(); - logger.info("Poliza's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not load Poliza list ", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findActive() ", e); - rollback(transaction); - } - return results; - } - - public List findDisable(Location location) { - logger.info("findDisable"); - List results = new ArrayList<>(); + logger.info("Poliza's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not load Poliza list ", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findActive() ", e); + rollback(transaction); + } + return results; + } - Transaction transaction = null; + public List findDisable(Location location) { + logger.info("findDisable"); + List results = new ArrayList<>(); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(Poliza.class); - Root root = query.from(Poliza.class); + Transaction transaction = null; - Predicate policyDisables = builder.equal(root.get("active"), Boolean.FALSE); - Predicate locations = builder.equal(root.get("location"), location); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(Poliza.class); + Root root = query.from(Poliza.class); - query.where(builder.and( - policyDisables, locations - )); - query.orderBy(builder.asc(root.get("createdOn"))); + Predicate policyDisables = builder.equal(root.get("active"), Boolean.FALSE); + Predicate locations = builder.equal(root.get("location"), location); - results = session.createQuery(query).getResultList(); + query.where(builder.and( + policyDisables, locations + )); + query.orderBy(builder.asc(root.get("createdOn"))); - transaction.commit(); + results = session.createQuery(query).getResultList(); - logger.info("Poliza's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not load Poliza list ", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findDisable() ", e); - rollback(transaction); - } - return results; - } + transaction.commit(); - /** - * Update active status (ENEBLED/DISABLED) of Expense company ID. - * - * @param id - * @param lastUpdatedBy - * @param comentario - * @return - */ - public boolean delete(String id, User lastUpdatedBy, String comentario) { - logger.info("delete"); + logger.info("Poliza's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not load Poliza list ", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findDisable() ", e); + rollback(transaction); + } + return results; + } - boolean success = false; - Transaction transaction = null; - + /** + * Update active status (ENEBLED/DISABLED) of Expense company ID. + * + * @param id + * @param lastUpdatedBy + * @param comentario + * @return + */ + public boolean delete(String id, User lastUpdatedBy, String comentario) { + logger.info("delete"); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaUpdate query = builder.createCriteriaUpdate(Poliza.class); - Root root = query.from(Poliza.class); - + boolean success = false; + Transaction transaction = null; - query.set(root.get("comentarios"), comentario); - query.set(root.get("active"), false); - query.set(root.get("lastUpdatedBy"), lastUpdatedBy); - query.set(root.get("lastUpdatedOn"), new Date()); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaUpdate query = builder.createCriteriaUpdate(Poliza.class); + Root root = query.from(Poliza.class); - query.where(builder.equal(root.get("id"), id)); + query.set(root.get("comentarios"), comentario); + query.set(root.get("active"), false); + query.set(root.get("lastUpdatedBy"), lastUpdatedBy); + query.set(root.get("lastUpdatedOn"), new Date()); - int total = session.createQuery(query).executeUpdate(); + query.where(builder.equal(root.get("id"), id)); - if (1 == total) { - transaction.commit(); - success = true; - logger.info("update Poliza status to disable"); - } else { - logger.info("CAN NOT update Poliza status"); - rollback(transaction); - } - } catch (HibernateException e) { - logger.error("Can not update Poliza status", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method delete() ", e); - rollback(transaction); - } - return success; - } - - /** - * Save a new poliza entry. - * - * @param poliza - * @return - */ - public boolean save(Poliza poliza) { - logger.info("saveHospitales"); - - boolean success = false; - Transaction transaction = null; - - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - - session.save(poliza); + int total = session.createQuery(query).executeUpdate(); + if (1 == total) { transaction.commit(); success = true; - } catch (HibernateException e) { - logger.error("Can not save poliza entry", e); + logger.info("update Poliza status to disable"); + } else { + logger.info("CAN NOT update Poliza status"); rollback(transaction); - } catch (Exception e) { - logger.error("Method save()", e); - rollback(transaction); - } - return success; - } - - public boolean save(PagosPoliza pagoPoliza) { - logger.info("saveHospitales"); + } + } catch (HibernateException e) { + logger.error("Can not update Poliza status", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method delete() ", e); + rollback(transaction); + } + return success; + } - boolean success = false; - Transaction transaction = null; + /** + * Save a new poliza entry. + * + * @param poliza + * @return + */ + public boolean save(Poliza poliza) { + logger.info("saveHospitales"); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + boolean success = false; + Transaction transaction = null; - session.save(pagoPoliza); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - transaction.commit(); - success = true; - } catch (HibernateException e) { - logger.error("Can not save poliza entry", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method save()", e); - rollback(transaction); - } - return success; - } - + session.save(poliza); - public Poliza fillFoliosByPolizas(String abreviacionFolio) { - Poliza result = null; - Transaction transaction = null; - try { - logger.info("Search last generated folio.."); + transaction.commit(); + success = true; + } catch (HibernateException e) { + logger.error("Can not save poliza entry", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method save()", e); + rollback(transaction); + } + return success; + } - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + public boolean save(PagosPoliza pagoPoliza) { + logger.info("saveHospitales"); - String query = "SELECT tap FROM Poliza tap " - + "WHERE tap.folio LIKE '" + abreviacionFolio + "%' " - + "ORDER BY " - + "SUBSTRING_INDEX(tap.folio, '-', 1) DESC, " - + "SUBSTRING_INDEX(SUBSTRING_INDEX(tap.folio, '-', -1), '-', -6) DESC "; + boolean success = false; + Transaction transaction = null; - result = (Poliza) session.createQuery(query) - .setMaxResults(1) - .uniqueResult(); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - transaction.commit(); - } catch (HibernateException e) { - logger.error("Search for the last generated folio " + e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method fillFoliosByPagos() " + e); - rollback(transaction); - } - return result; - } - - public Poliza fillFoliosByPolizas2(String abreviacionFolio) { - Poliza result = null; - Transaction transaction = null; - try { - logger.info("Search last generated folio.."); + session.save(pagoPoliza); - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + transaction.commit(); + success = true; + } catch (HibernateException e) { + logger.error("Can not save poliza entry", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method save()", e); + rollback(transaction); + } + return success; + } - String query = "SELECT tap FROM Poliza tap " - + "ORDER BY " - + "SUBSTRING_INDEX(SUBSTRING_INDEX(tap.folio, '-', -1), '-', -6) DESC "; + public boolean save(DetellePagoPoliza detallePagoPoliza) { + logger.info("saveHospitales"); + boolean success = false; + Transaction transaction = null; + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + session.save(detallePagoPoliza); + transaction.commit(); + success = true; + } catch (HibernateException e) { + logger.error("Can not save poliza entry", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method save()", e); + rollback(transaction); + } + return success; + } - result = (Poliza) session.createQuery(query) - .setMaxResults(1) - .uniqueResult(); + public Poliza fillFoliosByPolizas(String abreviacionFolio) { + Poliza result = null; + Transaction transaction = null; + try { + logger.info("Search last generated folio.."); - transaction.commit(); - } catch (HibernateException e) { - logger.error("Search for the last generated folio " + e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method fillFoliosByPagos() " + e); - rollback(transaction); - } - return result; - } + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - public List findPolizasByLocationAndEndDate(Location location, Date startDate, Date endDate) { - logger.info("findActive"); - List results = new ArrayList<>(); + String query = "SELECT tap FROM Poliza tap " + + "WHERE tap.folio LIKE '" + abreviacionFolio + "%' " + + "ORDER BY " + + "SUBSTRING_INDEX(tap.folio, '-', 1) DESC, " + + "SUBSTRING_INDEX(SUBSTRING_INDEX(tap.folio, '-', -1), '-', -6) DESC "; - Transaction transaction = null; + result = (Poliza) session.createQuery(query) + .setMaxResults(1) + .uniqueResult(); - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); - CriteriaBuilder builder = session.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(Poliza.class); - Root root = query.from(Poliza.class); + transaction.commit(); + } catch (HibernateException e) { + logger.error("Search for the last generated folio " + e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method fillFoliosByPagos() " + e); + rollback(transaction); + } + return result; + } - LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - LocalDate localEndDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + public Poliza fillFoliosByPolizas2(String abreviacionFolio) { + Poliza result = null; + Transaction transaction = null; + try { + logger.info("Search last generated folio.."); - Predicate criterio = builder.equal(root.get("active"), Boolean.TRUE); - Predicate criterio2 = builder.equal(root.get("location"), location); - Predicate startDatePredicate = builder.greaterThanOrEqualTo(root.get("endDate").as(LocalDate.class), localStartDate); - Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("endDate").as(LocalDate.class), localEndDate); + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); - query.where(builder.and(criterio, criterio2, startDatePredicate, endDatePredicate)); - query.orderBy(builder.asc(root.get("createdOn"))); + String query = "SELECT tap FROM Poliza tap " + + "ORDER BY " + + "SUBSTRING_INDEX(SUBSTRING_INDEX(tap.folio, '-', -1), '-', -6) DESC "; - results = session.createQuery(query).getResultList(); + result = (Poliza) session.createQuery(query) + .setMaxResults(1) + .uniqueResult(); - transaction.commit(); + transaction.commit(); + } catch (HibernateException e) { + logger.error("Search for the last generated folio " + e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method fillFoliosByPagos() " + e); + rollback(transaction); + } + return result; + } - logger.info("Poliza's list " + results.size()); - } catch (HibernateException e) { - logger.error("Can not load Poliza list ", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method findActive() ", e); - rollback(transaction); - } - return results; - } - - public boolean update(Poliza poliza) { - logger.info("saveHospitales"); + public List findPolizasByLocationAndEndDate(Location location, Date startDate, Date endDate) { + logger.info("findActive"); + List results = new ArrayList<>(); - boolean success = false; - Transaction transaction = null; + Transaction transaction = null; - try { - Session session = HibernateUtil.getSessionFactory().getCurrentSession(); - transaction = session.beginTransaction(); + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + CriteriaBuilder builder = session.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(Poliza.class); + Root root = query.from(Poliza.class); - session.update(poliza); + LocalDate localStartDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + LocalDate localEndDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - transaction.commit(); - success = true; - } catch (HibernateException e) { - logger.error("Can not save poliza entry", e); - rollback(transaction); - } catch (Exception e) { - logger.error("Method save()", e); - rollback(transaction); - } - return success; - } - - private static final long serialVersionUID = -8772793021819350069L; - final Logger logger = LogManager.getLogger(PolizaController.class); + Predicate criterio = builder.equal(root.get("active"), Boolean.TRUE); + Predicate criterio2 = builder.equal(root.get("location"), location); + Predicate startDatePredicate = builder.greaterThanOrEqualTo(root.get("endDate").as(LocalDate.class), localStartDate); + Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("endDate").as(LocalDate.class), localEndDate); + + query.where(builder.and(criterio, criterio2, startDatePredicate, endDatePredicate)); + query.orderBy(builder.asc(root.get("createdOn"))); + + results = session.createQuery(query).getResultList(); + + transaction.commit(); + + logger.info("Poliza's list " + results.size()); + } catch (HibernateException e) { + logger.error("Can not load Poliza list ", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method findActive() ", e); + rollback(transaction); + } + return results; + } + + public boolean update(Poliza poliza) { + logger.info("saveHospitales"); + + boolean success = false; + Transaction transaction = null; + + try { + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); + transaction = session.beginTransaction(); + + session.update(poliza); + + transaction.commit(); + success = true; + } catch (HibernateException e) { + logger.error("Can not save poliza entry", e); + rollback(transaction); + } catch (Exception e) { + logger.error("Method save()", e); + rollback(transaction); + } + return success; + } + + private static final long serialVersionUID = -8772793021819350069L; + final Logger logger = LogManager.getLogger(PolizaController.class); } diff --git a/crov-prase-model/src/main/java/com/arrebol/taxiservicios/model/enums/EstatusPagoMultiple.java b/crov-prase-model/src/main/java/com/arrebol/taxiservicios/model/enums/EstatusPagoMultiple.java index e658a9b..48f8d0d 100644 --- a/crov-prase-model/src/main/java/com/arrebol/taxiservicios/model/enums/EstatusPagoMultiple.java +++ b/crov-prase-model/src/main/java/com/arrebol/taxiservicios/model/enums/EstatusPagoMultiple.java @@ -9,31 +9,42 @@ package com.arrebol.taxiservicios.model.enums; * @author Crov */ public enum EstatusPagoMultiple { - PAGADO ("Pagado"){ - @Override - public String toString() { - return "Pagado"; - } - }, CANCELADO ("Cancelado"){ - @Override - public String toString() { - return "Cancelado"; - } - }, - DEVUELTO ("Devuelto"){ - @Override - public String toString() { - return "Devuelto"; - } - }; - - private final String type; + PROCESANDO("PROCESANDO") { + @Override + public String toString() { + return "PROCESANDO"; + } + }, PAGADO("PAGADO") { + @Override + public String toString() { + return "PAGADO"; + } + }, CANCELADO("CANCELADO") { + @Override + public String toString() { + return "CANCELADO"; + } + }, + DEVUELTO("DEVUELTO") { + @Override + public String toString() { + return "DEVUELTO"; + } + }, + FALLIDO("FALLIDO") { + @Override + public String toString() { + return "FALLIDO"; + } + }; - private EstatusPagoMultiple(String type) { - this.type = type; - } + private final String type; - public String getType() { - return type; - } + private EstatusPagoMultiple(String type) { + this.type = type; + } + + public String getType() { + return type; + } } diff --git a/crov-prase-model/src/main/java/com/crov/prase/model/prase/DetellePagoPoliza.java b/crov-prase-model/src/main/java/com/crov/prase/model/prase/DetellePagoPoliza.java index 27d6f60..382abcb 100644 --- a/crov-prase-model/src/main/java/com/crov/prase/model/prase/DetellePagoPoliza.java +++ b/crov-prase-model/src/main/java/com/crov/prase/model/prase/DetellePagoPoliza.java @@ -73,6 +73,14 @@ public class DetellePagoPoliza implements Serializable { @Column(name = "metodo_pago", nullable = true) private MetodoPago metodoPago; + @ManyToOne(fetch = FetchType.LAZY, optional = true) + @JoinColumn( + name = "id_abono_multiple", + referencedColumnName = "id", + nullable = true + ) + private HistorialAbonoMultiple historialAbonoMultiple; + @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_on") private Date createdOn; @@ -200,4 +208,12 @@ public class DetellePagoPoliza implements Serializable { this.cobro = cobro; } + public HistorialAbonoMultiple getHistorialAbonoMultiple() { + return historialAbonoMultiple; + } + + public void setHistorialAbonoMultiple(HistorialAbonoMultiple historialAbonoMultiple) { + this.historialAbonoMultiple = historialAbonoMultiple; + } + } diff --git a/crov-prase-model/src/main/java/com/crov/prase/model/prase/HistorialAbonoMultiple.java b/crov-prase-model/src/main/java/com/crov/prase/model/prase/HistorialAbonoMultiple.java new file mode 100644 index 0000000..9c31fb5 --- /dev/null +++ b/crov-prase-model/src/main/java/com/crov/prase/model/prase/HistorialAbonoMultiple.java @@ -0,0 +1,242 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package com.crov.prase.model.prase; + +import com.arrebol.taxiservicios.model.catalog.Location; +import com.arrebol.taxiservicios.model.core.User; +import com.arrebol.taxiservicios.model.enums.EstatusPagoMultiple; +import com.arrebol.taxiservicios.model.enums.MetodoPago; +import java.io.Serializable; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import org.hibernate.annotations.GenericGenerator; + +/** + * + * @author Crov + */ +@Entity +@Table(name = "historial_abono_multiple") +public class HistorialAbonoMultiple implements Serializable { + + private static final long serialVersionUID = -6653037938225719593L; + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + @Column(name = "id", length = 36) + private String id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn( + name = "id_location", + referencedColumnName = "id", + nullable = false + ) + private Location location; + + @Enumerated(EnumType.STRING) + @Column(name = "estatus", nullable = false) + private EstatusPagoMultiple estatus; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn( + name = "id_poliza", + referencedColumnName = "id", + nullable = false + ) + private Poliza poliza; + + @ManyToOne(fetch = FetchType.LAZY, optional = true) + @JoinColumn( + name = "cobro", + referencedColumnName = "id", + nullable = true + ) + private User cobro; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "fecha_pago") + private Date fechaPago; + + @Enumerated(EnumType.STRING) + @Column(name = "metodo_pago", nullable = true) + private MetodoPago metodoPago; + + @Column(name = "total_pago", nullable = true) + private Double totalPago; + + @Column(name = "folios", nullable = true) + private String folios; + + @Column(name = "detalle", nullable = true) + private String detalle; + + @Column(name = "cometario", nullable = true) + private String cometario; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created_on") + private Date createdOn; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn( + name = "created_by", + referencedColumnName = "id", + nullable = false + ) + private User createdBy; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "last_updated_on") + private Date lastUpdatedOn; + + @ManyToOne(fetch = FetchType.LAZY, optional = true) + @JoinColumn( + name = "last_updated_by", + referencedColumnName = "id", + nullable = true + ) + private User lastUpdatedBy; + + public HistorialAbonoMultiple() { + } + + public HistorialAbonoMultiple(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Location getLocation() { + return location; + } + + public void setLocation(Location location) { + this.location = location; + } + + public Poliza getPoliza() { + return poliza; + } + + public void setPoliza(Poliza poliza) { + this.poliza = poliza; + } + + public User getCobro() { + return cobro; + } + + public void setCobro(User cobro) { + this.cobro = cobro; + } + + public Double getTotalPago() { + return totalPago; + } + + public void setTotalPago(Double totalPago) { + this.totalPago = totalPago; + } + + public String getFolios() { + return folios; + } + + public void setFolios(String folios) { + this.folios = folios; + } + + public String getDetalle() { + return detalle; + } + + public void setDetalle(String detalle) { + this.detalle = detalle; + } + + public String getCometario() { + return cometario; + } + + public void setCometario(String cometario) { + this.cometario = cometario; + } + + public EstatusPagoMultiple getEstatus() { + return estatus; + } + + public void setEstatus(EstatusPagoMultiple estatus) { + this.estatus = estatus; + } + + public Date getFechaPago() { + return fechaPago; + } + + public void setFechaPago(Date fechaPago) { + this.fechaPago = fechaPago; + } + + public Date getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + + public User getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(User createdBy) { + this.createdBy = createdBy; + } + + public Date getLastUpdatedOn() { + return lastUpdatedOn; + } + + public void setLastUpdatedOn(Date lastUpdatedOn) { + this.lastUpdatedOn = lastUpdatedOn; + } + + public User getLastUpdatedBy() { + return lastUpdatedBy; + } + + public void setLastUpdatedBy(User lastUpdatedBy) { + this.lastUpdatedBy = lastUpdatedBy; + } + + public MetodoPago getMetodoPago() { + return metodoPago; + } + + public void setMetodoPago(MetodoPago metodoPago) { + this.metodoPago = metodoPago; + } + +} diff --git a/crov-prase-model/src/main/resources/taxi.cfg.xml b/crov-prase-model/src/main/resources/taxi.cfg.xml index 0238968..b2abf98 100644 --- a/crov-prase-model/src/main/resources/taxi.cfg.xml +++ b/crov-prase-model/src/main/resources/taxi.cfg.xml @@ -79,6 +79,7 @@ + diff --git a/crov-prase-web/src/main/java/com/arrebol/taxiservicios/beans/admin/AddClosingDayBean.java b/crov-prase-web/src/main/java/com/arrebol/taxiservicios/beans/admin/AddClosingDayBean.java index c594e52..5bd0716 100644 --- a/crov-prase-web/src/main/java/com/arrebol/taxiservicios/beans/admin/AddClosingDayBean.java +++ b/crov-prase-web/src/main/java/com/arrebol/taxiservicios/beans/admin/AddClosingDayBean.java @@ -1,8 +1,8 @@ /* * Arrebol Consultancy copyright. - * + * * This code belongs to Arrebol Consultancy - * its use, redistribution or modification are prohibited + * its use, redistribution or modification are prohibited * without written authorization from Arrebol Consultancy. */ package com.arrebol.taxiservicios.beans.admin; @@ -17,7 +17,6 @@ import com.arrebol.taxiservicios.model.admin.ClosingDayDetail; import com.arrebol.taxiservicios.model.catalog.Location; import com.arrebol.taxiservicios.model.core.User; import com.arrebol.taxiservicios.model.enums.BasicType; - import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; @@ -41,8 +40,8 @@ import java.util.List; import java.util.UUID; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; -import javax.faces.view.ViewScoped; import javax.faces.context.FacesContext; +import javax.faces.view.ViewScoped; import javax.inject.Named; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; @@ -57,610 +56,609 @@ import org.apache.logging.log4j.Logger; @ViewScoped public class AddClosingDayBean extends TaxiGenericBean implements Serializable { - /** - * On chane selected user find all totals to be set before save. - */ - public void onChangeSelectedUser() { - logger.info("onChangeSelectedUser"); - try { - if (null != getSelectedUserId()) { - findAllDetails(); + /** + * On chane selected user find all totals to be set before save. + */ + public void onChangeSelectedUser() { + logger.info("onChangeSelectedUser"); + try { + if (null != getSelectedUserId()) { + findAllDetails(); + } + } catch (Exception e) { + logger.error(e); + showMessage(FacesMessage.SEVERITY_ERROR, + getBundlePropertyFile().getString("cash.daily.cut"), + getBundlePropertyFile().getString("cash.daily.cut.search.exception.desc")); + } + } + + /** + * + */ + public void saveClosingDay() { + logger.info("saveClosingDay"); + try { + // se valida si ahi solisitudes de canselacion de abonos + + if (getGenericController().existStableSmallBoxByCurdate(getLoggedUser())) { + showMessage(FacesMessage.SEVERITY_WARN, + "Dia cerrado", + "No se pueden eliminar más registros porque ya existe un cuadre de caja chica del día"); + return; + } + + // Redondeo de la cantidad a pagar y la pagada al hacer el corte + Double totalAPagar = getTotalToPay(); + Double totalPago = getTotalPaid(); + Double totalAPagarR = Math.round(totalAPagar * 100.0) / 100.0; + Double totalPagoR = Math.round(totalPago * 100.0) / 100.0; + + if (!(totalAPagarR.equals(totalPagoR))) { + if (getComments() == null || getComments().isEmpty()) { + showMessage(FacesMessage.SEVERITY_WARN, + "Comentarios obligatorios", + "Si el corte es diferente al esperado los comentarios son obligatorios"); + return; } - } catch (Exception e) { - logger.error(e); + + } + ClosingDay closingDay = new ClosingDay(UUID.randomUUID().toString()); + + closingDay.setUser(new User(getSelectedUserId(), "")); + closingDay.setActiveStatus(BasicType.ENEBLED); + closingDay.setAmountExpected(new BigDecimal(getTotalToPay())); + closingDay.setAmountPaid(new BigDecimal(getTotalPaid())); + closingDay.setComments(getComments()); + closingDay.setAmountTransfer(BigDecimal.ZERO); + closingDay.setCreatedBy(getLoggedUser()); + closingDay.setCreatedOn(DateWrapper.getTodayMXTime()); + closingDay.setLocation(new Location(getLoggedUser().getLocation().getId())); + + getDetails().stream().map(detail -> { + detail.setId(UUID.randomUUID().toString()); + return detail; + }).map(detail -> { + detail.setClosingDay(closingDay); + return detail; + }).map(detail -> { + detail.setCreatedBy(getLoggedUser()); + return detail; + }).map(detail -> { + detail.setCreatedOn(DateWrapper.getTodayMXTime()); + return detail; + }).filter(detail -> (null == detail.getPerson() || null == detail.getPerson().getId())).forEachOrdered(detail -> { + detail.setPerson(null); + }); + + if (getController().saveClosingDayAndDetails(closingDay, getDetails())) { + showMessage(FacesMessage.SEVERITY_INFO, + getBundlePropertyFile().getString("cash.daily.cut"), + getBundlePropertyFile().getString("cash.daily.cut.add.success.desc")); + setComments(null); + setTotalSales(null); + setTotalSanctionsIn(null); + setTotalSanctionsOut(null); + setTotalExpenses(null); + setTotalInvoices(null); + setTotalTransferSend(null); + setTotalTransferReceiver(null); + setTotalToPay(null); + setTotalPaid(null); + setTotalTransfer(null); + setTotalPagosPoliza(null); + validateMutual = null; + setUsers(getController().getAllActiveUsers(getLoggedUser().getLocation())); + getDetails().clear(); + + //imprimir(closingDay); + } else { + logger.error("saveClosingDay else error"); showMessage(FacesMessage.SEVERITY_ERROR, - getBundlePropertyFile().getString("cash.daily.cut"), - getBundlePropertyFile().getString("cash.daily.cut.search.exception.desc")); - } - } - - /** - * - */ - public void saveClosingDay() { - logger.info("saveClosingDay"); - try { - // se valida si ahi solisitudes de canselacion de abonos - - if (getGenericController().existStableSmallBoxByCurdate(getLoggedUser())) { - showMessage(FacesMessage.SEVERITY_WARN, - "Dia cerrado", - "No se pueden eliminar más registros porque ya existe un cuadre de caja chica del día"); - return; - } - - // Redondeo de la cantidad a pagar y la pagada al hacer el corte - Double totalAPagar = getTotalToPay(); - Double totalPago = getTotalPaid(); - Double totalAPagarR = Math.round(totalAPagar * 100.0) / 100.0; - Double totalPagoR = Math.round(totalPago * 100.0) / 100.0; - - if (!(totalAPagarR.equals(totalPagoR))) { - if (getComments() == null || getComments().isEmpty()) { - showMessage(FacesMessage.SEVERITY_WARN, - "Comentarios obligatorios", - "Si el corte es diferente al esperado los comentarios son obligatorios"); - return; - } - - } - ClosingDay closingDay = new ClosingDay(UUID.randomUUID().toString()); - - closingDay.setUser(new User(getSelectedUserId(), "")); - closingDay.setActiveStatus(BasicType.ENEBLED); - closingDay.setAmountExpected(new BigDecimal(getTotalToPay())); - closingDay.setAmountPaid(new BigDecimal(getTotalPaid())); - closingDay.setComments(getComments()); - closingDay.setAmountTransfer(BigDecimal.ZERO); - closingDay.setCreatedBy(getLoggedUser()); - closingDay.setCreatedOn(DateWrapper.getTodayMXTime()); - closingDay.setLocation(new Location(getLoggedUser().getLocation().getId())); - - getDetails().stream().map(detail -> { - detail.setId(UUID.randomUUID().toString()); - return detail; - }).map(detail -> { - detail.setClosingDay(closingDay); - return detail; - }).map(detail -> { - detail.setCreatedBy(getLoggedUser()); - return detail; - }).map(detail -> { - detail.setCreatedOn(DateWrapper.getTodayMXTime()); - return detail; - }).filter(detail -> (null == detail.getPerson() || null == detail.getPerson().getId())).forEachOrdered(detail -> { - detail.setPerson(null); - }); - - if (getController().saveClosingDayAndDetails(closingDay, getDetails())) { - showMessage(FacesMessage.SEVERITY_INFO, - getBundlePropertyFile().getString("cash.daily.cut"), - getBundlePropertyFile().getString("cash.daily.cut.add.success.desc")); - setComments(null); - setTotalSales(null); - setTotalSanctionsIn(null); - setTotalSanctionsOut(null); - setTotalExpenses(null); - setTotalInvoices(null); - setTotalTransferSend(null); - setTotalTransferReceiver(null); - setTotalToPay(null); - setTotalPaid(null); - setTotalTransfer(null); - setTotalPagosPoliza(null); - validateMutual = null; - setUsers(getController().getAllActiveUsers(getLoggedUser().getLocation())); - getDetails().clear(); - - //imprimir(closingDay); - } else { - logger.error("saveClosingDay else error"); - showMessage(FacesMessage.SEVERITY_ERROR, - getBundlePropertyFile().getString("cash.daily.cut"), - getBundlePropertyFile().getString("cash.daily.cut.add.exception.desc")); - } - } catch (Exception e) { - logger.error(e); - showMessage(FacesMessage.SEVERITY_FATAL, getBundlePropertyFile().getString("cash.daily.cut"), getBundlePropertyFile().getString("cash.daily.cut.add.exception.desc")); - } - } + } + } catch (Exception e) { + logger.error(e); + showMessage(FacesMessage.SEVERITY_FATAL, + getBundlePropertyFile().getString("cash.daily.cut"), + getBundlePropertyFile().getString("cash.daily.cut.add.exception.desc")); + } + } - public void imprimir(ClosingDay closingDay) { - Document document = new Document(PageSize.LETTER); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - PdfWriter.getInstance(document, baos); - List results = new ArrayList<>(); - results = getController().findDetailsFromClosingDayID(new ClosingDay(closingDay.getId())); - User userTmp = getController().getUserById(closingDay.getUser().getId()); - document.open(); + public void imprimir(ClosingDay closingDay) { + Document document = new Document(PageSize.LETTER); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + PdfWriter.getInstance(document, baos); + List results = new ArrayList<>(); + results = getController().findDetailsFromClosingDayID(new ClosingDay(closingDay.getId())); + User userTmp = getController().getUserById(closingDay.getUser().getId()); + document.open(); - DateFormat formatter = new SimpleDateFormat("dd/MM/yy"); + DateFormat formatter = new SimpleDateFormat("dd/MM/yy"); - Paragraph printDate = new Paragraph("Fecha de impresión: " + formatter.format(new Date()), FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.DARK_GRAY)); - printDate.setAlignment(Element.ALIGN_RIGHT); - document.add(printDate); + Paragraph printDate = new Paragraph("Fecha de impresión: " + formatter.format(new Date()), FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.DARK_GRAY)); + printDate.setAlignment(Element.ALIGN_RIGHT); + document.add(printDate); - Paragraph title = new Paragraph("Corte del día", FontFactory.getFont("arial", 18, Font.BOLD, BaseColor.DARK_GRAY)); - title.setAlignment(Element.ALIGN_CENTER); - document.add(title); + Paragraph title = new Paragraph("Corte del día", FontFactory.getFont("arial", 18, Font.BOLD, BaseColor.DARK_GRAY)); + title.setAlignment(Element.ALIGN_CENTER); + document.add(title); - String date = formatter.format(closingDay.getCreatedOn()); - document.add(new Paragraph("Fecha de creación: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - document.add(new Paragraph(date, FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); - document.add(new Paragraph("Asesor: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - document.add(new Paragraph(userTmp.getPerson().getFirstName() + " " + userTmp.getPerson().getSecondName() + " " + userTmp.getPerson().getLastName() + " " + userTmp.getPerson().getMiddleName(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); + String date = formatter.format(closingDay.getCreatedOn()); + document.add(new Paragraph("Fecha de creación: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + document.add(new Paragraph(date, FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); + document.add(new Paragraph("Asesor: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + document.add(new Paragraph(userTmp.getPerson().getFirstName() + " " + userTmp.getPerson().getSecondName() + " " + userTmp.getPerson().getLastName() + " " + userTmp.getPerson().getMiddleName(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); - document.add(new Paragraph("Monto esperado: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - document.add(new Paragraph("$" + closingDay.getAmountExpected().toString(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); + document.add(new Paragraph("Monto esperado: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + document.add(new Paragraph("$" + closingDay.getAmountExpected().toString(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); - document.add(new Paragraph("Monto pagado: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - document.add(new Paragraph("$" + closingDay.getAmountPaid().toString(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); + document.add(new Paragraph("Monto pagado: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + document.add(new Paragraph("$" + closingDay.getAmountPaid().toString(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); - document.add(new Paragraph("Comentarios: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - document.add(new Paragraph(closingDay.getComments(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); + document.add(new Paragraph("Comentarios: ", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + document.add(new Paragraph(closingDay.getComments(), FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK))); - document.add(Chunk.NEWLINE); + document.add(Chunk.NEWLINE); - PdfPTable table = new PdfPTable(7); - table.setTotalWidth(new float[]{60, 60, 60, 60, 170, 60, 100}); + PdfPTable table = new PdfPTable(7); + table.setTotalWidth(new float[]{60, 60, 60, 60, 170, 60, 100}); - table.setLockedWidth(true); - PdfPCell cell = new PdfPCell(new Paragraph("Detalles del corte", - FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE))); + table.setLockedWidth(true); + PdfPCell cell = new PdfPCell(new Paragraph("Detalles del corte", + FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); - cell.setBackgroundColor(BaseColor.BLUE); - cell.setColspan(7); - table.addCell(cell); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setBackgroundColor(BaseColor.BLUE); + cell.setColspan(7); + table.addCell(cell); - cell = new PdfPCell(new Paragraph("Tipo", - FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell = new PdfPCell(new Paragraph("Tipo", + FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setColspan(1); + table.addCell(cell); + + cell = new PdfPCell(new Paragraph("Monto", + FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setColspan(1); + table.addCell(cell); + + cell = new PdfPCell(new Paragraph("Ahorro", + FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setColspan(1); + table.addCell(cell); + + cell = new PdfPCell(new Paragraph("Siniestro", + FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setColspan(1); + table.addCell(cell); + + cell = new PdfPCell(new Paragraph("Comentarios", + FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setColspan(1); + table.addCell(cell); + + cell = new PdfPCell(new Paragraph("Tipo", + FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setColspan(1); + table.addCell(cell); + + cell = new PdfPCell(new Paragraph("Persona", + FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell.setColspan(1); + table.addCell(cell); + + for (ClosingDayDetail tmp : results) { + + cell = new PdfPCell(new Paragraph(tmp.getType(), + FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(1); table.addCell(cell); - cell = new PdfPCell(new Paragraph("Monto", - FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell = new PdfPCell(new Paragraph(tmp.getAmount() != null ? "$" + tmp.getAmount().toString() : "$0.00", + FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(1); table.addCell(cell); - cell = new PdfPCell(new Paragraph("Ahorro", - FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell = new PdfPCell(new Paragraph(tmp.getAmountSaving() != null ? "$" + tmp.getAmountSaving().toString() : "$0.00", + FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(1); table.addCell(cell); - cell = new PdfPCell(new Paragraph("Siniestro", - FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell = new PdfPCell(new Paragraph(tmp.getAmountAccident() != null ? "$" + tmp.getAmountAccident().toString() : "$0.00", + FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(1); table.addCell(cell); - cell = new PdfPCell(new Paragraph("Comentarios", - FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell = new PdfPCell(new Paragraph(tmp.getComments(), + FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(1); table.addCell(cell); - cell = new PdfPCell(new Paragraph("Tipo", - FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell = new PdfPCell(new Paragraph(" ", + FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(1); table.addCell(cell); - cell = new PdfPCell(new Paragraph("Persona", - FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); + cell = new PdfPCell(new Paragraph(tmp.getPerson() != null ? tmp.getPerson().getFirstName() + " " + tmp.getPerson().getSecondName() + " " + tmp.getPerson().getLastName() + " " + tmp.getPerson().getMiddleName() : "", + FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); + cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(1); table.addCell(cell); - - for (ClosingDayDetail tmp : results) { - - cell = new PdfPCell(new Paragraph(tmp.getType(), - FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - cell.setColspan(1); - table.addCell(cell); - - cell = new PdfPCell(new Paragraph(tmp.getAmount() != null ? "$" + tmp.getAmount().toString() : "$0.00", - FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - cell.setColspan(1); - table.addCell(cell); - - cell = new PdfPCell(new Paragraph(tmp.getAmountSaving() != null ? "$" + tmp.getAmountSaving().toString() : "$0.00", - FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - cell.setColspan(1); - table.addCell(cell); - - cell = new PdfPCell(new Paragraph(tmp.getAmountAccident() != null ? "$" + tmp.getAmountAccident().toString() : "$0.00", - FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - cell.setColspan(1); - table.addCell(cell); - - cell = new PdfPCell(new Paragraph(tmp.getComments(), - FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - cell.setColspan(1); - table.addCell(cell); - - cell = new PdfPCell(new Paragraph(" ", - FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - cell.setColspan(1); - table.addCell(cell); - - cell = new PdfPCell(new Paragraph(tmp.getPerson() != null ? tmp.getPerson().getFirstName() + " " + tmp.getPerson().getSecondName() + " " + tmp.getPerson().getLastName() + " " + tmp.getPerson().getMiddleName() : "", - FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK))); - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - cell.setColspan(1); - table.addCell(cell); - } - - document.add(table); - - document.add(Chunk.NEWLINE); - document.add(Chunk.NEWLINE); - document.add(Chunk.NEWLINE); - document.add(Chunk.NEWLINE); - - document.add(new Paragraph(" __________________________ __________________________")); - document.add(new Paragraph(" Firma Nombre y firma cajero responsable")); - document.add(new Paragraph(" " + userTmp.getPerson().getFirstName() + " " + userTmp.getPerson().getSecondName() + " " + userTmp.getPerson().getLastName() + " " + userTmp.getPerson().getMiddleName())); - - } catch (Exception e) { - System.out.print("Error 1: " + e.getMessage()); - } - - document.close(); - FacesContext context = FacesContext.getCurrentInstance(); - Object response = context.getExternalContext().getResponse(); - if (response instanceof HttpServletResponse) { - HttpServletResponse hrs = (HttpServletResponse) response; - hrs.setContentType("application/pdf"); - hrs.setHeader("Content-disposition", "attachment; filename=\"corteDelDia.pdf\""); - hrs.setContentLength(baos.size()); - try { - ServletOutputStream out = hrs.getOutputStream(); - baos.writeTo(out); - out.flush(); - - } catch (IOException e) { - System.out.print("Error 2: " + e.getMessage()); - } - context.responseComplete(); - } - } - - /** - * - */ - private void findAllDetails() { - try { - Double totalIns = 0D; - - totalIns = totalIns + (getController().findTotals(query_total_inicio_expenses, getSelectedUserId())); - - setTotalSanctionsIn(totalIns + getController().findTotals(query_total_transfer_receiver, getSelectedUserId())); - - setTotalExpenses(getController().findTotals(query_total_expenses, getSelectedUserId()) + getController().findTotals(query_total_transfer_send, getSelectedUserId())); - setTotalPagosPoliza(getController().findTotals(query_total_poliza_prase, getSelectedUserId())); - setSaveCashDailyCut(true); - setDetails(getController().findClosingDayDetails(getSelectedUserId())); - sumTotals(); - } catch (Exception e) { - logger.error(e); - setSaveCashDailyCut(false); - throw e; - } - } - - private void sumTotals() { - try { - totalToPay = getTotalSanctionsIn() + getTotalPagosPoliza(); - totalToPay += -(getTotalSanctionsOut() + getTotalExpenses()); - totalExpenses = getTotalExpenses(); - } catch (Exception e) { - logger.error(e); - setSaveCashDailyCut(false); - throw e; - } - } - - @PostConstruct - public void init() { - logger.info("init"); - try { - loadBundlePropertyFile(); - - setController(new ClosingDayController()); - setGenericController(new GenericValidationController()); - setUserController(new UserController()); - setUsers(getController().getAllActiveUsers(getLoggedUser().getLocation())); - setSaveCashDailyCut(false); - - } catch (Exception e) { - logger.error(e); - } - } - - private ClosingDayController controller; - private GenericValidationController genericController; - private UserController userController; - private List users; - private String selectedUserId; - private Double totalSales; - private Double totalSanctionsIn; - private Double totalSanctionsOut; - private Double totalExpenses; - private Double totalDetalleUbicaciones; - private Double totalInvoices; - private Double totalTransferSend; - private Double totalTransferReceiver; - private Double totalPaymentClient; - private boolean saveCashDailyCut; - private List details; - private String comments; - private Double totalToPay; - private Double totalPaid; - - private Double totalPagosPoliza; - - private Double validateMutual; - private Double validateSale; - private Double validateSanction; - - private Double totalTransfer; - private boolean existSalesToPay; - - public Double getValidateSale() { - return validateSale; - } - - public void setValidateSale(Double validateSale) { - this.validateSale = validateSale; - } - - public Double getValidateSanction() { - return validateSanction; - } - - public void setValidateSanction(Double validateSanction) { - this.validateSanction = validateSanction; - } - - public GenericValidationController getGenericController() { - return genericController; - } - - public Double getValidateMutual() { - return validateMutual; - } - - public void setValidateMutual(Double validateMutual) { - this.validateMutual = validateMutual; - } - - public void setGenericController(GenericValidationController genericController) { - this.genericController = genericController; - } - - public Double getTotalTransfer() { - return totalTransfer; - } - - public void setTotalTransfer(Double totalTransfer) { - this.totalTransfer = totalTransfer; - } - - public Double getTotalPaymentClient() { - return totalPaymentClient; - } - - public void setTotalPaymentClient(Double totalPaymentClient) { - this.totalPaymentClient = totalPaymentClient; - } - - public Double getTotalTransferSend() { - return totalTransferSend; - } - - public void setTotalTransferSend(Double totalTransferSend) { - this.totalTransferSend = totalTransferSend; - } - - public Double getTotalTransferReceiver() { - return totalTransferReceiver; - } - - public void setTotalTransferReceiver(Double totalTransferReceiver) { - this.totalTransferReceiver = totalTransferReceiver; - } - - public ClosingDayController getController() { - return controller; - } - - public void setController(ClosingDayController controller) { - this.controller = controller; - } - - public List getUsers() { - return users; - } - - public void setUsers(List users) { - this.users = users; - } - - public String getSelectedUserId() { - return selectedUserId; - } - - public void setSelectedUserId(String selectedUserId) { - this.selectedUserId = selectedUserId; - } - - public Double getTotalSales() { - if (null == totalSales) { - totalSales = 0d; - } - return totalSales; - } - - public void setTotalSales(Double totalSales) { - this.totalSales = totalSales; - } - - public Double getTotalSanctionsIn() { - if (null == totalSanctionsIn) { - totalSanctionsIn = 0d; - } - return totalSanctionsIn; - } - - public void setTotalSanctionsIn(Double totalSanctionsIn) { - this.totalSanctionsIn = totalSanctionsIn; - } - - public Double getTotalSanctionsOut() { - if (null == totalSanctionsOut) { - totalSanctionsOut = 0d; - } - return totalSanctionsOut; - } - - public void setTotalSanctionsOut(Double totalSanctionsOut) { - this.totalSanctionsOut = totalSanctionsOut; - } - - public Double getTotalExpenses() { - if (null == totalExpenses) { - totalExpenses = 0d; - } - return totalExpenses; - } - - public void setTotalExpenses(Double totalExpenses) { - this.totalExpenses = totalExpenses; - } - - public Double getTotalInvoices() { - if (null == totalInvoices) { - totalInvoices = 0d; - } - return totalInvoices; - } - - public void setTotalInvoices(Double totalInvoices) { - this.totalInvoices = totalInvoices; - } - - public boolean isSaveCashDailyCut() { - return saveCashDailyCut; - } - - public void setSaveCashDailyCut(boolean saveCashDailyCut) { - this.saveCashDailyCut = saveCashDailyCut; - } - - public List getDetails() { - return details; - } - - public void setDetails(List details) { - this.details = details; - } - - public String getComments() { - return comments; - } - - public void setComments(String comments) { - this.comments = comments; - } - - public Double getTotalToPay() { - if (null == totalToPay) { - totalToPay = 0d; - } - return totalToPay; - } - - public void setTotalToPay(Double totalToPay) { - this.totalToPay = totalToPay; - } - - public Double getTotalPaid() { - return totalPaid; - } - - public void setTotalPaid(Double totalPaid) { - if (null == totalPaid) { - totalPaid = 0d; - } - this.totalPaid = totalPaid; - } - - public boolean isExistSalesToPay() { - return existSalesToPay; - } - - public Double getTotalDetalleUbicaciones() { - if (null == totalDetalleUbicaciones) { - totalDetalleUbicaciones = 0d; - } - return totalDetalleUbicaciones; - } - - public void setTotalDetalleUbicaciones(Double totalDetalleUbicaciones) { - if (null == totalDetalleUbicaciones) { - totalDetalleUbicaciones = 0d; - } - this.totalDetalleUbicaciones = totalDetalleUbicaciones; - } - - public void setExistSalesToPay(boolean existSalesToPay) { - this.existSalesToPay = existSalesToPay; - } - - public UserController getUserController() { - return userController; - } - - public void setUserController(UserController userController) { - this.userController = userController; - } - - public Double getTotalPagosPoliza() { - return totalPagosPoliza; - } - - public void setTotalPagosPoliza(Double totalPagosPoliza) { - this.totalPagosPoliza = totalPagosPoliza; - } - - final Logger logger = LogManager.getLogger(AddClosingDayBean.class); - private static final long serialVersionUID = -2421681541992908524L; - - private final String sub_query_to_find_previously_closing_day = "(SELECT DATE(cd.created_on) FROM closing_day cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = :userID AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)"; - private final String query_total_inicio_expenses = "SELECT IF(ISNULL(SUM(payment)),0, SUM(payment)) AS total_expenses FROM expense LEFT JOIN expense_income_catalog ON expense.id_expense_type = expense_income_catalog.id WHERE DATE(expense.created_on) > " + sub_query_to_find_previously_closing_day + " AND expense_status_type = 'AUTHORIZED' AND expense.created_by = :userID AND (expense_type IN ('INICIO','ABONO_FINANCIAMIENTO','PAGO_ORDEN_SERVICIO') OR (expense_income_catalog.type = 'EARNING')) AND id_bank_card is null"; - private final String query_total_expenses = "SELECT IF(ISNULL(SUM(payment)),0, SUM(payment)) AS total_expenses FROM expense INNER JOIN expense_income_catalog ON expense.id_expense_type = expense_income_catalog.id WHERE DATE(expense.created_on)> " + sub_query_to_find_previously_closing_day + " AND expense_status_type = 'AUTHORIZED' AND expense.created_by = :userID AND expense_income_catalog.type = 'EXPENSE' AND id_bank_card is null"; - - private final String query_total_transfer_send = "SELECT IF(ISNULL(SUM(amount_to_transfer)),0, SUM(amount_to_transfer)) AS total_transfer_send FROM transfer_car_driver WHERE DATE(created_on) > " + sub_query_to_find_previously_closing_day + " AND action_status = 'APPROVED' AND active_status = 'ENEBLED' AND id_user_transmitter = :userID"; - private final String query_total_transfer_receiver = "SELECT IF(ISNULL(SUM(amount_to_transfer)),0, SUM(amount_to_transfer)) AS total_transfer_receiver FROM transfer_car_driver WHERE DATE(created_on) > " + sub_query_to_find_previously_closing_day + " AND action_status = 'APPROVED' AND active_status = 'ENEBLED' AND id_user_receiver = :userID"; - - private final String query_total_poliza_prase = "SELECT IFNULL(SUM(pago), 0) AS total_pagos " - + "FROM pagos_poliza WHERE DATE(fecha_pago) > " + sub_query_to_find_previously_closing_day + " " - + " AND cobro = :userID " - + " AND metodo_pago = 'EFECTIVO' " - + " AND pago_estatus = 'ENABLED' " - + " AND estatus_activo = 'ENABLED' "; + } + + document.add(table); + + document.add(Chunk.NEWLINE); + document.add(Chunk.NEWLINE); + document.add(Chunk.NEWLINE); + document.add(Chunk.NEWLINE); + + document.add(new Paragraph(" __________________________ __________________________")); + document.add(new Paragraph(" Firma Nombre y firma cajero responsable")); + document.add(new Paragraph(" " + userTmp.getPerson().getFirstName() + " " + userTmp.getPerson().getSecondName() + " " + userTmp.getPerson().getLastName() + " " + userTmp.getPerson().getMiddleName())); + + } catch (Exception e) { + System.out.print("Error 1: " + e.getMessage()); + } + + document.close(); + FacesContext context = FacesContext.getCurrentInstance(); + Object response = context.getExternalContext().getResponse(); + if (response instanceof HttpServletResponse) { + HttpServletResponse hrs = (HttpServletResponse) response; + hrs.setContentType("application/pdf"); + hrs.setHeader("Content-disposition", "attachment; filename=\"corteDelDia.pdf\""); + hrs.setContentLength(baos.size()); + try { + ServletOutputStream out = hrs.getOutputStream(); + baos.writeTo(out); + out.flush(); + + } catch (IOException e) { + System.out.print("Error 2: " + e.getMessage()); + } + context.responseComplete(); + } + } + + /** + * + */ + private void findAllDetails() { + try { + Double totalIns = 0D; + + totalIns = totalIns + (getController().findTotals(query_total_inicio_expenses, getSelectedUserId())); + + setTotalSanctionsIn(totalIns + getController().findTotals(query_total_transfer_receiver, getSelectedUserId())); + + setTotalExpenses(getController().findTotals(query_total_expenses, getSelectedUserId()) + getController().findTotals(query_total_transfer_send, getSelectedUserId())); + setTotalPagosPoliza(getController().findTotals(query_total_poliza_prase, getSelectedUserId())); + setSaveCashDailyCut(true); + setDetails(getController().findClosingDayDetails(getSelectedUserId())); + sumTotals(); + } catch (Exception e) { + logger.error(e); + setSaveCashDailyCut(false); + throw e; + } + } + + private void sumTotals() { + try { + totalToPay = getTotalSanctionsIn() + getTotalPagosPoliza(); + totalToPay += -(getTotalSanctionsOut() + getTotalExpenses()); + totalExpenses = getTotalExpenses(); + } catch (Exception e) { + logger.error(e); + setSaveCashDailyCut(false); + throw e; + } + } + + @PostConstruct + public void init() { + logger.info("init"); + try { + loadBundlePropertyFile(); + + setController(new ClosingDayController()); + setGenericController(new GenericValidationController()); + setUserController(new UserController()); + setUsers(getController().getAllActiveUsers(getLoggedUser().getLocation())); + setSaveCashDailyCut(false); + + } catch (Exception e) { + logger.error(e); + } + } + + private ClosingDayController controller; + private GenericValidationController genericController; + private UserController userController; + private List users; + private String selectedUserId; + private Double totalSales; + private Double totalSanctionsIn; + private Double totalSanctionsOut; + private Double totalExpenses; + private Double totalDetalleUbicaciones; + private Double totalInvoices; + private Double totalTransferSend; + private Double totalTransferReceiver; + private Double totalPaymentClient; + private boolean saveCashDailyCut; + private List details; + private String comments; + private Double totalToPay; + private Double totalPaid; + + private Double totalPagosPoliza; + + private Double validateMutual; + private Double validateSale; + private Double validateSanction; + + private Double totalTransfer; + private boolean existSalesToPay; + + public Double getValidateSale() { + return validateSale; + } + + public void setValidateSale(Double validateSale) { + this.validateSale = validateSale; + } + + public Double getValidateSanction() { + return validateSanction; + } + + public void setValidateSanction(Double validateSanction) { + this.validateSanction = validateSanction; + } + + public GenericValidationController getGenericController() { + return genericController; + } + + public Double getValidateMutual() { + return validateMutual; + } + + public void setValidateMutual(Double validateMutual) { + this.validateMutual = validateMutual; + } + + public void setGenericController(GenericValidationController genericController) { + this.genericController = genericController; + } + + public Double getTotalTransfer() { + return totalTransfer; + } + + public void setTotalTransfer(Double totalTransfer) { + this.totalTransfer = totalTransfer; + } + + public Double getTotalPaymentClient() { + return totalPaymentClient; + } + + public void setTotalPaymentClient(Double totalPaymentClient) { + this.totalPaymentClient = totalPaymentClient; + } + + public Double getTotalTransferSend() { + return totalTransferSend; + } + + public void setTotalTransferSend(Double totalTransferSend) { + this.totalTransferSend = totalTransferSend; + } + + public Double getTotalTransferReceiver() { + return totalTransferReceiver; + } + + public void setTotalTransferReceiver(Double totalTransferReceiver) { + this.totalTransferReceiver = totalTransferReceiver; + } + + public ClosingDayController getController() { + return controller; + } + + public void setController(ClosingDayController controller) { + this.controller = controller; + } + + public List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + public String getSelectedUserId() { + return selectedUserId; + } + + public void setSelectedUserId(String selectedUserId) { + this.selectedUserId = selectedUserId; + } + + public Double getTotalSales() { + if (null == totalSales) { + totalSales = 0d; + } + return totalSales; + } + + public void setTotalSales(Double totalSales) { + this.totalSales = totalSales; + } + + public Double getTotalSanctionsIn() { + if (null == totalSanctionsIn) { + totalSanctionsIn = 0d; + } + return totalSanctionsIn; + } + + public void setTotalSanctionsIn(Double totalSanctionsIn) { + this.totalSanctionsIn = totalSanctionsIn; + } + + public Double getTotalSanctionsOut() { + if (null == totalSanctionsOut) { + totalSanctionsOut = 0d; + } + return totalSanctionsOut; + } + + public void setTotalSanctionsOut(Double totalSanctionsOut) { + this.totalSanctionsOut = totalSanctionsOut; + } + + public Double getTotalExpenses() { + if (null == totalExpenses) { + totalExpenses = 0d; + } + return totalExpenses; + } + + public void setTotalExpenses(Double totalExpenses) { + this.totalExpenses = totalExpenses; + } + + public Double getTotalInvoices() { + if (null == totalInvoices) { + totalInvoices = 0d; + } + return totalInvoices; + } + + public void setTotalInvoices(Double totalInvoices) { + this.totalInvoices = totalInvoices; + } + + public boolean isSaveCashDailyCut() { + return saveCashDailyCut; + } + + public void setSaveCashDailyCut(boolean saveCashDailyCut) { + this.saveCashDailyCut = saveCashDailyCut; + } + + public List getDetails() { + return details; + } + + public void setDetails(List details) { + this.details = details; + } + + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } + + public Double getTotalToPay() { + if (null == totalToPay) { + totalToPay = 0d; + } + return totalToPay; + } + + public void setTotalToPay(Double totalToPay) { + this.totalToPay = totalToPay; + } + + public Double getTotalPaid() { + return totalPaid; + } + + public void setTotalPaid(Double totalPaid) { + if (null == totalPaid) { + totalPaid = 0d; + } + this.totalPaid = totalPaid; + } + + public boolean isExistSalesToPay() { + return existSalesToPay; + } + + public Double getTotalDetalleUbicaciones() { + if (null == totalDetalleUbicaciones) { + totalDetalleUbicaciones = 0d; + } + return totalDetalleUbicaciones; + } + + public void setTotalDetalleUbicaciones(Double totalDetalleUbicaciones) { + if (null == totalDetalleUbicaciones) { + totalDetalleUbicaciones = 0d; + } + this.totalDetalleUbicaciones = totalDetalleUbicaciones; + } + + public void setExistSalesToPay(boolean existSalesToPay) { + this.existSalesToPay = existSalesToPay; + } + + public UserController getUserController() { + return userController; + } + + public void setUserController(UserController userController) { + this.userController = userController; + } + + public Double getTotalPagosPoliza() { + return totalPagosPoliza; + } + + public void setTotalPagosPoliza(Double totalPagosPoliza) { + this.totalPagosPoliza = totalPagosPoliza; + } + + final Logger logger = LogManager.getLogger(AddClosingDayBean.class); + private static final long serialVersionUID = -2421681541992908524L; + + private final String sub_query_to_find_previously_closing_day = "(SELECT DATE(cd.created_on) FROM closing_day cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = :userID AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)"; + private final String query_total_inicio_expenses = "SELECT IF(ISNULL(SUM(payment)),0, SUM(payment)) AS total_expenses FROM expense LEFT JOIN expense_income_catalog ON expense.id_expense_type = expense_income_catalog.id WHERE DATE(expense.created_on) > " + sub_query_to_find_previously_closing_day + " AND expense_status_type = 'AUTHORIZED' AND expense.created_by = :userID AND (expense_type IN ('INICIO','ABONO_FINANCIAMIENTO','PAGO_ORDEN_SERVICIO') OR (expense_income_catalog.type = 'EARNING')) AND id_bank_card is null"; + private final String query_total_expenses = "SELECT IF(ISNULL(SUM(payment)),0, SUM(payment)) AS total_expenses FROM expense INNER JOIN expense_income_catalog ON expense.id_expense_type = expense_income_catalog.id WHERE DATE(expense.created_on)> " + sub_query_to_find_previously_closing_day + " AND expense_status_type = 'AUTHORIZED' AND expense.created_by = :userID AND expense_income_catalog.type = 'EXPENSE' AND id_bank_card is null"; + + private final String query_total_transfer_send = "SELECT IF(ISNULL(SUM(amount_to_transfer)),0, SUM(amount_to_transfer)) AS total_transfer_send FROM transfer_car_driver WHERE DATE(created_on) > " + sub_query_to_find_previously_closing_day + " AND action_status = 'APPROVED' AND active_status = 'ENEBLED' AND id_user_transmitter = :userID"; + private final String query_total_transfer_receiver = "SELECT IF(ISNULL(SUM(amount_to_transfer)),0, SUM(amount_to_transfer)) AS total_transfer_receiver FROM transfer_car_driver WHERE DATE(created_on) > " + sub_query_to_find_previously_closing_day + " AND action_status = 'APPROVED' AND active_status = 'ENEBLED' AND id_user_receiver = :userID"; + + private final String query_total_poliza_prase = "SELECT IFNULL(SUM(cantidad_pagada), 0) AS total_pagos " + + "FROM detelle_pago_poliza WHERE DATE(fecha_pago) > " + sub_query_to_find_previously_closing_day + " " + + " AND cobro = :userID " + + " AND metodo_pago = 'EFECTIVO' " + + " AND estatus_activo = 'ENABLED' "; } diff --git a/crov-prase-web/src/main/java/com/crov/prase/prase/PagosPolizasBean.java b/crov-prase-web/src/main/java/com/crov/prase/prase/PagosPolizasBean.java index f0c95ce..c15b7c2 100644 --- a/crov-prase-web/src/main/java/com/crov/prase/prase/PagosPolizasBean.java +++ b/crov-prase-web/src/main/java/com/crov/prase/prase/PagosPolizasBean.java @@ -12,12 +12,14 @@ import com.arrebol.taxiservicios.model.enums.PolizaEstatus; import com.crov.prase.controller.prase.PagosPolizaController; import com.crov.prase.controller.prase.PolizaController; import com.crov.prase.model.prase.DetellePagoPoliza; +import com.crov.prase.model.prase.HistorialAbonoMultiple; import com.crov.prase.model.prase.PagosPoliza; import com.crov.prase.model.prase.Poliza; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.List; +import java.util.UUID; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.view.ViewScoped; @@ -48,9 +50,11 @@ public class PagosPolizasBean extends TaxiGenericBean implements Serializable { private DetellePagoPoliza selectedDetellePago; private String pagoSiguiente; private Double cantidadAPagar; + private String comentario; private Boolean pagoExitoso; private String imagen; private String metodoPago; + private HistorialAbonoMultiple selectedHistorialAbonoMultiple; @PostConstruct public void init() { @@ -92,6 +96,42 @@ public class PagosPolizasBean extends TaxiGenericBean implements Serializable { public void cargarPago() { setCantidadAPagar(getSelectedPago().getDiferenciaPago()); + setSelectedDetellePago(null); + setMetodoPago(""); + } + + public void pagarMultiple() { + logger.info("pagarMultiple()"); + setPagoExitoso(false); + + if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) { + showMessage(FacesMessage.SEVERITY_WARN, "Error", "No se puede hacer ninguna acción si existe un corte del día"); + return; + } + + if (getGenericController().existStableGeneralBoxByCurdate(getLoggedUser())) { + showMessage(FacesMessage.SEVERITY_WARN, "Dia cerrado", "No se puede hacer ninguna acción porque ya existe un cuadre de caja chica del día"); + return; + } + + if (getCantidadAPagar() <= 0.0) { + showMessage(FacesMessage.SEVERITY_WARN, "Error", "El monto a pagar debe de ser mayor a 0"); + return; + } + + // se actuliza el pago + String estatusPagoMultiple = getPagosPolizaController().procesarPagoMultiple(getSelectedPoliza(), getCantidadAPagar(), getMetodoPago(), getComentario(), getLoggedUser()); + if (esUUIDValido(estatusPagoMultiple)) { + setImagen("images/prase_logo.jpeg"); + setSelectedHistorialAbonoMultiple(getPagosPolizaController().getHistorialAbonoMultipleById(estatusPagoMultiple)); + setPagoExitoso(true); + cargarPolizas(); + showMessage(FacesMessage.SEVERITY_INFO, "Pago realizado", "El pago multiple se a realizado correctamente"); + } else { + setPagoExitoso(false); + setSelectedHistorialAbonoMultiple(null); + showMessage(FacesMessage.SEVERITY_ERROR, "Error", estatusPagoMultiple); + } } public void pagar() { @@ -131,7 +171,6 @@ public class PagosPolizasBean extends TaxiGenericBean implements Serializable { } else { showMessage(FacesMessage.SEVERITY_WARN, "Error", "Solo puede pagar el pago consecutivo"); } - } private boolean actualizarAbono(PagosPoliza pagoA, Double montoPagado, String metodoDePago) { @@ -191,6 +230,16 @@ public class PagosPolizasBean extends TaxiGenericBean implements Serializable { public void limpiarDetallePago() { setSelectedDetellePago(null); setPagoExitoso(false); + setCantidadAPagar(0.0); + setMetodoPago(""); + } + + public void limpiarDetallePagoMultiple() { + setSelectedHistorialAbonoMultiple(null); + setPagoExitoso(false); + setCantidadAPagar(0.0); + setMetodoPago(""); + setComentario(null); } private String obtenerFolio(String ab) { @@ -198,7 +247,7 @@ public class PagosPolizasBean extends TaxiGenericBean implements Serializable { try { // Se cargan los abonos para validar el folio String abreviacion = ab; - PagosPoliza ultimoFolio = getPagosPolizaController().fillFoliosByPagos(abreviacion); + DetellePagoPoliza ultimoFolio = getPagosPolizaController().fillFoliosByPagos(abreviacion); // Se valida si ya existen folios registrados para el proyecto y se le asigna el último encontrado int consecutivo = 0; if (ultimoFolio != null) { @@ -249,6 +298,18 @@ public class PagosPolizasBean extends TaxiGenericBean implements Serializable { } } + public static boolean esUUIDValido(String valor) { + if (valor == null) { + return false; + } + try { + UUID uuid = UUID.fromString(valor); + return valor.equals(uuid.toString()); + } catch (IllegalArgumentException ex) { + return false; + } + } + private Date correcciónDeHr(Date fecha, int horas) { Calendar calendar = Calendar.getInstance(); calendar.setTime(fecha); @@ -378,4 +439,20 @@ public class PagosPolizasBean extends TaxiGenericBean implements Serializable { this.listDetallePagosPolizas = listDetallePagosPolizas; } + public String getComentario() { + return comentario; + } + + public void setComentario(String comentario) { + this.comentario = comentario; + } + + public HistorialAbonoMultiple getSelectedHistorialAbonoMultiple() { + return selectedHistorialAbonoMultiple; + } + + public void setSelectedHistorialAbonoMultiple(HistorialAbonoMultiple selectedHistorialAbonoMultiple) { + this.selectedHistorialAbonoMultiple = selectedHistorialAbonoMultiple; + } + } diff --git a/crov-prase-web/src/main/java/com/crov/prase/prase/PolizaBean.java b/crov-prase-web/src/main/java/com/crov/prase/prase/PolizaBean.java index b4dc848..eed198e 100644 --- a/crov-prase-web/src/main/java/com/crov/prase/prase/PolizaBean.java +++ b/crov-prase-web/src/main/java/com/crov/prase/prase/PolizaBean.java @@ -34,6 +34,7 @@ import com.crov.prase.controller.prase.PagosPolizaController; import com.crov.prase.controller.prase.PolizaController; import com.crov.prase.model.catalog.Hospitales; import com.crov.prase.model.catalog.TipoPoliza; +import com.crov.prase.model.prase.DetellePagoPoliza; import com.crov.prase.model.prase.PagosPoliza; import com.crov.prase.model.prase.Poliza; import java.io.Serializable; @@ -61,625 +62,620 @@ import org.primefaces.event.RowEditEvent; @ViewScoped public class PolizaBean extends TaxiGenericBean implements Serializable, Datatable { - public void newPoliza() { - logger.info("Nueva póliza"); - setEditPoliza(false); - setPolizaAdd(new Poliza()); - getPolizaAdd().setCantidadPagada(0.0); - getPolizaAdd().setPeriodoGracia(7); - setInitDate(new Date()); - setPrimerPago(0.0); - setContador(0); - } + public void newPoliza() { + logger.info("Nueva póliza"); + setEditPoliza(false); + setPolizaAdd(new Poliza()); + getPolizaAdd().setCantidadPagada(0.0); + getPolizaAdd().setPeriodoGracia(7); + setInitDate(new Date()); + setPrimerPago(0.0); + setContador(0); + } - @Override - public void addRow() { - logger.info("Agregando póliza"); - try { - Taxi taxiTmp = null; + @Override + public void addRow() { + logger.info("Agregando póliza"); + try { + Taxi taxiTmp = null; - if (idTaxi != null && !idTaxi.isEmpty()) { - taxiTmp = getTaxiController().getTaxiByIdReport2(idTaxi); - } else { - FacesMessage msg = new FacesMessage("Vehículo vacio", "Se debe de seleccionar un vehículo"); - FacesContext.getCurrentInstance().addMessage(null, msg); - return; - } - - getPolizaAdd().setId(UUID.randomUUID().toString()); - getPolizaAdd().setActive(true); - getPolizaAdd().setCreatedOn(correcciónDeHr(new Date(), -7)); - getPolizaAdd().setInitDate(correcciónDeDias(getInitDate(), 1)); - getPolizaAdd().setTaxi(taxiTmp); - getPolizaAdd().setCustomer(taxiTmp.getCustomer()); - getPolizaAdd().setTipoPoliza(new TipoPoliza(idTipoPoliza)); - getPolizaAdd().setAsesor(new Person(idAsesor)); - getPolizaAdd().setCreatedBy(getLoggedUser()); - getPolizaAdd().setLocation(getLoggedUser().getLocation()); - getPolizaAdd().setUMA(getUMA()); - // Validación del periodo de pago para la generación de folios - switch (getIdPeriocidad()) { - case "ANUAL": - getPolizaAdd().setFolio(obtenerFolio("PA", getPolizaAdd().getInitDate())); - break; - case "SEMESTRAL": - getPolizaAdd().setFolio(obtenerFolio("PS", getPolizaAdd().getInitDate())); - break; - case "TRIMESTRAL": - getPolizaAdd().setFolio(obtenerFolio("PT", getPolizaAdd().getInitDate())); - break; - case "MENSUAL": - getPolizaAdd().setFolio(obtenerFolio("PM", getPolizaAdd().getInitDate())); - break; - default: - break; - } - - if (isLiquidado()) { - getPolizaAdd().setEstatus(PolizaEstatus.LIQUIDADO); - getPolizaAdd().setCantidadPagada(getPolizaAdd().getAmount()); - } else { - getPolizaAdd().setEstatus(PolizaEstatus.PENDIENTE); - } - - Calendar calendar = Calendar.getInstance(); - calendar.setTime(getPolizaAdd().getInitDate()); - calendar.add(Calendar.YEAR, 1); - getPolizaAdd().setEndDate(calendar.getTime()); - - controller.save(getPolizaAdd()); - - if (!isLiquidado()) { - Calendar fechaInicial = Calendar.getInstance(); - fechaInicial.setTime(getPolizaAdd().getInitDate()); - - int numeroPagos = 0; - - switch (getIdPeriocidad()) { - case "ANUAL": - numeroPagos = 1; - break; - case "SEMESTRAL": - numeroPagos = 2; - break; - case "TRIMESTRAL": - numeroPagos = 4; - break; - case "MENSUAL": - numeroPagos = 12; - break; - default: - break; - } - - List fechasPago = generarFechasDePago(fechaInicial, numeroPagos, getPolizaAdd().getPeriodoGracia()); - setContador(1); - for (Calendar fecha : fechasPago) { - if (getContador() == 1) { - PagosPoliza pagoPoliza = new PagosPoliza(); - pagoPoliza.setCantidadPagada(0D); - pagoPoliza.setPoliza(getPolizaAdd()); - pagoPoliza.setCreatedBy(getLoggedUser()); - pagoPoliza.setCreatedOn(correcciónDeHr(new Date(), -7)); - pagoPoliza.setDiferenciaPago(0D); - pagoPoliza.setPago(getPrimerPago()); - pagoPoliza.setEstatusActivo(GenericEnumType.ENABLED); - pagoPoliza.setPagoEstatus(GenericEnumType.DISABLED); - pagoPoliza.setTipoPago(TipoAbono.ABONO); - pagoPoliza.setFechaAPagar(fecha.getTime()); - getController().save(pagoPoliza); - setContador(2); - } else { - PagosPoliza pagoPoliza = new PagosPoliza(); - pagoPoliza.setCantidadPagada(0D); - pagoPoliza.setPoliza(getPolizaAdd()); - pagoPoliza.setCreatedBy(getLoggedUser()); - pagoPoliza.setCreatedOn(correcciónDeHr(new Date(), -7)); - pagoPoliza.setDiferenciaPago(0D); - pagoPoliza.setPago(((getPolizaAdd().getAmount() - getPolizaAdd().getCantidadPagada()) - getPrimerPago()) / (numeroPagos - 1)); - pagoPoliza.setEstatusActivo(GenericEnumType.ENABLED); - pagoPoliza.setPagoEstatus(GenericEnumType.DISABLED); - pagoPoliza.setTipoPago(TipoAbono.ABONO); - pagoPoliza.setFechaAPagar(fecha.getTime()); - getController().save(pagoPoliza); - } - } - } else { - PagosPoliza pagoPoliza = new PagosPoliza(); - pagoPoliza.setPoliza(getPolizaAdd()); - pagoPoliza.setEstatusActivo(GenericEnumType.ENABLED); - pagoPoliza.setTipoPago(TipoAbono.ABONO); - pagoPoliza.setPagoEstatus(GenericEnumType.ENABLED); - pagoPoliza.setFechaAPagar(correcciónDeHr(new Date(), -7)); - pagoPoliza.setFechaPago(correcciónDeHr(new Date(), -7)); - pagoPoliza.setPago(getPolizaAdd().getAmount()); - pagoPoliza.setCantidadPagada(getPolizaAdd().getAmount()); - pagoPoliza.setDiferenciaPago(0D); - pagoPoliza.setFolio(obtenerFolioAbonos("A-PRASE")); - pagoPoliza.setCobro(getLoggedUser()); - switch (getMetodoPago()) { - case "EFECTIVO": - pagoPoliza.setMetodoPago(MetodoPago.EFECTIVO); - break; - case "TARJETA": - pagoPoliza.setMetodoPago(MetodoPago.TARJETA); - break; - case "DEPOSITO": - pagoPoliza.setMetodoPago(MetodoPago.DEPOSITO); - break; - case "TRASFERENCIA": - pagoPoliza.setMetodoPago(MetodoPago.TRASFERENCIA); - break; - default: - pagoPoliza.setMetodoPago(MetodoPago.EFECTIVO); - } - pagoPoliza.setCreatedBy(getLoggedUser()); - pagoPoliza.setCreatedOn(correcciónDeHr(new Date(), -7)); - getController().save(pagoPoliza); - } - - setPoliza(getController().findActive(getLoggedUser().getLocation())); - clearPolizaForm(); - FacesMessage msg = new FacesMessage("Nueva póliza", "Se agregó correctamente"); + if (idTaxi != null && !idTaxi.isEmpty()) { + taxiTmp = getTaxiController().getTaxiByIdReport2(idTaxi); + } else { + FacesMessage msg = new FacesMessage("Vehículo vacio", "Se debe de seleccionar un vehículo"); FacesContext.getCurrentInstance().addMessage(null, msg); - } catch (Exception e) { - showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Ocurrió un error al guardar la póliza."); - logger.error("addRow(): " + e); - } - } + return; + } - public void clearPolizaForm() { - logger.info("Limpiando formulario póliza "); - setPolizaAdd(null); - setIdTaxi(null); - setIdTipoPoliza(null); - setIdAsesor(null); - setIdPeriocidad(null); - setUMA(null); - } + getPolizaAdd().setId(UUID.randomUUID().toString()); + getPolizaAdd().setActive(true); + getPolizaAdd().setCreatedOn(correcciónDeHr(new Date(), -7)); + getPolizaAdd().setInitDate(correcciónDeDias(getInitDate(), 1)); + getPolizaAdd().setTaxi(taxiTmp); + getPolizaAdd().setCustomer(taxiTmp.getCustomer()); + getPolizaAdd().setTipoPoliza(new TipoPoliza(idTipoPoliza)); + getPolizaAdd().setAsesor(new Person(idAsesor)); + getPolizaAdd().setCreatedBy(getLoggedUser()); + getPolizaAdd().setLocation(getLoggedUser().getLocation()); + getPolizaAdd().setUMA(getUMA()); + // Validación del periodo de pago para la generación de folios + switch (getIdPeriocidad()) { + case "ANUAL": + getPolizaAdd().setFolio(obtenerFolio("PA", getPolizaAdd().getInitDate())); + break; + case "SEMESTRAL": + getPolizaAdd().setFolio(obtenerFolio("PS", getPolizaAdd().getInitDate())); + break; + case "TRIMESTRAL": + getPolizaAdd().setFolio(obtenerFolio("PT", getPolizaAdd().getInitDate())); + break; + case "MENSUAL": + getPolizaAdd().setFolio(obtenerFolio("PM", getPolizaAdd().getInitDate())); + break; + default: + break; + } - public void cargarPoliza() { - logger.info("cargarPoliza()"); - setEditPoliza(true); - try { - setPolizaAdd(getSelectedPoliza()); - setInitDate(getSelectedPoliza().getInitDate()); - setIdTaxi(getSelectedPoliza().getTaxi().getId()); - setIdTipoPoliza(getSelectedPoliza().getTipoPoliza().getId()); - setIdAsesor(getSelectedPoliza().getAsesor().getId()); - setIdPeriocidad("NO"); - setUMA(getSelectedPoliza().getUMA()); - } catch (Exception e) { - logger.error("cargarPoliza(): " + e); - } - } + if (isLiquidado()) { + getPolizaAdd().setEstatus(PolizaEstatus.LIQUIDADO); + getPolizaAdd().setCantidadPagada(getPolizaAdd().getAmount()); + } else { + getPolizaAdd().setEstatus(PolizaEstatus.PENDIENTE); + } - public void editarPoliza() { - logger.info("editarPoliza()"); - try { - Taxi taxiTmp = null; - if (getIdTaxi() != null && !getIdTaxi().isEmpty()) { - taxiTmp = getTaxiController().getTaxiByIdReport2(getIdTaxi()); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(getPolizaAdd().getInitDate()); + calendar.add(Calendar.YEAR, 1); + getPolizaAdd().setEndDate(calendar.getTime()); + + controller.save(getPolizaAdd()); + + if (!isLiquidado()) { + Calendar fechaInicial = Calendar.getInstance(); + fechaInicial.setTime(getPolizaAdd().getInitDate()); + + int numeroPagos = 0; + + switch (getIdPeriocidad()) { + case "ANUAL": + numeroPagos = 1; + break; + case "SEMESTRAL": + numeroPagos = 2; + break; + case "TRIMESTRAL": + numeroPagos = 4; + break; + case "MENSUAL": + numeroPagos = 12; + break; + default: + break; + } + + List fechasPago = generarFechasDePago(fechaInicial, numeroPagos, getPolizaAdd().getPeriodoGracia()); + setContador(1); + for (Calendar fecha : fechasPago) { + if (getContador() == 1) { + PagosPoliza pagoPoliza = new PagosPoliza(); + pagoPoliza.setCantidadPagada(0D); + pagoPoliza.setPoliza(getPolizaAdd()); + pagoPoliza.setCreatedBy(getLoggedUser()); + pagoPoliza.setCreatedOn(correcciónDeHr(new Date(), -7)); + pagoPoliza.setDiferenciaPago(0D); + pagoPoliza.setPago(getPrimerPago()); + pagoPoliza.setEstatusActivo(GenericEnumType.ENABLED); + pagoPoliza.setPagoEstatus(GenericEnumType.DISABLED); + pagoPoliza.setTipoPago(TipoAbono.ABONO); + pagoPoliza.setFechaAPagar(fecha.getTime()); + getController().save(pagoPoliza); + setContador(2); + } else { + PagosPoliza pagoPoliza = new PagosPoliza(); + pagoPoliza.setCantidadPagada(0D); + pagoPoliza.setPoliza(getPolizaAdd()); + pagoPoliza.setCreatedBy(getLoggedUser()); + pagoPoliza.setCreatedOn(correcciónDeHr(new Date(), -7)); + pagoPoliza.setDiferenciaPago(0D); + pagoPoliza.setPago(((getPolizaAdd().getAmount() - getPolizaAdd().getCantidadPagada()) - getPrimerPago()) / (numeroPagos - 1)); + pagoPoliza.setEstatusActivo(GenericEnumType.ENABLED); + pagoPoliza.setPagoEstatus(GenericEnumType.DISABLED); + pagoPoliza.setTipoPago(TipoAbono.ABONO); + pagoPoliza.setFechaAPagar(fecha.getTime()); + getController().save(pagoPoliza); + } + } + } else { + PagosPoliza pagoPoliza = new PagosPoliza(); + pagoPoliza.setId(UUID.randomUUID().toString()); + pagoPoliza.setPoliza(getPolizaAdd()); + pagoPoliza.setEstatusActivo(GenericEnumType.ENABLED); + pagoPoliza.setTipoPago(TipoAbono.ABONO); + pagoPoliza.setPagoEstatus(GenericEnumType.ENABLED); + pagoPoliza.setFechaAPagar(correcciónDeHr(new Date(), -7)); + pagoPoliza.setPago(getPolizaAdd().getAmount()); + pagoPoliza.setCantidadPagada(getPolizaAdd().getAmount()); + pagoPoliza.setDiferenciaPago(0D); + pagoPoliza.setCreatedBy(getLoggedUser()); + pagoPoliza.setCreatedOn(correcciónDeHr(new Date(), -7)); + getController().save(pagoPoliza); + + DetellePagoPoliza detalle = new DetellePagoPoliza(); + detalle.setId(UUID.randomUUID().toString()); + detalle.setPagoPoliza(pagoPoliza); + detalle.setEstatusActivo(GenericEnumType.ENABLED); + detalle.setFechaPago(correcciónDeHr(new Date(), -7)); + detalle.setCantidadPagada(pagoPoliza.getCantidadPagada()); + detalle.setCobro(getLoggedUser()); + detalle.setFolio(obtenerFolioAbonos("A-PRASE")); + detalle.setMetodoPago(MetodoPago.valueOf(getMetodoPago())); + detalle.setCreatedBy(getLoggedUser()); + detalle.setCreatedOn(correcciónDeHr(new Date(), -7)); + getController().save(detalle); + } + + setPoliza(getController().findActive(getLoggedUser().getLocation())); + clearPolizaForm(); + FacesMessage msg = new FacesMessage("Nueva póliza", "Se agregó correctamente"); + FacesContext.getCurrentInstance().addMessage(null, msg); + } catch (Exception e) { + showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Ocurrió un error al guardar la póliza."); + logger.error("addRow(): " + e); + } + } + + public void clearPolizaForm() { + logger.info("Limpiando formulario póliza "); + setPolizaAdd(null); + setIdTaxi(null); + setIdTipoPoliza(null); + setIdAsesor(null); + setIdPeriocidad(null); + setUMA(null); + } + + public void cargarPoliza() { + logger.info("cargarPoliza()"); + setEditPoliza(true); + try { + setPolizaAdd(getSelectedPoliza()); + setInitDate(getSelectedPoliza().getInitDate()); + setIdTaxi(getSelectedPoliza().getTaxi().getId()); + setIdTipoPoliza(getSelectedPoliza().getTipoPoliza().getId()); + setIdAsesor(getSelectedPoliza().getAsesor().getId()); + setIdPeriocidad("NO"); + setUMA(getSelectedPoliza().getUMA()); + } catch (Exception e) { + logger.error("cargarPoliza(): " + e); + } + } + + public void editarPoliza() { + logger.info("editarPoliza()"); + try { + Taxi taxiTmp = null; + if (getIdTaxi() != null && !getIdTaxi().isEmpty()) { + taxiTmp = getTaxiController().getTaxiByIdReport2(getIdTaxi()); + } else { + FacesMessage msg = new FacesMessage("Vehículo vacio", "Se debe de seleccionar un vehículo"); + FacesContext.getCurrentInstance().addMessage(null, msg); + return; + } + getPolizaAdd().setTaxi(taxiTmp); + getPolizaAdd().setInitDate(correcciónDeDias(getInitDate(), 1)); + getPolizaAdd().setCustomer(taxiTmp.getCustomer()); + getPolizaAdd().setTipoPoliza(new TipoPoliza(getIdTipoPoliza())); + getPolizaAdd().setAsesor(new Person(getIdAsesor())); + getPolizaAdd().setUMA(getUMA()); + getPolizaAdd().setLastUpdatedOn(correcciónDeHr(new Date(), -7)); + getPolizaAdd().setLastUpdatedBy(getLoggedUser()); + getController().update(getPolizaAdd()); + setPoliza(getController().findActive(getLoggedUser().getLocation())); + clearPolizaForm(); + showMessage(FacesMessage.SEVERITY_INFO, "Actualización realizada", "Póliza actualizada correctamente."); + logger.info("Póliza actualizada correctamente"); + } catch (Exception e) { + showMessage(FacesMessage.SEVERITY_INFO, "Error", "Ocurrió un error al tratar de actualizar la póliza."); + logger.error("editarPoliza(): " + e); + } + } + + public List generarFechasDePago(Calendar fechaInicial, int numeroPagos, int periodoGracia) { + logger.info("Generación fechas"); + //lista de fechas + List fechasDePago = new ArrayList<>(); + + fechasDePago.add(fechaInicial); + + Calendar fechaActual = (Calendar) fechaInicial.clone(); + //captura el dia de una fecha en caso de que no se encuntre en le mes siguinte + boolean detenerFecha = false; + Calendar fechaDetenida = Calendar.getInstance(); + + for (int i = 1; i < numeroPagos; i++) { + Calendar fechaSiguiente = (Calendar) fechaActual.clone(); + + switch (numeroPagos) { + case 2: { + fechaSiguiente.add(Calendar.MONTH, 6); + break; + } + case 4: { + fechaSiguiente.add(Calendar.MONTH, 3); + break; + } + case 12: { + fechaSiguiente.add(Calendar.MONTH, 1); + break; + } + + } + + if (detenerFecha == false) { + if (fechaActual.get(Calendar.DAY_OF_MONTH) > fechaSiguiente.getActualMaximum(Calendar.DAY_OF_MONTH)) { + detenerFecha = true; + fechaDetenida = (Calendar) fechaActual.clone(); + fechaSiguiente.set(Calendar.DAY_OF_MONTH, fechaSiguiente.getActualMaximum(Calendar.DAY_OF_MONTH)); + } + } else { + if (fechaSiguiente.get(Calendar.DAY_OF_MONTH) <= fechaDetenida.get(Calendar.DAY_OF_MONTH)) { + detenerFecha = false; + fechaSiguiente.set(Calendar.DAY_OF_MONTH, fechaDetenida.get(Calendar.DAY_OF_MONTH)); } else { - FacesMessage msg = new FacesMessage("Vehículo vacio", "Se debe de seleccionar un vehículo"); - FacesContext.getCurrentInstance().addMessage(null, msg); - return; + fechaSiguiente.set(Calendar.DAY_OF_MONTH, fechaSiguiente.getActualMaximum(Calendar.DAY_OF_MONTH)); } - getPolizaAdd().setTaxi(taxiTmp); - getPolizaAdd().setInitDate(correcciónDeDias(getInitDate(), 1)); - getPolizaAdd().setCustomer(taxiTmp.getCustomer()); - getPolizaAdd().setTipoPoliza(new TipoPoliza(getIdTipoPoliza())); - getPolizaAdd().setAsesor(new Person(getIdAsesor())); - getPolizaAdd().setUMA(getUMA()); - getPolizaAdd().setLastUpdatedOn(correcciónDeHr(new Date(), -7)); - getPolizaAdd().setLastUpdatedBy(getLoggedUser()); - getController().update(getPolizaAdd()); - setPoliza(getController().findActive(getLoggedUser().getLocation())); - clearPolizaForm(); - showMessage(FacesMessage.SEVERITY_INFO, "Actualización realizada", "Póliza actualizada correctamente."); - logger.info("Póliza actualizada correctamente"); - } catch (Exception e) { - showMessage(FacesMessage.SEVERITY_INFO, "Error", "Ocurrió un error al tratar de actualizar la póliza."); - logger.error("editarPoliza(): " + e); - } - } + } + fechasDePago.add(fechaSiguiente); + fechaActual = fechaSiguiente; + } - public List generarFechasDePago(Calendar fechaInicial, int numeroPagos, int periodoGracia) { - logger.info("Generación fechas"); - //lista de fechas - List fechasDePago = new ArrayList<>(); + // Se valida si hubo un periodo de gracia para agregárselo a la primera fecha de pago + if (periodoGracia > 0) { + fechasDePago.get(0).add(Calendar.DATE, periodoGracia); + } - fechasDePago.add(fechaInicial); + return fechasDePago; + } - Calendar fechaActual = (Calendar) fechaInicial.clone(); - //captura el dia de una fecha en caso de que no se encuntre en le mes siguinte - boolean detenerFecha = false; - Calendar fechaDetenida = Calendar.getInstance(); + public void liquidadoChange() { + if (isLiquidado()) { + getPolizaAdd().setPeriodoGracia(0); + } + } - for (int i = 1; i < numeroPagos; i++) { - Calendar fechaSiguiente = (Calendar) fechaActual.clone(); + @Override + public void deleteRow() { + logger.info("deleteRow"); + try { - switch (numeroPagos) { - case 2: { - fechaSiguiente.add(Calendar.MONTH, 6); - break; - } - case 4: { - fechaSiguiente.add(Calendar.MONTH, 3); - break; - } - case 12: { - fechaSiguiente.add(Calendar.MONTH, 1); - break; - } + controller.delete(selectedPoliza.getId(), getLoggedUser(), getComentario()); + getPolizaList(); + selectedPoliza = null; + showMessage(FacesMessage.SEVERITY_INFO, "Póliza deshabilitado", "Se deshabilito correctamente."); + } catch (Exception e) { + logger.error("deleteRow: " + e); + showMessage(FacesMessage.SEVERITY_FATAL, + "Póliza", + "Ocurrió un error"); + } + } + + private String obtenerFolio(String ab, Date fecha) { + logger.info("Obteniendo último folio "); + try { + // Se cargan los abonos para validar el folio + String abreviacion = ab; + Poliza ultimoFolio = getController().fillFoliosByPolizas2(abreviacion); + // Se valida si ya existen folios registrados para el proyecto y se le asigna el último encontrado + int consecutivo = 0; + if (ultimoFolio != null) { + String folior = ultimoFolio.getFolio(); + // Dividir el folio en partes utilizando el guion como separador + String[] partes = folior.split("-"); + // Obtener la parte del consecutivo + String consecutivoParte = partes[4]; + // Convertir el consecutivo a un entero + consecutivo = Integer.parseInt(consecutivoParte); + } + // se formatea el consecutivo + String numeroFormateado = String.format("%05d", consecutivo + 1); + String folio; + // se formatea la fecha + SimpleDateFormat formatoF = new SimpleDateFormat("dd-MM-yy"); + String fechaFormateada = formatoF.format(fecha); + // Se valida si se creara el primer folio + if (consecutivo == 0) { + folio = abreviacion + "-" + fechaFormateada + "-" + "00001"; + } else { + folio = abreviacion + "-" + fechaFormateada + "-" + numeroFormateado; + } + return folio; + } catch (NumberFormatException e) { + logger.error("Ocurrió un erro al obtener el último folio "); + showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Ocurrió un error al generar el folio"); + return null; + } + } + + private String obtenerFolioAbonos(String ab) { + logger.info("Obteniendo último folio "); + try { + // Se cargan los abonos para validar el folio + String abreviacion = ab; + DetellePagoPoliza ultimoFolio = getPagosPolizaController().fillFoliosByPagos(abreviacion); + // Se valida si ya existen folios registrados para el proyecto y se le asigna el último encontrado + int consecutivo = 0; + if (ultimoFolio != null) { + String folior = ultimoFolio.getFolio(); + // Dividir el folio en partes utilizando el guion como separador + String[] partes = folior.split("-"); + // Obtener la parte del consecutivo + String consecutivoParte = partes[2]; + // Convertir el consecutivo a un entero + consecutivo = Integer.parseInt(consecutivoParte); + } + // se formatea el consecutivo + String numeroFormateado = String.format("%06d", consecutivo + 1); + String folio; + // Se obtiene el año actual + Calendar calendario = Calendar.getInstance(); + int ano = calendario.get(Calendar.YEAR); + String anoActual = String.valueOf(ano); + // Se valida si se creara el primer folio + if (consecutivo == 0) { + folio = abreviacion + "-" + "000001" + "-" + anoActual; + } else { + folio = abreviacion + "-" + numeroFormateado + "-" + anoActual; + } + return folio; + } catch (NumberFormatException e) { + logger.error("Ocurrió un erro al obtener el último folio "); + showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Ocurrió un error al generar el folio"); + return null; + } + } + + private Date correcciónDeHr(Date fecha, int horas) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(fecha); + calendar.add(Calendar.HOUR_OF_DAY, horas); + Date nuevaFecha = calendar.getTime(); + return nuevaFecha; + } + + @Override + public void editRow(RowEditEvent event) { + + } + + @Override + public void onRowCancel(RowEditEvent event) { + showMessage(FacesMessage.SEVERITY_INFO, "Edición Cancelada", ((Hospitales) event.getObject()).getName()); + } + + @Override + public void onRowReorder(ReorderEvent event) { + showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1)); + } + + @PostConstruct + public void init() { + logger.info("init"); + try { + loadBundlePropertyFile(); + setPrimerPago(0.0); + + setController(new PolizaController()); + setTaxiController(new TaxiController()); + setTipoPolizaController(new TipoPolizaController()); + setEmployeeController(new EmployeeController()); + setCustomerController(new CustomerController()); + setGenericController(new GenericValidationController()); + setPagosPolizaController(new PagosPolizaController()); + setDriverController(new DriverController()); + setGenericPersonController(new GenericPersonController() { + }); + + setEditPoliza(false); + setTipoPoliza(getTipoPolizaController().findTipoPoliza()); + setTaxi(getTaxiController().findAllTaxisByLocation(getLoggedUser().getLocation())); + setAsesor(getEmployeeController().getAllPersonsByPersonTye(PersonType.EMPLOYEE)); + setListCustomer(getGenericPersonController().getAllPersonsByPersonTye(PersonType.CUSTOMER)); + getPolizaList(); //obtiene las polizas activas y desactivadas + + setPolizaAdd(new Poliza()); + getPolizaAdd().setPeriodoGracia(7); + setInitDate(new Date()); + + setListVehicle(getTaxiController().findAllVehicles()); + setListColor(getTaxiController().fillColorsComboBox()); + setListDriver(getTaxiController().getAllPersonsByPersonTye(PersonType.DRIVER)); + + //Se cargan los números telefónicos de los clientes en las pólizas + for (Poliza pol : getPoliza()) { + try { + List tels = getCustomerController().fillPreferencedContactNumberByPerson(pol.getCustomer().getId()); + for (ContactNumber tel : tels) { + if (tel.getPreferenced() != null && tel.getPreferenced().equals(true)) { + pol.setTelefonoCliente(tel.getPhone()); + } + } + } catch (Exception e) { + logger.error(pol.getId() + " :" + e); } + } - if (detenerFecha == false) { - if (fechaActual.get(Calendar.DAY_OF_MONTH) > fechaSiguiente.getActualMaximum(Calendar.DAY_OF_MONTH)) { - detenerFecha = true; - fechaDetenida = (Calendar) fechaActual.clone(); - fechaSiguiente.set(Calendar.DAY_OF_MONTH, fechaSiguiente.getActualMaximum(Calendar.DAY_OF_MONTH)); - } + } catch (Exception e) { + logger.error(e); + } + } + + public void agregarCliente() { + logger.info("Agregando nuevo cliente"); + try { + Person per = addCustomer(); + if (per.getId() != null) { + showMessage(FacesMessage.SEVERITY_INFO, "Cliente agregado", "El cliente se agregó correctamente"); + if (getSerialNumber() != null && !getSerialNumber().isEmpty()) { + if (addVehicle(per)) { + showMessage(FacesMessage.SEVERITY_INFO, "Vehículo agregado", "Vehículo agregado correctamente"); + } else { + showMessage(FacesMessage.SEVERITY_ERROR, "Error al agregar el vehículo", "Ocurrió un error al agregar el vehículo"); + } } else { - if (fechaSiguiente.get(Calendar.DAY_OF_MONTH) <= fechaDetenida.get(Calendar.DAY_OF_MONTH)) { - detenerFecha = false; - fechaSiguiente.set(Calendar.DAY_OF_MONTH, fechaDetenida.get(Calendar.DAY_OF_MONTH)); - } else { - fechaSiguiente.set(Calendar.DAY_OF_MONTH, fechaSiguiente.getActualMaximum(Calendar.DAY_OF_MONTH)); - } + logger.info("No se agregó ningún vehículo"); } - fechasDePago.add(fechaSiguiente); - fechaActual = fechaSiguiente; - } + } else { + showMessage(FacesMessage.SEVERITY_ERROR, "Error al agregar el cliente", "Ocurrió un error al agregar el cliente"); + } + clearFormClient(); + setTaxi(getTaxiController().findAllTaxisByLocation(getLoggedUser().getLocation())); + } catch (Exception e) { + showMessage(FacesMessage.SEVERITY_FATAL, "ERROR", "Ocurrió un error al agregar el cliente"); + logger.error("agregarCliente " + e); + } + } - // Se valida si hubo un periodo de gracia para agregárselo a la primera fecha de pago - if (periodoGracia > 0) { - fechasDePago.get(0).add(Calendar.DATE, periodoGracia); - } + private boolean addVehicle(Person customer) { + logger.info("addVehicle"); + try { + Taxi tax = new Taxi(); + tax.setLocation(getLoggedUser().getLocation()); + tax.setActive(true); + tax.setPlaca(getPlaca()); + tax.setEconomicNumber(""); + tax.setSerialNumber(getSerialNumber()); + tax.setMotorNmumber(getMotorNumber()); + tax.setYear(getYear()); + tax.setCustomer(customer); + Person con = null; + tax.setDriver(con); + tax.setVehicle(new Vehicle(getSelectVehicle())); + tax.setGps(BasicType.DISABLED); + tax.setApc(BasicType.DISABLED); + tax.setComments(""); + boolean success = getCustomerController().addVehiculo(tax, getLoggedUser()); + if (success) { + logger.info("Taxi agregado correctamente"); + return success; + } else { + logger.error("Ocurrió un error al agregar el taxi"); + return success; + } + } catch (Exception e) { + logger.error("addVehicle(): " + e); + return false; + } + } - return fechasDePago; - } + private Person addCustomer() { + logger.info("addCustomer"); + try { + Person person = new Person(); + person.setId(UUID.randomUUID().toString()); - public void liquidadoChange() { - if (isLiquidado()) { - getPolizaAdd().setPeriodoGracia(0); - } - } + person.setFirstName(getPrimerNombre()); + person.setSecondName(getSegundoNombre()); + person.setLastName(getPrimerApellido()); + person.setMiddleName(getSegundoApellido()); - @Override - public void deleteRow() { - logger.info("deleteRow"); - try { + person.setActive(true); + person.setRoot(false); + person.setCreatedOn(new Date()); + person.setPersonType(PersonType.CUSTOMER); + person.setLocation(getLoggedUser().getLocation()); + person.setAjustador(Boolean.FALSE); + boolean success = getCustomerController().addPerson(person, getLoggedUser().getUserName(), true); - controller.delete(selectedPoliza.getId(), getLoggedUser(), getComentario()); - getPolizaList(); - selectedPoliza = null; - showMessage(FacesMessage.SEVERITY_INFO, "Póliza deshabilitado", "Se deshabilito correctamente."); - } catch (Exception e) { - logger.error("deleteRow: " + e); + if (success) { - showMessage(FacesMessage.SEVERITY_FATAL, - "Póliza", - "Ocurrió un error"); - } - } - - private String obtenerFolio(String ab, Date fecha) { - logger.info("Obteniendo último folio "); - try { - // Se cargan los abonos para validar el folio - String abreviacion = ab; - Poliza ultimoFolio = getController().fillFoliosByPolizas2(abreviacion); - // Se valida si ya existen folios registrados para el proyecto y se le asigna el último encontrado - int consecutivo = 0; - if (ultimoFolio != null) { - String folior = ultimoFolio.getFolio(); - // Dividir el folio en partes utilizando el guion como separador - String[] partes = folior.split("-"); - // Obtener la parte del consecutivo - String consecutivoParte = partes[4]; - // Convertir el consecutivo a un entero - consecutivo = Integer.parseInt(consecutivoParte); - } - // se formatea el consecutivo - String numeroFormateado = String.format("%05d", consecutivo + 1); - String folio; - // se formatea la fecha - SimpleDateFormat formatoF = new SimpleDateFormat("dd-MM-yy"); - String fechaFormateada = formatoF.format(fecha); - // Se valida si se creara el primer folio - if (consecutivo == 0) { - folio = abreviacion + "-" + fechaFormateada + "-" + "00001"; - } else { - folio = abreviacion + "-" + fechaFormateada + "-" + numeroFormateado; - } - return folio; - } catch (NumberFormatException e) { - logger.error("Ocurrió un erro al obtener el último folio "); - showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Ocurrió un error al generar el folio"); - return null; - } - } - - private String obtenerFolioAbonos(String ab) { - logger.info("Obteniendo último folio "); - try { - // Se cargan los abonos para validar el folio - String abreviacion = ab; - PagosPoliza ultimoFolio = getPagosPolizaController().fillFoliosByPagos(abreviacion); - // Se valida si ya existen folios registrados para el proyecto y se le asigna el último encontrado - int consecutivo = 0; - if (ultimoFolio != null) { - String folior = ultimoFolio.getFolio(); - // Dividir el folio en partes utilizando el guion como separador - String[] partes = folior.split("-"); - // Obtener la parte del consecutivo - String consecutivoParte = partes[2]; - // Convertir el consecutivo a un entero - consecutivo = Integer.parseInt(consecutivoParte); - } - // se formatea el consecutivo - String numeroFormateado = String.format("%06d", consecutivo + 1); - String folio; - // Se obtiene el año actual - Calendar calendario = Calendar.getInstance(); - int ano = calendario.get(Calendar.YEAR); - String anoActual = String.valueOf(ano); - // Se valida si se creara el primer folio - if (consecutivo == 0) { - folio = abreviacion + "-" + "000001" + "-" + anoActual; - } else { - folio = abreviacion + "-" + numeroFormateado + "-" + anoActual; - } - return folio; - } catch (NumberFormatException e) { - logger.error("Ocurrió un erro al obtener el último folio "); - showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Ocurrió un error al generar el folio"); - return null; - } - } - - private Date correcciónDeHr(Date fecha, int horas) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(fecha); - calendar.add(Calendar.HOUR_OF_DAY, horas); - Date nuevaFecha = calendar.getTime(); - return nuevaFecha; - } - - @Override - public void editRow(RowEditEvent event) { - - } - - @Override - public void onRowCancel(RowEditEvent event) { - showMessage(FacesMessage.SEVERITY_INFO, "Edición Cancelada", ((Hospitales) event.getObject()).getName()); - } - - @Override - public void onRowReorder(ReorderEvent event) { - showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1)); - } - - @PostConstruct - public void init() { - logger.info("init"); - try { - loadBundlePropertyFile(); - setPrimerPago(0.0); - - setController(new PolizaController()); - setTaxiController(new TaxiController()); - setTipoPolizaController(new TipoPolizaController()); - setEmployeeController(new EmployeeController()); - setCustomerController(new CustomerController()); - setGenericController(new GenericValidationController()); - setPagosPolizaController(new PagosPolizaController()); - setDriverController(new DriverController()); - setGenericPersonController(new GenericPersonController() { - }); - - setEditPoliza(false); - setTipoPoliza(getTipoPolizaController().findTipoPoliza()); - setTaxi(getTaxiController().findAllTaxisByLocation(getLoggedUser().getLocation())); - setAsesor(getEmployeeController().getAllPersonsByPersonTye(PersonType.EMPLOYEE)); - setListCustomer(getGenericPersonController().getAllPersonsByPersonTye(PersonType.CUSTOMER)); - getPolizaList(); //obtiene las polizas activas y desactivadas - - setPolizaAdd(new Poliza()); - getPolizaAdd().setPeriodoGracia(7); - setInitDate(new Date()); - - setListVehicle(getTaxiController().findAllVehicles()); - setListColor(getTaxiController().fillColorsComboBox()); - setListDriver(getTaxiController().getAllPersonsByPersonTye(PersonType.DRIVER)); - - //Se cargan los números telefónicos de los clientes en las pólizas - for (Poliza pol : getPoliza()) { - try { - List tels = getCustomerController().fillPreferencedContactNumberByPerson(pol.getCustomer().getId()); - for (ContactNumber tel : tels) { - if (tel.getPreferenced() != null && tel.getPreferenced().equals(true)) { - pol.setTelefonoCliente(tel.getPhone()); - } - } - } catch (Exception e) { - logger.error(pol.getId() + " :" + e); - } + if (getTelefono() != null && !getTelefono().isEmpty()) { + logger.info("Agregando número telefónico "); + ContactNumber num = new ContactNumber(); + num.setPhone(getTelefono()); + num.setPhoneType(PhoneType.MOBILE); + num.setPreferenced(true); + num.setPerson(person); + getDriverController().addContactNumber(num, getLoggedUser(), true); } - } catch (Exception e) { - logger.error(e); - } - } - - public void agregarCliente() { - logger.info("Agregando nuevo cliente"); - try { - Person per = addCustomer(); - if (per.getId() != null) { - showMessage(FacesMessage.SEVERITY_INFO, "Cliente agregado", "El cliente se agregó correctamente"); - if (getSerialNumber() != null && !getSerialNumber().isEmpty()) { - if (addVehicle(per)) { - showMessage(FacesMessage.SEVERITY_INFO, "Vehículo agregado", "Vehículo agregado correctamente"); - } else { - showMessage(FacesMessage.SEVERITY_ERROR, "Error al agregar el vehículo", "Ocurrió un error al agregar el vehículo"); - } - } else { - logger.info("No se agregó ningún vehículo"); - } - } else { - showMessage(FacesMessage.SEVERITY_ERROR, "Error al agregar el cliente", "Ocurrió un error al agregar el cliente"); + if (getStreet() != null && !getStreet().isEmpty()) { + Address direccion = new Address(); + direccion.setStreet(getStreet()); + direccion.setExtendedAddress(getExtendedAddress()); + direccion.setLocality(getLocality()); + direccion.setRegion(getRegion()); + direccion.setZipCode(getZipCode()); + direccion.setPerson(person); + direccion.setAddressType(AddressType.HOME); + getDriverController().addAddress(direccion, getLoggedUser(), true); } - clearFormClient(); - setTaxi(getTaxiController().findAllTaxisByLocation(getLoggedUser().getLocation())); - } catch (Exception e) { - showMessage(FacesMessage.SEVERITY_FATAL, "ERROR", "Ocurrió un error al agregar el cliente"); - logger.error("agregarCliente " + e); - } - } - private boolean addVehicle(Person customer) { - logger.info("addVehicle"); - try { - Taxi tax = new Taxi(); - tax.setLocation(getLoggedUser().getLocation()); - tax.setActive(true); - tax.setPlaca(getPlaca()); - tax.setEconomicNumber(""); - tax.setSerialNumber(getSerialNumber()); - tax.setMotorNmumber(getMotorNumber()); - tax.setYear(getYear()); - tax.setCustomer(customer); - Person con = null; - tax.setDriver(con); - tax.setVehicle(new Vehicle(getSelectVehicle())); - tax.setGps(BasicType.DISABLED); - tax.setApc(BasicType.DISABLED); - tax.setComments(""); - boolean success = getCustomerController().addVehiculo(tax, getLoggedUser()); - if (success) { - logger.info("Taxi agregado correctamente"); - return success; - } else { - logger.error("Ocurrió un error al agregar el taxi"); - return success; - } - } catch (Exception e) { - logger.error("addVehicle(): " + e); - return false; - } - } - - private Person addCustomer() { - logger.info("addCustomer"); - try { - Person person = new Person(); - person.setId(UUID.randomUUID().toString()); - - person.setFirstName(getPrimerNombre()); - person.setSecondName(getSegundoNombre()); - person.setLastName(getPrimerApellido()); - person.setMiddleName(getSegundoApellido()); - - person.setActive(true); - person.setRoot(false); - person.setCreatedOn(new Date()); - person.setPersonType(PersonType.CUSTOMER); - person.setLocation(getLoggedUser().getLocation()); - person.setAjustador(Boolean.FALSE); - boolean success = getCustomerController().addPerson(person, getLoggedUser().getUserName(), true); - - if (success) { - - if (getTelefono() != null && !getTelefono().isEmpty()) { - logger.info("Agregando número telefónico "); - ContactNumber num = new ContactNumber(); - num.setPhone(getTelefono()); - num.setPhoneType(PhoneType.MOBILE); - num.setPreferenced(true); - num.setPerson(person); - getDriverController().addContactNumber(num, getLoggedUser(), true); - } - - if (getStreet() != null && !getStreet().isEmpty()) { - Address direccion = new Address(); - direccion.setStreet(getStreet()); - direccion.setExtendedAddress(getExtendedAddress()); - direccion.setLocality(getLocality()); - direccion.setRegion(getRegion()); - direccion.setZipCode(getZipCode()); - direccion.setPerson(person); - direccion.setAddressType(AddressType.HOME); - getDriverController().addAddress(direccion, getLoggedUser(), true); - } - - logger.info("Cliente agregado correctamente"); - return person; - } else { - logger.error("Ocurrió un error al agregar el cliente"); - return new Person(); - } - } catch (Exception e) { - logger.error("addCustomer: " + e); + logger.info("Cliente agregado correctamente"); + return person; + } else { + logger.error("Ocurrió un error al agregar el cliente"); return new Person(); - } - } + } + } catch (Exception e) { + logger.error("addCustomer: " + e); + return new Person(); + } + } - public void prueva() { - logger.info("Hola"); - } + public void prueva() { + logger.info("Hola"); + } - public void clearFormClient() { - setPrimerNombre(null); - setSegundoNombre(null); - setPrimerApellido(null); - setSegundoApellido(null); - setRfc(null); - setSelectColor(null); - setSelectDriver(null); - setSelectVehicle(null); - setPlaca(null); - setEconomicNumber(null); - setSerialNumber(null); - setMotorNumber(null); - setYear(null); - } + public void clearFormClient() { + setPrimerNombre(null); + setSegundoNombre(null); + setPrimerApellido(null); + setSegundoApellido(null); + setRfc(null); + setSelectColor(null); + setSelectDriver(null); + setSelectVehicle(null); + setPlaca(null); + setEconomicNumber(null); + setSerialNumber(null); + setMotorNumber(null); + setYear(null); + } - public void resetagregarVehiculoForm() { - setIdCustomer(null); - setSerialNumber(null); - setPlaca(null); - setYear(null); - setMotorNumber(null); - setSelectVehicle(null); - } + public void resetagregarVehiculoForm() { + setIdCustomer(null); + setSerialNumber(null); + setPlaca(null); + setYear(null); + setMotorNumber(null); + setSelectVehicle(null); + } - public void agregarVehiculo() { - logger.info("agregarVehiculo()"); - try { - if (addVehicle(new Person(getIdCustomer()))) { - setTaxi(getTaxiController().findAllTaxisByLocation(getLoggedUser().getLocation())); - showMessage(FacesMessage.SEVERITY_INFO, "Vehículo agregado", "Vehículo agregado correctamente"); - } else { - showMessage(FacesMessage.SEVERITY_ERROR, "Error al agregar el vehículo", "Ocurrió un error al agregar el vehículo"); - } - } catch (Exception e) { - showMessage(FacesMessage.SEVERITY_FATAL, "Error al agregar el vehículo", "Ocurrió un error al agregar el vehículo"); - logger.error("agregarVehiculo(): " + e); - } - } + public void agregarVehiculo() { + logger.info("agregarVehiculo()"); + try { + if (addVehicle(new Person(getIdCustomer()))) { + setTaxi(getTaxiController().findAllTaxisByLocation(getLoggedUser().getLocation())); + showMessage(FacesMessage.SEVERITY_INFO, "Vehículo agregado", "Vehículo agregado correctamente"); + } else { + showMessage(FacesMessage.SEVERITY_ERROR, "Error al agregar el vehículo", "Ocurrió un error al agregar el vehículo"); + } + } catch (Exception e) { + showMessage(FacesMessage.SEVERITY_FATAL, "Error al agregar el vehículo", "Ocurrió un error al agregar el vehículo"); + logger.error("agregarVehiculo(): " + e); + } + } - private Date correcciónDeDias(Date fecha, int dias) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(fecha); - calendar.add(Calendar.DAY_OF_YEAR, dias); - return calendar.getTime(); - } + private Date correcciónDeDias(Date fecha, int dias) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(fecha); + calendar.add(Calendar.DAY_OF_YEAR, dias); + return calendar.getTime(); + } - /* + /* public void soapInit() { try { // URL del servicio SOAP @@ -726,497 +722,497 @@ public class PolizaBean extends TaxiGenericBean implements Serializable, Datatab logger.error("Error al realizar la petición SOAP: " + e.getMessage()); } } - */ - private PolizaController controller; - private TaxiController taxiController; - private TipoPolizaController tipoPolizaController; - private GenericValidationController genericController; - private EmployeeController employeeController; - private CustomerController customerController; - private PagosPolizaController pagosPolizaController; - private DriverController driverController; - private GenericPersonController genericPersonController; - - private List poliza; - private List taxi; - private List tipoPoliza; - private List asesor; - private List listCustomer; - private String idTaxi; - private String idTipoPoliza; - private String idAsesor; - private String idPeriocidad; - private String UMA; - private Boolean editPoliza; - private Date initDate; - private String metodoPago; - private Double primerPago; - - private Poliza selectedPoliza; - private Poliza polizaAdd; - - //CUSTOMER - private String primerNombre; - private String segundoNombre; - private String primerApellido; - private String segundoApellido; - private String rfc; - private String telefono; - - private String street; - private String extendedAddress; - private String locality; - private String region; - private String zipCode; - - //TAXI - private List listColor; - private String selectColor; - private List listVehicle; - private String selectVehicle; - private List listDriver; - private String selectDriver; - private String placa; - private String economicNumber; - private String serialNumber; - private String motorNumber; - private String year; - private boolean liquidado; - private int contador; - - private String idCustomer; - - private String comentario; - - public int getContador() { - return contador; - } - - public void setContador(int contador) { - this.contador = contador; - } - - public String getComentario() { - return comentario; - } - - public void setComentario(String comentario) { - this.comentario = comentario; - } - - public String getIdPeriocidad() { - return idPeriocidad; - } - - public Double getPrimerPago() { - return primerPago; - } - - public void setPrimerPago(Double primerPago) { - this.primerPago = primerPago; - } - - public void setIdPeriocidad(String idPeriocidad) { - this.idPeriocidad = idPeriocidad; - } - - public EmployeeController getEmployeeController() { - return employeeController; - } - - public void setEmployeeController(EmployeeController employeeController) { - this.employeeController = employeeController; - } - - public List getAsesor() { - return asesor; - } - - public void setAsesor(List asesor) { - this.asesor = asesor; - } - - public String getIdAsesor() { - return idAsesor; - } - - public void setIdAsesor(String idAsesor) { - this.idAsesor = idAsesor; - } - - public String getIdTaxi() { - return idTaxi; - } - - public void setIdTaxi(String idTaxi) { - this.idTaxi = idTaxi; - } - - public String getIdTipoPoliza() { - return idTipoPoliza; - } - - public void setIdTipoPoliza(String idTipoPoliza) { - this.idTipoPoliza = idTipoPoliza; - } - - public TipoPolizaController getTipoPolizaController() { - return tipoPolizaController; - } - - public void setTipoPolizaController(TipoPolizaController tipoPolizaController) { - this.tipoPolizaController = tipoPolizaController; - } - - public List getTipoPoliza() { - return tipoPoliza; - } - - public void setTipoPoliza(List tipoPoliza) { - this.tipoPoliza = tipoPoliza; - } + */ + private PolizaController controller; + private TaxiController taxiController; + private TipoPolizaController tipoPolizaController; + private GenericValidationController genericController; + private EmployeeController employeeController; + private CustomerController customerController; + private PagosPolizaController pagosPolizaController; + private DriverController driverController; + private GenericPersonController genericPersonController; + + private List poliza; + private List taxi; + private List tipoPoliza; + private List asesor; + private List listCustomer; + private String idTaxi; + private String idTipoPoliza; + private String idAsesor; + private String idPeriocidad; + private String UMA; + private Boolean editPoliza; + private Date initDate; + private String metodoPago; + private Double primerPago; + + private Poliza selectedPoliza; + private Poliza polizaAdd; + + //CUSTOMER + private String primerNombre; + private String segundoNombre; + private String primerApellido; + private String segundoApellido; + private String rfc; + private String telefono; + + private String street; + private String extendedAddress; + private String locality; + private String region; + private String zipCode; + + //TAXI + private List listColor; + private String selectColor; + private List listVehicle; + private String selectVehicle; + private List listDriver; + private String selectDriver; + private String placa; + private String economicNumber; + private String serialNumber; + private String motorNumber; + private String year; + private boolean liquidado; + private int contador; + + private String idCustomer; + + private String comentario; + + public int getContador() { + return contador; + } + + public void setContador(int contador) { + this.contador = contador; + } + + public String getComentario() { + return comentario; + } + + public void setComentario(String comentario) { + this.comentario = comentario; + } + + public String getIdPeriocidad() { + return idPeriocidad; + } + + public Double getPrimerPago() { + return primerPago; + } + + public void setPrimerPago(Double primerPago) { + this.primerPago = primerPago; + } + + public void setIdPeriocidad(String idPeriocidad) { + this.idPeriocidad = idPeriocidad; + } + + public EmployeeController getEmployeeController() { + return employeeController; + } + + public void setEmployeeController(EmployeeController employeeController) { + this.employeeController = employeeController; + } + + public List getAsesor() { + return asesor; + } + + public void setAsesor(List asesor) { + this.asesor = asesor; + } + + public String getIdAsesor() { + return idAsesor; + } + + public void setIdAsesor(String idAsesor) { + this.idAsesor = idAsesor; + } + + public String getIdTaxi() { + return idTaxi; + } + + public void setIdTaxi(String idTaxi) { + this.idTaxi = idTaxi; + } + + public String getIdTipoPoliza() { + return idTipoPoliza; + } + + public void setIdTipoPoliza(String idTipoPoliza) { + this.idTipoPoliza = idTipoPoliza; + } + + public TipoPolizaController getTipoPolizaController() { + return tipoPolizaController; + } + + public void setTipoPolizaController(TipoPolizaController tipoPolizaController) { + this.tipoPolizaController = tipoPolizaController; + } + + public List getTipoPoliza() { + return tipoPoliza; + } + + public void setTipoPoliza(List tipoPoliza) { + this.tipoPoliza = tipoPoliza; + } - public List getTaxi() { - return taxi; - } + public List getTaxi() { + return taxi; + } - public void setTaxi(List taxi) { - this.taxi = taxi; - } + public void setTaxi(List taxi) { + this.taxi = taxi; + } - public TaxiController getTaxiController() { - return taxiController; - } + public TaxiController getTaxiController() { + return taxiController; + } - public void setTaxiController(TaxiController taxiController) { - this.taxiController = taxiController; - } + public void setTaxiController(TaxiController taxiController) { + this.taxiController = taxiController; + } - public GenericValidationController getGenericController() { - return genericController; - } + public GenericValidationController getGenericController() { + return genericController; + } - public void setGenericController(GenericValidationController genericController) { - this.genericController = genericController; - } + public void setGenericController(GenericValidationController genericController) { + this.genericController = genericController; + } - public PolizaController getController() { - return controller; - } + public PolizaController getController() { + return controller; + } - public void setController(PolizaController controller) { - this.controller = controller; - } + public void setController(PolizaController controller) { + this.controller = controller; + } - public List getPoliza() { - return poliza; - } + public List getPoliza() { + return poliza; + } - public void setPoliza(List poliza) { - this.poliza = poliza; - } + public void setPoliza(List poliza) { + this.poliza = poliza; + } - public Poliza getSelectedPoliza() { - return selectedPoliza; - } + public Poliza getSelectedPoliza() { + return selectedPoliza; + } - public void setSelectedPoliza(Poliza selectedPoliza) { - this.selectedPoliza = selectedPoliza; - } + public void setSelectedPoliza(Poliza selectedPoliza) { + this.selectedPoliza = selectedPoliza; + } - public Poliza getPolizaAdd() { - return polizaAdd; - } + public Poliza getPolizaAdd() { + return polizaAdd; + } - public void setPolizaAdd(Poliza polizaAdd) { - this.polizaAdd = polizaAdd; - } + public void setPolizaAdd(Poliza polizaAdd) { + this.polizaAdd = polizaAdd; + } - public CustomerController getCustomerController() { - return customerController; - } + public CustomerController getCustomerController() { + return customerController; + } - public void setCustomerController(CustomerController customerController) { - this.customerController = customerController; - } + public void setCustomerController(CustomerController customerController) { + this.customerController = customerController; + } - public List getListColor() { - return listColor; - } + public List getListColor() { + return listColor; + } - public void setListColor(List listColor) { - this.listColor = listColor; - } + public void setListColor(List listColor) { + this.listColor = listColor; + } - public String getSelectColor() { - return selectColor; - } + public String getSelectColor() { + return selectColor; + } - public void setSelectColor(String selectColor) { - this.selectColor = selectColor; - } + public void setSelectColor(String selectColor) { + this.selectColor = selectColor; + } - public List getListVehicle() { - return listVehicle; - } + public List getListVehicle() { + return listVehicle; + } - public void setListVehicle(List listVehicle) { - this.listVehicle = listVehicle; - } + public void setListVehicle(List listVehicle) { + this.listVehicle = listVehicle; + } - public String getSelectVehicle() { - return selectVehicle; - } + public String getSelectVehicle() { + return selectVehicle; + } - public void setSelectVehicle(String selectVehicle) { - this.selectVehicle = selectVehicle; - } + public void setSelectVehicle(String selectVehicle) { + this.selectVehicle = selectVehicle; + } - public List getListDriver() { - return listDriver; - } + public List getListDriver() { + return listDriver; + } - public void setListDriver(List listDriver) { - this.listDriver = listDriver; - } + public void setListDriver(List listDriver) { + this.listDriver = listDriver; + } - public String getSelectDriver() { - return selectDriver; - } + public String getSelectDriver() { + return selectDriver; + } - public void setSelectDriver(String selectDriver) { - this.selectDriver = selectDriver; - } + public void setSelectDriver(String selectDriver) { + this.selectDriver = selectDriver; + } - public String getPrimerNombre() { - return primerNombre; - } + public String getPrimerNombre() { + return primerNombre; + } - public void setPrimerNombre(String primerNombre) { - this.primerNombre = primerNombre; - } + public void setPrimerNombre(String primerNombre) { + this.primerNombre = primerNombre; + } - public String getSegundoNombre() { - return segundoNombre; - } + public String getSegundoNombre() { + return segundoNombre; + } - public void setSegundoNombre(String segundoNombre) { - this.segundoNombre = segundoNombre; - } + public void setSegundoNombre(String segundoNombre) { + this.segundoNombre = segundoNombre; + } - public String getPrimerApellido() { - return primerApellido; - } + public String getPrimerApellido() { + return primerApellido; + } - public void setPrimerApellido(String primerApellido) { - this.primerApellido = primerApellido; - } + public void setPrimerApellido(String primerApellido) { + this.primerApellido = primerApellido; + } - public String getSegundoApellido() { - return segundoApellido; - } + public String getSegundoApellido() { + return segundoApellido; + } - public void setSegundoApellido(String segundoApellido) { - this.segundoApellido = segundoApellido; - } + public void setSegundoApellido(String segundoApellido) { + this.segundoApellido = segundoApellido; + } - public String getPlaca() { - return placa; - } + public String getPlaca() { + return placa; + } - public void setPlaca(String placa) { - this.placa = placa; - } + public void setPlaca(String placa) { + this.placa = placa; + } - public String getEconomicNumber() { - return economicNumber; - } + public String getEconomicNumber() { + return economicNumber; + } - public void setEconomicNumber(String economicNumber) { - this.economicNumber = economicNumber; - } + public void setEconomicNumber(String economicNumber) { + this.economicNumber = economicNumber; + } - public String getSerialNumber() { - return serialNumber; - } + public String getSerialNumber() { + return serialNumber; + } - public void setSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - } + public void setSerialNumber(String serialNumber) { + this.serialNumber = serialNumber; + } - public String getMotorNumber() { - return motorNumber; - } + public String getMotorNumber() { + return motorNumber; + } - public void setMotorNumber(String motorNumber) { - this.motorNumber = motorNumber; - } + public void setMotorNumber(String motorNumber) { + this.motorNumber = motorNumber; + } - public String getYear() { - return year; - } + public String getYear() { + return year; + } - public void setYear(String year) { - this.year = year; - } + public void setYear(String year) { + this.year = year; + } - public boolean isLiquidado() { - return liquidado; - } + public boolean isLiquidado() { + return liquidado; + } - public void setLiquidado(boolean liquidado) { - this.liquidado = liquidado; - } + public void setLiquidado(boolean liquidado) { + this.liquidado = liquidado; + } - public PagosPolizaController getPagosPolizaController() { - return pagosPolizaController; - } + public PagosPolizaController getPagosPolizaController() { + return pagosPolizaController; + } - public void setPagosPolizaController(PagosPolizaController pagosPolizaController) { - this.pagosPolizaController = pagosPolizaController; - } + public void setPagosPolizaController(PagosPolizaController pagosPolizaController) { + this.pagosPolizaController = pagosPolizaController; + } - public String getRfc() { - return rfc; - } + public String getRfc() { + return rfc; + } - public void setRfc(String rfc) { - this.rfc = rfc; - } + public void setRfc(String rfc) { + this.rfc = rfc; + } - public DriverController getDriverController() { - return driverController; - } + public DriverController getDriverController() { + return driverController; + } - public void setDriverController(DriverController driverController) { - this.driverController = driverController; - } + public void setDriverController(DriverController driverController) { + this.driverController = driverController; + } - public String getTelefono() { - return telefono; - } + public String getTelefono() { + return telefono; + } - public void setTelefono(String telefono) { - this.telefono = telefono; - } + public void setTelefono(String telefono) { + this.telefono = telefono; + } - public String getStreet() { - return street; - } + public String getStreet() { + return street; + } - public void setStreet(String street) { - this.street = street; - } - - public String getExtendedAddress() { - return extendedAddress; - } - - public void setExtendedAddress(String extendedAddress) { - this.extendedAddress = extendedAddress; - } - - public String getLocality() { - return locality; - } - - public void setLocality(String locality) { - this.locality = locality; - } - - public String getRegion() { - return region; - } - - public void setRegion(String region) { - this.region = region; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } - - public String getUMA() { - return UMA; - } - - public void setUMA(String UMA) { - this.UMA = UMA; - } - - public Boolean getEditPoliza() { - return editPoliza; - } - - public void setEditPoliza(Boolean editPoliza) { - this.editPoliza = editPoliza; - } - - public Date getInitDate() { - return initDate; - } - - public void setInitDate(Date initDate) { - this.initDate = initDate; - } - - public String getIdCustomer() { - return idCustomer; - } - - public void setIdCustomer(String idCustomer) { - this.idCustomer = idCustomer; - } - - public List getListCustomer() { - return listCustomer; - } - - public void setListCustomer(List listCustomer) { - this.listCustomer = listCustomer; - } - - public GenericPersonController getGenericPersonController() { - return genericPersonController; - } - - public void setGenericPersonController(GenericPersonController genericPersonController) { - this.genericPersonController = genericPersonController; - } - - public String getMetodoPago() { - return metodoPago; - } - - public void setMetodoPago(String metodoPago) { - this.metodoPago = metodoPago; - } - - public void getPolizaList() { - List PolizaActiva = getController().findActive(getLoggedUser().getLocation()); - List PolizaDeshabilitada = getController().findDisable(getLoggedUser().getLocation()); - setPoliza(new ArrayList<>()); - getPoliza().addAll(PolizaActiva); - getPoliza().addAll(PolizaDeshabilitada); - } - - public String validarColores(Boolean estatus) { - // Validadar color  - if (estatus) { - return ""; - } else { - return "grayRow"; - } - } - - public void resetSelectedComentario() { - setComentario(null); - } - - private static final long serialVersionUID = -136031528440947006L; - final Logger logger = LogManager.getLogger(PolizaBean.class); + public void setStreet(String street) { + this.street = street; + } + + public String getExtendedAddress() { + return extendedAddress; + } + + public void setExtendedAddress(String extendedAddress) { + this.extendedAddress = extendedAddress; + } + + public String getLocality() { + return locality; + } + + public void setLocality(String locality) { + this.locality = locality; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } + + public String getUMA() { + return UMA; + } + + public void setUMA(String UMA) { + this.UMA = UMA; + } + + public Boolean getEditPoliza() { + return editPoliza; + } + + public void setEditPoliza(Boolean editPoliza) { + this.editPoliza = editPoliza; + } + + public Date getInitDate() { + return initDate; + } + + public void setInitDate(Date initDate) { + this.initDate = initDate; + } + + public String getIdCustomer() { + return idCustomer; + } + + public void setIdCustomer(String idCustomer) { + this.idCustomer = idCustomer; + } + + public List getListCustomer() { + return listCustomer; + } + + public void setListCustomer(List listCustomer) { + this.listCustomer = listCustomer; + } + + public GenericPersonController getGenericPersonController() { + return genericPersonController; + } + + public void setGenericPersonController(GenericPersonController genericPersonController) { + this.genericPersonController = genericPersonController; + } + + public String getMetodoPago() { + return metodoPago; + } + + public void setMetodoPago(String metodoPago) { + this.metodoPago = metodoPago; + } + + public void getPolizaList() { + List PolizaActiva = getController().findActive(getLoggedUser().getLocation()); + List PolizaDeshabilitada = getController().findDisable(getLoggedUser().getLocation()); + setPoliza(new ArrayList<>()); + getPoliza().addAll(PolizaActiva); + getPoliza().addAll(PolizaDeshabilitada); + } + + public String validarColores(Boolean estatus) { + // Validadar color  + if (estatus) { + return ""; + } else { + return "grayRow"; + } + } + + public void resetSelectedComentario() { + setComentario(null); + } + + private static final long serialVersionUID = -136031528440947006L; + final Logger logger = LogManager.getLogger(PolizaBean.class); } diff --git a/crov-prase-web/src/main/webapp/app/prase/poliza/pagos.xhtml b/crov-prase-web/src/main/webapp/app/prase/poliza/pagos.xhtml index eb37250..16fa3d9 100644 --- a/crov-prase-web/src/main/webapp/app/prase/poliza/pagos.xhtml +++ b/crov-prase-web/src/main/webapp/app/prase/poliza/pagos.xhtml @@ -105,7 +105,7 @@ - + + + + + @@ -193,7 +204,7 @@ - - - - - - - + + + + + + + @@ -309,6 +320,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -355,7 +407,52 @@ + + + + + + + +
+

Poliza: + +

+

Fecha: + + + +

+

+

+

+

+

+

+
+


AGRADECE SU PREFERENCIA 

+

+ + + + +

+

+

+
+ +

ERROR AL GENERAR EL PAGO 

+
+ + + + + + + + +