details:   https://code.openbravo.com/erp/devel/pi/rev/d66d2a414898
changeset: 30540:d66d2a414898
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Mon Sep 19 13:55:25 2016 +0200
summary:   Fixes issue 33968: Wrong costs calculated with Backdated Transactions

CumStock and CumCost will not be calculated in case there is a cost adjustment.

details:   https://code.openbravo.com/erp/devel/pi/rev/65be458e7d27
changeset: 30541:65be458e7d27
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Mon Sep 19 14:53:39 2016 +0200
summary:   Related to issue 33968: Code review improvements

details:   https://code.openbravo.com/erp/devel/pi/rev/5f40df94e94e
changeset: 30542:5f40df94e94e
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Mon Sep 19 13:55:25 2016 +0200
summary:   Fixes issue 33968: Filter by costing transaction instead of current 
transaction

Filter by costing transaction instead of current transaction when 
existsCumulatedStockOnTrxDate or existsCumulatedValuationOnTrxDate in 
CostAdjustmentUtils.getStockOnTransactionDate and 
CostAdjustmentUtils.getValuedStockOnTransactionDate.

details:   https://code.openbravo.com/erp/devel/pi/rev/2cd8d93344f8
changeset: 30543:2cd8d93344f8
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Mon Sep 19 14:53:39 2016 +0200
summary:   Related to issue 33968: Retrieve costing transaction only once

Retrieve costing transaction only once in 
CostAdjustmentUtils.getStockOnTransactionDate, 
CostAdjustmentUtils.getValuedStockOnTransactionDate, 
CostingUtils.getCurrentStock and CostingUtils.getCurrentValuedStock.

details:   https://code.openbravo.com/erp/devel/pi/rev/deff2af56118
changeset: 30544:deff2af56118
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Mon Sep 19 13:55:25 2016 +0200
summary:   Fixes issue 33968: Add movementdate filter in CostAdjustmentUtils in 
case BDT

Add movementdate filter in case costing rule allows backdated transactions in 
CostAdjustmentUtils.getStockOnTransactionDate and 
CostAdjustmentUtils.getValuedStockOnTransactionDate.

details:   https://code.openbravo.com/erp/devel/pi/rev/ca6556a42072
changeset: 30545:ca6556a42072
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Mon Sep 19 14:53:39 2016 +0200
summary:   Related to issue 33968: Rename movementdate and dateFrom parameters

Rename movementdate and dateFrom parameters to cmvtdate and ctrxdate and use 
costing transaction trxprocessdate instead of costing starting date in 
CostAdjustmentUtils.getStockOnTransactionDate and 
CostAdjustmentUtils.getValuedStockOnTransactionDate.

details:   https://code.openbravo.com/erp/devel/pi/rev/b6192a72cbba
changeset: 30546:b6192a72cbba
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Tue Sep 20 18:27:30 2016 +0200
summary:   Fixes issue 33968: Use getLastCumulatedCosting instead of 
getProductCost

Use AverageAlgorithm.getLastCumulatedCosting instead of 
AverageAlgorithm.getProductCost to retrieve last costing entry with cumulated 
values in CostAdjustmentUtils.getStockOnTransactionDate, 
CostingUtils.getCurrentStock and CostingUtils.getCurrentValuedStock.

details:   https://code.openbravo.com/erp/devel/pi/rev/e711b068ea90
changeset: 30547:e711b068ea90
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 20 19:01:51 2016 +0200
summary:   Related to issue 33968: Avoid API change

Add cumcost not null restriction and retrieve unique result in 
AverageAlgorithm.getLastCumulatedCosting.
Avoid API change by calculating correct date outside the method and removing 
unneeded transaction parameter in CostingUtils.getCurrentStock and 
CostingUtils.getCurrentValuedStock.
Use AverageAlgorithm.getLastCumulatedCosting also in 
CostAdjustmentUtils.getValuedStockOnTransactionDate.
Call to AverageAlgorithm.getLastCumulatedCosting with movementdate or 
trxprocessdate depending on areBackdatedTrxFixed in 
CostAdjustmentUtils.getStockOnTransactionDate and 
CostAdjustmentUtils.getValuedStockOnTransactionDate.

details:   https://code.openbravo.com/erp/devel/pi/rev/05a2c5a0d127
changeset: 30548:05a2c5a0d127
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 20 19:40:33 2016 +0200
summary:   Related to issue 33968: Return costing cumulated values if trx is 
costing trx

Return costing cumulated values if trx is costing trx in 
CostAdjustmentUtils.getStockOnTransactionDate and 
CostAdjustmentUtils.getValuedStockOnTransactionDate.

details:   https://code.openbravo.com/erp/devel/pi/rev/61f70f49b809
changeset: 30549:61f70f49b809
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Tue Sep 20 19:49:10 2016 +0200
summary:   Fixes issue 33968: Truncate costing rule fix backdated from date

Truncate costing rule fix backdated from date when compering it with 
transaction movement date in CostingServer.java.

details:   https://code.openbravo.com/erp/devel/pi/rev/528ed62798da
changeset: 30550:528ed62798da
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 20 20:05:45 2016 +0200
summary:   Related to issue 33968: Truncate also transaction movement date

Truncate also transaction movement date when compering it with costing rule fix 
backdated from date in CostingServer.java.
Truncate also transaction movement date and costing rule fix backdated from 
date for costing rules with standard algorithm.

details:   https://code.openbravo.com/erp/devel/pi/rev/353d8721b32b
changeset: 30551:353d8721b32b
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Tue Sep 20 20:59:27 2016 +0200
summary:   Fixes issue 33968: Revert negative adjustment if needed by BDT

Revert negative adjustment when a backdated transaction turns negative stock 
into positive stock.

details:   https://code.openbravo.com/erp/devel/pi/rev/35bfe769e1e6
changeset: 30552:35bfe769e1e6
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 20 21:05:21 2016 +0200
summary:   Related to issue 33968: Move getNegativeStockAdjustments method

Move AverageCostAdjustment.getNegativeStockAdjustments method to the end of the 
file and add documentation.

details:   https://code.openbravo.com/erp/devel/pi/rev/742ee19c4ecd
changeset: 30553:742ee19c4ecd
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Tue Sep 20 20:29:15 2016 +0200
summary:   Fixes issue 33968: Fix rounding issue when cumulate stock has many 
decimals

Round cumcost and cumstock to currency cost precision before divide them to 
calculate cost to avoid rounding issues in 
CostAdjustmentUtils.getStockOnTransactionDate, 
CostAdjustmentUtils.getValuedStockOnTransactionDate, 
CostingUtils.getCurrentStock and CostingUtils.getCurrentValuedStock.

details:   https://code.openbravo.com/erp/devel/pi/rev/cd566f557bd6
changeset: 30554:cd566f557bd6
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 20 20:53:11 2016 +0200
summary:   Related to issue 33968: Send parameters in order

Send parameters in order, first currency and then costing, to 
CostAdjustmentUtils.getStockOnTransactionDate and CostingUtils.getCurrentStock.
Round also cumstock and cumcost when transaction is the costing transaction.

details:   https://code.openbravo.com/erp/devel/pi/rev/14bc76dba26d
changeset: 30555:14bc76dba26d
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 20 22:20:32 2016 +0200
summary:   Related to issue 33968: Avoid another API change

Use client or organization currency to round cumstock and cumcost, to avoid 
send currency to CostAdjustmentUtils.getStockOnTransactionDate and 
CostingUtils.getCurrentStock and avoid the API change.

details:   https://code.openbravo.com/erp/devel/pi/rev/d7a06320f6d9
changeset: 30556:d7a06320f6d9
user:      David Miguelez <david.miguelez <at> openbravo.com>
date:      Tue Sep 20 21:06:34 2016 +0200
summary:   Fixes issue 33968: Avoid errors with Goods Movements

details:   https://code.openbravo.com/erp/devel/pi/rev/b11822652ce5
changeset: 30557:b11822652ce5
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 27 13:24:12 2016 +0200
summary:   Related to issue 33968: Use cumulated values when movement date is 
the same

Use also cumulated values in CostAdjustmentUtils.getStockOnTransactionDate and 
CostAdjustmentUtils.getValuedStockOnTransactionDate methods when trx and ctrx 
movementdate is the same.
Also, truncate movementdate before comparing it.

details:   https://code.openbravo.com/erp/devel/pi/rev/4da571921aeb
changeset: 30558:4da571921aeb
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Sep 20 22:21:54 2016 +0200
summary:   Related to issue 33968: Remove cumstock and cumcost assert in 
TestCosting

details:   https://code.openbravo.com/erp/devel/pi/rev/12db641af792
changeset: 30559:12db641af792
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Wed Sep 28 13:57:03 2016 +0200
summary:   Related to issue 33968: Make an API change

Add MaterialTransaction trx parameter to CostingUtils.getCurrentStock and 
CostingUtils.getCurrentValuedStock methods.
Also, remove product and date unneeded parameters and add areBackdatedTrxFixed 
parameter to avoid get again the costingRule.

details:   https://code.openbravo.com/erp/devel/pi/rev/45f2a306bf71
changeset: 30560:45f2a306bf71
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Wed Sep 28 14:12:00 2016 +0200
summary:   Related to issue 33968: Make another API change

Send currency to CostAdjustmentUtils.getStockOnTransactionDate and 
CostingUtils.getCurrentStock.

details:   https://code.openbravo.com/erp/devel/pi/rev/ff578582c72c
changeset: 30561:ff578582c72c
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Wed Sep 28 14:16:44 2016 +0200
summary:   Related to issue 33968: Exclude M+ in case M- also in 
CostAdjustmentUtils

Exclude M+ in case M- also in CostAdjustmentUtils.getStockOnTransactionDate and 
CostAdjustmentUtils.getValuedStockOnTransactionDate as it is done in 
CostingUtils.getCurrentStock and CostingUtils.getCurrentValuedStock.

details:   https://code.openbravo.com/erp/devel/pi/rev/96cab7afad17
changeset: 30562:96cab7afad17
user:      Alvaro Ferraz <alvaro.ferraz <at> openbravo.com>
date:      Tue Oct 11 17:41:03 2016 +0200
summary:   Related to issue 33968: Add comments

diffstat:

 src-test/src/org/openbravo/test/costing/TestCosting.java |    7 -
 src/org/openbravo/costing/AverageAlgorithm.java          |   48 +++-
 src/org/openbravo/costing/AverageCostAdjustment.java     |   74 ++++-
 src/org/openbravo/costing/CostAdjustmentUtils.java       |  213 ++++++++++----
 src/org/openbravo/costing/CostingServer.java             |   18 +-
 src/org/openbravo/costing/CostingUtils.java              |  133 +++++++--
 6 files changed, 369 insertions(+), 124 deletions(-)

diffs (truncated from 956 to 300 lines):

diff -r 9ec41af386ae -r 96cab7afad17 
src-test/src/org/openbravo/test/costing/TestCosting.java
--- a/src-test/src/org/openbravo/test/costing/TestCosting.java  Thu Oct 13 
13:35:09 2016 -0400
+++ b/src-test/src/org/openbravo/test/costing/TestCosting.java  Tue Oct 11 
17:41:03 2016 +0200
@@ -12727,18 +12727,11 @@
             productCostingAssert.getOriginalCost() == null ? null : 
productCostingAssert
                 .getOriginalCost().setScale(4, BigDecimal.ROUND_HALF_UP));
 
-        assertEquals(productCosting.getTotalMovementQuantity(), 
productCostingAssert.getQuantity());
-
         if (productCostingAssert.getQuantity() == null) {
           assertEquals(productCosting.getQuantity(), null);
-          assertEquals(productCosting.getTotalStockValuation(), null);
         } else {
           assertEquals(productCosting.getQuantity(), 
productCostingAssert.getTransaction()
               .getMovementQuantity());
-          assertEquals(productCosting.getTotalStockValuation()
-              .setScale(1, BigDecimal.ROUND_HALF_UP),
-              
productCostingAssert.getFinalCost().multiply(productCostingAssert.getQuantity())
-                  .setScale(1, BigDecimal.ROUND_HALF_UP));
         }
 
         assertEquals(productCosting.isManual(), 
productCostingAssert.isManual());
diff -r 9ec41af386ae -r 96cab7afad17 
src/org/openbravo/costing/AverageAlgorithm.java
--- a/src/org/openbravo/costing/AverageAlgorithm.java   Thu Oct 13 13:35:09 
2016 -0400
+++ b/src/org/openbravo/costing/AverageAlgorithm.java   Tue Oct 11 17:41:03 
2016 +0200
@@ -50,10 +50,10 @@
       BigDecimal trxCostWithSign = (transaction.getMovementQuantity().signum() 
== -1) ? trxCost
           .negate() : trxCost;
       BigDecimal newCost = null;
-      BigDecimal currentStock = 
CostingUtils.getCurrentStock(transaction.getProduct(), costOrg,
-          transaction.getTransactionProcessDate(), costDimensions);
-      BigDecimal currentValuedStock = 
CostingUtils.getCurrentValuedStock(transaction.getProduct(),
-          costOrg, transaction.getTransactionProcessDate(), costDimensions, 
costCurrency);
+      BigDecimal currentStock = CostingUtils.getCurrentStock(transaction, 
costOrg, costDimensions,
+          costingRule.isBackdatedTransactionsFixed(), costCurrency);
+      BigDecimal currentValuedStock = 
CostingUtils.getCurrentValuedStock(transaction, costOrg,
+          costDimensions, costingRule.isBackdatedTransactionsFixed(), 
costCurrency);
       if (currentCosting == null) {
         if (transaction.getMovementQuantity().signum() == 0) {
           newCost = BigDecimal.ZERO;
@@ -257,6 +257,46 @@
     return costList.get(0);
   }
 
+  protected static Costing getLastCumulatedCosting(Date date, Product product,
+      HashMap<CostDimension, BaseOBObject> costDimensions, Organization 
costOrg) {
+    StringBuffer where = new StringBuffer();
+    where.append(Costing.PROPERTY_PRODUCT + ".id = :product");
+    where.append("  and " + Costing.PROPERTY_STARTINGDATE + " <= 
:startingDate");
+    where.append("  and " + Costing.PROPERTY_COSTTYPE + " = 'AVA'");
+    where.append("  and " + Costing.PROPERTY_COST + " is not null");
+    where.append("  and " + Costing.PROPERTY_TOTALMOVEMENTQUANTITY + " is not 
null");
+    where.append("  and " + Costing.PROPERTY_TOTALSTOCKVALUATION + " is not 
null");
+    if (costDimensions.get(CostDimension.Warehouse) != null) {
+      where.append("  and " + Costing.PROPERTY_WAREHOUSE + ".id = :warehouse");
+    } else {
+      where.append("  and " + Costing.PROPERTY_WAREHOUSE + " is null");
+    }
+    // FIXME: remove when manufacturing costs are fully migrated
+    if (product.isProduction()) {
+      where.append("  and " + Costing.PROPERTY_CLIENT + ".id = :client");
+    } else {
+      where.append("  and " + Costing.PROPERTY_ORGANIZATION + ".id = :org");
+    }
+    where.append("  order by " + Costing.PROPERTY_STARTINGDATE + " desc,");
+    where.append(" " + Costing.PROPERTY_ENDINGDATE + " desc");
+    OBQuery<Costing> costQry = OBDal.getInstance().createQuery(Costing.class, 
where.toString());
+    costQry.setFilterOnReadableOrganization(false);
+    costQry.setNamedParameter("product", product.getId());
+    costQry.setNamedParameter("startingDate", date);
+    if (costDimensions.get(CostDimension.Warehouse) != null) {
+      costQry.setNamedParameter("warehouse", 
costDimensions.get(CostDimension.Warehouse).getId());
+    }
+    // FIXME: remove when manufacturing costs are fully migrated
+    if (product.isProduction()) {
+      costQry.setNamedParameter("client", costOrg.getClient().getId());
+    } else {
+      costQry.setNamedParameter("org", costOrg.getId());
+    }
+
+    costQry.setMaxResult(1);
+    return costQry.uniqueResult();
+  }
+
   private Date getLastDate() {
     SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
     try {
diff -r 9ec41af386ae -r 96cab7afad17 
src/org/openbravo/costing/AverageCostAdjustment.java
--- a/src/org/openbravo/costing/AverageCostAdjustment.java      Thu Oct 13 
13:35:09 2016 -0400
+++ b/src/org/openbravo/costing/AverageCostAdjustment.java      Tue Oct 11 
17:41:03 2016 +0200
@@ -117,7 +117,7 @@
 
     // Initialize current stock qty and value amt.
     BigDecimal currentStock = 
CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
-        getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed);
+        getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed, 
getCostCurrency());
     BigDecimal currentValueAmt = 
CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(),
         basetrx, getCostDimensions(), isManufacturingProduct, 
areBackdatedTrxFixed,
         getCostCurrency());
@@ -194,8 +194,8 @@
               Organization.ENTITY_NAME, strCostOrgId));
         }
         newCosting.setQuantity(basetrx.getMovementQuantity());
-        newCosting.setTotalMovementQuantity(currentStock);
-        
newCosting.setTotalStockValuation(currentValueAmt.add(adjustmentBalance));
+        newCosting.setTotalMovementQuantity(null);
+        newCosting.setTotalStockValuation(null);
         newCosting.setPrice(cost);
         newCosting.setCostType("AVA");
         newCosting.setManual(Boolean.FALSE);
@@ -208,7 +208,8 @@
         Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0);
 
         if (curCosting.getCost().compareTo(cost) != 0
-            || curCosting.getTotalMovementQuantity().compareTo(currentStock) 
!= 0) {
+            || (curCosting.getTotalMovementQuantity() != null && curCosting
+                .getTotalMovementQuantity().compareTo(currentStock) != 0)) {
           curCosting.setPermanent(Boolean.FALSE);
           OBDal.getInstance().save(curCosting);
           OBDal.getInstance().flush();
@@ -220,8 +221,8 @@
             curCosting.setCost(cost);
             curCosting.setPrice(trxPrice);
           }
-          curCosting.setTotalMovementQuantity(currentStock);
-          
curCosting.setTotalStockValuation(currentValueAmt.add(adjustmentBalance));
+          curCosting.setTotalMovementQuantity(null);
+          curCosting.setTotalStockValuation(null);
           curCosting.setPermanent(Boolean.TRUE);
           OBDal.getInstance().flush();
           OBDal.getInstance().save(curCosting);
@@ -339,10 +340,35 @@
             cost = trxPrice;
             log.debug("Negative stock correction. Amount: {}, new cost {}",
                 negCorrAmt.toPlainString(), cost.toPlainString());
+          } else if (checkNegativeStockCorrection
+              && currentStock.compareTo(trx.getMovementQuantity()) >= 0) {
+            List<CostAdjustmentLine> costAdjustmentLineList = 
getNegativeStockAdjustments(trx);
+            BigDecimal revertedNegativeAdjustment = BigDecimal.ZERO;
+            if (!costAdjustmentLineList.isEmpty()) {
+              for (CostAdjustmentLine costAdjustmentLine : 
costAdjustmentLineList) {
+                revertedNegativeAdjustment = 
revertedNegativeAdjustment.add(costAdjustmentLine
+                    .getAdjustmentAmount().negate());
+              }
+              adjustmentBalance = 
adjustmentBalance.add(revertedNegativeAdjustment);
+              trxAdjAmt = trxAdjAmt.add(revertedNegativeAdjustment);
+              // If there is a difference insert a cost adjustment line.
+              CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, 
revertedNegativeAdjustment,
+                  null);
+              newCAL.setNegativeStockCorrection(Boolean.TRUE);
+              newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
+              newCAL.setUnitCost(Boolean.FALSE);
+              OBDal.getInstance().save(newCAL);
+              cost = 
currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
+                  RoundingMode.HALF_UP);
+              log.debug("Revert Negative stock correction. Amount: {}, new 
cost {}",
+                  revertedNegativeAdjustment.toPlainString(), 
cost.toPlainString());
+            }
           }
 
-          if (curCosting.getCost().compareTo(cost) == 0 && 
StringUtils.isEmpty(bdCostingId)
-              && curCosting.getTotalMovementQuantity().compareTo(currentStock) 
== 0) {
+          if (curCosting.getCost().compareTo(cost) == 0
+              && StringUtils.isEmpty(bdCostingId)
+              && (curCosting.getTotalMovementQuantity() != null && curCosting
+                  .getTotalMovementQuantity().compareTo(currentStock) == 0)) {
             // new cost hasn't changed and total movement qty is equal to 
current stock, following
             // transactions will have the same cost, so no more
             // related transactions are needed to include.
@@ -362,8 +388,8 @@
               curCosting.setPrice(trxPrice);
               curCosting.setCost(cost);
             }
-            curCosting.setTotalMovementQuantity(currentStock);
-            
curCosting.setTotalStockValuation(currentValueAmt.add(adjustmentBalance));
+            curCosting.setTotalMovementQuantity(null);
+            curCosting.setTotalStockValuation(null);
             curCosting.setPermanent(Boolean.TRUE);
             OBDal.getInstance().save(curCosting);
           }
@@ -406,7 +432,8 @@
                   costCurPrecission, RoundingMode.HALF_UP);
             }
             if (curCosting.getCost().compareTo(cost) != 0
-                || 
curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
+                || (curCosting.getTotalMovementQuantity() != null && curCosting
+                    .getTotalMovementQuantity().compareTo(currentStock) != 0)) 
{
               curCosting.setPermanent(Boolean.FALSE);
               OBDal.getInstance().save(curCosting);
               OBDal.getInstance().flush();
@@ -417,8 +444,8 @@
                 curCosting.setPrice(trxPrice);
                 curCosting.setCost(cost);
               }
-              curCosting.setTotalMovementQuantity(currentStock);
-              
curCosting.setTotalStockValuation(currentValueAmt.add(adjustmentBalance));
+              curCosting.setTotalMovementQuantity(null);
+              curCosting.setTotalStockValuation(null);
               curCosting.setPermanent(Boolean.TRUE);
               OBDal.getInstance().save(curCosting);
             }
@@ -452,8 +479,8 @@
         }
         currentCosting.setPrice(cost);
         currentCosting.setCost(cost);
-        currentCosting.setTotalMovementQuantity(currentStock);
-        
currentCosting.setTotalStockValuation(currentValueAmt.add(adjustmentBalance));
+        currentCosting.setTotalMovementQuantity(null);
+        currentCosting.setTotalStockValuation(null);
         currentCosting.setManual(Boolean.FALSE);
         currentCosting.setPermanent(Boolean.TRUE);
         OBDal.getInstance().save(currentCosting);
@@ -679,7 +706,7 @@
         && 
!CostingUtils.getCostingRuleFixBackdatedFrom(getCostingRule()).before(
             basetrx.getTransactionProcessDate());
     BigDecimal currentStock = 
CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
-        getCostDimensions(), isManufacturingProduct, areBaseTrxBackdatedFixed);
+        getCostDimensions(), isManufacturingProduct, areBaseTrxBackdatedFixed, 
getCostCurrency());
     BigDecimal currentValueAmt = 
CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(),
         basetrx, getCostDimensions(), isManufacturingProduct, 
areBaseTrxBackdatedFixed,
         getCostCurrency());
@@ -954,4 +981,19 @@
     critLines.setMaxResults(1);
     return critLines.uniqueResult() != null;
   }
+
+  /**
+   * Get negative cost adjustment lines related to trx
+   * 
+   * @param trx
+   *          MaterialTransaction to get related negative cost adjustment lines
+   * @return CostAdjustmentLine list
+   */
+  private List<CostAdjustmentLine> 
getNegativeStockAdjustments(MaterialTransaction trx) {
+    OBCriteria<CostAdjustmentLine> critLines = 
OBDal.getInstance().createCriteria(
+        CostAdjustmentLine.class);
+    
critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_INVENTORYTRANSACTION, 
trx));
+    
critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_ISNEGATIVESTOCKCORRECTION,
 true));
+    return critLines.list();
+  }
 }
diff -r 9ec41af386ae -r 96cab7afad17 
src/org/openbravo/costing/CostAdjustmentUtils.java
--- a/src/org/openbravo/costing/CostAdjustmentUtils.java        Thu Oct 13 
13:35:09 2016 -0400
+++ b/src/org/openbravo/costing/CostAdjustmentUtils.java        Tue Oct 11 
17:41:03 2016 +0200
@@ -20,11 +20,13 @@
 
 import java.math.BigDecimal;
 import java.math.RoundingMode;
+import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Set;
 
 import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang.time.DateUtils;
 import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
@@ -363,11 +365,12 @@
    */
   public static BigDecimal getStockOnTransactionDate(Organization costorg, 
MaterialTransaction trx,
       HashMap<CostDimension, BaseOBObject> _costDimensions, boolean 
isManufacturingProduct,
-      boolean areBackdatedTrxFixed) {
-    Costing costing = 
AverageAlgorithm.getProductCost(trx.getTransactionProcessDate(),
-        trx.getProduct(), _costDimensions, costorg);
+      boolean areBackdatedTrxFixed, Currency currency) {
+    Date date = areBackdatedTrxFixed ? trx.getMovementDate() : 
trx.getTransactionProcessDate();
+    Costing costing = AverageAlgorithm.getLastCumulatedCosting(date, 
trx.getProduct(),
+        _costDimensions, costorg);
     return getStockOnTransactionDate(costorg, trx, _costDimensions, 
isManufacturingProduct,
-        areBackdatedTrxFixed, costing);
+        areBackdatedTrxFixed, currency, costing);
   }
 
   /**
@@ -376,7 +379,7 @@
    */
   public static BigDecimal getStockOnTransactionDate(Organization costorg, 
MaterialTransaction trx,
       HashMap<CostDimension, BaseOBObject> _costDimensions, boolean 
isManufacturingProduct,
-      boolean areBackdatedTrxFixed, Costing costing) {
+      boolean areBackdatedTrxFixed, Currency currency, Costing costing) {
 
     // Get child tree of organizations.
     OrganizationStructureProvider osp = 
OBContext.getOBContext().getOrganizationStructureProvider(
@@ -390,38 +393,76 @@
     CostingRule costingRule = CostingUtils.getCostDimensionRule(costorg,
         trx.getTransactionProcessDate());
 
-    boolean existsCumulatedStockOnTrxDate = costing != null
-        && costing.getTotalMovementQuantity() != null
-        && costing.getInventoryTransaction() != null
-        && (!costingRule.isBackdatedTransactionsFixed() || 
trx.getMovementDate().after(
-            costing.getInventoryTransaction().getMovementDate()));
+    BigDecimal cumulatedStock = null;
+    int costingPrecision = currency.getCostingPrecision().intValue();
+    MaterialTransaction ctrx = costing != null ? 
costing.getInventoryTransaction() : null;
+    boolean existsCumulatedStockOnTrxDate = ctrx != null
+        && costing.getTotalMovementQuantity() != null;
+
+    // Backdated transactions can't use cumulated values

------------------------------------------------------------------------------
The Command Line: Reinvented for Modern Developers
Did the resurgence of CLI tooling catch you by surprise?
Reconnect with the command line and become more productive. 
Learn the new .NET and ASP.NET CLI. Get your free copy!
http://sdm.link/telerik
_______________________________________________
Openbravo-commits mailing list
Openbravo-commits@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/openbravo-commits

Reply via email to