Advertisement
tko_pb

GenerateSPD 21 nov.java

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