details:   https://code.openbravo.com/erp/devel/pi/rev/e1a669f00999
changeset: 13979:e1a669f00999
user:      Gorka Ion Damián <gorkaion.damian <at> openbravo.com>
date:      Thu Oct 13 15:54:41 2011 +0200
summary:   Added method to know if a psd is payment confirmed.

details:   https://code.openbravo.com/erp/devel/pi/rev/a7122d9b429a
changeset: 13980:a7122d9b429a
user:      Gorka Ion Damián <gorkaion.damian <at> openbravo.com>
date:      Thu Oct 13 15:55:46 2011 +0200
summary:   Fixed issue 18276.Fixed issue 18277.Several fixes and inprovements 
on Payment Monitor process.

diffstat:

 
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentMonitorProcess.java
 |  402 ++++++++-
 
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java
               |   17 +
 2 files changed, 360 insertions(+), 59 deletions(-)

diffs (truncated from 518 to 300 lines):

diff -r 3e33b387946b -r a7122d9b429a 
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentMonitorProcess.java
--- 
a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentMonitorProcess.java
      Thu Oct 13 14:11:48 2011 +0200
+++ 
b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentMonitorProcess.java
      Thu Oct 13 15:55:46 2011 +0200
@@ -20,74 +20,84 @@
 package org.openbravo.advpaymentmngt.process;
 
 import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
 
-import org.hibernate.LockOptions;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.base.exception.OBException;
+import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
+import org.openbravo.database.ConnectionProvider;
+import org.openbravo.erpCommon.ad_forms.AcctServer;
 import org.openbravo.erpCommon.businessUtility.Preferences;
 import org.openbravo.erpCommon.utility.PropertyException;
 import org.openbravo.erpCommon.utility.PropertyNotFoundException;
 import org.openbravo.model.ad.domain.Preference;
-import org.openbravo.model.ad.module.Module;
 import org.openbravo.model.common.invoice.Invoice;
+import org.openbravo.model.financialmgmt.payment.DebtPayment;
+import org.openbravo.model.financialmgmt.payment.FIN_Payment;
 import org.openbravo.model.financialmgmt.payment.FIN_PaymentSchedule;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
 import org.openbravo.scheduling.ProcessBundle;
 import org.openbravo.scheduling.ProcessLogger;
 import org.openbravo.service.db.DalBaseProcess;
+import org.openbravo.service.db.DalConnectionProvider;
 import org.quartz.JobExecutionException;
 
 public class FIN_PaymentMonitorProcess extends DalBaseProcess {
-  private ProcessLogger logger;
+  private static ProcessLogger logger;
+  private static ConnectionProvider conn = null;
 
   public void doExecute(ProcessBundle bundle) throws Exception {
     logger = bundle.getLogger();
-    // Extra check for PaymentMonitor-disabling switch, to build correct 
message for users
+    conn = bundle.getConnection();
+    // Check to know if PaymentMonitor property is set in the system.
     try {
-      try {
-        Preferences.getPreferenceValue("PaymentMonitor", true, null, null, 
OBContext.getOBContext()
-            .getUser(), null, null);
-
-        if (isPreferenceOfModule("PaymentMonitor", 
"A918E3331C404B889D69AA9BFAFB23AC")) {
-          logger
-              .log("There is an extension module installed managing the 
Payment Monitor information.\n");
-          logger.log("Starting Update Paid Amount for Invoices Background 
Process.\n");
-        } else {
-          logger.log("Payment Monitor active for other module.\n");
-          logger.log("Core's background process is executed.\n");
-          return;
-        }
-
-      } catch (PropertyNotFoundException e) {
-        logger.log("Property not found \n");
-        return;
-      }
+      Preferences.getPreferenceValue("PaymentMonitor", true, null, null, 
OBContext.getOBContext()
+          .getUser(), null, null);
+    } catch (PropertyNotFoundException e) {
+      logger.log("Property not found \n");
+      return;
     } catch (PropertyException e) {
       logger.log("PropertyException, there is a conflict for PaymentMonitor 
property\n");
       return;
     }
+    // Check to know that this APR is the module implementing the 
PaymentMonitor property
+    if (isPreferenceOfModule("PaymentMonitor", 
"A918E3331C404B889D69AA9BFAFB23AC")) {
+      logger.log("Starting Update Paid Amount for Invoices Background 
Process.\n");
+    } else {
+      logger.log("Payment Monitor active for other module.\n");
+      logger.log("Core's background process is executed.\n");
+      return;
+    }
 
     try {
       int counter = 0;
       final OBCriteria<Invoice> obc = 
OBDal.getInstance().createCriteria(Invoice.class);
       obc.add(Restrictions.eq(Invoice.PROPERTY_PROCESSED, true));
-      obc.add(Restrictions.ne(Invoice.PROPERTY_OUTSTANDINGAMOUNT, 
BigDecimal.ZERO));
-      
obc.add(Restrictions.isNotEmpty(Invoice.PROPERTY_FINPAYMENTSCHEDULELIST));
+      
obc.add(Restrictions.or(Restrictions.eq(Invoice.PROPERTY_PAYMENTCOMPLETE, 
false),
+          Restrictions.ne(Invoice.PROPERTY_OUTSTANDINGAMOUNT, 
BigDecimal.ZERO)));
 
       // For Background process execution at system level
       if (OBContext.getOBContext().isInAdministratorMode()) {
         obc.setFilterOnReadableClients(false);
         obc.setFilterOnReadableOrganization(false);
       }
-      final List<Invoice> invoices = obc.list();
-      for (Invoice invoice : invoices) {
-        OBDal.getInstance().getSession().buildLockRequest(LockOptions.NONE);
+      final List<String> invoiceIds = new ArrayList<String>();
+      for (Invoice invoice : obc.list()) {
+        invoiceIds.add(invoice.getId());
+      }
+
+      for (String invoiceId : invoiceIds) {
+        Invoice invoice = OBDal.getInstance().get(Invoice.class, invoiceId);
         updateInvoice(invoice);
         counter++;
         OBDal.getInstance().getSession().flush();
@@ -112,6 +122,111 @@
    * @throws OBException
    */
   public static void updateInvoice(Invoice invoice) throws OBException {
+    OBContext.setAdminMode();
+    try {
+      HashMap<String, BigDecimal> oldFlowAmounts = new HashMap<String, 
BigDecimal>();
+      // If the invoice has old flow's related payments calculate its statuses 
and amounts
+      if (invoice.getFinancialMgmtDebtPaymentList() != null
+          && invoice.getFinancialMgmtDebtPaymentList().size() > 0) {
+        oldFlowAmounts = 
getOldflowAmounts(invoice.getFinancialMgmtDebtPaymentList(), invoice
+            .getCurrency().getId(), invoice.getAccountingDate());
+      } else {
+        oldFlowAmounts.put("paidAmt", BigDecimal.ZERO);
+        oldFlowAmounts.put("outstandingAmt", BigDecimal.ZERO);
+        oldFlowAmounts.put("overdueAmt", BigDecimal.ZERO);
+      }
+
+      HashMap<String, BigDecimal> amounts = calculateAmounts(invoice);
+      
invoice.setTotalPaid(amounts.get("paidAmt").add(oldFlowAmounts.get("paidAmt")));
+      invoice.setOutstandingAmount(amounts.get("outstandingAmt").add(
+          oldFlowAmounts.get("outstandingAmt")));
+      
invoice.setPaymentComplete(invoice.getOutstandingAmount().compareTo(BigDecimal.ZERO)
 == 0);
+      
invoice.setDueAmount(amounts.get("overdueAmt").add(oldFlowAmounts.get("overdueAmt")));
+      invoice.setDaysTillDue(getDaysTillDue(invoice));
+      invoice.setLastCalculatedOnDate(new Date());
+
+      OBDal.getInstance().save(invoice);
+      OBDal.getInstance().flush();
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+  }
+
+  private static HashMap<String, BigDecimal> 
getOldflowAmounts(List<DebtPayment> debtPayments,
+      String currencyTo, Date conversionDate) {
+    BigDecimal paidAmt = BigDecimal.ZERO;
+    BigDecimal outstandingAmt = BigDecimal.ZERO;
+    BigDecimal overdueAmt = BigDecimal.ZERO;
+    for (DebtPayment debtPayment : debtPayments) {
+      // Calculate paid amount.
+      BigDecimal paid = calculatePaidAmount(debtPayment, currencyTo, 
conversionDate, BigDecimal.ONE);
+      paidAmt = paidAmt.add(paid);
+      // Calculate outstanding amount.
+      outstandingAmt = 
outstandingAmt.add(debtPayment.getAmount().subtract(paid));
+      // Calculate overdue amount.
+      overdueAmt = overdueAmt.add(calculateOverdueAmount(debtPayment, 
currencyTo, conversionDate,
+          BigDecimal.ONE));
+    }
+    HashMap<String, BigDecimal> amounts = new HashMap<String, BigDecimal>();
+    amounts.put("paidAmt", paidAmt);
+    amounts.put("outstandingAmt", outstandingAmt);
+    amounts.put("overdueAmt", overdueAmt);
+    return amounts;
+  }
+
+  private static HashMap<String, BigDecimal> calculateAmounts(Invoice invoice) 
{
+    BigDecimal paidAmt = BigDecimal.ZERO;
+    BigDecimal outstandingAmt = BigDecimal.ZERO;
+    BigDecimal overdueAmt = BigDecimal.ZERO;
+    for (FIN_PaymentSchedule paymentSchedule : 
invoice.getFINPaymentScheduleList()) {
+      BigDecimal paid = BigDecimal.ZERO;
+      for (FIN_PaymentScheduleDetail psd : paymentSchedule
+          .getFINPaymentScheduleDetailInvoicePaymentScheduleList()) {
+        if (psd.isCanceled()) {
+          // If payment scheduled is cancelled don't consider its amount.
+          continue;
+        }
+        if (psd.getPaymentDetails() != null
+            && 
FIN_Utility.isPaymentConfirmed(psd.getPaymentDetails().getFinPayment().getStatus(),
+                psd)) {
+          paid = paid.add(psd.getAmount().add(psd.getWriteoffAmount()));
+        }
+      }
+
+      if (paymentSchedule.getPaidAmount().compareTo(paid) != 0) {
+        logger.log("ERROR Invoice " + invoice.getDocumentNo()
+            + ": wrong payment plan info, paid amount is "
+            + paymentSchedule.getPaidAmount().toPlainString() + " when it 
should be "
+            + paid.toPlainString());
+        paymentSchedule.setPaidAmount(paid);
+        OBDal.getInstance().save(paymentSchedule);
+      }
+      if (paymentSchedule.getOutstandingAmount().compareTo(
+          paymentSchedule.getAmount().subtract(paid)) != 0) {
+        logger.log("ERROR Invoice " + invoice.getDocumentNo()
+            + ": wrong payment plan info, outstanding amount is "
+            + paymentSchedule.getOutstandingAmount().toPlainString() + " when 
it should be "
+            + paymentSchedule.getAmount().subtract(paid).toPlainString());
+        
paymentSchedule.setOutstandingAmount(paymentSchedule.getAmount().subtract(paid));
+        OBDal.getInstance().save(paymentSchedule);
+      }
+
+      if (paymentSchedule.getDueDate().before(new Date())
+          && paymentSchedule.getOutstandingAmount() != BigDecimal.ZERO) {
+        overdueAmt = overdueAmt.add(paymentSchedule.getOutstandingAmount());
+      }
+      paidAmt = paidAmt.add(paymentSchedule.getPaidAmount());
+      outstandingAmt = 
outstandingAmt.add(paymentSchedule.getOutstandingAmount());
+    }
+    HashMap<String, BigDecimal> amounts = new HashMap<String, BigDecimal>();
+    amounts.put("paidAmt", paidAmt);
+    amounts.put("outstandingAmt", outstandingAmt);
+    amounts.put("overdueAmt", overdueAmt);
+    return amounts;
+  }
+
+  private static Long getDaysTillDue(Invoice invoice) {
+    // Calculate days till due
     final OBCriteria<FIN_PaymentSchedule> obc = 
OBDal.getInstance().createCriteria(
         FIN_PaymentSchedule.class);
     // For Background process execution at system level
@@ -119,27 +234,14 @@
       obc.setFilterOnReadableClients(false);
       obc.setFilterOnReadableOrganization(false);
     }
-
-    OBContext.setAdminMode();
-    try {
-      obc.add(Restrictions.eq(FIN_PaymentSchedule.PROPERTY_INVOICE, invoice));
-      obc.add(Restrictions.ne(FIN_PaymentSchedule.PROPERTY_OUTSTANDINGAMOUNT, 
BigDecimal.ZERO));
-      obc.setProjection(Projections.min(FIN_PaymentSchedule.PROPERTY_DUEDATE));
-      Object o = obc.list().get(0);
-      if (o != null) {
-        System.err.println("updating invoice ='" + invoice.getId() + "'");
-        invoice.setLastCalculatedOnDate(new Date());
-        invoice.setDaysTillDue(FIN_Utility.getDaysToDue((Date) o));
-      } else {
-        System.err.println("select c_invoice_id, documentno from c_invoice 
where c_invoice_id ='"
-            + invoice.getId() + "'");
-        invoice.setDaysTillDue(0L);
-      }
-
-      OBDal.getInstance().save(invoice);
-      OBDal.getInstance().flush();
-    } finally {
-      OBContext.restorePreviousMode();
+    obc.add(Restrictions.eq(FIN_PaymentSchedule.PROPERTY_INVOICE, invoice));
+    obc.add(Restrictions.ne(FIN_PaymentSchedule.PROPERTY_OUTSTANDINGAMOUNT, 
BigDecimal.ZERO));
+    obc.setProjection(Projections.min(FIN_PaymentSchedule.PROPERTY_DUEDATE));
+    Object o = obc.list().get(0);
+    if (o != null) {
+      return (FIN_Utility.getDaysToDue((Date) o));
+    } else {
+      return 0L;
     }
   }
 
@@ -157,28 +259,210 @@
 
     final OBCriteria<Preference> obcNotSel = 
OBDal.getInstance().createCriteria(Preference.class);
     obcNotSel.add(Restrictions.eq(Preference.PROPERTY_PROPERTY, property));
-    obcNotSel.add(Restrictions.eq(Preference.PROPERTY_MODULE,
-        OBDal.getInstance().get(Module.class, moduleId)));
-    obcNotSel.add(Restrictions.eq(Preference.PROPERTY_SELECTED, false));
     obcNotSel.setFilterOnReadableClients(false);
     obcNotSel.setFilterOnReadableOrganization(false);
 
     final OBCriteria<Preference> obcSel = 
OBDal.getInstance().createCriteria(Preference.class);
     obcSel.add(Restrictions.eq(Preference.PROPERTY_PROPERTY, property));
-    obcSel.add(Restrictions.eq(Preference.PROPERTY_MODULE,
-        OBDal.getInstance().get(Module.class, moduleId)));
     obcSel.add(Restrictions.eq(Preference.PROPERTY_SELECTED, true));
     obcSel.setFilterOnReadableClients(false);
     obcSel.setFilterOnReadableOrganization(false);
 
-    if (obcNotSel.list() != null && obcNotSel.list().size() > 0) {
-      return (obcNotSel.list().size() == 1);
+    if (obcNotSel.list() != null && obcNotSel.list().size() == 1) {
+      return obcNotSel.list().get(0).getModule().getId().equals(moduleId);
+    } else if (obcSel.list() != null && obcSel.list().size() == 1) {
+      return obcSel.list().get(0).getModule().getId().equals(moduleId);
     } else {
-      if (obcSel.list() != null && obcSel.list().size() > 0) {
-        return (obcSel.list().size() == 1);
-      } else {
-        return false;
+      return false;
+    }
+  }
+
+  public static BigDecimal calculatePaidAmount(DebtPayment payment, String 
strCurrencyTo,
+      Date conversionDate, BigDecimal multiplier) {
+    BigDecimal paidAmount = BigDecimal.ZERO;
+    String finPaymentStatus = getMigratedPaymentStatus(payment);

------------------------------------------------------------------------------
All the data continuously generated in your IT infrastructure contains a
definitive record of customers, application performance, security
threats, fraudulent activity and more. Splunk takes this data and makes
sense of it. Business sense. IT sense. Common sense.
http://p.sf.net/sfu/splunk-d2d-oct
_______________________________________________
Openbravo-commits mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openbravo-commits

Reply via email to