Advertisement
aadddrr

FindSalesOrderInfoForApprovalForIndocom

Nov 22nd, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.40 KB | None | 0 0
  1. package org.jleaf.erp.sls.bo.salesorder;
  2.  
  3. import java.math.BigDecimal;
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.text.DecimalFormat;
  8. import java.text.NumberFormat;
  9. import java.util.ArrayList;
  10. import java.util.Arrays;
  11. import java.util.List;
  12.  
  13. import javax.persistence.Query;
  14.  
  15. import org.jleaf.core.AbstractBusinessFunction;
  16. import org.jleaf.core.BusinessFunction;
  17. import org.jleaf.core.Dto;
  18. import org.jleaf.core.GeneralConstants;
  19. import org.jleaf.core.annotation.ErrorList;
  20. import org.jleaf.core.annotation.Info;
  21. import org.jleaf.core.annotation.InfoIn;
  22. import org.jleaf.core.annotation.InfoOut;
  23. import org.jleaf.core.dao.QueryBuilder;
  24. import org.jleaf.erp.master.entity.Partner;
  25. import org.jleaf.erp.master.entity.SellPriceProductForSo;
  26. import org.jleaf.erp.sls.SalesConstants;
  27. import org.jleaf.erp.sls.dao.SalesOrderDao;
  28. import org.jleaf.erp.sls.entity.SalesOrder;
  29. import org.jleaf.erp.sls.entity.SalesOrderExternalCommission;
  30. import org.jleaf.erp.sls.entity.SalesOrderItem;
  31. import org.jleaf.erp.sls.entity.SalesOrderItemPurchasing;
  32. import org.jleaf.util.Calc;
  33. import org.jleaf.util.DateUtil;
  34. import org.jleaf.util.DtoUtil;
  35. import org.jleaf.util.ValidationUtil;
  36. import org.springframework.beans.factory.annotation.Autowired;
  37. import org.springframework.jdbc.core.JdbcTemplate;
  38. import org.springframework.stereotype.Service;
  39.  
  40.  
  41. /**
  42.  * Find Sales Order Info For appproval purpose
  43.  *
  44.  * @author fredie, 27 Feb 2014
  45.  * @version 1.0
  46.  */
  47.  
  48. //@ formatter:off
  49. @Service("findSalesOrderInfoForApproval")
  50. @InfoIn(value = {
  51.     @Info(name="sessionId", description="Session Id", type=String.class, required=true),
  52.     @Info(name="userId", description="User Id", type=Long.class, required=true),
  53.     @Info(name="roleId", description="Role Id", type=Long.class, required=true),
  54.     @Info(name="soId", description="Sales Order Id", type=Long.class, required=true),
  55.     @Info(name="datetime", description="Datetime", type=String.class, required=true),
  56.     @Info(name = "arCurrCode", description = "AR curr code", type = String.class)
  57. })
  58. @InfoOut(value = {
  59.     @Info(name = "soId", description = "Sales Order Id", type = Long.class),
  60.     @Info(name = "totalNettAmount", description = "Total nett amount", type = Double.class),
  61.     @Info(name = "totalpurchAmount", description = "Total Purchasing Amount", type = Double.class),
  62.     @Info(name = "totalCurrCode", description = "Curr Code of totalNettAmount", type = String.class),
  63.     @Info(name = "gpPercentage", description = "GP Percentage", type = Double.class),
  64.     @Info(name = "gpAmount", description = "GP Amount", type = Double.class),
  65.     @Info(name = "arAmount", description = "AR Amount", type = Double.class),
  66.     @Info(name = "arCurrCode", description = "AR curr code", type = String.class),
  67.     @Info(name = "currCodeAr", description = "curr code AR", type = String.class),
  68.     @Info(name = "amountAr", description = "Amount AR", type = Double.class),
  69.     @Info(name = "notYetDueArAmount", description = "Not Yet Due Ar Amount", type = Double.class),
  70.     @Info(name = "currentArAmount", description = "Current AR Amount", type = Double.class),
  71.     @Info(name = "overdueArAmount", description = "Overdue AR Amount", type = Double.class),
  72.     @Info(name = "comparePriceString", description = "Compare Price String", type = String.class),
  73.     @Info(name = "flagFaultComparePrice", description = "Flag Fault Compare Price", type = Long.class)
  74. })
  75. @ErrorList(errorKeys = {
  76.  
  77.  })
  78. //@ formatter:on
  79. public class FindSalesOrderInfoForApprovalForIndocom extends AbstractBusinessFunction implements BusinessFunction {
  80.      
  81.     @Autowired
  82.     SalesOrderDao salesOrderDao;
  83.    
  84.     @Autowired
  85.     private JdbcTemplate jdbcTemplate;
  86.      
  87.     @Override
  88.     public String getDescription() {
  89.          return "Find Sales Order Info For appproval purpose";
  90.     }
  91.      
  92.     @SuppressWarnings("unchecked")
  93.     @Override
  94.     public Dto execute(Dto inputDto) throws Exception {    
  95.         ValidationUtil.valDtoContainsKey(inputDto, "soId");
  96.         ValidationUtil.valDtoContainsKey(inputDto, "arCurrCode");
  97.         ValidationUtil.valDtoContainsKey(inputDto, "datetime");
  98.         ValidationUtil.valDatetime(inputDto, "datetime");
  99.        
  100.         Long soId = inputDto.getLong("soId");
  101.         String arCurrCode = inputDto.getString("arCurrCode");
  102.         String datetime = inputDto.getString("datetime");
  103.         String date = datetime.substring(0, 8);
  104.        
  105.         Dto outputDto = new Dto();
  106.          
  107.         // get summary nettItemAmount
  108.         QueryBuilder builderNettAmount = new QueryBuilder();
  109.         builderNettAmount.add(" SELECT SUM(A.nett_item_amount) AS total_nett_amount, A.curr_code, B.partner_id, B.tenant_id, B.ou_id ")
  110.             .add(" FROM " + SalesOrderItem.TABLE_NAME + " A ")
  111.             .add(" INNER JOIN "+ SalesOrder.TABLE_NAME+" B ON A.so_id = B.so_id " )
  112.             .add(" WHERE A.so_id = :soId ")
  113.             .add(" GROUP BY A.curr_code, B.partner_id, B.tenant_id, B.ou_id ");
  114.            
  115.         Query queryNettAmount = salesOrderDao.createNativeQuery(builderNettAmount.toString());
  116.         queryNettAmount.setParameter("soId", soId);
  117.          
  118.         List<Object[]> resultNettAmount = queryNettAmount.getResultList();
  119.         Double totalNettAmount = 0d;
  120.         String totalCurrCode = GeneralConstants.EMPTY_VALUE;
  121.         Long partnerId  = GeneralConstants.NULL_REF_VALUE_LONG;
  122.         Long tenantId  = GeneralConstants.NULL_REF_VALUE_LONG;
  123.         Long ouId  = GeneralConstants.NULL_REF_VALUE_LONG;
  124.        
  125.         if(resultNettAmount!=null && resultNettAmount.size()>0){
  126.             List<Dto> resultNettAmountList = new ArrayList<Dto>();
  127.             resultNettAmountList = DtoUtil.createDtoListFromArray(resultNettAmount, "totalNettAmount", "totalCurrCode", "partnerId", "tenantId", "ouId");
  128.            
  129.             totalNettAmount = resultNettAmountList.get(0).getDouble("totalNettAmount");
  130.             totalCurrCode = resultNettAmountList.get(0).getString("totalCurrCode");
  131.             partnerId = resultNettAmountList.get(0).getLong("partnerId");
  132.             tenantId = resultNettAmountList.get(0).getLong("tenantId");
  133.             ouId = resultNettAmountList.get(0).getLong("ouId");
  134.         }
  135.        
  136.         totalNettAmount = new Calc(totalNettAmount).doubleValue();
  137.        
  138.         // get purcha and GP
  139.         QueryBuilder builderGp = new QueryBuilder();
  140.         builderGp
  141.             .add(" WITH summary_purch_per_currency AS (")
  142.             .add("  SELECT SUM(A.price * B.qty_int) AS total_price_purch, A.curr_code AS curr_code_purch, B.curr_code AS curr_code_so ")
  143.             .add("  FROM "+SalesOrderItemPurchasing.TABLE_NAME+" A ")
  144.             .add("  INNER JOIN "+SalesOrderItem.TABLE_NAME+" B ON A.so_item_id = B.so_item_id ")
  145.             .add("  WHERE B.so_id = :soId ")
  146.             .add("  GROUP BY A.curr_code, B.curr_code ")
  147.             .add(" ) ")
  148.             .add(" SELECT COALESCE(SUM(f_get_amount_in_nearest_com_rate(:tenantId, A.total_price_purch, :date, A.curr_code_purch, A.curr_code_so )), 0) AS total_price_as_so_currency ")
  149.             .add(" FROM summary_purch_per_currency A ");
  150.  
  151.         Double totalpurchAmount = 0d;
  152.         Query queryGp = salesOrderDao.createNativeQuery(builderGp.toString());
  153.         queryGp.setParameter("tenantId", tenantId);
  154.         queryGp.setParameter("date", date);
  155.         queryGp.setParameter("soId", soId);
  156.  
  157.         Object resultQueryGp = queryGp.getSingleResult();
  158.         if(resultQueryGp!=null ){
  159.             totalpurchAmount = Double.valueOf(resultQueryGp.toString());
  160.         }
  161.        
  162.        
  163.         // get external commission
  164.         QueryBuilder builderExtComm = new QueryBuilder();
  165.         builderExtComm
  166.             .add(" SELECT COALESCE(SUM(B.commission_amount * f_commercial_rate(A.tenant_id, A.doc_date, B.commission_curr_code, A.curr_code)),0) AS ext_comm_amount FROM ")
  167.             .add(SalesOrder.TABLE_NAME)
  168.             .add(" A ")
  169.             .add(" INNER JOIN ")
  170.             .add(SalesOrderExternalCommission.TABLE_NAME)
  171.             .add(" B ON A.so_id=B.so_id AND A.tenant_id = B.tenant_id ")
  172.             .add(" WHERE A.so_id = :soId AND A.tenant_id = :tenantId ");
  173.        
  174.         Double extCommAmount = 0d;
  175.         Query queryExtComm = salesOrderDao.createNativeQuery(builderExtComm.toString());
  176.         queryExtComm.setParameter("soId", soId);
  177.         queryExtComm.setParameter("tenantId", tenantId);
  178.        
  179.         Object resultExtComm = queryExtComm.getSingleResult();
  180.         if(resultExtComm!=null ){
  181.             extCommAmount = Double.valueOf(resultExtComm.toString());
  182.         }
  183.        
  184.         Double gpAmount = new Calc(totalNettAmount).subtract(extCommAmount).subtract(totalpurchAmount).doubleValue();
  185.         Double gpPercentage = 0d;
  186.        
  187.         /**
  188.          * Modify By Henik , Nov 19 , 2015
  189.          * -> modify untuk perhitungan gpPercentage yang sebelum nya gpPercentage = (selisih harga jual - harga ref beli) / harga beli
  190.          * sekarang di ubah gpPercentage = (selsih harga jual - harga bref beli) / harga jual
  191.          */
  192.         // lakukan perhitungan GP lebih lanjut, jika dan hanya jika, total amount purch tidak 0 (nol), tuk menghindari divide by zero
  193.         if (totalpurchAmount.compareTo(0d) != 0) {
  194.             gpPercentage = new Calc(gpAmount).multiply(100).divide(totalNettAmount, BigDecimal.ROUND_HALF_UP, 2).doubleValue();
  195.         }
  196.        
  197.         // get ar amount
  198.         QueryBuilder builderArAmount = new QueryBuilder();
  199.         builderArAmount
  200.             .add(" WITH all_currency_invoice_ar AS ( ")
  201.             .add("      SELECT SUM(A.amount - A.payment_amount) AS ar_amount, A.curr_code ")
  202.             .add("      FROM vw_fi_all_invoice_ar A ")
  203.             .add("      WHERE A.partner_id = :partnerId ")
  204.             .add("          AND A.flg_payment IN (:flgPayments) ")
  205.             .add("      GROUP BY A.curr_code, A.flg_payment ")
  206.             .add(" ), current_os_invoice_ar AS ( ")
  207.             .add("      SELECT SUM( f_get_amount_in_nearest_com_rate(:tenantId, A.ar_amount, :date, A.curr_code, :arCurrCode ) ) AS total_ar_amount ")
  208.             .add("      FROM all_currency_invoice_ar A")
  209.             .add(" ) SELECT COALESCE(A.total_ar_amount, 0) ")
  210.             .add(" FROM current_os_invoice_ar A ");
  211.         Query queryArAmount = salesOrderDao.createNativeQuery(builderArAmount.toString());
  212.         queryArAmount.setParameter("partnerId", partnerId);
  213.         queryArAmount.setParameter("tenantId", tenantId);
  214.         queryArAmount.setParameter("date", date);
  215.         queryArAmount.setParameter("arCurrCode", arCurrCode);
  216.         queryArAmount.setParameter("flgPayments", Arrays.asList(new String[] {SalesConstants.IN_PROGRESS_TRANSACTION, GeneralConstants.NO}));
  217.  
  218.         Object resultArAmount = queryArAmount.getSingleResult();
  219.         Double arAmount = Double.valueOf(resultArAmount.toString());
  220.                
  221.         outputDto.put("soId", soId);
  222.         outputDto.put("totalNettAmount", Double.valueOf(new DecimalFormat("#.00").format(totalNettAmount)));
  223.         outputDto.put("totalpurchAmount", totalpurchAmount);
  224.         outputDto.put("totalCurrCode", totalCurrCode);
  225.         outputDto.put("extCommAmount", extCommAmount);
  226.         outputDto.put("gpPercentage", Double.valueOf(new DecimalFormat("#.00").format(gpPercentage)));
  227.         outputDto.put("gpAmount", Double.valueOf(new DecimalFormat("#.00").format(gpAmount)));
  228.         outputDto.put("arAmount", Double.valueOf(new DecimalFormat("#.00").format(arAmount)));
  229.         outputDto.put("arCurrCode", arCurrCode);
  230.        
  231.         //not yet due dan overdue ar amount
  232.         Connection conn = jdbcTemplate.getDataSource().getConnection();
  233.         conn.setAutoCommit(false);
  234.         PreparedStatement stm = null;
  235.  
  236.         try {
  237.  
  238.             String sessionId = inputDto.getString("sessionId");
  239.             Long userId = inputDto.getLong("userId");
  240.             Long roleId = inputDto.getLong("roleId");
  241.             String dueDateType = GeneralConstants.EMPTY_VALUE;
  242.             String dueDateFrom = GeneralConstants.START_DATE;
  243.             String dueDateTo = GeneralConstants.END_DATE;
  244.             String dateNow = DateUtil.dateNow();
  245.  
  246.             stm = conn.prepareStatement("SELECT f_get_summary_aging_ar_list_for_inquiry_progress_ar(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  247.             stm.setString(1, sessionId);
  248.             stm.setLong(2, tenantId);
  249.             stm.setLong(3, ouId);
  250.             stm.setLong(4, userId);
  251.             stm.setLong(5, roleId);
  252.             stm.setLong(6, partnerId);
  253.             stm.setString(7, dueDateType);
  254.             stm.setString(8, dueDateFrom);
  255.             stm.setString(9, dueDateTo);
  256.             stm.setString(10, dateNow);
  257.  
  258.             ResultSet resultSetFromFunction = stm.executeQuery();
  259.             ResultSet resultSetFromQuery = null;
  260.             if (resultSetFromFunction.next()) {
  261.                 resultSetFromQuery = (ResultSet) resultSetFromFunction.getObject(1);
  262.             }
  263.  
  264.             resultSetFromFunction.close();
  265.  
  266.             Dto detailDto = new Dto();
  267.  
  268.             while (resultSetFromQuery != null && resultSetFromQuery.next()) {
  269.                 detailDto.put("currCodeAr", resultSetFromQuery.getString(1));
  270.                 detailDto.put("amountAr", resultSetFromQuery.getBigDecimal(2).doubleValue());
  271.                 detailDto.put("notYetDueArAmount", resultSetFromQuery.getBigDecimal(3).doubleValue());
  272.                 detailDto.put("currentArAmount", resultSetFromQuery.getBigDecimal(4).doubleValue());
  273.                 detailDto.put("overdueArAmount", resultSetFromQuery.getBigDecimal(5).doubleValue());
  274.             }
  275.  
  276.             stm.close();
  277.             conn.commit();
  278.             conn.close();
  279.  
  280.             outputDto.putAll(detailDto);
  281.  
  282.         } catch (Exception e) {
  283.             if (stm != null)
  284.                 stm.close();
  285.  
  286.             if (conn != null && !conn.isClosed())
  287.                 conn.rollback();
  288.  
  289.             throw e;
  290.         }
  291.        
  292.         // compare gross price product from m_sell_price_product_for_so
  293.         //select, trus loop, trus tampung di stringbuilder product_code dan gross_price kedua table
  294.         int preferredFractionDigits = 2;
  295.         NumberFormat formatter = NumberFormat.getNumberInstance();
  296.         formatter.setMinimumFractionDigits(preferredFractionDigits);
  297.        
  298.         QueryBuilder builderComparePrice = new QueryBuilder();
  299.         builderComparePrice.add(" SELECT A.product_id, f_get_product_code(A.product_id) AS product_code, B.curr_code AS curr_code_for_so, B.gross_sell_price AS sell_price_for_so, A.gross_sell_price AS so_sell_price, A.curr_code AS so_curr_code FROM ")
  300.         .add(SalesOrderItem.TABLE_NAME)
  301.         .add(" A INNER JOIN ").add(SellPriceProductForSo.TABLE_NAME).add(" B ON A.product_id = B.product_id ")
  302.         .add(" INNER JOIN ").add(SalesOrder.TABLE_NAME).add(" C ON A.so_id=C.so_id AND B.tenant_id = C.tenant_id AND B.ou_id = C.ou_id ")
  303.         .add(" INNER JOIN ").add(Partner.TABLE_NAME).add(" D ON C.partner_id = D.partner_id ")
  304.         .add(" WHERE A.gross_sell_price < B.gross_sell_price ")
  305.         .add(" AND B.curr_code = A.curr_code ")
  306.         .add(" AND C.doc_date BETWEEN B.date_from AND B.date_to ")
  307.         .add(" AND B.price_level = D.price_level ")
  308.         .add(" AND C.so_id = :soId ");
  309.  
  310.         Query queryComparePrice = salesOrderDao.createNativeQuery(builderComparePrice.toString());
  311.         queryComparePrice.setParameter("soId", soId);
  312.  
  313.         List<Object[]> resultComparePrice = queryComparePrice.getResultList();
  314.         StringBuilder comparePriceString = new StringBuilder();
  315.         Long productId  = GeneralConstants.NULL_REF_VALUE_LONG;
  316.         String productCode = GeneralConstants.EMPTY_VALUE;
  317.         String currCodeForSo = GeneralConstants.EMPTY_VALUE;
  318.         Double sellPriceForSo  = 0d;
  319.         Double soSellPrice  = 0d;
  320.         String soCurrCode = GeneralConstants.EMPTY_VALUE;
  321.         Long flagFaultComparePrice = 0L;
  322.  
  323.         if(resultComparePrice!=null && resultComparePrice.size()>0){
  324.             List<Dto> resultComparePriceList = new ArrayList<Dto>();
  325.             resultComparePriceList = DtoUtil.createDtoListFromArray(resultComparePrice, "productId", "productCode", "currCodeForSo", "sellPriceForSo", "soSellPrice", "soCurrCode");
  326.  
  327.             for (Dto dto : resultComparePriceList) {
  328.                 productId = dto.getLong("productId");
  329.                 productCode = dto.getString("productCode");
  330.                 currCodeForSo = dto.getString("currCodeForSo");
  331.                 sellPriceForSo = dto.getDouble("sellPriceForSo");
  332.                 soSellPrice = dto.getDouble("soSellPrice");
  333.                 soCurrCode = dto.getString("soCurrCode");
  334.  
  335.                 flagFaultComparePrice = 1L;
  336.                 comparePriceString.append("Product with code ").append(productCode).append(" SO Price(").append(soCurrCode).append(" ").append(formatter.format(Double.valueOf(soSellPrice))).append(") is below default product sell price(").append(currCodeForSo).append(" ").append(formatter.format(Double.valueOf(sellPriceForSo))).append(") \n");
  337.             }
  338.         }
  339.         outputDto.put("comparePriceString", comparePriceString.toString());
  340.         outputDto.put("flagFaultComparePrice", flagFaultComparePrice);
  341.        
  342.         return outputDto;
  343.      }
  344.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement