Advertisement
samuel025

BT Add DO

Nov 28th, 2021
618
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 34.14 KB | None | 0 0
  1. package org.jleaf.erp.sls.bo.deliveryorder;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Map.Entry;
  8.  
  9. import javax.persistence.Query;
  10.  
  11. import org.jleaf.common.CommonExceptionConstants;
  12. import org.jleaf.core.BusinessFunction;
  13. import org.jleaf.core.BusinessTransaction;
  14. import org.jleaf.core.CoreException;
  15. import org.jleaf.core.DefaultBusinessTransaction;
  16. import org.jleaf.core.Dto;
  17. import org.jleaf.core.GeneralConstants;
  18. import org.jleaf.core.annotation.ErrorList;
  19. import org.jleaf.core.annotation.Info;
  20. import org.jleaf.core.annotation.InfoIn;
  21. import org.jleaf.core.annotation.InfoOut;
  22. import org.jleaf.core.dao.QueryBuilder;
  23. import org.jleaf.erp.inv.dao.ProductBalanceStockDao;
  24. import org.jleaf.erp.inv.entity.ProductBalanceStock;
  25. import org.jleaf.erp.master.MasterConstants;
  26. import org.jleaf.erp.master.MasterExceptionConstants;
  27. import org.jleaf.erp.master.bo.ComboIdMasterConstants;
  28. import org.jleaf.erp.sls.SalesConstants;
  29. import org.jleaf.erp.sls.SalesExceptionConstants;
  30. import org.jleaf.erp.sls.dao.DeliveryOrderDao;
  31. import org.jleaf.erp.sls.dao.DeliveryOrderItemDao;
  32. import org.jleaf.erp.sls.dao.DeliveryOrderProductDao;
  33. import org.jleaf.erp.sls.dao.SalesOrderBalanceItemDao;
  34. import org.jleaf.erp.sls.entity.DeliveryOrder;
  35. import org.jleaf.erp.sls.entity.DeliveryOrderItem;
  36. import org.jleaf.erp.sls.entity.DeliveryOrderProduct;
  37. import org.jleaf.erp.sls.entity.SalesOrderBalanceItem;
  38. import org.jleaf.util.Calc;
  39. import org.jleaf.util.DtoUtil;
  40. import org.jleaf.util.GsonUtil;
  41. import org.jleaf.util.ValidationUtil;
  42. import org.jleaf.validator.CommonBusinessValidator;
  43. import org.slf4j.Logger;
  44. import org.slf4j.LoggerFactory;
  45. import org.springframework.beans.factory.annotation.Autowired;
  46. import org.springframework.beans.factory.annotation.Qualifier;
  47. import org.springframework.stereotype.Service;
  48.  
  49. /**
  50.  *
  51.  * @see http://jleaf.org:8181/browse/SLSSVC-38
  52.  * modified by Fredi, 7 Agustus 2014
  53.  * flgDelivery, partnerShipToId, dan partnerShipAddressId
  54.  * tidak diinput, melainkan diset dari Sales Order terkait (dengan demikian, pada info-in juga perlu dihapus)
  55.  *
  56.  * Modified Fitra 2018 Jan 4,
  57.  * Update balance product stock diganti menggunakan native query
  58.  */
  59. //@formatter:off
  60. @Service
  61. @InfoIn(value = {
  62.         @Info(name = "docNo", description = "Doc No", type = String.class),
  63.         @Info(name = "docDate", description = "Doc Date", type = String.class),
  64.         @Info(name = "ouId", description = "Ou id", type = Long.class),
  65.         @Info(name = "warehouseId", description = "Warehouse id", type = Long.class),
  66. //      @Info(name = "partnerShipToId", description = "Partner Ship to id", type = Long.class),
  67. //      @Info(name = "partnerShipAddressId", description = "Partner Ship address id", type = Long.class),
  68.         @Info(name = "deliveryCode", description = "Delivery code", type = String.class),
  69.         @Info(name = "remark", description = "Remark", type = String.class),
  70.         @Info(name = "refId", description = "refId (So Id)", type = Long.class),
  71.         @Info(name = "itemList", description = "list of do item(lineNo, productId, productName, productStatus, refId, qtyDlvInt)", type = List.class),
  72.         @Info(name = "eta", description = "Eta", type = String.class),
  73.         @Info(name = "etaDay", description = "Eta day", type = String.class),
  74.         @Info(name = "tenantLoginId", description = "Tenant login id", type = Long.class),
  75.         @Info(name = "userLoginId", description = "User login id", type = Long.class),
  76.         @Info(name = "roleLoginId", description = "User login id", type = Long.class),
  77.         @Info(name = "datetime", description = "Datetime", type = String.class)    
  78. })
  79. @InfoOut(value = {
  80.         @Info(name = "id", description = "Do id", type = Long.class),
  81.         @Info(name = "docNo", description = "Doc no", type = String.class),
  82.         @Info(name = "docDate", description = "Doc date", type = String.class),
  83.         @Info(name = "ouId", description = "Ou id", type = Long.class),
  84.         @Info(name = "warehouseId", description = "Warehouse Id", type = Long.class),
  85.         @Info(name = "partnerShipToId", description = "Partner Ship to id", type = Long.class),
  86.         @Info(name = "partnerShipAddressId", description = "Partner Ship address id", type = Long.class),
  87.         @Info(name = "deliveryCode", description = "Delivery Code", type = String.class),
  88.         @Info(name = "remark", description = "remark", type = String.class),
  89.         @Info(name = "refId", description = "refId (So id)", type = String.class),
  90.         @Info(name = "version", description = "Version", type = Long.class)
  91. })
  92. @ErrorList(errorKeys = {
  93.         CommonExceptionConstants.TENANT_LOGIN_CANT_USED,
  94.         CommonExceptionConstants.DATA_CANT_USE_DIFF_TENANT,
  95.         MasterExceptionConstants.DATA_NOT_ACTIVE,
  96.         SalesExceptionConstants.OU_IN_SALES_ORDER_MUST_NOT_AN_OUTLET,
  97.         SalesExceptionConstants.USER_ROLE_NOT_AUTHORIZED_IN_OU,
  98.         MasterExceptionConstants.DATA_NOT_ACTIVE,
  99.         MasterExceptionConstants.POLICY_WAREHOUSE_AUTHORIZATION_FAILED,
  100.         SalesExceptionConstants.PARTNER_NOT_AUTHORIZED_AS_CUSTOMER,
  101.         MasterExceptionConstants.PARTNER_ID_NOT_FOUND,
  102.         SalesExceptionConstants.CUSTOMER_NOT_RELATED_AS_CUSTOMER_SHIP_TO,
  103.         MasterExceptionConstants.PARTNER_ADDRESS_ID_NOT_FOUND,
  104.         SalesExceptionConstants.PARTNER_ADDRESS_IS_NOT_ASSOCIATED_TO_PARTNER
  105. })
  106. //@formatter:on
  107. public class AddDeliveryOrder extends DefaultBusinessTransaction implements BusinessTransaction {
  108.     private static Logger log = LoggerFactory.getLogger(AddDeliveryOrder.class);
  109.  
  110.     @Autowired
  111.     DeliveryOrderDao deliveryOrderDao;
  112.  
  113.     @Autowired
  114.     DeliveryOrderItemDao deliveryOrderItemDao;
  115.  
  116.     @Autowired
  117.     DeliveryOrderProductDao deliveryOrderProductDao;
  118.  
  119.     @Autowired
  120.     SalesOrderBalanceItemDao salesOrderBalanceItemDao;
  121.    
  122.     @Autowired
  123.     ProductBalanceStockDao productBalanceStockDao;
  124.    
  125.     @Autowired
  126.     @Qualifier("valTenantLoginCanUse")
  127.     BusinessFunction valTenantLoginCanUse;
  128.  
  129.     @Autowired
  130.     @Qualifier("findSalesOrderById")
  131.     BusinessFunction findSalesOrderById;
  132.  
  133.     @Autowired
  134.     @Qualifier("findOUById")
  135.     BusinessFunction findOUById;
  136.  
  137.     @Autowired
  138.     @Qualifier("valOUAsMainBusinessUnitOrBranch")
  139.     BusinessFunction valOUAsMainBusinessUnitOrBranch;
  140.  
  141.     @Autowired
  142.     @Qualifier("isOUAsSubBusinessUnit")
  143.     BusinessFunction isOUAsSubBusinessUnit;
  144.  
  145.     @Autowired
  146.     @Qualifier("isUserRoleExistsByIndex")
  147.     BusinessFunction isUserRoleExistsByIndex;
  148.  
  149.     @Autowired
  150.     @Qualifier("getPolicyOUListByPolicyId")
  151.     BusinessFunction getPolicyOUListByPolicyId;
  152.  
  153.     @Autowired
  154.     @Qualifier("findWarehouseById")
  155.     BusinessFunction findWarehouseById;
  156.  
  157.     @Autowired
  158.     @Qualifier("valAuthorizedPolicyWarehouse")
  159.     BusinessFunction valAuthorizedPolicyWarehouse;
  160.  
  161.     @Autowired
  162.     @Qualifier("isPartnerTypeExistsByIndex")
  163.     BusinessFunction isPartnerTypeExistsByIndex;
  164.  
  165.     @Autowired
  166.     @Qualifier("findPartnerById")
  167.     BusinessFunction findPartnerById;
  168.  
  169.     @Autowired
  170.     @Qualifier("isPartnerRelationExistsByIndex")
  171.     BusinessFunction isPartnerRelationExistsByIndex;
  172.  
  173.     @Autowired
  174.     @Qualifier("findPartnerAddressById")
  175.     BusinessFunction findPartnerAddressById;
  176.  
  177.     @Autowired
  178.     @Qualifier("isDeliveryOrderExistsByIndex")
  179.     BusinessFunction isDeliveryOrderExistsByIndex;
  180.  
  181.     @Autowired
  182.     @Qualifier("findSalesOrderItemById")
  183.     BusinessFunction findSalesOrderItemById;
  184.  
  185.     @Autowired
  186.     @Qualifier("findSalesOrderBalanceItemById")
  187.     BusinessFunction findSalesOrderBalanceItemById;
  188.  
  189.     @Autowired
  190.     @Qualifier("isProductHasSerialNumber")
  191.     BusinessFunction isProductHasSerialNumber;
  192.  
  193.     @Autowired
  194.     @Qualifier("findProductBalanceStockByIndex")
  195.     BusinessFunction findProductBalanceStockByIndex;
  196.    
  197.     @Autowired
  198.     @Qualifier("findProductBalanceById")
  199.     BusinessFunction findProductBalanceById;
  200.    
  201.     @Autowired
  202.     @Qualifier("valSufficientProductBalanceStock")
  203.     BusinessFunction valSufficientProductBalanceStock;
  204.  
  205.     @Autowired
  206.     @Qualifier("valWarehouseExistsInOu")
  207.     BusinessFunction valWarehouseExistsInOu;
  208.  
  209.     @Autowired
  210.     @Qualifier("valAuthorizedPolicyOU")
  211.     BusinessFunction valAuthorizedPolicyOU;
  212.  
  213.     @Autowired
  214.     @Qualifier("valComboValueByCode")
  215.     BusinessFunction valComboValueByCode;
  216.    
  217.     @Autowired
  218.     @Qualifier("isProductStatusExistsByIndex")
  219.     BusinessFunction isProductStatusExistsByIndex;
  220.    
  221.     @Autowired
  222.     @Qualifier("findProductById")
  223.     BusinessFunction findProductById;
  224.    
  225.     @Override
  226.     public String getDescription() {
  227.         return "Add delivery order";
  228.     }
  229.  
  230.     @SuppressWarnings("unchecked")
  231.     @Override
  232.     public Dto prepare(Dto inputDto, Dto originalDto) throws Exception {
  233.         // Validation not empty / null / date / etc
  234.         // docNo
  235.         ValidationUtil.valBlankOrNull(inputDto.getString("docNo"), "Document No");
  236.         // docDate
  237.         ValidationUtil.valBlankOrNull(inputDto.getString("docDate"), "Document Date");
  238.         // ouId
  239.         ValidationUtil.valDtoContainsKey(inputDto, "ouId");
  240.         // warehouseId
  241.         ValidationUtil.valDtoContainsKey(inputDto, "warehouseId");
  242.         // partnerShipToId
  243. //      ValidationUtil.valDtoContainsKey(inputDto, "partnerShipToId");
  244.         // partnerShipAddressId
  245. //      ValidationUtil.valDtoContainsKey(inputDto, "partnerShipAddressId");
  246.         // deliveryCode
  247.         ValidationUtil.valBlankOrNull(inputDto.getString("deliveryCode"), "Delivery code");
  248.         // remark
  249.         ValidationUtil.valDtoContainsKey(inputDto, "remark");
  250.         // refId (maksudnya soId)
  251.         ValidationUtil.valDtoContainsKey(inputDto, "refId");
  252.         ValidationUtil.valDtoContainsKey(inputDto, "itemList");
  253.         // itemList (lineNo, refId, qtyDlvInt), (maksudnya refId adalah
  254.         // soItemId)
  255.         // tenantLoginId
  256.         // userLoginId
  257.         // roleLoginId
  258.         // datetime
  259.  
  260.         // validation date
  261.         ValidationUtil.valDate(inputDto.getString("docDate"), "Document Date");
  262.  
  263.         ValidationUtil.valBlankOrNull(inputDto.get("eta")==null?null:inputDto.getString("eta"), "ETD");
  264.         ValidationUtil.valDate(inputDto.getString("eta"), "ETD");
  265.         ValidationUtil.valBlankOrNull(inputDto.get("etaDay")==null?null:inputDto.getString("etaDay"), "ETD Day");
  266.        
  267.         Long tenantLoginId = inputDto.getLong("tenantLoginId");
  268.         Long userLoginId = inputDto.getLong("userLoginId");
  269.         Long roleLoginId = inputDto.getLong("roleLoginId");
  270.         String datetime = inputDto.getString("datetime");
  271.  
  272.         String docNo = inputDto.getString("docNo");
  273.         String docDate = inputDto.getString("docDate");
  274.         Long ouId = inputDto.getLong("ouId");
  275.         Long warehouseId = inputDto.getLong("warehouseId");
  276.         String remark = inputDto.getString("remark");
  277.         Long refId = inputDto.getLong("refId");
  278.         String deliveryCode = inputDto.getString("deliveryCode");
  279.         String eta = inputDto.getString("eta");
  280.         String etaDay = inputDto.getString("etaDay");
  281.        
  282.         // - validation: tenant login can use
  283.         Dto inputDtoForValTenantLoginCanUse = new Dto();
  284.         inputDtoForValTenantLoginCanUse.put("tenantLoginId", tenantLoginId);
  285.         inputDtoForValTenantLoginCanUse.put("userLoginId", userLoginId);
  286.         inputDtoForValTenantLoginCanUse.put("roleLoginId", roleLoginId);
  287.         valTenantLoginCanUse.execute(inputDto);
  288.  
  289.         // - validation: document date >= soDocDate (ambil dulu pakai
  290.         // findSalesOrderById)
  291.         Dto inputDtoForFindSalesOrderById = new Dto();
  292.         inputDtoForFindSalesOrderById.put("id", refId);
  293.         Dto outputDtoForFindSalesOrderById = findSalesOrderById.execute(inputDtoForFindSalesOrderById);
  294.  
  295.         // get partner ship to from SO
  296.         Long partnerShipToId = outputDtoForFindSalesOrderById.getLong("partnerShipToId");
  297.         Long partnerShipAddressId = outputDtoForFindSalesOrderById.getLong("partnerShipAddressId");
  298.         String flgDelivery = outputDtoForFindSalesOrderById.getString("flgDelivery");
  299.        
  300.         String docDateSalesOrder = outputDtoForFindSalesOrderById.getString("docDate");
  301.         CommonBusinessValidator.valCompareDate(docDate, docDateSalesOrder, CommonBusinessValidator.COMPARE_GREATER_EQUAL, "Delivery Order Document Date",
  302.                 "Sales Order Document Date");
  303.  
  304.         // - ouId harus terdaftar dan aktif dan harus merupakan BU dan bukan
  305.         // merupakan outlet (pakai findOUById, valOUAsBusinessUnit dan
  306.         // isOuHasOutlet)
  307.         Dto ouDto = findOUById.execute(new Dto().put("id", ouId));
  308.         if (!tenantLoginId.equals(ouDto.getLong("tenantId"))) {
  309.             throw new CoreException(CommonExceptionConstants.DATA_CANT_USE_DIFF_TENANT, "Delivery Order", "OU");
  310.         }
  311.  
  312.         if (!GeneralConstants.YES.equals(ouDto.getString("active"))) {
  313.             throw new CoreException(MasterExceptionConstants.DATA_NOT_ACTIVE, "OU");
  314.         }
  315.  
  316.         valOUAsMainBusinessUnitOrBranch.execute(new Dto().put("id", ouId));
  317.  
  318.         Dto inputDtoForValAuthorizedPolicyOU = new Dto();
  319.         inputDtoForValAuthorizedPolicyOU.put("userLoginId", userLoginId);
  320.         inputDtoForValAuthorizedPolicyOU.put("roleLoginId", roleLoginId);
  321.         inputDtoForValAuthorizedPolicyOU.put("ouId", ouId);
  322.         inputDtoForValAuthorizedPolicyOU.put("varName", "OU");
  323.         valAuthorizedPolicyOU.execute(inputDtoForValAuthorizedPolicyOU);
  324.  
  325.         // - gudang harus terdaftar dan aktif (pakai findWarehouseById)
  326.         Dto warehouseDto = findWarehouseById.execute(new Dto().put("id", warehouseId));
  327.         if (!warehouseDto.getString("active").equals(GeneralConstants.YES)) {
  328.             throw new CoreException(MasterExceptionConstants.DATA_NOT_ACTIVE, "Warehouse");
  329.         }
  330.  
  331.         // - gudang harus termasuk dalam OU yg dipilih
  332.         // (valWarehouseOuExistsByIndex)
  333.         Dto inputDtoForValWarehouseExistsInOu = new Dto();
  334.         inputDtoForValWarehouseExistsInOu.put("warehouseId", warehouseId);
  335.         inputDtoForValWarehouseExistsInOu.put("ouId", ouId);
  336.         valWarehouseExistsInOu.execute(inputDtoForValWarehouseExistsInOu);
  337.  
  338.         // - user dan role login harus berhak untuk warehouse tersebut
  339.         // (valAuthorizedPolicyWarehouse)
  340.         Dto inputDtoForValAuthorizedPolicyWarehouse = new Dto();
  341.         inputDtoForValAuthorizedPolicyWarehouse.put("userLoginId", userLoginId);
  342.         inputDtoForValAuthorizedPolicyWarehouse.put("roleLoginId", roleLoginId);
  343.         inputDtoForValAuthorizedPolicyWarehouse.put("warehouseId", warehouseId);
  344.         inputDtoForValAuthorizedPolicyWarehouse.put("varName", "DeliveryOrder");
  345.         valAuthorizedPolicyWarehouse.execute(inputDtoForValAuthorizedPolicyWarehouse);
  346.  
  347.         // - partner (ambil dari SO nya) harus masih merupakan Customer
  348.         // (isPartnerTypeExistsByIndex)
  349.         Long partnerId = outputDtoForFindSalesOrderById.getLong("partnerId");
  350.         Dto inputDtoForIsPartnerTypeExistsByIndex = new Dto();
  351.         inputDtoForIsPartnerTypeExistsByIndex.put("tenantId", tenantLoginId);
  352.         inputDtoForIsPartnerTypeExistsByIndex.put("partnerId", partnerId);
  353.         inputDtoForIsPartnerTypeExistsByIndex.put("groupPartner", MasterConstants.GROUP_PARTNER_CODE_CUSTOMER);
  354.  
  355.         Dto ouputDtoForIsPartnerTypeExistsByIndex = isPartnerTypeExistsByIndex.execute(inputDtoForIsPartnerTypeExistsByIndex);
  356.         if (!ouputDtoForIsPartnerTypeExistsByIndex.getBoolean("exists")) {
  357.             throw new CoreException(SalesExceptionConstants.PARTNER_NOT_AUTHORIZED_AS_CUSTOMER, partnerId);
  358.         }
  359.  
  360.         // - partnerShipToId harus terdaftar di master partner dan aktif dan
  361.         // punya relasi dengan partner sebagai ship to (ambil dari SO)
  362.         // (isPartnerRelationExistsByIndex) dan cek lagi flag shipping Y (bisa
  363.         // lihat di AddSalesOrder contoh yg mirip)
  364.         Dto outputDtoForFindPartnerById = findPartnerById.execute(new Dto().put("id", partnerShipToId));
  365.         if (!outputDtoForFindPartnerById.getString("active").equals(GeneralConstants.YES)) {
  366.             throw new CoreException(MasterExceptionConstants.DATA_NOT_ACTIVE, "Partner");
  367.         }
  368.  
  369.         if (!outputDtoForFindPartnerById.getLong("tenantId").equals(tenantLoginId)) {
  370.             throw new CoreException(CommonExceptionConstants.DATA_CANT_USE_DIFF_TENANT, "Partner", "Partner Ship To");
  371.         }
  372.  
  373.         Dto paramCustomerShipToRelation = new Dto();
  374.         paramCustomerShipToRelation.put("tenantId", tenantLoginId);
  375.         paramCustomerShipToRelation.put("partnerId", partnerId);
  376.         paramCustomerShipToRelation.put("relationId", partnerShipToId);
  377.  
  378.         Dto resultCustomerShipToRelation = isPartnerRelationExistsByIndex.execute(paramCustomerShipToRelation);
  379.  
  380.         if (resultCustomerShipToRelation.getBoolean("exists")) {
  381.             Dto partnerRelationDto = resultCustomerShipToRelation.getDto("partnerRelationDto");
  382.             if (!GeneralConstants.YES.equals(partnerRelationDto.getString("flagShipping"))) {
  383.                 throw new CoreException(SalesExceptionConstants.CUSTOMER_NOT_RELATED_AS_CUSTOMER_SHIP_TO, partnerShipToId, partnerId);
  384.             }
  385.         } else {
  386.             throw new CoreException(SalesExceptionConstants.CUSTOMER_NOT_RELATED_AS_CUSTOMER_SHIP_TO, partnerShipToId, partnerId);
  387.         }
  388.  
  389.         // - partnerShipAddressId harus terdaftar di master partner address dan
  390.         // aktif dan punya relasi dengan partner. (cukup cek apakah partner id
  391.         // di partner address dan partnerShipToId itu sama atau tidak) gunakan
  392.         // FindPartnerAddressById
  393.         Dto ouputDtoForFindPartnerAddressById = findPartnerAddressById.execute(new Dto().put("id", partnerShipAddressId));
  394.         if (!ouputDtoForFindPartnerAddressById.getString("active").equals(GeneralConstants.YES)) {
  395.             throw new CoreException(MasterExceptionConstants.DATA_NOT_ACTIVE, "Partner Ship Address");
  396.         }
  397.  
  398.         if (!ouputDtoForFindPartnerAddressById.getLong("partnerId").equals(partnerShipToId)) {
  399.             throw new CoreException(SalesExceptionConstants.PARTNER_ADDRESS_IS_NOT_ASSOCIATED_TO_PARTNER, partnerShipAddressId, partnerShipToId);
  400.         }
  401.        
  402.         // validation eta >= so date
  403.         CommonBusinessValidator.valCompareDate(inputDto.getString("eta"), inputDto.getString("docDate"), CommonBusinessValidator.COMPARE_GREATER_EQUAL,
  404.                 "ETD", "Document Date");
  405.        
  406.         // validation combo eta day
  407.         Dto inputComboEtaDayDto = new Dto();
  408.         inputComboEtaDayDto.put("comboId", ComboIdMasterConstants.COMBO_ETADAY);
  409.         inputComboEtaDayDto.put("code", inputDto.getString("etaDay"));
  410.         inputComboEtaDayDto.put("varName", "ETD Day");
  411.         valComboValueByCode.execute(inputComboEtaDayDto);
  412.  
  413.         // - semua validasi di atas (yg berhubungan dengan master) harus
  414.         // memiliki tenantId yg sama dengan tenantLoginId
  415.  
  416.         // - status doc diisi DRAFT
  417.  
  418.         // - cek data exists atau nggak berdasarkan unique constraint (jika
  419.         // exists, maka throw error) gunakan isDeliveryOrderExistsByIndex
  420.         Dto inputDtoForIsDeliveryOrderExistsByIndex = new Dto();
  421.         inputDtoForIsDeliveryOrderExistsByIndex.put("tenantId", tenantLoginId);
  422.         inputDtoForIsDeliveryOrderExistsByIndex.put("docTypeId", SalesConstants.DOCUMENT_DELIVERY_ORDER);
  423.         inputDtoForIsDeliveryOrderExistsByIndex.put("docNo", docNo);
  424.         inputDtoForIsDeliveryOrderExistsByIndex.put("docDate", docDate);
  425.         inputDtoForIsDeliveryOrderExistsByIndex.put("ouId", ouId);
  426.  
  427.         Dto outputDtoForIsDeliveryOrderExistsByIndex = isDeliveryOrderExistsByIndex.execute(inputDtoForIsDeliveryOrderExistsByIndex);
  428.         if (outputDtoForIsDeliveryOrderExistsByIndex.getBoolean("exists")) {
  429.             throw new CoreException(SalesExceptionConstants.DELIVERY_ORDER_ALREADY_EXISTS, tenantLoginId, SalesConstants.DOCUMENT_DELIVERY_ORDER, docNo,
  430.                     docDate, ouId);
  431.         }
  432.  
  433.         // create delivery order dto for insert
  434.         Dto deliveryOrderDto = new Dto();
  435.         deliveryOrderDto.put("tenantId", tenantLoginId);
  436.         deliveryOrderDto.put("docTypeId", SalesConstants.DOCUMENT_DELIVERY_ORDER);
  437.         deliveryOrderDto.put("docNo", docNo);
  438.         deliveryOrderDto.put("docDate", docDate);
  439.         deliveryOrderDto.put("ouId", ouId);
  440.         deliveryOrderDto.put("extDocNo", outputDtoForFindSalesOrderById.getString("extDocNo"));
  441.         deliveryOrderDto.put("extDocDate", outputDtoForFindSalesOrderById.getString("extDocDate"));
  442.         deliveryOrderDto.put("refDocTypeId", outputDtoForFindSalesOrderById.getLong("docTypeId"));
  443.         deliveryOrderDto.put("refId", outputDtoForFindSalesOrderById.getLong("id"));
  444.         deliveryOrderDto.put("remark", remark);
  445.         deliveryOrderDto.put("partnerShipToId", partnerShipToId);
  446.         deliveryOrderDto.put("partnerShipAddressId", partnerShipAddressId);
  447.         deliveryOrderDto.put("warehouseId", warehouseId);
  448.         deliveryOrderDto.put("noVehicle", GeneralConstants.EMPTY_VALUE);
  449.         deliveryOrderDto.put("flgDelivery", flgDelivery);
  450.         deliveryOrderDto.put("deliveryCode", deliveryCode);
  451.         deliveryOrderDto.put("eta", eta);
  452.         deliveryOrderDto.put("etaDay", etaDay);
  453.         deliveryOrderDto.put("statusDoc", SalesConstants.DRAFT_TRANSACTION);
  454.         deliveryOrderDto.put("workflowStatus", SalesConstants.WORKFLOW_STATUS_DRAFT);
  455.  
  456.         this.prepareInsertAudit(deliveryOrderDto, userLoginId, datetime);
  457.         this.prepareUpdateAudit(deliveryOrderDto, userLoginId, datetime);
  458.  
  459.         List<Dto> failList = new ArrayList<Dto>();
  460.         List<Dto> resultDeliveryOrderItemList = new ArrayList<Dto>();
  461.  
  462.         // - qtyDlvInt harus > 0 (jika error waktu looping di list, maka harus
  463.         // di try catch dan disimpan dulu, tidak langsung di throw, contohnya
  464.         // bisa lihat di AddPurchaseOrder)
  465.        
  466.         Map<Long, Dto> mapItemVsQty = new HashMap<Long, Dto>();
  467.        
  468.         List<Dto> itemList = inputDto.getList("itemList");
  469.         if (itemList != null && !itemList.isEmpty()) {
  470.             for (Dto itemDto : itemList) {
  471.                 // itemDto = lineNo, refId, qtyDlvInt
  472.                 String lineNo = itemDto.get("lineNo").toString();
  473.                 Long itemRefId = Long.valueOf(itemDto.get("refId").toString());
  474.                 Double qtyDlvInt = Double.valueOf(itemDto.get("qtyDlvInt").toString());
  475.                 // get So Item
  476.                 Dto refSoItemDto = findSalesOrderItemById.execute(new Dto().put("id", itemRefId));
  477.                 Long itemDoProductId = refSoItemDto.getLong("productId");
  478.                 itemDto.put("productId", itemDoProductId);
  479.                
  480.                 if (!refSoItemDto.getLong("soId").equals(Long.valueOf(inputDto.getLong("refId").toString()))) {
  481.                     throw new CoreException(SalesExceptionConstants.DELIVERY_ORDER_ITEM_NOT_FROM_REFERENCE_SALES_ORDER_ITEM, refSoItemDto.getLong("productId"));
  482.                 }
  483.                
  484.                 // get ratio for soQty and soQtyInt
  485.                 Dto soBalanceItemDto = findSalesOrderBalanceItemById.execute(new Dto().put("soItemId", itemRefId));
  486.                 Double qtySo = soBalanceItemDto.getDouble("qtySo");
  487.                 Double qtySoInt = soBalanceItemDto.getDouble("qtySoInt");
  488.                 //b.qty_so_int - b.qty_cancel_int + b.qty_add_int - b.qty_dlv_int + b.qty_return_int AS outstandingQtyInt,
  489.                
  490.                 // count qtyDlvSoCalc using ratio
  491.                 Calc qtyDlvSoCalc = new Calc(qtySo).multiply(qtyDlvInt).divide(qtySoInt);
  492.  
  493.                 try {
  494.                     if (qtyDlvInt <= 0) {
  495.                         throw new CoreException(SalesExceptionConstants.QUANTITY_INTERNAL_MUST_BE_GREATER_THAN_ZERO);
  496.                     }
  497.                    
  498.                     if(!SalesConstants.RELEASED_TRANSACTION.equals(soBalanceItemDto.get("statusItem"))){
  499.                         throw new CoreException(SalesExceptionConstants.BALANCE_DELIVERY_ORDER_ITEM_ALREADY_USED_IN_OTHER_TRANSACTION);
  500.                     }
  501.                    
  502.                     ValidationUtil.valBlankOrNull(itemDto.get("productStatus")==null?null:itemDto.getString("productStatus"), "Product Status Item");
  503.                     String productStatus = itemDto.getString("productStatus");
  504.                    
  505.                     // validation product status
  506.                     Dto outputIsProductStatusExistsByIndex = isProductStatusExistsByIndex.execute(new Dto()
  507.                             .put("tenantId", tenantLoginId)
  508.                             .put("productStatusCode", productStatus));
  509.                    
  510.                     if(!outputIsProductStatusExistsByIndex.getBoolean("exists")){
  511.                         throw new CoreException(MasterExceptionConstants.PRODUCT_STATUS_NOT_FOUND, tenantLoginId, productStatus);
  512.                     } else{
  513.                         Dto productStatusDto = outputIsProductStatusExistsByIndex.getDto("productStatusDto");
  514.                         if(!GeneralConstants.YES.equals(productStatusDto.get("flgSell"))){
  515.                             throw new CoreException(SalesExceptionConstants.PRODUCT_WITH_STATUS_IS_NOT_FOR_SELL, productStatus);
  516.                         }
  517.                     }
  518.                    
  519.                     Dto deliveryOrderItemDto = new Dto();
  520.                     deliveryOrderItemDto.put("tenantId", tenantLoginId);
  521.                     deliveryOrderItemDto.put("doId", GeneralConstants.NULL_REF_VALUE_LONG);
  522.                     deliveryOrderItemDto.put("lineNo", lineNo);
  523.                     deliveryOrderItemDto.put("refDocTypeId", refSoItemDto.getLong("refDocTypeId"));
  524.                     deliveryOrderItemDto.put("refId", itemRefId);
  525.                     deliveryOrderItemDto.put("productId", itemDoProductId);
  526.                     deliveryOrderItemDto.put("qtyDlvSo", qtyDlvSoCalc.doubleValue());
  527.                     deliveryOrderItemDto.put("soUomId", refSoItemDto.get("soUomId"));
  528.                     deliveryOrderItemDto.put("qtyDlvInt", qtyDlvInt);
  529.                     deliveryOrderItemDto.put("baseUomId", refSoItemDto.get("baseUomId"));
  530.                     deliveryOrderItemDto.put("remark", GeneralConstants.EMPTY_VALUE);
  531.                     deliveryOrderItemDto.put("productStatus", productStatus);
  532.  
  533.                     // check if product has serial number
  534.                     Dto inputDtoForIsProductHasSerialNumber = new Dto();
  535.                     inputDtoForIsProductHasSerialNumber.put("tenantId", tenantLoginId);
  536.                     inputDtoForIsProductHasSerialNumber.put("productId", itemDoProductId);
  537.                     Dto outputDtoForIsProductHasSerialNumber = isProductHasSerialNumber.execute(inputDtoForIsProductHasSerialNumber);
  538.                    
  539.                     String flgSerialNumber = GeneralConstants.NO;
  540.                     Long productBalanceId = outputDtoForIsProductHasSerialNumber.getLong("productBalanceId");
  541.  
  542.                     if (outputDtoForIsProductHasSerialNumber.getBoolean("hasSerialNumber")) {
  543.                         flgSerialNumber = GeneralConstants.YES;
  544.                     } else {
  545.                         flgSerialNumber = GeneralConstants.NO;
  546.                        
  547.                         Dto itemProductBalanceDto = findProductBalanceById.execute(new Dto().put("id", productBalanceId));
  548.                         Dto paramSufficientProductBalanceStock = new Dto();
  549.                         paramSufficientProductBalanceStock.put("tenantId", tenantLoginId);
  550.                         paramSufficientProductBalanceStock.put("productId", itemDoProductId);
  551.                         paramSufficientProductBalanceStock.put("serialNumber", itemProductBalanceDto.getString("serialNumber"));
  552.                         paramSufficientProductBalanceStock.put("lotNumber", itemProductBalanceDto.getString("lotNumber"));
  553.                         paramSufficientProductBalanceStock.put("qty", qtyDlvInt);
  554.                         paramSufficientProductBalanceStock.put("warehouseId", warehouseId);
  555.                         paramSufficientProductBalanceStock.put("productStatus", productStatus);
  556.                         valSufficientProductBalanceStock.execute(paramSufficientProductBalanceStock);
  557.                        
  558.                         Dto deliveryOrderProductDto = new Dto();
  559.                         deliveryOrderProductDto.put("tenantId", tenantLoginId);
  560.                         deliveryOrderProductDto.put("doItemId", GeneralConstants.NULL_REF_VALUE_LONG);
  561.                         deliveryOrderProductDto.put("lineNo", lineNo);
  562.                         deliveryOrderProductDto.put("productId", itemDoProductId);
  563.                         deliveryOrderProductDto.put("productBalanceId", productBalanceId);
  564.                         deliveryOrderProductDto.put("productStatus", productStatus);
  565.                         deliveryOrderProductDto.put("qtyDlvInt", qtyDlvInt);
  566.                         deliveryOrderProductDto.put("baseUomId", refSoItemDto.get("baseUomId"));
  567.                         deliveryOrderProductDto.put("remark", GeneralConstants.EMPTY_VALUE);
  568.  
  569.                         deliveryOrderItemDto.put("deliveryOrderProduct", deliveryOrderProductDto);
  570.                     }
  571.                     deliveryOrderItemDto.put("flgSerialNumber", flgSerialNumber);
  572.                     deliveryOrderItemDto.put("productBalanceId", productBalanceId);
  573.  
  574.                     this.prepareInsertAudit(deliveryOrderItemDto, userLoginId, datetime);
  575.                     this.prepareUpdateAudit(deliveryOrderItemDto, userLoginId, datetime);
  576.  
  577.                     resultDeliveryOrderItemList.add(deliveryOrderItemDto);
  578.  
  579.                     Dto findProductByIdDto = findProductById.execute(new Dto().put("id", itemDoProductId));
  580.                    
  581.                     //map to check qtyDlvInt < qtyOs
  582.                     Dto mapItemDto = mapItemVsQty.get(deliveryOrderItemDto.getLong("refId"));
  583.                     if (mapItemDto == null) {
  584.                         mapItemDto = new Dto();
  585.                         mapItemDto.putDouble("qtyDlvSo", deliveryOrderItemDto.getDouble("qtyDlvSo"));
  586.                         mapItemDto.putString("productCode", findProductByIdDto.getString("code"));
  587.                         mapItemDto.putString("productName", findProductByIdDto.getString("name"));
  588.                     } else {
  589.                         mapItemDto.putDouble("qtyDlvSo", new Calc(mapItemDto.getDouble("qtyDlvSo")).add(deliveryOrderItemDto.getDouble("qtyDlvSo")).doubleValue());
  590.                     }
  591.                     mapItemVsQty.put(deliveryOrderItemDto.getLong("refId"), mapItemDto);
  592.                    
  593.                 } catch (CoreException e) {
  594.                     log.error("", e);
  595.                     Dto errorDto = (Dto) itemDto.clone();
  596.                     errorDto.put("errorKey", e.getErrorKey());
  597.  
  598.                     List<Object> argsList = new ArrayList<Object>();
  599.                     if (e.getParamValues() != null && e.getParamValues().length > 0)
  600.                         for (Object paramValue : e.getParamValues()) {
  601.                             argsList.add(paramValue);
  602.                         }
  603.                     errorDto.put("args", argsList);
  604.                     errorDto.put("version", GeneralConstants.NULL_REF_VALUE_LONG);
  605.  
  606.                     failList.add(errorDto);
  607.                 }
  608.             }
  609.             // Validasi total qty
  610.             for (Entry<Long, Dto> entry : mapItemVsQty.entrySet()) {
  611.                 Dto entryDto = entry.getValue();
  612.                
  613.                 // qty tolerance = ( qty_so - qty_cancel + qty add) * percentage tolerance
  614.                 // validasi : qty so - qty cancel + qty add + qty tolerance - qty dlv (yg ada di saldo item) + qty retur >= 0
  615.                 Dto soBalanceItemDto = findSalesOrderBalanceItemById.execute(new Dto().put("soItemId", entry.getKey()));
  616.                 Calc totalQtySo = new Calc(soBalanceItemDto.getDouble("qtySo"))
  617.                                         .add(soBalanceItemDto.getDouble("qtyAdd"))
  618.                                         .subtract(soBalanceItemDto.getDouble("qtyCancel"));
  619.                 Calc qtySoToleranceCalc = totalQtySo.multiply(soBalanceItemDto.getDouble("toleranceDlvQty")).divide(100);
  620.                 Calc qtyDlvSoMaxInput = totalQtySo.add(qtySoToleranceCalc)
  621.                                             .subtract(soBalanceItemDto.getDouble("qtyDlv"));
  622.                
  623.                 if (entryDto.getDouble("qtyDlvSo") > qtyDlvSoMaxInput.doubleValue()) {
  624.                     // throw error
  625.                     throw new CoreException(SalesExceptionConstants.TOTAL_QTY_DLV_SO_IS_MORE_THAN_ALLOWED, entryDto.getDouble("qtyDlvSo"),
  626.                             qtyDlvSoMaxInput.doubleValue(), entryDto.getString("productCode"), entryDto.getString("productName"));
  627.                 }
  628.                
  629.             }
  630.         }
  631.  
  632.         if (!failList.isEmpty()) {
  633.             Dto errorParamDto = new Dto();
  634.             DtoUtil.putInErrorParamDto(errorParamDto, "failList",
  635.                     new String[] { "lineNo", "productId", "productName", "refId", "qtyDlvInt", "errorKey", "args" }, failList);
  636.             throw new CoreException(SalesExceptionConstants.DELIVERY_ORDER_ITEMS_ERROR, errorParamDto);
  637.         }
  638.  
  639.         inputDto.put("resultDeliveryOrder", deliveryOrderDto);
  640.         inputDto.put("resultDeliveryOrderItemList", resultDeliveryOrderItemList);
  641.  
  642.         return null;
  643.     }
  644.  
  645.     @SuppressWarnings("unchecked")
  646.     @Override
  647.     public Dto process(Dto inputDto, Dto originalDto) throws Exception {
  648.         Dto outputDto = new Dto();
  649.  
  650.         // add delivery order
  651.         DeliveryOrder deliveryOrder = GsonUtil.fromDto(inputDto.getDto("resultDeliveryOrder"), DeliveryOrder.class);
  652.         deliveryOrderDao.persist(deliveryOrder);
  653.  
  654.         List<Dto> resultDeliveryOrderItemList = inputDto.getList("resultDeliveryOrderItemList");
  655.         for (Dto deliveryOrderItemDto : resultDeliveryOrderItemList) {
  656.             // add delivery order item
  657.             deliveryOrderItemDto.put("doId", deliveryOrder.getId());
  658.             DeliveryOrderItem deliveryOrderItem = GsonUtil.fromDto(deliveryOrderItemDto, DeliveryOrderItem.class);
  659.  
  660.             deliveryOrderItemDao.persist(deliveryOrderItem);
  661.  
  662.             // update sl_so_balance_item
  663.             Dto salesOrderBalanceItemDto = findSalesOrderBalanceItemById.execute(new Dto().put("soItemId", deliveryOrderItem.getRefId()));
  664.             this.prepareUpdateAudit(salesOrderBalanceItemDto, inputDto.getLong("userLoginId"), inputDto.getString("datetime"));
  665.  
  666.             SalesOrderBalanceItem salesOrderBalanceItem = GsonUtil.fromDto(salesOrderBalanceItemDto, SalesOrderBalanceItem.class);
  667.             salesOrderBalanceItem.setStatusItem(SalesConstants.IN_PROGRESS_TRANSACTION);
  668.             salesOrderBalanceItem.setQtyDlv(salesOrderBalanceItem.getQtyDlv() + deliveryOrderItem.getQtyDlvSo());
  669.             salesOrderBalanceItem.setQtyDlvInt(salesOrderBalanceItem.getQtyDlvInt() + deliveryOrderItem.getQtyDlvInt());
  670.  
  671.             salesOrderBalanceItemDao.merge(salesOrderBalanceItem.getSoItemId(), salesOrderBalanceItem);
  672.  
  673.             // insert DoProduct and update in_product_balance_stock if no
  674.             // serial number
  675.             if (GeneralConstants.NO.equals(deliveryOrderItemDto.getString("flgSerialNumber"))) {
  676.                 Dto deliveryOrderProductDto = deliveryOrderItemDto.getDto("deliveryOrderProduct");
  677.                 deliveryOrderProductDto.put("doItemId", deliveryOrderItem.getId());
  678.  
  679.                 DeliveryOrderProduct deliveryOrderProduct = GsonUtil.fromDto(deliveryOrderProductDto, DeliveryOrderProduct.class);
  680.                 deliveryOrderProductDao.persist(deliveryOrderProduct);
  681.  
  682.                 // update in_product_balance_stock
  683.                 Long productBalanceId = deliveryOrderItemDto.getLong("productBalanceId");
  684.                 Dto inputDtoForFindProductBalanceStockByIndex = new Dto();
  685.                 inputDtoForFindProductBalanceStockByIndex.put("tenantId", deliveryOrder.getTenantId());
  686.                 inputDtoForFindProductBalanceStockByIndex.put("warehouseId", deliveryOrder.getWarehouseId());
  687.                 inputDtoForFindProductBalanceStockByIndex.put("productId", deliveryOrderItem.getProductId());
  688.                 inputDtoForFindProductBalanceStockByIndex.put("productBalanceId", productBalanceId);
  689.                 inputDtoForFindProductBalanceStockByIndex.put("productStatus", deliveryOrderItemDto.get("productStatus"));
  690.  
  691.                 Dto productBalanceStockDto = findProductBalanceStockByIndex.execute(inputDtoForFindProductBalanceStockByIndex);
  692.                 this.prepareUpdateAudit(productBalanceStockDto, inputDto.getLong("userLoginId"), inputDto.getString("datetime"));
  693.  
  694.                 ProductBalanceStock productBalanceStock = GsonUtil.fromDto(productBalanceStockDto, ProductBalanceStock.class);
  695.                 //productBalanceStock.setQty(productBalanceStock.getQty() - deliveryOrderItem.getQtyDlvInt());
  696.  
  697.                 //productBalanceStockDao.merge(productBalanceStock.getId(), productBalanceStock);
  698.                
  699.                 //query untuk mengurangi product balance stock
  700.                 QueryBuilder builder;
  701.                 builder = new QueryBuilder();
  702.                 builder.add("UPDATE ").add(ProductBalanceStock.TABLE_NAME)
  703.                     .add(" SET qty = qty - :qtyPerubahan, ")
  704.                     .add(" update_datetime = :updateDatetime, ")
  705.                     .add(" update_user_id = :updateUserId, ")
  706.                     .add(" version = version+1 ")
  707.                     .add(" WHERE product_balance_stock_id = :id");
  708.                 Query q;
  709.                 q = productBalanceStockDao.createNativeQuery(builder.toString());
  710.                
  711.                 q.setParameter("updateDatetime", inputDto.getString("datetime"));
  712.                 q.setParameter("updateUserId", inputDto.getLong("userLoginId"));
  713.                 q.setParameter("qtyPerubahan",deliveryOrderItem.getQtyDlvInt());
  714.                 q.setParameter("id", productBalanceStockDto.getLong("id"));
  715.                 log.debug("query update stock :"+builder.toString());
  716.                 q.executeUpdate();
  717.             }
  718.  
  719.         }
  720.  
  721.         outputDto.put("id", deliveryOrder.getId());
  722.         outputDto.put("docNo", deliveryOrder.getDocNo());
  723.         outputDto.put("docDate", deliveryOrder.getDocDate());
  724.         outputDto.put("ouId", deliveryOrder.getOuId());
  725.         outputDto.put("warehouseId", deliveryOrder.getWarehouseId());
  726.         outputDto.put("partnerShipToId", deliveryOrder.getPartnerShipToId());
  727.         outputDto.put("partnerShipAddressId", deliveryOrder.getPartnerShipAddressId());
  728.         outputDto.put("deliveryCode", deliveryOrder.getDeliveryCode());
  729.         outputDto.put("remark", deliveryOrder.getRemark());
  730.         outputDto.put("refId", deliveryOrder.getRefId());
  731.         outputDto.put("version", deliveryOrder.getVersion());
  732.         outputDto.put("eta", deliveryOrder.getEta());
  733.         outputDto.put("etaDay", deliveryOrder.getEtaDay());
  734.  
  735.         return outputDto;
  736.     }
  737. }
  738.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement