List of usage examples for org.hibernate ScrollableResults get
Object[] get();
From source file:org.openbravo.costing.CostingAlgorithmAdjustmentImp.java
License:Open Source License
protected void searchReturnShipments(CostAdjustmentLine _costAdjLine) { CostAdjustmentLine costAdjLine;//from ww w.ja v a 2 s . c o m if (_costAdjLine != null) { costAdjLine = _costAdjLine; } else { costAdjLine = getCostAdjLine(); } ShipmentInOutLine inoutline = costAdjLine.getInventoryTransaction().getGoodsShipmentLine(); BigDecimal costAdjAmt = costAdjLine.getAdjustmentAmount().negate(); int precission = getCostCurrency().getStandardPrecision().intValue(); StringBuffer where = new StringBuffer(); where.append(" as trx"); where.append(" join trx." + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + " as iol"); where.append(" join iol." + ShipmentInOutLine.PROPERTY_SALESORDERLINE + " as ol"); where.append(" where ol." + OrderLine.PROPERTY_GOODSSHIPMENTLINE + " = :shipment"); OBQuery<MaterialTransaction> qryTrx = OBDal.getInstance().createQuery(MaterialTransaction.class, where.toString()); qryTrx.setFilterOnReadableOrganization(false); qryTrx.setNamedParameter("shipment", inoutline); ScrollableResults trxs = qryTrx.scroll(ScrollMode.FORWARD_ONLY); try { int counter = 0; while (trxs.next()) { counter++; MaterialTransaction trx = (MaterialTransaction) trxs.get()[0]; if (trx.isCostCalculated()) { BigDecimal adjAmt = costAdjAmt.multiply(trx.getMovementQuantity().abs()) .divide(inoutline.getMovementQuantity().abs(), precission, RoundingMode.HALF_UP); insertCostAdjustmentLine(trx, adjAmt, _costAdjLine); } if (counter % 1000 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } } } finally { trxs.close(); } }
From source file:org.openbravo.costing.CostingRuleProcess.java
License:Open Source License
protected void createCostingRuleInits(String ruleId, Set<String> childOrgs, Date date) { CostingRule rule = OBDal.getInstance().get(CostingRule.class, ruleId); ScrollableResults stockLines = getStockLines(childOrgs, date); // The key of the Map is the concatenation of orgId and warehouseId Map<String, String> initLines = new HashMap<String, String>(); Map<String, Long> maxLineNumbers = new HashMap<String, Long>(); InventoryCountLine closingInventoryLine = null; InventoryCountLine openInventoryLine = null; int i = 1;//from www . jav a 2 s . co m try { while (stockLines.next()) { Object[] stockLine = stockLines.get(); String productId = (String) stockLine[0]; String attrSetInsId = (String) stockLine[1]; String uomId = (String) stockLine[2]; String orderUOMId = (String) stockLine[3]; String locatorId = (String) stockLine[4]; String warehouseId = (String) stockLine[5]; BigDecimal qty = (BigDecimal) stockLine[6]; BigDecimal orderQty = (BigDecimal) stockLine[7]; String criId = initLines.get(warehouseId); CostingRuleInit cri = null; if (criId == null) { cri = createCostingRuleInitLine(rule, warehouseId, date); initLines.put(warehouseId, cri.getId()); } else { cri = OBDal.getInstance().get(CostingRuleInit.class, criId); } Long lineNo = (maxLineNumbers.get(criId) == null ? 0L : maxLineNumbers.get(criId)) + 10L; maxLineNumbers.put(criId, lineNo); if (BigDecimal.ZERO.compareTo(qty) < 0) { // Do not insert negative values in Inventory lines, instead reverse the Quantity Count // and the Book Quantity. For example: // Instead of CountQty=0 and BookQty=-5 insert CountQty=5 and BookQty=0 // By doing so the difference between both quantities remains the same and no negative // values have been inserted. openInventoryLine = insertInventoryLine(cri.getInitInventory(), productId, attrSetInsId, uomId, orderUOMId, locatorId, qty, BigDecimal.ZERO, orderQty, BigDecimal.ZERO, lineNo, null); insertInventoryLine(cri.getCloseInventory(), productId, attrSetInsId, uomId, orderUOMId, locatorId, BigDecimal.ZERO, qty, BigDecimal.ZERO, orderQty, lineNo, openInventoryLine); } else { openInventoryLine = insertInventoryLine(cri.getInitInventory(), productId, attrSetInsId, uomId, orderUOMId, locatorId, BigDecimal.ZERO, qty.abs(), BigDecimal.ZERO, orderQty == null ? null : orderQty.abs(), lineNo, closingInventoryLine); insertInventoryLine(cri.getCloseInventory(), productId, attrSetInsId, uomId, orderUOMId, locatorId, qty == null ? null : qty.abs(), BigDecimal.ZERO, orderQty == null ? null : orderQty.abs(), BigDecimal.ZERO, lineNo, openInventoryLine); } if ((i % 100) == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); // Reload rule after clear session. rule = OBDal.getInstance().get(CostingRule.class, ruleId); } i++; } } finally { stockLines.close(); } // Process closing physical inventories. for (CostingRuleInit cri : rule.getCostingRuleInitList()) { new InventoryCountProcess().processInventory(cri.getCloseInventory(), false); } }
From source file:org.openbravo.costing.CostingServer.java
License:Open Source License
private void checkCostAdjustments() { TrxType trxType = TrxType.getTrxType(transaction); boolean adjustmentAlreadyCreated = false; if (trxType == TrxType.InventoryClosing) { OBDal.getInstance().refresh(transaction.getPhysicalInventoryLine().getPhysInventory()); if (transaction.getPhysicalInventoryLine().getPhysInventory().getCostingRuleInitCloseInventoryList() .size() > 0) {/*from ww w .j av a 2s .c o m*/ // Closing inventories from costing rule process are not automatically adjusted. return; } } boolean checkPriceCorrectionTrxs = false; boolean checkNegativeStockCorrectionTrxs = false; // check if price correction is needed try { checkPriceCorrectionTrxs = Preferences.getPreferenceValue( CostAdjustmentUtils.ENABLE_AUTO_PRICE_CORRECTION_PREF, true, OBContext.getOBContext().getCurrentClient(), OBContext.getOBContext().getCurrentOrganization(), OBContext.getOBContext().getUser(), OBContext.getOBContext().getRole(), null).equals("Y"); } catch (PropertyException e1) { checkPriceCorrectionTrxs = false; } if (checkPriceCorrectionTrxs && transaction.isCheckpricedifference()) { JSONObject message = PriceDifferenceProcess.processPriceDifferenceTransaction(transaction); if (message.has("documentNo")) { adjustmentAlreadyCreated = true; } } // check if landed cost need to be processed if (trxType == TrxType.Receipt || trxType == TrxType.ReceiptReturn || trxType == TrxType.ReceiptNegative) { StringBuffer where = new StringBuffer(); where.append(" as lc"); where.append(" where not exists "); where.append(" (select 1 from " + MaterialTransaction.ENTITY_NAME + " mtrans"); where.append(" join mtrans." + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + " iol"); where.append(" where iol." + ShipmentInOutLine.PROPERTY_SHIPMENTRECEIPT + ".id = :inoutId"); where.append(" and mtrans." + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + "= false"); where.append(" )"); where.append(" and lc." + LandedCostCost.PROPERTY_LANDEDCOST + " is null"); where.append(" and lc." + LandedCostCost.PROPERTY_GOODSSHIPMENT + ".id = :inoutId"); OBQuery<LandedCostCost> qry = OBDal.getInstance().createQuery(LandedCostCost.class, where.toString()); qry.setNamedParameter("inoutId", transaction.getGoodsShipmentLine().getShipmentReceipt().getId()); ScrollableResults lcLines = qry.scroll(ScrollMode.FORWARD_ONLY); try { LandedCost landedCost = null; while (lcLines.next()) { if (landedCost == null) { final DocumentType docType = FIN_Utility.getDocumentType(organization, strCategoryLandedCost); final String docNo = FIN_Utility.getDocumentNo(docType, strTableLandedCost); landedCost = OBProvider.getInstance().get(LandedCost.class); landedCost.setReferenceDate(new Date()); landedCost.setDocumentType(docType); landedCost.setDocumentNo(docNo); landedCost.setOrganization(organization); OBDal.getInstance().save(landedCost); LCReceipt lcReceipt = OBProvider.getInstance().get(LCReceipt.class); lcReceipt.setLandedCost(landedCost); lcReceipt.setOrganization(organization); lcReceipt.setGoodsShipment(transaction.getGoodsShipmentLine().getShipmentReceipt()); OBDal.getInstance().save(lcReceipt); } final LandedCostCost landedCostCost = (LandedCostCost) lcLines.get()[0]; landedCostCost.setLandedCost(landedCost); landedCost.getLandedCostCostList().add(landedCostCost); OBDal.getInstance().save(landedCost); OBDal.getInstance().save(landedCostCost); } if (landedCost != null) { OBDal.getInstance().flush(); JSONObject message = LandedCostProcess.doProcessLandedCost(landedCost); if (message.has("documentNo")) { adjustmentAlreadyCreated = true; } if (message.get("severity") != "success") { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingLandedCost@") + ": " + landedCost.getDocumentNo() + " - " + message.getString("text")); } } } catch (JSONException e) { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingLandedCost@")); } finally { lcLines.close(); } } if (getCostingRule().isBackdatedTransactionsFixed() && transaction.getMovementDate().after(CostingUtils.getCostingRuleStartingDate(getCostingRule())) && CostAdjustmentUtils.isNeededBackdatedCostAdjustment(transaction, getCostingRule().isWarehouseDimension(), CostingUtils.getCostingRuleStartingDate(getCostingRule()))) { // BDT= Backdated transaction CostAdjustment costAdjustmentHeader = CostAdjustmentUtils .insertCostAdjustmentHeader(transaction.getOrganization(), "BDT"); CostAdjustmentLine cal = CostAdjustmentUtils.insertCostAdjustmentLine(transaction, costAdjustmentHeader, null, Boolean.TRUE, transaction.getMovementDate()); cal.setBackdatedTrx(Boolean.TRUE); OBDal.getInstance().save(cal); OBDal.getInstance().flush(); JSONObject message = CostAdjustmentProcess.doProcessCostAdjustment(costAdjustmentHeader); try { if (message.get("severity") != "success") { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@") + ": " + costAdjustmentHeader.getDocumentNo() + " - " + message.getString("text")); } adjustmentAlreadyCreated = true; } catch (JSONException ignore) { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@")); } } // check if negative stock correction should be done try { checkNegativeStockCorrectionTrxs = Preferences.getPreferenceValue( CostAdjustmentUtils.ENABLE_NEGATIVE_STOCK_CORRECTION_PREF, true, OBContext.getOBContext().getCurrentClient(), OBContext.getOBContext().getCurrentOrganization(), OBContext.getOBContext().getUser(), OBContext.getOBContext().getRole(), null).equals("Y"); } catch (PropertyException e1) { checkNegativeStockCorrectionTrxs = false; } boolean modifiesAvg = AverageAlgorithm.modifiesAverage(TrxType.getTrxType(transaction)); BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getOrganization(), transaction, getCostingAlgorithm().costDimensions, transaction.getProduct().isProduction(), costingRule.isBackdatedTransactionsFixed()); // the stock previous to transaction was negative if (checkNegativeStockCorrectionTrxs && currentStock.compareTo(transaction.getMovementQuantity()) < 0 && modifiesAvg && !adjustmentAlreadyCreated) { CostAdjustment costAdjustmentHeader = CostAdjustmentUtils .insertCostAdjustmentHeader(transaction.getOrganization(), "NSC"); // NSC= Negative Stock Correction Date acctDate = transaction.getMovementDate(); CostAdjustmentLine cal = CostAdjustmentUtils.insertCostAdjustmentLine(transaction, costAdjustmentHeader, null, Boolean.TRUE, acctDate); cal.setNegativeStockCorrection(Boolean.TRUE); cal.setUnitCost(Boolean.FALSE); OBDal.getInstance().save(cal); OBDal.getInstance().flush(); JSONObject message = CostAdjustmentProcess.doProcessCostAdjustment(costAdjustmentHeader); try { if (!"success".equals(message.get("severity"))) { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@") + ": " + costAdjustmentHeader.getDocumentNo() + " - " + message.getString("text")); } } catch (JSONException e) { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@")); } } // update trxCost after cost adjustments transaction = OBDal.getInstance().get(MaterialTransaction.class, transaction.getId()); trxCost = CostAdjustmentUtils.getTrxCost(transaction, false, getCostCurrency()); }
From source file:org.openbravo.costing.FixBackdatedTransactionsProcess.java
License:Open Source License
@Override protected JSONObject doExecute(Map<String, Object> parameters, String content) { costAdjHeader = null;//from www. j a v a 2 s .co m JSONObject jsonResponse = new JSONObject(); OBError msg = new OBError(); JSONObject jsonRequest; try { jsonRequest = new JSONObject(content); JSONObject jsonparams = jsonRequest.getJSONObject("_params"); final String ruleId = jsonRequest.getString("M_Costing_Rule_ID"); Date fixbackdatedfrom = null; CostingRule rule = OBDal.getInstance().get(CostingRule.class, ruleId); rule.setBackdatedTransactionsFixed(Boolean.TRUE); OBDal.getInstance().save(rule); if (jsonparams.has("fixbackdatedfrom") && !jsonparams.getString("fixbackdatedfrom").equals("null")) { try { final String repairedfixbackdatedfrom = JsonUtils .convertFromXSDToJavaFormat(jsonparams.getString("fixbackdatedfrom")); fixbackdatedfrom = JsonUtils.createDateTimeFormat().parse(repairedfixbackdatedfrom); } catch (ParseException ignore) { } } else { fixbackdatedfrom = CostingUtils.getCostingRuleStartingDate(rule); } rule.setFixbackdatedfrom(fixbackdatedfrom); try { OBContext.setAdminMode(false); if (rule.getStartingDate() != null && rule.getFixbackdatedfrom() != null && rule.isBackdatedTransactionsFixed() && rule.getFixbackdatedfrom().before(rule.getStartingDate())) { throw new OBException(OBMessageUtils.parseTranslation("@FixBackdateFromBeforeStartingDate2@")); } OrganizationStructureProvider osp = OBContext.getOBContext() .getOrganizationStructureProvider(rule.getClient().getId()); final Set<String> childOrgs = osp.getChildTree(rule.getOrganization().getId(), true); ScrollableResults transactions = getTransactions(childOrgs, fixbackdatedfrom, rule.getEndingDate()); int i = 0; try { while (transactions.next()) { MaterialTransaction trx = (MaterialTransaction) transactions.get()[0]; if (CostAdjustmentUtils.isNeededBackdatedCostAdjustment(trx, rule.isWarehouseDimension(), CostingUtils.getCostingRuleStartingDate(rule))) { createCostAdjustmenHeader(rule.getOrganization()); CostAdjustmentLine cal = CostAdjustmentUtils.insertCostAdjustmentLine(trx, costAdjHeader, null, Boolean.TRUE, trx.getMovementDate()); cal.setBackdatedTrx(Boolean.TRUE); OBDal.getInstance().save(cal); i++; OBDal.getInstance().flush(); if ((i % 100) == 0) { OBDal.getInstance().getSession().clear(); // Reload rule after clear session. rule = OBDal.getInstance().get(CostingRule.class, ruleId); } } } } finally { transactions.close(); } } catch (final Exception e) { OBDal.getInstance().rollbackAndClose(); String message = DbUtility.getUnderlyingSQLException(e).getMessage(); log4j.error(message, e); JSONObject errorMessage = new JSONObject(); errorMessage.put("severity", "error"); errorMessage.put("title", OBMessageUtils.messageBD("Error")); errorMessage.put("text", message); jsonResponse.put("message", errorMessage); return jsonResponse; } finally { OBContext.restorePreviousMode(); } if (costAdjHeader != null) { try { JSONObject message = CostAdjustmentProcess.doProcessCostAdjustment(costAdjHeader); if (message.get("severity") != "success") { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@") + ": " + costAdjHeader.getDocumentNo() + " - " + message.getString("text")); } msg.setType((String) message.get("severity")); msg.setTitle((String) message.get("title")); msg.setMessage((String) message.get("text")); } catch (JSONException e) { throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@")); } catch (Exception e) { OBDal.getInstance().rollbackAndClose(); String message = DbUtility.getUnderlyingSQLException(e).getMessage(); log4j.error(message, e); JSONObject errorMessage = new JSONObject(); errorMessage.put("severity", "error"); errorMessage.put("title", OBMessageUtils.messageBD("Error")); errorMessage.put("text", message); jsonResponse.put("message", errorMessage); return jsonResponse; } } else { msg.setType("Success"); msg.setMessage(OBMessageUtils.messageBD("Success")); } JSONObject errorMessage = new JSONObject(); errorMessage.put("severity", "success"); errorMessage.put("text", msg.getMessage()); jsonResponse.put("message", errorMessage); } catch (JSONException e2) { e2.printStackTrace(); } return jsonResponse; }
From source file:org.openbravo.costing.InventoryAmountUpdateProcess.java
License:Open Source License
@Override protected JSONObject execute(Map<String, Object> parameters, String data) { JSONObject result = new JSONObject(); JSONObject errorMessage = new JSONObject(); OBContext.setAdminMode(true);// w ww . ja v a2s . c o m try { final JSONObject jsonData = new JSONObject(data); String orgId = jsonData.getString("inpadOrgId"); String invAmtUpdId = jsonData.getString("M_Ca_Inventoryamt_ID"); InventoryAmountUpdate invAmtUpd = OBDal.getInstance().get(InventoryAmountUpdate.class, invAmtUpdId); final OBCriteria<InventoryAmountUpdateLine> qLines = OBDal.getInstance() .createCriteria(InventoryAmountUpdateLine.class); qLines.add(Restrictions.eq(InventoryAmountUpdateLine.PROPERTY_CAINVENTORYAMT, invAmtUpd)); ScrollableResults scrollLines = qLines.scroll(ScrollMode.FORWARD_ONLY); try { int cnt = 0; while (scrollLines.next()) { final InventoryAmountUpdateLine line = (InventoryAmountUpdateLine) scrollLines.get()[0]; String lineId = line.getId(); CostingRule rule = CostingUtils.getCostDimensionRule( OBDal.getInstance().get(Organization.class, orgId), line.getReferenceDate()); String ruleId = rule.getId(); OrganizationStructureProvider osp = OBContext.getOBContext() .getOrganizationStructureProvider(rule.getClient().getId()); final Set<String> childOrgs = osp.getChildTree(rule.getOrganization().getId(), true); if (!rule.isWarehouseDimension()) { createInventories(lineId, null, ruleId, childOrgs, line.getReferenceDate()); } else { createInventories(lineId, line.getWarehouse(), ruleId, childOrgs, line.getReferenceDate()); } if ((cnt++ % 10) == 0) { OBDal.getInstance().flush(); // clear session after each line iteration because the number of objects read in memory // is big OBDal.getInstance().getSession().clear(); } } invAmtUpd = OBDal.getInstance().get(InventoryAmountUpdate.class, invAmtUpdId); invAmtUpd.setProcessed(true); OBDal.getInstance().save(invAmtUpd); OBDal.getInstance().flush(); try { // to ensure that the closed inventory is created before opening inventory Thread.sleep(2000); } catch (InterruptedException e) { log.error("Error waiting between processing close an open inventories", e); } StringBuffer where = new StringBuffer(); where.append(" as inv"); where.append(" where exists ("); where.append(" select 1 from " + InvAmtUpdLnInventories.ENTITY_NAME + " invAmtUpd"); where.append(" where invAmtUpd." + InvAmtUpdLnInventories.PROPERTY_CAINVENTORYAMTLINE + "." + InventoryAmountUpdateLine.PROPERTY_CAINVENTORYAMT + ".id =:invAmtUpdId"); where.append(" and invAmtUpd." + InvAmtUpdLnInventories.PROPERTY_INITINVENTORY + "= inv)"); OBQuery<InventoryCount> qry = OBDal.getInstance().createQuery(InventoryCount.class, where.toString()); qry.setNamedParameter("invAmtUpdId", invAmtUpdId); ScrollableResults invLines = qry.scroll(ScrollMode.FORWARD_ONLY); try { while (invLines.next()) { final InventoryCount inventory = (InventoryCount) invLines.get()[0]; new InventoryCountProcess().processInventory(inventory, false, true); } } finally { invLines.close(); } } finally { scrollLines.close(); } errorMessage.put("severity", "success"); errorMessage.put("text", OBMessageUtils.messageBD("Success")); result.put("message", errorMessage); } catch (Exception e) { OBDal.getInstance().rollbackAndClose(); log.error(e.getMessage(), e); try { Throwable ex = DbUtility.getUnderlyingSQLException(e); String message = OBMessageUtils.translateError(ex.getMessage()).getMessage(); errorMessage = new JSONObject(); errorMessage.put("severity", "error"); errorMessage.put("title", OBMessageUtils.messageBD("Error")); errorMessage.put("text", message); result.put("message", errorMessage); } catch (Exception ignore) { } } finally { OBContext.restorePreviousMode(); } return result; }
From source file:org.openbravo.costing.InventoryAmountUpdateProcess.java
License:Open Source License
protected void createInventories(String lineId, Warehouse warehouse, String ruleId, Set<String> childOrgs, Date date) {//from w ww. ja v a 2 s. co m CostingRule costRule = OBDal.getInstance().get(CostingRule.class, ruleId); InventoryAmountUpdateLine line = OBDal.getInstance().get(InventoryAmountUpdateLine.class, lineId); ScrollableResults stockLines = getStockLines(childOrgs, date, line.getProduct(), warehouse, costRule.isBackdatedTransactionsFixed()); // The key of the Map is the concatenation of orgId and warehouseId Map<String, String> inventories = new HashMap<String, String>(); Map<String, Long> maxLineNumbers = new HashMap<String, Long>(); InventoryCountLine closingInventoryLine = null; InventoryCountLine openInventoryLine = null; int i = 1; try { while (stockLines.next()) { Object[] stockLine = stockLines.get(); String attrSetInsId = (String) stockLine[0]; String uomId = (String) stockLine[1]; String orderUOMId = (String) stockLine[2]; String locatorId = (String) stockLine[3]; String warehouseId = (String) stockLine[4]; BigDecimal qty = (BigDecimal) stockLine[5]; BigDecimal orderQty = (BigDecimal) stockLine[6]; // String invId = inventories.get(warehouseId); InvAmtUpdLnInventories inv = null; if (invId == null) { inv = createInventorieLine(line, warehouseId, date); inventories.put(warehouseId, inv.getId()); } else { inv = OBDal.getInstance().get(InvAmtUpdLnInventories.class, invId); } Long lineNo = (maxLineNumbers.get(invId) == null ? 0L : maxLineNumbers.get(invId)) + 10L; maxLineNumbers.put(invId, lineNo); if (BigDecimal.ZERO.compareTo(qty) < 0) { // Do not insert negative values in Inventory lines, instead reverse the Quantity Count // and the Book Quantity. For example: // Instead of CountQty=0 and BookQty=-5 insert CountQty=5 and BookQty=0 // By doing so the difference between both quantities remains the same and no negative // values have been inserted. openInventoryLine = insertInventoryLine(inv.getInitInventory(), line.getProduct().getId(), attrSetInsId, uomId, orderUOMId, locatorId, qty, BigDecimal.ZERO, orderQty, BigDecimal.ZERO, lineNo, null, line.getUnitCost()); insertInventoryLine(inv.getCloseInventory(), line.getProduct().getId(), attrSetInsId, uomId, orderUOMId, locatorId, BigDecimal.ZERO, qty, BigDecimal.ZERO, orderQty, lineNo, openInventoryLine, null); } else { openInventoryLine = insertInventoryLine(inv.getInitInventory(), line.getProduct().getId(), attrSetInsId, uomId, orderUOMId, locatorId, BigDecimal.ZERO, qty.negate(), BigDecimal.ZERO, orderQty == null ? null : orderQty, lineNo, closingInventoryLine, line.getUnitCost()); insertInventoryLine(inv.getCloseInventory(), line.getProduct().getId(), attrSetInsId, uomId, orderUOMId, locatorId, qty == null ? null : qty.negate(), BigDecimal.ZERO, orderQty == null ? null : orderQty, BigDecimal.ZERO, lineNo, openInventoryLine, null); } if ((i % 100) == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); // Reload line after clear session. line = OBDal.getInstance().get(InventoryAmountUpdateLine.class, lineId); } i++; } } finally { stockLines.close(); } // Process closing physical inventories. for (InvAmtUpdLnInventories inv : line.getInventoryAmountUpdateLineInventoriesList()) { new InventoryCountProcess().processInventory(inv.getCloseInventory(), false); } }
From source file:org.openbravo.costing.LandedCostDistributionByAmount.java
License:Open Source License
@Override public void distributeAmount(LandedCostCost lcCost, boolean isMatching) { // Calculate total amount of all receipt lines assigned to the landed cost. lcCost = (LandedCostCost) OBDal.getInstance().getProxy(LandedCostCost.ENTITY_NAME, lcCost.getId()); LandedCost landedCost = lcCost.getLandedCost(); // Get the currency of the Landed Cost Cost String strCurId = lcCost.getCurrency().getId(); String strOrgId = landedCost.getOrganization().getId(); Date dateReference = landedCost.getReferenceDate(); int precission = lcCost.getCurrency().getCostingPrecision().intValue(); BigDecimal baseAmt;// w ww . ja v a 2 s . c o m if (isMatching) { baseAmt = lcCost.getMatchingAmount().subtract(lcCost.getAmount()); } else { baseAmt = lcCost.getAmount(); } BigDecimal totalAmt = BigDecimal.ZERO; // Loop to get all receipts amounts and calculate the total. OBCriteria<LCReceipt> critLCRL = OBDal.getInstance().createCriteria(LCReceipt.class); critLCRL.add(Restrictions.eq(LCReceipt.PROPERTY_LANDEDCOST, landedCost)); ScrollableResults receiptCosts = getReceiptCosts(landedCost, false); int i = 0; try { while (receiptCosts.next()) { String strTrxCur = (String) receiptCosts.get()[2]; BigDecimal trxAmt = (BigDecimal) receiptCosts.get()[3]; if (!strTrxCur.equals(strCurId)) { trxAmt = getConvertedAmount(trxAmt, strTrxCur, strCurId, dateReference, strOrgId); } totalAmt = totalAmt.add(trxAmt); if (i % 100 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } i++; } } finally { receiptCosts.close(); } BigDecimal pendingAmt = baseAmt; // Loop to calculate the corresponding adjustment amount for each receipt line. receiptCosts = getReceiptCosts(landedCost, true); i = 0; while (receiptCosts.next()) { ShipmentInOutLine receiptline = OBDal.getInstance().get(ShipmentInOutLine.class, receiptCosts.get()[1]); String strTrxCurId = (String) receiptCosts.get()[2]; BigDecimal trxAmt = (BigDecimal) receiptCosts.get()[3]; if (!strTrxCurId.equals(strCurId)) { trxAmt = getConvertedAmount(trxAmt, strTrxCurId, strCurId, dateReference, strOrgId); } BigDecimal receiptAmt = BigDecimal.ZERO; if (receiptCosts.isLast()) { // Insert pending amount on receipt with higher cost to avoid rounding issues. receiptAmt = pendingAmt; } else { receiptAmt = baseAmt.multiply(trxAmt).divide(totalAmt, precission, RoundingMode.HALF_UP); } pendingAmt = pendingAmt.subtract(receiptAmt); LCReceipt lcrl = (LCReceipt) OBDal.getInstance().getProxy(LCReceipt.ENTITY_NAME, receiptCosts.get()[0]); LCReceiptLineAmt lcrla = OBProvider.getInstance().get(LCReceiptLineAmt.class); lcrla.setLandedCostCost( (LandedCostCost) OBDal.getInstance().getProxy(LandedCostCost.ENTITY_NAME, lcCost.getId())); lcCost = (LandedCostCost) OBDal.getInstance().getProxy(LandedCostCost.ENTITY_NAME, lcCost.getId()); lcrla.setLandedCostReceipt(lcrl); lcrla.setGoodsShipmentLine(receiptline); lcrla.setMatchingAdjustment(isMatching); lcrla.setAmount(receiptAmt); lcrla.setOrganization(lcCost.getOrganization()); OBDal.getInstance().save(lcrla); if (i % 100 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } i++; } }
From source file:org.openbravo.costing.LandedCostProcess.java
License:Open Source License
private CostAdjustment generateCostAdjustment(String strLandedCostId, JSONObject message) { LandedCost landedCost = OBDal.getInstance().get(LandedCost.class, strLandedCostId); Date referenceDate = landedCost.getReferenceDate(); CostAdjustment ca = CostAdjustmentUtils.insertCostAdjustmentHeader(landedCost.getOrganization(), "LC"); String strResult = OBMessageUtils.messageBD("LandedCostProcessed"); Map<String, String> map = new HashMap<String, String>(); map.put("documentNo", ca.getDocumentNo()); try {/*from w ww .j av a 2s . co m*/ message.put("title", OBMessageUtils.messageBD("Success")); message.put("text", OBMessageUtils.parseTranslation(strResult, map)); } catch (JSONException ignore) { } StringBuffer hql = new StringBuffer(); hql.append(" select sum(rla." + LCReceiptLineAmt.PROPERTY_AMOUNT + ") as amt"); hql.append(" , rla." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTCOST + ".currency.id as lcCostCurrency"); hql.append(" , rla." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + ".id as receipt"); hql.append(" , (select " + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " from " + MaterialTransaction.ENTITY_NAME + " as transaction where " + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + ".id = rla." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + ".id) as trxprocessdate"); hql.append(" from " + LCReceiptLineAmt.ENTITY_NAME + " as rla"); hql.append(" join rla." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTRECEIPT + " as rl"); hql.append(" where rl." + LCReceipt.PROPERTY_LANDEDCOST + " = :lc"); hql.append(" and rla." + LCReceiptLineAmt.PROPERTY_ISMATCHINGADJUSTMENT + " = false "); hql.append(" group by rla." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTCOST + ".currency.id"); hql.append(" , rla." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + ".id"); hql.append(" order by trxprocessdate, amt"); Query qryLCRLA = OBDal.getInstance().getSession().createQuery(hql.toString()); qryLCRLA.setParameter("lc", landedCost); ScrollableResults receiptamts = qryLCRLA.scroll(ScrollMode.FORWARD_ONLY); int i = 0; try { while (receiptamts.next()) { log.debug("Process receipt amounts"); Object[] receiptAmt = receiptamts.get(); BigDecimal amt = (BigDecimal) receiptAmt[0]; Currency lcCostCurrency = OBDal.getInstance().get(Currency.class, receiptAmt[1]); ShipmentInOutLine receiptLine = OBDal.getInstance().get(ShipmentInOutLine.class, receiptAmt[2]); // MaterialTransaction receiptLine = (MaterialTransaction) record[1]; MaterialTransaction trx = receiptLine.getMaterialMgmtMaterialTransactionList().get(0); CostAdjustmentLine cal = CostAdjustmentUtils.insertCostAdjustmentLine(trx, ca, amt, true, referenceDate); cal.setNeedsPosting(Boolean.FALSE); cal.setUnitCost(Boolean.FALSE); cal.setCurrency(lcCostCurrency); cal.setLineNo((i + 1) * 10L); OBDal.getInstance().save(cal); if (i % 100 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); ca = OBDal.getInstance().get(CostAdjustment.class, ca.getId()); } i++; } } finally { receiptamts.close(); } CostAdjustmentProcess.doProcessCostAdjustment(ca); return ca; }
From source file:org.openbravo.costing.LCMatchingProcess.java
License:Open Source License
private String generateCostAdjustment(String strLCCostId, JSONObject message) throws JSONException { LandedCostCost lcCost = OBDal.getInstance().get(LandedCostCost.class, strLCCostId); Date referenceDate = lcCost.getAccountingDate(); CostAdjustment ca = CostAdjustmentUtils.insertCostAdjustmentHeader(lcCost.getOrganization(), "LC"); String strResult = OBMessageUtils.messageBD("LCMatchingProcessed"); Map<String, String> map = new HashMap<String, String>(); map.put("documentNo", ca.getDocumentNo()); message.put("title", OBMessageUtils.messageBD("Success")); message.put("text", OBMessageUtils.parseTranslation(strResult, map)); StringBuffer hql = new StringBuffer(); hql.append(" select sum(rla." + LCReceiptLineAmt.PROPERTY_AMOUNT + ") as amt"); hql.append(" , rla." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + ".id as receipt"); hql.append(" , (select " + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " from " + MaterialTransaction.ENTITY_NAME + " as transaction where " + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + ".id = rla." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + ".id) as trxprocessdate"); hql.append(" from " + LCReceiptLineAmt.ENTITY_NAME + " as rla"); hql.append(" where rla." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTCOST + " = :lcc"); hql.append(" and rla." + LCReceiptLineAmt.PROPERTY_ISMATCHINGADJUSTMENT + " = true "); hql.append(" group by rla." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + ".id"); hql.append(" order by trxprocessdate, amt"); Query qryLCRLA = OBDal.getInstance().getSession().createQuery(hql.toString()); qryLCRLA.setParameter("lcc", lcCost); ScrollableResults receiptamts = qryLCRLA.scroll(ScrollMode.FORWARD_ONLY); int i = 0;//from www . j av a 2 s .c o m try { while (receiptamts.next()) { Object[] receiptAmt = receiptamts.get(); BigDecimal amt = (BigDecimal) receiptAmt[0]; ShipmentInOutLine receiptLine = OBDal.getInstance().get(ShipmentInOutLine.class, receiptAmt[1]); MaterialTransaction trx = receiptLine.getMaterialMgmtMaterialTransactionList().get(0); CostAdjustmentLine cal = CostAdjustmentUtils.insertCostAdjustmentLine(trx, ca, amt, true, referenceDate); cal.setNeedsPosting(Boolean.FALSE); cal.setUnitCost(Boolean.FALSE); cal.setCurrency(lcCost.getCurrency()); OBDal.getInstance().save(cal); if (i % 100 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); ca = OBDal.getInstance().get(CostAdjustment.class, ca.getId()); } i++; } } finally { receiptamts.close(); } ca = OBDal.getInstance().get(CostAdjustment.class, ca.getId()); CostAdjustmentProcess.doProcessCostAdjustment(ca); return ca.getId(); }
From source file:org.openbravo.costing.StandardCostAdjustment.java
License:Open Source License
@Override protected void getRelatedTransactionsByAlgorithm() { // Inventory opening transactions are the only transaction types that can generates a new // Standard Cost. Having a new Standard Cost on a backdated transaction forces to adjust the // cost off all the transactions from the backdated transaction to the next defined standard // cost./*from ww w . jav a 2 s . c om*/ if (trxType == TrxType.InventoryOpening) { // If it is a backdated transaction of an inventory opening, insert a new costing if the // standard cost is different than the unit cost of the inventory. MaterialTransaction trx = getTransaction(); BigDecimal unitCost = trx.getPhysicalInventoryLine().getCost().setScale(costCurPrecission, RoundingMode.HALF_UP); // Cost is effective on the beginning of the following date. Date backDatedTrxDate = CostAdjustmentUtils.getLastTrxDateOfMvmntDate(trx.getMovementDate(), trx.getProduct(), getCostOrg(), getCostDimensions()); if (backDatedTrxDate == null) { backDatedTrxDate = trx.getTransactionProcessDate(); } Costing stdCost = CostingUtils.getStandardCostDefinition(trx.getProduct(), getCostOrg(), backDatedTrxDate, getCostDimensions()); // Modify isManufacturingProduct flag in case it has changed at some point. isManufacturingProduct = ((String) DalUtil.getId(stdCost.getOrganization())).equals("0"); BigDecimal baseCurrentCost = stdCost.getCost(); if (!stdCost.getCurrency().equals(strCostCurrencyId)) { baseCurrentCost = FinancialUtils.getConvertedAmount(baseCurrentCost, stdCost.getCurrency(), getCostCurrency(), trx.getMovementDate(), getCostOrg(), "C"); } if (baseCurrentCost.compareTo(unitCost) == 0) { // If current cost is the same than the unit cost there is no need to create a new costing // so it is not needed to adjust any other transaction. return; } Costing newCosting = insertCost(stdCost, unitCost, backDatedTrxDate); // Adjust all transactions calculated with the previous costing. ScrollableResults trxs = getRelatedTransactions(newCosting.getStartingDate(), newCosting.getEndingDate()); int i = 1; try { while (trxs.next()) { MaterialTransaction relTrx = (MaterialTransaction) trxs.get()[0]; BigDecimal currentCost = CostAdjustmentUtils.getTrxCost(relTrx, true, trx.getCurrency()); BigDecimal expectedCost = relTrx.getMovementQuantity().abs().multiply(unitCost) .setScale(stdCurPrecission, RoundingMode.HALF_UP); if (expectedCost.compareTo(currentCost) != 0) { CostAdjustmentLine newCAL = insertCostAdjustmentLine(relTrx, expectedCost.subtract(currentCost), null); newCAL.setRelatedTransactionAdjusted(true); } if (i % 100 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } i++; } } finally { trxs.close(); } } }