tko_pb

GenerateSPD.java

Nov 19th, 2018
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.16 KB | None | 0 0
  1. package org.infinite.idolmart.process;
  2.  
  3. import java.math.BigDecimal;
  4. import java.math.RoundingMode;
  5. import java.sql.Connection;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.text.ParseException;
  10. import java.text.SimpleDateFormat;
  11. import java.util.Calendar;
  12. import java.util.Date;
  13. import java.util.HashMap;
  14. import java.util.List;
  15. import java.util.concurrent.TimeUnit;
  16.  
  17. import org.apache.log4j.Logger;
  18. import org.hibernate.criterion.Restrictions;
  19. import org.openbravo.base.exception.OBException;
  20. import org.openbravo.base.provider.OBProvider;
  21. import org.openbravo.dal.core.OBContext;
  22. import org.openbravo.dal.service.OBCriteria;
  23. import org.openbravo.dal.service.OBDal;
  24. import org.openbravo.erpCommon.utility.OBError;
  25. import org.openbravo.model.common.enterprise.Warehouse;
  26. import org.openbravo.model.common.plm.ApprovedVendor;
  27. import org.openbravo.model.common.plm.Product;
  28. import org.openbravo.scheduling.ProcessBundle;
  29. import org.openbravo.service.db.DalBaseProcess;
  30. import org.wirabumi.gen.oez.SalesPerformance;
  31.  
  32. import com.google.common.collect.HashBasedTable;
  33.  
  34. public class GenerateSPD extends DalBaseProcess {
  35.    
  36.     private static final Logger log4j = Logger.getLogger(GenerateSPD.class);
  37.    
  38.     @Override
  39.     protected void doExecute(ProcessBundle bundle) throws Exception {
  40.        
  41.         //get period
  42.         Period period = getPeriod(bundle);
  43.        
  44.         HashMap<Product, Long> leadtimeDC = getLeadTimeDC();
  45.         HashMap<Product, BigDecimal> ssDC = getSafetyStockDC();
  46.         HashBasedTable<Product, Warehouse, Long> leadtimeToko = getLeadTimeToko();
  47.         HashBasedTable<Product, Warehouse, BigDecimal> ssToko = getSafetyStockToko();
  48.        
  49.         //get distribution center
  50.         Warehouse dc = getDistributionCenter();
  51.         if (dc==null)
  52.             throw new OBException("Distribution center not found. Please set one of warehouse as distribution center.");
  53.        
  54.         //delete existing SPD
  55.         log4j.debug("deleting existing SPD");
  56.         deleteExistingSPD();
  57.         log4j.debug("existing SPD deleted");
  58.        
  59.         BigDecimal avgleadtimetoko = getAverageLeadTimeToko();
  60.         log4j.debug("average lead time toko "+avgleadtimetoko);
  61.        
  62.         HashMap<Product, BigDecimal> tsmDCMap = new HashMap<>();
  63.         HashMap<Product, BigDecimal> spdDCMap = new HashMap<>();
  64.        
  65.         //get total sales
  66.         String sql = "select a.m_warehouse_id, c.m_product_id, sum(c.qtyordered) as totalsales\n" +
  67.                 " from c_externalpos a\n" +
  68.                 " inner join c_order b on a.m_warehouse_id=b.m_warehouse_id and b.issotrx='Y' and b.processed='Y'\n" +
  69.                 " inner join c_orderline c on c.c_order_id=b.c_order_id\n" +
  70.                 " where a.ad_client_id=?\n" +
  71.                 " and b.dateordered>=?\n" +
  72.                 " and b.dateordered<=?\n" +
  73.                 " group by a.m_warehouse_id, c.m_product_id";
  74.         Connection conn = OBDal.getInstance().getConnection();
  75.         PreparedStatement ps = conn.prepareStatement(sql);
  76.         ps.setString(1, OBContext.getOBContext().getCurrentClient().getId());
  77.         ps.setDate(2, period.getFromSql());
  78.         ps.setDate(3, period.getToSql());
  79.         ResultSet rs = ps.executeQuery();
  80.         while (rs.next()) {
  81.             //untuk setiap toko
  82.             String warehouseID = rs.getString("m_warehouse_id");
  83.             Warehouse warehouse = OBDal.getInstance().get(Warehouse.class, warehouseID);
  84.             log4j.debug("processing warehouse "+warehouse.getName());
  85.             String productID = rs.getString("m_product_id");
  86.             Product product = OBDal.getInstance().get(Product.class, productID);
  87.             log4j.debug("processing product "+product.getName());
  88.             BigDecimal totalsales = rs.getBigDecimal("totalsales");
  89.             log4j.debug("total sales of "+product.getName()+" "+totalsales);
  90.             BigDecimal averagesales = totalsales.divide(new BigDecimal(period.getPeriod()), RoundingMode.HALF_DOWN);
  91.             log4j.debug("average sales of "+product.getName()+" "+averagesales);
  92.             SalesPerformance salesPerformance = OBProvider.getInstance().get(SalesPerformance.class);
  93.             salesPerformance.setWarehouse(warehouse);
  94.             salesPerformance.setProduct(product);
  95.             salesPerformance.setValidFromDate(period.getFrom());
  96.             salesPerformance.setValidToDate(period.getTo());
  97.             salesPerformance.setAverageDailySalesQTY(averagesales);
  98.            
  99.             BigDecimal spddc = averagesales;
  100.             if (spdDCMap.containsKey(product)) {
  101.                 spddc = spdDCMap.get(product);
  102.                 spddc = spddc.add(averagesales);
  103.             }
  104.             spdDCMap.put(product, spddc);
  105.             log4j.debug("SPD DC of "+product.getName()+" "+spddc);
  106.            
  107.             //TSM toko = SPD toko x (LT toko  +  SS toko)
  108.             BigDecimal leadtimetoko = BigDecimal.ZERO;
  109.             if (leadtimeToko.contains(product, warehouse))
  110.                 leadtimetoko = new BigDecimal(leadtimeToko.get(product, warehouse));
  111.             log4j.debug("lead time of "+product.getName()+" "+leadtimetoko);
  112.             BigDecimal sstoko = BigDecimal.ZERO;
  113.             if (ssToko.contains(product, warehouse))
  114.                     sstoko = ssToko.get(product, warehouse);
  115.             log4j.debug("SS toko of "+product.getName()+" "+sstoko);
  116.             BigDecimal faktorkali = leadtimetoko.add(sstoko);
  117.             BigDecimal tsm = averagesales.multiply(faktorkali);
  118.             log4j.debug("TSM of "+product.getName()+" "+tsm);
  119.             salesPerformance.setMaximumStock(tsm);
  120.            
  121.             //TSM DC = SPD DC x (LT toko  + LT DC + SS DC)
  122.             BigDecimal leadtimedc = BigDecimal.ZERO;
  123.             if (leadtimeDC.containsKey(product))
  124.                 leadtimedc = new BigDecimal(leadtimeDC.get(product));
  125.             log4j.debug("lead time DC of "+product.getName()+" "+leadtimedc);
  126.             BigDecimal ssdc = BigDecimal.ZERO;
  127.             if (ssDC.containsKey(product))
  128.                 ssdc = ssDC.get(product);
  129.             log4j.debug("SS DC of "+product.getName()+" "+ssdc);
  130.             BigDecimal tsmdc =  spddc.multiply(avgleadtimetoko.add(leadtimedc).add(ssdc));
  131.             tsmDCMap.put(product, tsmdc);
  132.             log4j.debug("TSM DC of "+product.getName()+" "+tsmdc);
  133.  
  134.             OBDal.getInstance().save(salesPerformance);
  135.         }
  136.        
  137.         //add record for TSM DC
  138.         for (Product product : spdDCMap.keySet()) {
  139.             BigDecimal spd = spdDCMap.get(product);
  140.             SalesPerformance salesPerformance = OBProvider.getInstance().get(SalesPerformance.class);
  141.             salesPerformance.setWarehouse(dc);
  142.             salesPerformance.setProduct(product);
  143.             salesPerformance.setValidFromDate(period.getFrom());
  144.             salesPerformance.setValidToDate(period.getTo());
  145.             salesPerformance.setAverageDailySalesQTY(spd);
  146.            
  147.             if (tsmDCMap.containsKey(product)) {
  148.                 BigDecimal tsm = tsmDCMap.get(product);
  149.                 salesPerformance.setMaximumStock(tsm);
  150.             }
  151.            
  152.             OBDal.getInstance().save(salesPerformance);
  153.         }
  154.        
  155.         OBDal.getInstance().commitAndClose();
  156.        
  157.         OBError msg = new OBError();
  158.         msg.setTitle("Success");
  159.         msg.setType("Success");
  160.         msg.setMessage("process executed successfully.");
  161.         bundle.setResult(msg);
  162.        
  163.     }
  164.  
  165.     private BigDecimal getAverageLeadTimeToko() throws SQLException {
  166.         String sql = "select coalesce(avg(a.delaymin),0) as avgleadtimetoko \n" +
  167.                 "from m_product_org a\n" +
  168.                 "inner join m_locator b on b.m_locator_id=a.m_locator_id\n" +
  169.                 "inner join m_warehouse c on c.m_warehouse_id=b.m_warehouse_id\n" +
  170.                 "inner join c_externalpos d on d.m_warehouse_id=c.m_warehouse_id --warehousenya selalu toko\n" +
  171.                 "where a.ad_client_id=?";
  172.        
  173.         Connection conn = OBDal.getInstance().getConnection();
  174.         PreparedStatement ps = conn.prepareStatement(sql);
  175.         ps.setString(1, OBContext.getOBContext().getCurrentClient().getId());
  176.         ResultSet rs = ps.executeQuery();
  177.         while (rs.next()) {
  178.             BigDecimal avgleadtimetoko = rs.getBigDecimal("avgleadtimetoko");
  179.             return avgleadtimetoko;
  180.         }
  181.        
  182.         return BigDecimal.ZERO;
  183.        
  184.     }
  185.  
  186.     private void deleteExistingSPD() throws SQLException {
  187.         String sql = "delete from oez_salespreformance where ad_client_id=?";
  188.         Connection conn = OBDal.getInstance().getConnection();
  189.         PreparedStatement ps = conn.prepareStatement(sql);
  190.         ps.setString(1, OBContext.getOBContext().getCurrentClient().getId());
  191.         ps.executeUpdate();
  192.         conn.commit();
  193.        
  194.     }
  195.  
  196.     private HashMap<Product, BigDecimal> getSafetyStockDC() {
  197.         HashMap<Product, BigDecimal> output = new HashMap<>();
  198.         OBCriteria<ApprovedVendor> approvedVendorCriteria = OBDal.getInstance().createCriteria(ApprovedVendor.class);
  199.         for (ApprovedVendor approvedVendor : approvedVendorCriteria.list()) {
  200.             output.put(approvedVendor.getProduct(), approvedVendor.getOezSafetystockindays());
  201.         }
  202.        
  203.         return output;
  204.     }
  205.  
  206.     private HashBasedTable<Product, Warehouse, BigDecimal> getSafetyStockToko() throws SQLException {
  207.         HashBasedTable<Product, Warehouse, BigDecimal> output = HashBasedTable.create();
  208.         String sql = "select a.m_warehouse_id, b.m_product_id, avg(b.em_oez_safetystockindays) as sstoko\n" +
  209.                 " from c_externalpos a\n" +
  210.                 " inner join m_warehouse c on c.m_warehouse_id=a.m_warehouse_id\n" +
  211.                 " inner join m_locator d on d.m_warehouse_id=a.m_warehouse_id\n" +
  212.                 " inner join m_product_org b on b.m_locator_id=d.m_locator_id\n" +
  213.                 " where a.ad_client_id=?\n" +
  214.                 " group by a.m_warehouse_id, b.m_product_id";
  215.        
  216.         Connection conn = OBDal.getInstance().getConnection();
  217.         PreparedStatement ps = conn.prepareStatement(sql);
  218.         ps.setString(1, OBContext.getOBContext().getCurrentClient().getId());
  219.         ResultSet rs = ps.executeQuery();
  220.         while (rs.next()) {
  221.             String warehouseID = rs.getString("m_warehouse_id");
  222.             Warehouse warehouse = OBDal.getInstance().get(Warehouse.class, warehouseID);
  223.             String productID = rs.getString("m_product_id");
  224.             Product product = OBDal.getInstance().get(Product.class, productID);
  225.             BigDecimal sstoko = rs.getBigDecimal("sstoko");
  226.             output.put(product, warehouse, sstoko);
  227.         }
  228.        
  229.         return output;
  230.     }
  231.  
  232.     private Period getPeriod(ProcessBundle bundle) throws ParseException {
  233.         //get params
  234.         String strvalidfrom = (String) bundle.getParams().get("validfrom");
  235.         String strvalidto = (String) bundle.getParams().get("validto");
  236.         SimpleDateFormat df = new SimpleDateFormat(bundle.getContext().getJavaDateFormat());
  237.  
  238.         Date validfrom = df.parse(strvalidfrom);
  239.         Date validto = df.parse(strvalidto);
  240.  
  241.         if (validfrom==null || validto==null) {
  242.             //run from background
  243.             Calendar cal = Calendar.getInstance();
  244.             cal.set(Calendar.HOUR, 0);
  245.             cal.set(Calendar.MINUTE, 0);
  246.             cal.set(Calendar.SECOND, 0);
  247.             cal.set(Calendar.MILLISECOND, 0);
  248.             validto = cal.getTime();
  249.             validfrom = cal.getTime();
  250.         }
  251.  
  252.         java.sql.Date validfromsql = new java.sql.Date(validfrom.getTime());
  253.         java.sql.Date validtosql = new java.sql.Date(validto.getTime());
  254.  
  255.         //get period
  256.         long timediff = validto.getTime()-validfrom.getTime();
  257.         long periodl = TimeUnit.DAYS.convert(timediff, TimeUnit.MILLISECONDS) + 1;
  258.         Period period = new Period(validfrom, validto, validfromsql, validtosql, periodl);
  259.         return period;
  260.     }
  261.  
  262.     private Warehouse getDistributionCenter() {
  263.         OBCriteria<Warehouse> whCriteria = OBDal.getInstance().createCriteria(Warehouse.class);
  264.         whCriteria.add(Restrictions.eq(Warehouse.PROPERTY_OEZIDDISTRIBUTIONCENTER, true));
  265.         whCriteria.setFetchSize(1);
  266.         List<Warehouse> whList = whCriteria.list();
  267.         if (whList.size()>0)
  268.             return whList.get(0);
  269.         return null;
  270.     }
  271.  
  272.     private HashBasedTable<Product, Warehouse, Long> getLeadTimeToko() throws SQLException {
  273.         HashBasedTable<Product, Warehouse, Long> output = HashBasedTable.create();
  274.         String sql = "select a.m_warehouse_id, b.m_product_id, avg(b.delaymin) as leadtimetoko\n" +
  275.                 " from c_externalpos a\n" +
  276.                 " inner join m_warehouse c on c.m_warehouse_id=a.m_warehouse_id\n" +
  277.                 " inner join m_locator d on d.m_warehouse_id=a.m_warehouse_id\n" +
  278.                 " inner join m_product_org b on b.m_locator_id=d.m_locator_id\n" +
  279.                 " where a.ad_client_id=?\n" +
  280.                 " group by a.m_warehouse_id, b.m_product_id";
  281.        
  282.         Connection conn = OBDal.getInstance().getConnection();
  283.         PreparedStatement ps = conn.prepareStatement(sql);
  284.         ps.setString(1, OBContext.getOBContext().getCurrentClient().getId());
  285.         ResultSet rs = ps.executeQuery();
  286.         while (rs.next()) {
  287.             String warehouseID = rs.getString("m_warehouse_id");
  288.             Warehouse warehouse = OBDal.getInstance().get(Warehouse.class, warehouseID);
  289.             String productID = rs.getString("m_product_id");
  290.             Product product = OBDal.getInstance().get(Product.class, productID);
  291.             Long leadtimetoko = rs.getLong("leadtimetoko");
  292.             output.put(product, warehouse, leadtimetoko);
  293.         }
  294.        
  295.         return output;
  296.     }
  297.  
  298.     private HashMap<Product, Long> getLeadTimeDC() {
  299.         HashMap<Product, Long> output = new HashMap<>();
  300.         OBCriteria<ApprovedVendor> approvedVendorCriteria = OBDal.getInstance().createCriteria(ApprovedVendor.class);
  301.         for (ApprovedVendor approvedVendor : approvedVendorCriteria.list()) {
  302.             output.put(approvedVendor.getProduct(), approvedVendor.getPurchasingLeadTime());
  303.         }
  304.        
  305.         return output;
  306.     }
  307.    
  308.     //private nested class (aka struc) of period
  309.     private class Period{
  310.         private final Date from;
  311.         private final Date to;
  312.         private final java.sql.Date fromSql;
  313.         private final java.sql.Date toSql;
  314.         private long period;
  315.         public Date getFrom() {
  316.             return from;
  317.         }
  318.         public Date getTo() {
  319.             return to;
  320.         }
  321.         public java.sql.Date getFromSql() {
  322.             return fromSql;
  323.         }
  324.         public java.sql.Date getToSql() {
  325.             return toSql;
  326.         }
  327.         public long getPeriod() {
  328.             return period;
  329.         }
  330.         public Period(Date from, Date to, java.sql.Date fromSql, java.sql.Date toSql, long period) {
  331.             super();
  332.             this.from = from;
  333.             this.to = to;
  334.             this.fromSql = fromSql;
  335.             this.toSql = toSql;
  336.             this.period = period;
  337.         }
  338.        
  339.     }
  340.  
  341. }
Add Comment
Please, Sign In to add comment