Fixed bug 24055 system allows unpost a document in a period closed
authorSandra Huguet <sandra.huguet@openbravo.com>
Tue, 18 Jun 2013 12:05:47 +0200
changeset 20517 89b8a18aaa8d
parent 20516 2a1c35b2bb8b
child 20518 dffc58601712
Fixed bug 24055 system allows unpost a document in a period closed
src/org/openbravo/financial/ResetAccounting.java
--- a/src/org/openbravo/financial/ResetAccounting.java	Thu Jun 06 14:51:21 2013 +0200
+++ b/src/org/openbravo/financial/ResetAccounting.java	Tue Jun 18 12:05:47 2013 +0200
@@ -23,7 +23,9 @@
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 import org.apache.log4j.Logger;
@@ -66,7 +68,7 @@
     String client = adClientId;
     List<String> tables = getTables(adTableId);
     try {
-      Set<String> orgIds = new OrganizationStructureProvider().getNaturalTree(adOrgId);
+      Set<String> orgIds = new OrganizationStructureProvider().getChildTree(adOrgId, true);
       for (String table : tables) {
         List<String> docbasetypes = getDocbasetypes(client, table, recordId);
         String myQuery = "select distinct e.recordID from FinancialMgmtAccountingFact e where e.organization.id in (:orgIds) and e.client.id = :clientId and e.table.id = :tableId";
@@ -75,64 +77,95 @@
         }
         for (String dbt : docbasetypes) {
           List<Date[]> periods = new ArrayList<Date[]>();
+          // organizationPeriod: hashmap with organizations allow period control and their open
+          // periods
+          Map<String, List<Date[]>> organizationPeriod = new HashMap<String, List<Date[]>>();
+          // organizationPeriodControl: hashmap with organizations and their organization allow
+          // period control associated
+          Map<String, String> organizationPeriodControl = new HashMap<String, String>();
           String calendarId = getCalendarId(adOrgId);
-          periods = getPeriodsDates(getOpenPeriods(client, dbt, orgIds, calendarId, table,
-              recordId, strdatefrom, strdateto));
+          Iterator<String> iterator = orgIds.iterator();
+          while (iterator.hasNext()) {
+            String organization = iterator.next();
+            String myQuery1 = "select p.id from Organization p where ad_org_getperiodcontrolallow(:organization)=p.id";
+            Query query1 = OBDal.getInstance().getSession().createQuery(myQuery1);
+            query1.setString("organization", organization);
+            query1.setMaxResults(1);
+            if (query1.uniqueResult() != null) {
+              String orgperiodcontrol = query1.uniqueResult().toString();
+              organizationPeriodControl.put(organization, orgperiodcontrol);
+              if (!organizationPeriod.keySet().contains(orgperiodcontrol)) {
+                periods = getPeriodsDates(getOpenPeriods(client, dbt, orgIds, calendarId, table,
+                    recordId, strdatefrom, strdateto, orgperiodcontrol));
+                organizationPeriod.put(orgperiodcontrol, periods);
+              }
+            }
+          }
           int docUpdated = 0;
           int docDeleted = 0;
-          for (Date[] p : periods) {
-            StringBuffer consDate = new StringBuffer();
-            consDate.append(" and e.documentCategory = :dbt");
-            consDate.append(" and e.accountingDate >= :dateFrom and e.accountingDate <= :dateTo");
-            String exceptionsSql = myQuery + consDate.toString();
-            consDate
-                .append(" and not exists (select a from FinancialMgmtAccountingFact a where a.recordID = e.recordID and a.table.id = e.table.id and (a.accountingDate < :dateFrom or a.accountingDate > :dateTo))");
-            final Query query = OBDal.getInstance().getSession()
-                .createQuery(myQuery + consDate.toString());
-            if (recordId != null && !"".equals(recordId)) {
-              query.setString("recordId", recordId);
-            }
-            query.setParameterList("orgIds", orgIds);
-            query.setString("clientId", client);
-            query.setString("dbt", dbt);
-            query.setString("tableId", table);
-            query.setDate("dateFrom", p[0]);
-            query.setDate("dateTo", p[1]);
-            if (recordId != null && !"".equals(recordId)) {
-              query.setMaxResults(1);
-            } else {
-              query.setFetchSize(FETCH_SIZE);
-            }
-            start = System.currentTimeMillis();
-            List<String> transactions = query.list();
-            end = System.currentTimeMillis();
-            totalselect = totalselect + end - start;
-            while (transactions.size() > 0) {
-              HashMap<String, Integer> partial = delete(transactions, table, client);
+          for (String organization : orgIds) {
+            String orgAllow = organizationPeriodControl.get(organization);
+            periods = organizationPeriod.get(orgAllow);
+            for (Date[] p : periods) {
+              StringBuffer consDate = new StringBuffer();
+              consDate.append(" and e.documentCategory = :dbt");
+              consDate.append(" and e.organization.id = :organization");
+              consDate.append(" and e.accountingDate >= :dateFrom and e.accountingDate <= :dateTo");
+              String exceptionsSql = myQuery + consDate.toString();
+              consDate
+                  .append(" and not exists (select a from FinancialMgmtAccountingFact a where a.recordID = e.recordID and a.table.id = e.table.id and (a.accountingDate < :dateFrom or a.accountingDate > :dateTo))");
+              final Query query = OBDal.getInstance().getSession()
+                  .createQuery(myQuery + consDate.toString());
+              if (recordId != null && !"".equals(recordId)) {
+                query.setString("recordId", recordId);
+              }
+              query.setParameterList("orgIds", orgIds);
+              query.setString("clientId", client);
+              query.setString("dbt", dbt);
+              query.setString("tableId", table);
+              query.setDate("dateFrom", p[0]);
+              query.setDate("dateTo", p[1]);
+              query.setString("organization", organization);
+              if (recordId != null && !"".equals(recordId)) {
+                query.setMaxResults(1);
+              } else {
+                query.setFetchSize(FETCH_SIZE);
+              }
+              start = System.currentTimeMillis();
+              List<String> transactions = query.list();
+              end = System.currentTimeMillis();
+              totalselect = totalselect + end - start;
+              while (transactions.size() > 0) {
+                HashMap<String, Integer> partial = delete(transactions, table, client);
+                deleted = deleted + partial.get("deleted");
+                updated = updated + partial.get("updated");
+                docUpdated = docUpdated + partial.get("updated");
+                docDeleted = docDeleted + partial.get("deleted");
+                start = System.currentTimeMillis();
+                transactions = query.list();
+                end = System.currentTimeMillis();
+                totalselect = totalselect + end - start;
+              }
+              // Documents with postings in different periods are treated separately to validate
+              // all
+              // dates are within an open period
+              HashMap<String, Integer> partial = treatExceptions(exceptionsSql, recordId, table,
+                  orgIds, client, p[0], p[1], calendarId, strdatefrom, strdateto, dbt, orgAllow,
+                  organization);
               deleted = deleted + partial.get("deleted");
               updated = updated + partial.get("updated");
               docUpdated = docUpdated + partial.get("updated");
               docDeleted = docDeleted + partial.get("deleted");
-              start = System.currentTimeMillis();
-              transactions = query.list();
-              end = System.currentTimeMillis();
-              totalselect = totalselect + end - start;
             }
-            // Documents with postings in different periods are treated separately to validate all
-            // dates are within an open period
-            HashMap<String, Integer> partial = treatExceptions(exceptionsSql, recordId, table,
-                orgIds, client, p[0], p[1], calendarId, strdatefrom, strdateto, dbt);
-            deleted = deleted + partial.get("deleted");
-            updated = updated + partial.get("updated");
-            docUpdated = docUpdated + partial.get("updated");
-            docDeleted = docDeleted + partial.get("deleted");
           }
           log4j.debug("docBaseType: " + dbt);
           log4j.debug("updated: " + docUpdated);
           log4j.debug("deleted: " + docDeleted);
         }
       }
+
     } catch (OBException e) {
+
       throw e;
     } catch (Exception e) {
       throw new OBException("Delete failed", e);
@@ -301,13 +334,14 @@
   @SuppressWarnings("unchecked")
   private static List<Period> getOpenPeriods(String clientId, String docBaseType,
       Set<String> orgIds, String calendarId, String tableId, String recordId, String datefrom,
-      String dateto) {
+      String dateto, String orgPeriodControl) {
     if (!"".equals(recordId)) {
       List<Period> periods = new ArrayList<Period>();
-      periods.add(getDocumentPeriod(clientId, tableId, recordId, docBaseType));
+      periods.add(getDocumentPeriod(clientId, tableId, recordId, docBaseType, orgPeriodControl));
       return periods;
+
     }
-    String myQuery = "select distinct p from FinancialMgmtPeriodControl e left join e.period p left join p.year y left join y.calendar c where c.id = :calendarId and e.client.id = :clientId and e.documentCategory = :docbasetype and e.periodStatus = 'O'";
+    String myQuery = "select distinct p from FinancialMgmtPeriodControl e left join e.period p left join p.year y left join y.calendar c where c.id = :calendarId and e.client.id = :clientId and e.documentCategory = :docbasetype and e.periodStatus = 'O' and e.organization.id = :orgPeriodControl";
 
     if (!("".equals(datefrom))) {
       myQuery = myQuery + " and p.startingDate >= :dateFrom";
@@ -321,6 +355,8 @@
     query.setString("calendarId", calendarId);
     query.setString("clientId", clientId);
     query.setString("docbasetype", docBaseType);
+    query.setString("orgPeriodControl", orgPeriodControl);
+
     try {
       if (!("".equals(datefrom))) {
         query.setDate("dateFrom", OBDateUtils.getDate(datefrom));
@@ -335,13 +371,14 @@
   }
 
   private static Period getDocumentPeriod(String clientId, String tableId, String recordId,
-      String docBaseType) {
-    String myQuery = "select distinct e.period from FinancialMgmtAccountingFact e , FinancialMgmtPeriodControl p where p.period=e.period and p.periodStatus = 'O' and e.client.id = :clientId and e.table.id = :tableId and e.recordID=:recordId and p.documentCategory = :docbasetype";
+      String docBaseType, String orgPeriodControl) {
+    String myQuery = "select distinct e.period from FinancialMgmtAccountingFact e , FinancialMgmtPeriodControl p where p.period=e.period and p.periodStatus = 'O' and e.client.id = :clientId and e.table.id = :tableId and e.recordID=:recordId and p.documentCategory = :docbasetype and p.organization.id  = :orgPeriodControl";
     Query query = OBDal.getInstance().getSession().createQuery(myQuery);
     query.setString("clientId", clientId);
     query.setString("tableId", tableId);
     query.setString("recordId", recordId);
     query.setString("docbasetype", docBaseType);
+    query.setString("orgPeriodControl", orgPeriodControl);
     query.setMaxResults(1);
     Period period = (Period) query.uniqueResult();
     if (period == null) {
@@ -392,7 +429,8 @@
 
   private static HashMap<String, Integer> treatExceptions(String myQuery, String recordId,
       String table, Set<String> orgIds, String client, Date dateFrom, Date dateTo,
-      String calendarId, String datefrom, String dateto, String dbt) {
+      String calendarId, String datefrom, String dateto, String dbt, String orgPeriodControl,
+      String targetOrganization) {
     HashMap<String, Integer> results = new HashMap<String, Integer>();
     results.put("deleted", 0);
     results.put("updated", 0);
@@ -406,6 +444,7 @@
     query.setString("tableId", table);
     query.setDate("dateFrom", dateFrom);
     query.setDate("dateTo", dateTo);
+    query.setString("organization", targetOrganization);
     if (recordId != null && !"".equals(recordId)) {
       query.setMaxResults(1);
     }
@@ -428,7 +467,7 @@
         }
       }
       if (checkDates(exceptionDates, client, orgIds, facts.get(0).getDocumentCategory(),
-          calendarId, datefrom, dateto)) {
+          calendarId, datefrom, dateto, orgPeriodControl)) {
         List<String> toDelete = new ArrayList<String>();
         toDelete.add(transaction);
         results = delete(toDelete, table, client);
@@ -442,9 +481,10 @@
   }
 
   private static boolean checkDates(Set<Date> exceptionDates, String clientId, Set<String> orgIds,
-      String documentCategory, String calendarId, String datefrom, String dateto) {
+      String documentCategory, String calendarId, String datefrom, String dateto,
+      String orgPeriodControl) {
     List<Period> openPeriods = getOpenPeriods(clientId, documentCategory, orgIds, calendarId, "",
-        "", datefrom, dateto);
+        "", datefrom, dateto, orgPeriodControl);
     int validDates = 0;
     for (Period period : openPeriods) {
       for (Date date : exceptionDates) {