· 9 years ago · Oct 12, 2016, 03:34 AM
1package org.jleaf.erp.sls.bo.sosettlement;
2
3import java.util.ArrayList;
4import java.util.List;
5import java.util.UUID;
6
7import javax.persistence.Query;
8
9import org.jleaf.common.CommonExceptionConstants;
10import org.jleaf.core.BusinessFunction;
11import org.jleaf.core.BusinessTransaction;
12import org.jleaf.core.CoreException;
13import org.jleaf.core.DefaultBusinessTransaction;
14import org.jleaf.core.Dto;
15import org.jleaf.core.GeneralConstants;
16import org.jleaf.core.annotation.ErrorList;
17import org.jleaf.core.annotation.Info;
18import org.jleaf.core.annotation.InfoIn;
19import org.jleaf.core.annotation.InfoOut;
20import org.jleaf.core.dao.QueryBuilder;
21import org.jleaf.erp.inv.dao.ProductBalanceStockReservedDao;
22import org.jleaf.erp.master.MasterExceptionConstants;
23import org.jleaf.erp.sls.SalesConstantsForKtmt;
24import org.jleaf.erp.sls.SalesExceptionConstantsForKtmt;
25import org.jleaf.erp.sls.dao.SalesOrderDao;
26import org.jleaf.erp.sls.dao.SoAdminSettleDao;
27import org.jleaf.erp.sls.dao.SoCalculationDao;
28import org.jleaf.erp.sls.dao.SoSettlementDao;
29import org.jleaf.erp.sls.dao.SoSettlementItemDao;
30import org.jleaf.erp.sls.dao.SoStatusDao;
31import org.jleaf.erp.sls.dao.SoStatusLogDao;
32import org.jleaf.erp.sls.entity.SalesOrder;
33import org.jleaf.erp.sls.entity.SoAdminSettle;
34import org.jleaf.erp.sls.entity.SoSettlement;
35import org.jleaf.erp.sls.entity.SoSettlementItem;
36import org.jleaf.erp.sls.entity.SoStatus;
37import org.jleaf.erp.sls.entity.SoStatusLog;
38import org.jleaf.util.Calc;
39import org.jleaf.util.DtoUtil;
40import org.jleaf.util.GsonUtil;
41import org.jleaf.util.ValidationUtil;
42import org.jleaf.validator.CommonBusinessValidator;
43import org.springframework.beans.factory.annotation.Autowired;
44import org.springframework.beans.factory.annotation.Qualifier;
45import org.springframework.stereotype.Service;
46
47/**
48 *
49 * @author Agik, Sep 21, 2015
50 *
51 * Add New SO Settlement
52 *
53 * modify by congky 11 Mar 2016
54 * - melepas validasi QTY_SO_BRAND_ITEM_NOT_MATCH_WITH_QTY_DETAIL_ITEM / qty so brand item harus sama dengan qty detail item dan mengubahnya dengan
55 * validasi QTY_DETAIL_ITEM_CAN_NOT_BE_GREATER_THAN_QTY_BRAND_ITEM artinya boleh kurang, tapi tidak boleh lebih
56 *
57 *
58**/
59
60//@formatter:off
61@Service
62@InfoIn(value = {
63 @Info(name = "ouId", description = "Ou Id", type = Long.class),
64 @Info(name = "docNo", description = "Nomor Transaksi", type = String.class),
65 @Info(name = "docDate", description = "Tanggal Transaksi", type = String.class),
66 @Info(name = "soId", description = "Sales Order Id", type = Long.class),
67 @Info(name = "remark", description = "remark", type = String.class),
68
69 @Info(name = "tenantLoginId", description = "tenant login id", type = Long.class),
70 @Info(name = "userLoginId", description = "user login id", type = Long.class),
71 @Info(name = "roleLoginId", description = "role login id", type = Long.class),
72 @Info(name = "datetime", description = "datetime", type = String.class)
73})
74@InfoOut(value = {
75 @Info(name = "id", description= "SO Settlement Id ", type = Long.class),
76 @Info(name = "tenantId", description = "tenant Id", type = Long.class),
77 @Info(name = "ouId", description = "Ou Id", type = Long.class),
78 @Info(name = "docTypeId", description = "doc type Id", type = Long.class),
79 @Info(name = "docNo", description = "Nomor Transaksi", type = String.class),
80 @Info(name = "docDate", description = "Tanggal Transaksi", type = String.class),
81 @Info(name = "refDocTypeId", description = "ref doc type Id", type = Long.class),
82 @Info(name = "refId", description = "ref Id", type = Long.class),
83 @Info(name = "statusDoc", description = "statusDoc", type = String.class),
84 @Info(name = "workflowStatus", description = "workflowStatus", type = String.class),
85 @Info(name = "remark", description = "remark", type = String.class)
86})
87@ErrorList(errorKeys = {
88})
89//@formatter:on
90public class AddSoSettlement extends DefaultBusinessTransaction implements BusinessTransaction {
91
92 @Autowired
93 @Qualifier("valTenantLoginCanUse")
94 private BusinessFunction valTenantLoginCanUse;
95
96 @Autowired
97 @Qualifier("findOUById")
98 private BusinessFunction findOUById;
99
100 @Autowired
101 @Qualifier("valAuthorizedPolicyOU")
102 private BusinessFunction valAuthorizedPolicyOU;
103
104 @Autowired
105 @Qualifier("valSoSettlementExistsByIndex")
106 private BusinessFunction valSoSettlementExistsByIndex;
107
108 @Autowired
109 @Qualifier("findSalesOrderById")
110 private BusinessFunction findSalesOrderById;
111
112 @Autowired
113 @Qualifier("findSoAdminSettleById")
114 private BusinessFunction findSoAdminSettleById;
115
116 @Autowired
117 @Qualifier("getProductListByBrandForSettlement")
118 private BusinessFunction getProductListByBrandForSettlement;
119
120 @Autowired
121 @Qualifier("getSoCalculationListBySoId")
122 private BusinessFunction getSoCalculationListBySoId;
123
124 @Autowired
125 @Qualifier("findSoBrandItemById")
126 private BusinessFunction findSoBrandItemById;
127
128 @Autowired
129 @Qualifier("getSalesOrderDetailBrandListBySalesOrder")
130 private BusinessFunction getSalesOrderDetailBrandListBySalesOrder;
131
132 @Autowired
133 @Qualifier("getSalesOrderDetailItemListByBrandIdAndSoId")
134 private BusinessFunction getSalesOrderDetailItemListByBrandIdAndSoId;
135
136 @Autowired
137 @Qualifier("findBrandById")
138 private BusinessFunction findBrandById;
139
140 @Autowired
141 @Qualifier("findProductById")
142 private BusinessFunction findProductById;
143
144 @Autowired
145 @Qualifier("findSoStatusById")
146 private BusinessFunction findSoStatusById;
147
148 @Autowired
149 private SoCalculationDao soCalculationDao;
150
151 @Autowired
152 private SoSettlementDao soSettlementDao;
153
154 @Autowired
155 private SoSettlementItemDao soSettlementItemDao;
156
157 @Autowired
158 private SoAdminSettleDao soAdminSettleDao;
159
160 @Autowired
161 private ProductBalanceStockReservedDao productBalanceStockReservedDao;
162
163 @Autowired
164 private SoStatusDao soStatusDao;
165
166 @Autowired
167 private SalesOrderDao salesOrderDao;
168
169 @Autowired
170 private SoStatusLogDao soStatusLogDao;
171
172 @Autowired
173 @Qualifier("isQtyBrandSufficientForSettlement")
174 private BusinessFunction isQtyBrandSufficientForSettlement;
175
176 @Override
177 public String getDescription() {
178 return "Add New SO Settlement";
179 }
180
181 @SuppressWarnings("unchecked")
182 @Override
183 public Dto prepare(Dto inputDto, Dto originalDto) throws Exception {
184
185 // Validation tidak boleh kosong / null / tanggal / etc
186 ValidationUtil.valBlankOrNull(inputDto, "ouId");
187 ValidationUtil.valBlankOrNull(inputDto, "docNo");
188 ValidationUtil.valDate(inputDto, "docDate");
189 ValidationUtil.valBlankOrNull(inputDto, "soId");
190 ValidationUtil.valDtoContainsKey(inputDto, "remark");
191
192 //penamaan variable
193 Long tenantLoginId = inputDto.getLong("tenantLoginId");
194 Long roleLoginId = inputDto.getLong("roleLoginId");
195 Long userLoginId = inputDto.getLong("userLoginId");
196 String datetime = inputDto.getString("datetime");
197
198 Long ouId = inputDto.getLong("ouId");
199 Long docTypeId = SalesConstantsForKtmt.DOCUMENT_SO_SETTLEMENT;
200 String docNo = inputDto.getString("docNo");
201 String docDate = inputDto.getString("docDate");
202 Long soId = inputDto.getLong("soId");
203 String remark = inputDto.getString("remark");
204
205 // Validation tenant login id can be use
206 Dto loginDto = new Dto();
207 loginDto.put("tenantLoginId", tenantLoginId);
208 loginDto.put("userLoginId", userLoginId);
209 loginDto.put("roleLoginId", roleLoginId);
210 valTenantLoginCanUse.execute(loginDto);
211
212 //cek apakah ada SO lain yg sedang dilakukan Settlement
213 // Dto cekOtherSoDto = isSoAdminSettleExistsWithInProgressStatus.execute(new Dto().put("tenantId", tenantLoginId).put(
214 // "ouId", ouId));
215 //
216 // if (cekOtherSoDto.getBoolean("exists")) {
217 // Long soIdInProgress = cekOtherSoDto.getDto("soAdminSettleDto").getLong("id");
218 // if (!soIdInProgress.equals(soId)) {
219 // Dto otherSoDto = findSalesOrderById.execute(new Dto().put("id", soIdInProgress));
220 // throw new CoreException(SalesExceptionConstantsForKtmt.CANT_CREATE_SO_SETTLEMENT_CAUSE_OTHER_SO_IS_IN_PROGRESS,
221 // otherSoDto.getString("docNo"));
222 // }
223 // }
224
225 //validation ouId harus ada di table t_ou
226 Dto ouDto = findOUById.execute(new Dto().put("id", ouId));
227 checkTenant(tenantLoginId, ouDto, "tenant login", "ou");
228 checkActive(ouDto, "ou SO Settlement");
229
230 //validation user must authorized for ou
231 Dto inputDtoForValAuthorizedPolicyOU = new Dto();
232 inputDtoForValAuthorizedPolicyOU.put("userLoginId", userLoginId);
233 inputDtoForValAuthorizedPolicyOU.put("roleLoginId", roleLoginId);
234 inputDtoForValAuthorizedPolicyOU.put("ouId", ouId);
235 inputDtoForValAuthorizedPolicyOU.put("varName", "OU SO Settlement");
236 valAuthorizedPolicyOU.execute(inputDtoForValAuthorizedPolicyOU);
237
238 //cek soId must be exist & status doc = R
239 Dto soDto = findSalesOrderById.execute(new Dto().put("id", soId));
240
241 if (!soDto.getString("statusDoc").equals(SalesConstantsForKtmt.RELEASED_TRANSACTION)) {
242 throw new CoreException(SalesExceptionConstantsForKtmt.CANT_CREATE_SO_SETTLEMENT_CAUSE_SO_NOT_RELEASE_YET,
243 soDto.getString("docNo"));
244 }
245
246 CommonBusinessValidator.valCompareDate(docDate, soDto.getString("docDate"),
247 CommonBusinessValidator.COMPARE_GREATER_EQUAL, "SO Settlement Document Date", "Sales Order Document Date");
248
249 //find detail data so admin settle
250 Dto soAdminSettleDto = findSoAdminSettleById.execute(new Dto().put("id", soId));
251
252 //cek SO tersebut harus belum pernah di settle sebelumnya
253 if (soAdminSettleDto.getString("flgSettle").equals(GeneralConstants.YES)) {
254 throw new CoreException(SalesExceptionConstantsForKtmt.CANT_CREATE_SO_SETTLEMENT_CAUSE_SO_ALREADY_SETTLE);
255 }
256
257 //get detail SO brand item
258 Dto resultBrandDto = getSalesOrderDetailBrandListBySalesOrder.execute(new Dto().put("tenantId", tenantLoginId).put(
259 "soId", soId));
260 List<Dto> salesOrderDetailBrandList = resultBrandDto.getList("salesOrderDetailBrandList");
261
262 boolean needValidate = true;
263 List<Dto> failCekBrandList = new ArrayList<Dto>();
264 if (salesOrderDetailBrandList != null && salesOrderDetailBrandList.size() > 0) {
265 for (Dto soBrandItemDto : salesOrderDetailBrandList) {
266 Long brandId = soBrandItemDto.getLong("brandId");
267 Double qty = soBrandItemDto.getDouble("qty");
268 try {
269 Dto isValidBrandDto = isQtyBrandSufficientForSettlement.execute(new Dto()
270 .put("ouId", ouId)
271 .put("brandId", brandId)
272 .put("qty", qty)
273 );
274 Dto brandDto = isValidBrandDto.getDto("brandDto");
275 boolean isValidBrand = isValidBrandDto.getBoolean("isValid");
276 if (!isValidBrand) {
277 throw new CoreException(SalesExceptionConstantsForKtmt.INSUFFICIENT_STOCK_AFTER_CALCULATE_QTY_BRAND,
278 brandDto.getString("brandName"));
279 } else {
280 needValidate = false;
281 }
282
283 } catch (CoreException e) {
284 Dto inputDtoforCekQty = (Dto) soBrandItemDto.clone();
285 // success dto
286 inputDtoforCekQty.put("errorKey", e.getErrorKey());
287
288 List<Object> argsList = new ArrayList<Object>();
289 if (e.getParamValues() != null && e.getParamValues().length > 0)
290 for (Object paramValue : e.getParamValues()) {
291 argsList.add(paramValue);
292 }
293 inputDtoforCekQty.put("args", argsList);
294
295 failCekBrandList.add(inputDtoforCekQty);
296 }
297 }
298 }
299
300 if (needValidate && !failCekBrandList.isEmpty()) {
301 Dto errorParamDto = new Dto();
302 DtoUtil.putInErrorParamDto(errorParamDto, "failList", new String[] { "brandCode","brandName","qty","errorKey", "args" }, failCekBrandList);
303 throw new CoreException(SalesExceptionConstantsForKtmt.SO_SETTLEMENT_ITEM_ERROR, errorParamDto);
304 }
305
306 //generate so calculation item
307 Dto paramDto = new Dto();
308 paramDto.put("ouId", ouId);
309 paramDto.put("soId", soId);
310 paramDto.put("tenantLoginId", tenantLoginId);
311 paramDto.put("userLoginId", userLoginId);
312 paramDto.put("datetime", datetime);
313 paramDto.put("salesOrderDetailBrandList", salesOrderDetailBrandList);
314 generateSoCalculation(paramDto);
315
316 //get detail item list
317 Dto resultItem = getSoCalculationListBySoId.execute(new Dto().put("soId", soId));
318 List<Dto> itemList = resultItem.getList("soCalculationList");
319
320 List<Dto> resultItemList = new ArrayList<Dto>();
321 List<Dto> failList = new ArrayList<Dto>();
322 Dto detailPerProductDto = null;
323 //cek itemList
324 if (itemList != null && itemList.size() > 0) {
325 Long lineNo = 0L;
326 detailPerProductDto = new Dto();
327 for (Dto itemDto : itemList) {
328 try {
329 //get variable
330 Long soBrandItemId = itemDto.getLong("soBrandItemId");
331 Long brandId = itemDto.getLong("brandId");
332 Long productId = itemDto.getLong("productId");
333 Double qtySo = itemDto.getDouble("qtySo");
334 Double qtySettlement = itemDto.getDouble("qtySettlement");
335 Long soItemId = itemDto.getLong("soItemId");
336
337 //soBrandItem harus exists
338 findSoBrandItemById.execute(new Dto().put("id", soBrandItemId));
339
340 //brand harus exists
341 Dto brandDto = findBrandById.execute(new Dto().put("id", brandId));
342 checkTenant(tenantLoginId, brandDto, "tenant login", "brand");
343 checkActive(brandDto, "Brand SO Settlement");
344
345 //product harus exists
346 Dto productDto = findProductById.execute(new Dto().put("id", productId));
347 checkTenant(tenantLoginId, productDto, "tenant login", "Product");
348 checkActive(productDto, "Product SO Settlement");
349
350 // qtySettlement amount must > 0
351 //if (qtySettlement <= 0) {
352 // throw new CoreException(SalesExceptionConstantsForKtmt.QTY_SETTLEMENT_MUST_GREATER_THAN_ZERO,
353 // qtySettlement);
354 //}
355
356 //create Map of qty per product
357 if (detailPerProductDto.containsKey(brandId.toString())) {
358 Double qty = detailPerProductDto.getDouble(brandId.toString());
359 Calc qtyCalc = new Calc(qty);
360 qtyCalc = qtyCalc.add(qtySettlement);
361
362 detailPerProductDto.put(brandId.toString(), qtyCalc.doubleValue());
363 } else {
364 detailPerProductDto.put(brandId.toString(), qtySettlement);
365 }
366
367 //create list item
368 Dto soSettlementItemDto = new Dto();
369 soSettlementItemDto.put("tenantId", tenantLoginId);
370 soSettlementItemDto.put("refItemId", soBrandItemId);
371 soSettlementItemDto.put("lineNo", lineNo++);
372 soSettlementItemDto.put("productId", productId);
373 soSettlementItemDto.put("qtySo", qtySo);
374 soSettlementItemDto.put("qtySettlement", qtySettlement);
375 soSettlementItemDto.put("soItemId", soItemId);
376 soSettlementItemDto.put("baseUomId", productDto.getLong("baseUomId"));
377 this.prepareInsertAudit(soSettlementItemDto, userLoginId, datetime);
378 this.prepareUpdateAudit(soSettlementItemDto, userLoginId, datetime);
379
380 resultItemList.add(soSettlementItemDto);
381 } catch (CoreException e) {
382 Dto inputDtoForAddSoSettlement = new Dto();
383 // success dto
384 inputDtoForAddSoSettlement.put("errorKey", e.getErrorKey());
385
386 List<Object> argsList = new ArrayList<Object>();
387 if (e.getParamValues() != null && e.getParamValues().length > 0)
388 for (Object paramValue : e.getParamValues()) {
389 argsList.add(paramValue);
390 }
391 inputDtoForAddSoSettlement.put("args", argsList);
392
393 failList.add(inputDtoForAddSoSettlement);
394 }
395 }
396 } else {
397 throw new CoreException(SalesExceptionConstantsForKtmt.SO_SETTLEMENT_MINIMAL_MUST_HAVE_1_ITEM);
398 }
399
400 if (!failList.isEmpty()) {
401 Dto errorParamDto = new Dto();
402 DtoUtil.putInErrorParamDto(errorParamDto, "failList", new String[] { "errorKey", "args" }, failList);
403 throw new CoreException(SalesExceptionConstantsForKtmt.SO_SETTLEMENT_ITEM_ERROR, errorParamDto);
404 }
405
406 //cek masing2 qty di SO brand item harus lebih besar atau sama dengan total detail per item SO Settlement
407 List<Dto> failCekQtyList = new ArrayList<Dto>();
408 if (salesOrderDetailBrandList != null && salesOrderDetailBrandList.size() > 0) {
409 for (Dto soBrandItemDto : salesOrderDetailBrandList) {
410 try {
411 if (detailPerProductDto != null) {
412 if (detailPerProductDto.containsKey(soBrandItemDto.getLong("brandId").toString())) {
413
414 boolean compareQty = CommonBusinessValidator.compareNumber(
415 detailPerProductDto.getDouble(soBrandItemDto.getLong("brandId").toString()).toString(),
416 soBrandItemDto.getDouble("qty").toString(), CommonBusinessValidator.COMPARE_GREATER,
417 "Qty Settle", "Qty Brand Item");
418
419 if (compareQty) {
420 throw new CoreException(
421 SalesExceptionConstantsForKtmt.QTY_DETAIL_ITEM_CAN_NOT_BE_GREATER_THAN_QTY_BRAND_ITEM,
422 detailPerProductDto.getDouble(soBrandItemDto.getLong("brandId").toString()),
423 soBrandItemDto.getDouble("qty"));
424 }
425
426 } else {
427 throw new CoreException(SalesExceptionConstantsForKtmt.ALL_SO_BRAND_ID_MUST_HAVE_DETAIL_ITEM,
428 soBrandItemDto.getString("brandCode"));
429 }
430 }
431 } catch (CoreException e) {
432 Dto inputDtoforCekQty = new Dto();
433 // success dto
434 inputDtoforCekQty.put("errorKey", e.getErrorKey());
435
436 List<Object> argsList = new ArrayList<Object>();
437 if (e.getParamValues() != null && e.getParamValues().length > 0)
438 for (Object paramValue : e.getParamValues()) {
439 argsList.add(paramValue);
440 }
441 inputDtoforCekQty.put("args", argsList);
442
443 failCekQtyList.add(inputDtoforCekQty);
444 }
445 }
446 }
447
448 if (!failCekQtyList.isEmpty()) {
449 Dto errorParamDto = new Dto();
450 DtoUtil.putInErrorParamDto(errorParamDto, "failList", new String[] { "errorKey", "args" }, failCekQtyList);
451 throw new CoreException(SalesExceptionConstantsForKtmt.SO_SETTLEMENT_ITEM_ERROR, errorParamDto);
452 }
453
454 //create data So Settlement
455 SoSettlement soSettlement = new SoSettlement();
456 soSettlement.setTenantId(tenantLoginId);
457 soSettlement.setOuId(ouId);
458 soSettlement.setDocTypeId(docTypeId);
459 soSettlement.setDocNo(docNo);
460 soSettlement.setDocDate(docDate);
461 soSettlement.setRefDocTypeId(soDto.getLong("docTypeId"));
462 soSettlement.setRefId(soId);
463 soSettlement.setStatusDoc(SalesConstantsForKtmt.DRAFT_TRANSACTION);
464 soSettlement.setWorkflowStatus(SalesConstantsForKtmt.WORKFLOW_STATUS_DRAFT);
465 soSettlement.setRemark(remark);
466 Dto soSettlementDto = new Dto(soSettlement);
467 this.prepareInsertAudit(soSettlementDto, userLoginId, datetime);
468 this.prepareUpdateAudit(soSettlementDto, userLoginId, datetime);
469
470 //update data so admin settle
471 soAdminSettleDto.put("flgSettle", SalesConstantsForKtmt.IN_PROGRESS_TRANSACTION);
472 soAdminSettleDto.put("createDocDatetime", datetime);
473 soAdminSettleDto.put("createDocUserId", userLoginId);
474 this.prepareUpdateAudit(soAdminSettleDto, userLoginId, datetime);
475
476 //update data SO Status
477 Dto soStatusDto = findSoStatusById.execute(new Dto().put("id", soId));
478 soStatusDto.put("statusSettlement", SalesConstantsForKtmt.IN_PROGRESS_TRANSACTION);
479 this.prepareUpdateAudit(soStatusDto, userLoginId, datetime);
480
481 Dto soStatusLogDto = new Dto();
482 soStatusLogDto.put("soId", soId);
483 soStatusLogDto.put("state", SalesConstantsForKtmt.SO_STATUS_STATE_SETTLEMENT);
484 soStatusLogDto.put("docTypeId", SalesConstantsForKtmt.DOCUMENT_SO_SETTLEMENT);
485 soStatusLogDto.put("docAction", SalesConstantsForKtmt.SO_STATUS_DOC_ACTION_CREATE);
486
487 // Update status doc so by brand to In progess transaction
488 soDto.put("statusDoc", SalesConstantsForKtmt.IN_PROGRESS_TRANSACTION);
489 this.prepareUpdateAudit(soDto, userLoginId, datetime);
490
491 inputDto.put("resultItemList", resultItemList);
492 inputDto.put("soSettlementDto", soSettlementDto);
493 inputDto.put("soAdminSettleDto", soAdminSettleDto);
494 inputDto.put("soStatusDto", soStatusDto);
495 inputDto.put("soStatusLogDto", soStatusLogDto);
496 inputDto.put("salesOrderDto", soDto);
497
498 return null;
499 }
500
501 @SuppressWarnings("unchecked")
502 @Override
503 public Dto process(Dto inputDto, Dto originalDto) throws Exception {
504 List<Dto> resultItemList = inputDto.getList("resultItemList");
505 Dto soSettlementDto = inputDto.getDto("soSettlementDto");
506 Dto soAdminSettleDto = inputDto.getDto("soAdminSettleDto");
507
508 //insert data header
509 SoSettlement soSettlement = GsonUtil.fromDto(soSettlementDto, SoSettlement.class);
510 soSettlementDao.persist(soSettlement);
511
512 Long docId = soSettlement.getId();
513
514 if (resultItemList != null & resultItemList.size() > 0) {
515 for (Dto item : resultItemList) {
516 //update data stock reserved
517 QueryBuilder builderAddReserved = new QueryBuilder();
518 //@formatter:off
519 builderAddReserved.add(" WITH origin_updated_product AS ( ")
520 .add(" UPDATE in_product_balance_stock_reserved ")
521 .add(" SET qty= (qty + :qty), ")
522 .add(" version= (version + 1), ")
523 .add(" update_datetime = :updateDatetime, ")
524 .add(" update_user_id = :updateUserId ")
525 .add(" WHERE tenant_id = :tenantId ")
526 .add(" AND ou_id = :ouId ")
527 .add(" AND product_id = :productId ")
528 .add(" AND product_status = :productStatus ")
529 .add(" RETURNING * ) ")
530 .add(" INSERT INTO in_product_balance_stock_reserved ")
531 .add(" (tenant_id, ou_id, product_id, base_uom_id, product_status, qty, ")
532 .add(" version, create_datetime, create_user_id, update_datetime, update_user_id) ")
533 .add(" SELECT :tenantId, :ouId, :productId, :baseUomId, :productStatus, :qty, ")
534 .add(" :version, :createDatetime, :createUserId, :updateDatetime, :updateUserId ")
535 .add(" WHERE NOT EXISTS (SELECT 1 FROM origin_updated_product); ");
536 //@formatter:on
537
538 Query queryAddReserved = productBalanceStockReservedDao.createNativeQuery(builderAddReserved.toString());
539 queryAddReserved.setParameter("qty", item.getDouble("qtySettlement"));
540 queryAddReserved.setParameter("tenantId", inputDto.getLong("tenantLoginId"));
541 queryAddReserved.setParameter("ouId", inputDto.getLong("ouId"));
542 queryAddReserved.setParameter("productId", item.getLong("productId"));
543 queryAddReserved.setParameter("baseUomId", item.getLong("baseUomId"));
544 queryAddReserved.setParameter("productStatus", SalesConstantsForKtmt.STATUS_GOOD);
545 queryAddReserved.setParameter("version", SalesConstantsForKtmt.ZERO_REF_VALUE_LONG);
546 queryAddReserved.setParameter("createDatetime", inputDto.getString("datetime"));
547 queryAddReserved.setParameter("createUserId", inputDto.getLong("userLoginId"));
548 queryAddReserved.setParameter("updateDatetime", inputDto.getString("datetime"));
549 queryAddReserved.setParameter("updateUserId", inputDto.getLong("userLoginId"));
550
551 queryAddReserved.executeUpdate();
552 productBalanceStockReservedDao.flush();
553
554 //insert data item
555 SoSettlementItem soSettlementItem = GsonUtil.fromDto(item, SoSettlementItem.class);
556 soSettlementItem.setSoSettlementId(docId);
557 soSettlementItemDao.persist(soSettlementItem);
558
559 }
560 }
561
562 //update data so admin
563 SoAdminSettle soAdminSettle = GsonUtil.fromDto(soAdminSettleDto, SoAdminSettle.class);
564 soAdminSettleDao.merge(soAdminSettle.getId(), soAdminSettle);
565
566 //update data SO Status
567 Dto soStatusDto = inputDto.getDto("soStatusDto");
568 soStatusDto.put("soSettlementId", soSettlement.getId());
569 SoStatus soStatus = GsonUtil.fromDto(soStatusDto, SoStatus.class);
570 soStatus = soStatusDao.merge(soStatus.getId(), soStatus);
571
572 //update status doc SO
573 Dto salesOrderDto = inputDto.getDto("salesOrderDto");
574 SalesOrder salesOrder = GsonUtil.fromDto(salesOrderDto, SalesOrder.class);
575 salesOrder = salesOrderDao.merge(salesOrder.getId(), salesOrder);
576
577 Dto soStatusLogDto = inputDto.getDto("soStatusLogDto");
578 soStatusLogDto.put("docId", soSettlement.getId());
579 SoStatusLog soStatusLog = GsonUtil.fromDto(soStatusLogDto, SoStatusLog.class);
580 soStatusLogDao.persist(soStatusLog);
581
582 return new Dto(soSettlement);
583 }
584
585 @SuppressWarnings("unchecked")
586 private void generateSoCalculation(Dto paramDto) throws Exception {
587 //get variable
588 Long ouId = paramDto.getLong("ouId");
589 Long soId = paramDto.getLong("soId");
590 Long tenantLoginId = paramDto.getLong("tenantLoginId");
591 Long userLoginId = paramDto.getLong("userLoginId");
592 String datetime = paramDto.getString("datetime");
593 List<Dto> brandList = paramDto.getList("salesOrderDetailBrandList");
594 String sessionId = UUID.randomUUID().toString();
595 //List<Dto> reservedList = new ArrayList<Dto>();
596 List<Dto> prePreparationList = new ArrayList<Dto>();
597
598 if (brandList != null && brandList.size() > 0) {
599 for (Dto brandDto : brandList) {
600 Long brandId = brandDto.getLong("brandId");
601 Double qty = brandDto.getDouble("qty");
602
603 //get item reserved
604 Dto resultReservedDto = getSalesOrderDetailItemListByBrandIdAndSoId.execute(new Dto().put("soId", soId).put(
605 "brandId", brandId));
606 List<Dto> itemList = resultReservedDto.getList("salesOrderDetailItemList");
607 Calc totalReservedCalc = new Calc(0);
608 Calc limitCalc = new Calc(qty.doubleValue());
609 if (itemList != null && itemList.size() > 0) {
610 for (Dto itemDto : itemList) {
611 //create Dto for ReservedData
612 //Dto itemReservedDto = new Dto();
613 //itemReservedDto.put("sessionId", sessionId);
614 //itemReservedDto.put("dataId", SalesConstantsForKtmt.DATA_ID_RESERVED_SETTLEMENT);
615 //itemReservedDto.put("tenantId", tenantLoginId);
616 //itemReservedDto.put("soId", soId);
617 //itemReservedDto.put("brandId", brandId);
618 //itemReservedDto.put("productId", itemDto.getLong("productId"));
619 //itemReservedDto.put("qty", itemDto.getDouble("qtyInt"));
620
621 //reservedList.add(itemReservedDto);
622
623 totalReservedCalc = totalReservedCalc.add(itemDto.getDouble("qtyInt"));
624 }
625 }
626
627 limitCalc = limitCalc.subtract(totalReservedCalc);
628 Long limit = limitCalc.longValue();
629
630 //limit product for calculation
631 Dto resultProductDto = getProductListByBrandForSettlement.execute(new Dto().put("tenantId", tenantLoginId)
632 .put("ouId", ouId).put("brandId", brandId).put("limit", limit).put("soId", soId));
633
634 List<Dto> productList = resultProductDto.getList("productList");
635
636 if (productList != null && productList.size() > 0) {
637 for (Dto productDto : productList) {
638 //create Dto for pre-Preparation Data
639 Dto prePreparationDto = new Dto();
640 prePreparationDto.put("sessionId", sessionId);
641 prePreparationDto.put("dataId", SalesConstantsForKtmt.DATA_ID_PRE_PREPARATION_SETTLEMENT);
642 prePreparationDto.put("tenantId", tenantLoginId);
643 prePreparationDto.put("soId", soId);
644 prePreparationDto.put("brandId", productDto.getLong("brandId"));
645 prePreparationDto.put("productId", productDto.getLong("productId"));
646 prePreparationDto.put("stock", productDto.getDouble("stock"));
647
648 prePreparationList.add(prePreparationDto);
649 }
650 }
651 }
652 }
653 //insert reserved data
654 //soCalculationDao.insertDataReserved(reservedList);
655 //soCalculationDao.flush();
656
657 //insert pre-Preparation Data
658 soCalculationDao.insertDataPrePreparation(prePreparationList);
659
660 Dto parameterDto = new Dto();
661 parameterDto.put("sessionId", sessionId);
662 parameterDto.put("tenantId", tenantLoginId);
663 parameterDto.put("soId", soId);
664 parameterDto.put("datetime", datetime);
665 parameterDto.put("userLoginId", userLoginId);
666
667 //call function to generate combination
668 soCalculationDao.callPreparationSoSettlement(parameterDto);
669 }
670
671 private void checkTenant(Long tenantLoginId, Dto dto, String desc1, String desc2) {
672 if (!tenantLoginId.equals(dto.getLong("tenantId"))) {
673 throw new CoreException(CommonExceptionConstants.DATA_CANT_USE_DIFF_TENANT, desc1, desc2);
674 }
675 }
676
677 private void checkActive(Dto dto, String desc) {
678 if (!GeneralConstants.YES.equals(dto.getString("active"))) {
679 throw new CoreException(MasterExceptionConstants.DATA_NOT_ACTIVE, desc);
680 }
681 }
682}