@things-factory/sales-base 4.3.656 → 4.3.664

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,6 +46,8 @@ const _1 = require("./");
46
46
  const arrival_notice_1 = require("./arrival-notice");
47
47
  const arrival_notice_types_1 = require("./arrival-notice-types");
48
48
  const i18next_1 = __importDefault(require("i18next"));
49
+ const order_inventory_1 = require("../order-inventory/order-inventory");
50
+ const goods_receival_note_1 = require("../goods-receival-note/goods-receival-note");
49
51
  const debug = require('debug')('things-factory:operato-wms:addArrivalNotice');
50
52
  let ArrivalNoticeMutation = class ArrivalNoticeMutation {
51
53
  async deleteArrivalNotice(name, context) {
@@ -61,7 +63,7 @@ let ArrivalNoticeMutation = class ArrivalNoticeMutation {
61
63
  async confirmArrivalNotice(name, context) {
62
64
  const { tx } = context.state;
63
65
  const arrivalNotice = await confirmArrivalNoticeFunction(name, context, tx);
64
- // If current GAN has cross docking
66
+ // If current has cross docking
65
67
  if (arrivalNotice.crossDocking) {
66
68
  const { releaseGood } = await tx.getRepository(arrival_notice_1.ArrivalNotice).findOne(arrivalNotice.id, {
67
69
  relations: ['releaseGood']
@@ -97,6 +99,274 @@ let ArrivalNoticeMutation = class ArrivalNoticeMutation {
97
99
  }
98
100
  return arrivalNotice;
99
101
  }
102
+ async submitDirectInboundArrivalNotice(context, arrivalNotice, files) {
103
+ const { user, domain, tx } = context.state;
104
+ let orderProducts = arrivalNotice.orderProducts;
105
+ let myBizplace;
106
+ if (arrivalNotice.customerBizplaceId) {
107
+ const permittedBizplaces = await (0, biz_base_1.getPermittedBizplaces)(domain, user);
108
+ let foundPermittedBizplace = permittedBizplaces.find(biz => biz.id == arrivalNotice.customerBizplaceId);
109
+ if (!foundPermittedBizplace)
110
+ throw new Error(`This user does not permitted for this company`);
111
+ myBizplace = { id: arrivalNotice.customerBizplaceId };
112
+ }
113
+ else if (arrivalNotice.partnerBizplaceId) {
114
+ const permittedBizplaces = await (0, biz_base_1.getPermittedBizplaces)(domain, user);
115
+ let foundPermittedBizplace = permittedBizplaces.find(biz => biz.id == arrivalNotice.partnerBizplaceId);
116
+ if (!foundPermittedBizplace)
117
+ throw new Error(`This user does not permitted for this company`);
118
+ myBizplace = { id: arrivalNotice.partnerBizplaceId };
119
+ }
120
+ else if (arrivalNotice.warehouseId)
121
+ myBizplace = await (0, biz_base_1.getOutletBizplace)(arrivalNotice.warehouseId);
122
+ else
123
+ myBizplace = await (0, biz_base_1.getMyBizplace)(domain, user);
124
+ let orderProductsMap = mergeDuplicateRow(orderProducts, ['product.id', 'location.id', 'batchId', 'expDate'], 'packQty');
125
+ orderProducts = [...orderProductsMap.values()];
126
+ const pendingArrivalNotice = await tx.getRepository(arrival_notice_1.ArrivalNotice).save(Object.assign(Object.assign({}, arrivalNotice), { name: order_no_generator_1.OrderNoGenerator.arrivalNotice(), domain, bizplace: myBizplace, status: constants_1.ORDER_STATUS.PENDING, creator: user, updater: user }));
127
+ const orderProductRepo = tx.getRepository(order_product_1.OrderProduct);
128
+ const pendingOrderProducts = orderProducts.map(op => {
129
+ var _a;
130
+ return ({
131
+ name: order_no_generator_1.OrderNoGenerator.orderProduct(),
132
+ product_id: op.product.id,
133
+ product_detail_id: op.productDetail.id,
134
+ batch_id: op.batchId,
135
+ batch_id_ref: op.batchIdRef,
136
+ packing_type: op.packingType,
137
+ packing_size: op.packingSize,
138
+ uom: op.uom,
139
+ uom_value: op.uomValue || 0,
140
+ pack_qty: op.packQty || 0,
141
+ total_uom_value: op.totalUomValue,
142
+ pallet_qty: op.palletQty,
143
+ pallet_id: op.palletId,
144
+ unit_price: op.unitPrice,
145
+ remark: op.remark,
146
+ manufacture_date: op.manufactureDate,
147
+ status: constants_1.ORDER_STATUS.PENDING,
148
+ adjusted_batch_id: op.adjustedBatchId,
149
+ adjusted_batch_id_ref: op.adjustedBatchIdRef,
150
+ adjusted_packing_type: op.adjustedPackingType,
151
+ adjusted_uom_value: op.adjustedUomValue,
152
+ adjusted_uom: op.adjustedUom,
153
+ adjusted_pack_qty: op.adjustedPackQty,
154
+ adjusted_total_uom_value: op.adjustedTotalUomValue,
155
+ adjusted_pallet_qty: op.adjustedPalletQty,
156
+ adjusted_unit_price: op.adjustedUnitPrice,
157
+ domain_id: domain.id,
158
+ bizplace_id: pendingArrivalNotice.bizplaceId || ((_a = pendingArrivalNotice.bizplace) === null || _a === void 0 ? void 0 : _a.id),
159
+ arrival_notice_id: pendingArrivalNotice.id,
160
+ creator_id: user.id,
161
+ updater_id: user.id,
162
+ warehouse_id: op.warehouse.id,
163
+ location_id: op.location.id,
164
+ exp_date: op.expDate
165
+ });
166
+ });
167
+ await orderProductRepo.query(`
168
+ INSERT INTO order_products (
169
+ "name", "product_detail_id", "product_id",
170
+ "batch_id", "batch_id_ref", "packing_type",
171
+ "packing_size", "uom", "uom_value",
172
+ "pack_qty", "total_uom_value", "pallet_qty",
173
+ "pallet_id", "unit_price", "remark",
174
+ "manufacture_date", "status", "adjusted_batch_id",
175
+ "adjusted_batch_id_ref", "adjusted_packing_type",
176
+ "adjusted_uom_value", "adjusted_uom",
177
+ "adjusted_pack_qty", "adjusted_total_uom_value",
178
+ "adjusted_pallet_qty", "adjusted_unit_price",
179
+ "domain_id", "bizplace_id", "arrival_notice_id",
180
+ "creator_id", "updater_id", "warehouse_id", "location_id", "exp_date"
181
+ )
182
+ SELECT
183
+ "name",
184
+ "product_detail_id",
185
+ "product_id",
186
+ "batch_id",
187
+ "batch_id_ref",
188
+ "packing_type",
189
+ "packing_size",
190
+ "uom",
191
+ "uom_value",
192
+ "pack_qty",
193
+ "total_uom_value",
194
+ "pallet_qty",
195
+ "pallet_id",
196
+ "unit_price",
197
+ "remark",
198
+ "manufacture_date",
199
+ "status",
200
+ "adjusted_batch_id",
201
+ "adjusted_batch_id_ref",
202
+ "adjusted_packing_type",
203
+ "adjusted_uom_value",
204
+ "adjusted_uom",
205
+ "adjusted_pack_qty",
206
+ "adjusted_total_uom_value",
207
+ "adjusted_pallet_qty",
208
+ "adjusted_unit_price",
209
+ "domain_id",
210
+ "bizplace_id",
211
+ "arrival_notice_id",
212
+ "creator_id",
213
+ "updater_id",
214
+ "warehouse_id",
215
+ "location_id",
216
+ "exp_date"
217
+ FROM
218
+ JSON_POPULATE_RECORDSET(NULL :: order_products, $1) op
219
+ `, [JSON.stringify(pendingOrderProducts)]);
220
+ return pendingArrivalNotice;
221
+ }
222
+ async confirmDirectInboundArrivalNotice(context, name) {
223
+ const { user, domain, tx } = context.state;
224
+ const pendingArrivalNotice = await tx.getRepository(arrival_notice_1.ArrivalNotice).findOne({
225
+ where: { domain, name, status: constants_1.ORDER_STATUS.PENDING },
226
+ relations: [
227
+ 'bizplace',
228
+ 'bizplace.domain',
229
+ 'releaseGood',
230
+ 'orderProducts',
231
+ 'orderProducts.product',
232
+ 'orderVass',
233
+ 'orderVass.vas',
234
+ 'creator',
235
+ 'updater'
236
+ ]
237
+ });
238
+ if (!pendingArrivalNotice)
239
+ throw new Error(`Arrival notice doesn't exist.`);
240
+ await tx.getRepository(arrival_notice_1.ArrivalNotice).update({ id: pendingArrivalNotice.id }, {
241
+ status: constants_1.ORDER_STATUS.DONE,
242
+ updater: user,
243
+ acceptedBy: user,
244
+ acceptedAt: new Date()
245
+ });
246
+ // find orderProducts tied to the arrival notice and assign inventory, inventory_histories, order_inventories
247
+ let pendingOrderProducts = await tx.getRepository(order_product_1.OrderProduct).find({
248
+ where: { arrivalNotice: { id: pendingArrivalNotice.id } },
249
+ relations: ['bizplace', 'domain', 'warehouse', 'location']
250
+ });
251
+ const inventoryRepo = tx.getRepository(warehouse_base_1.Inventory);
252
+ const opRepo = tx.getRepository(order_product_1.OrderProduct);
253
+ const inventoryHistoryRepo = tx.getRepository(warehouse_base_1.InventoryHistory);
254
+ const orderInventoryRepo = tx.getRepository(order_inventory_1.OrderInventory);
255
+ const inventories = [];
256
+ for (const op of pendingOrderProducts) {
257
+ const palletId = op.palletId ||
258
+ (await (0, id_rule_base_1.generateId)({ domain, type: warehouse_base_1.RULE_TYPE.LOT_NUMBER_ID, seed: { date: warehouse_base_1.DateGenerator.generateDate() } }));
259
+ const numericTotalUomValue = typeof op.totalUomValue === 'string' ? parseFloat(op.totalUomValue) : op.totalUomValue;
260
+ const cartonId = await (0, id_rule_base_1.generateId)({
261
+ domain,
262
+ type: warehouse_base_1.RULE_TYPE.CARTON_NUMBER_ID,
263
+ seed: { date: warehouse_base_1.DateGenerator.generateDate() }
264
+ });
265
+ const inventory = inventoryRepo.create({
266
+ domain,
267
+ bizplace: pendingArrivalNotice.bizplace,
268
+ name: warehouse_base_1.InventoryNoGenerator.inventoryName(),
269
+ cartonId: cartonId,
270
+ refOrderId: pendingArrivalNotice.id,
271
+ product: op.productId,
272
+ productDetail: op.productDetailId,
273
+ palletId,
274
+ packingType: op.packingType,
275
+ packingSize: op.packingSize,
276
+ batchId: op.batchId,
277
+ batchIdRef: op.batchIdRef,
278
+ expirationDate: op.expDate,
279
+ manufactureDate: op.manufactureDate,
280
+ uom: op.uom,
281
+ qty: op.packQty,
282
+ uomValue: numericTotalUomValue,
283
+ status: warehouse_base_1.INVENTORY_STATUS.STORED,
284
+ warehouse: op.warehouse,
285
+ zone: op.location.zone,
286
+ location: op.location,
287
+ creator: user,
288
+ updater: user
289
+ });
290
+ inventories.push(inventory);
291
+ op.status = constants_1.ORDER_PRODUCT_STATUS.STORED;
292
+ op.updater = user;
293
+ op.updatedAt = new Date();
294
+ op.actualPackQty = op.packQty;
295
+ await opRepo.save(op);
296
+ const newInventoryHistory = inventoryHistoryRepo.create({
297
+ name: warehouse_base_1.InventoryNoGenerator.inventoryHistoryName(),
298
+ refOrderId: pendingArrivalNotice.id,
299
+ orderNo: pendingArrivalNotice.name,
300
+ uom: inventory.uom,
301
+ transactionType: warehouse_base_1.INVENTORY_TRANSACTION_TYPE.NEW,
302
+ status: inventory.status,
303
+ qty: inventory.qty,
304
+ uomValue: inventory.uomValue,
305
+ openingQty: 0,
306
+ openingUomValue: 0,
307
+ seq: 0,
308
+ domain: inventory.domain,
309
+ bizplace: pendingArrivalNotice.bizplace,
310
+ inventory: inventory,
311
+ product: inventory.product,
312
+ productDetail: inventory.productDetail,
313
+ warehouse: inventory.warehouse,
314
+ location: inventory.location,
315
+ cartonId: inventory.cartonId,
316
+ palletId: inventory.palletId,
317
+ batchId: inventory.batchId,
318
+ zone: inventory.zone,
319
+ packingType: inventory.packingType,
320
+ description: inventory.description,
321
+ expirationDate: inventory.expirationDate,
322
+ unitCost: inventory.unitCost,
323
+ batchIdRef: inventory.batchIdRef,
324
+ manufactureDate: inventory.manufactureDate,
325
+ creator: user,
326
+ updater: user
327
+ });
328
+ await inventoryHistoryRepo.save(newInventoryHistory);
329
+ const orderInventory = orderInventoryRepo.create({
330
+ domain,
331
+ bizplace: inventory.bizplace,
332
+ name: order_no_generator_1.OrderNoGenerator.orderInventory(),
333
+ status: constants_1.ORDER_INVENTORY_STATUS.DONE,
334
+ batchId: inventory.batchId,
335
+ batchIdRef: inventory.batchIdRef,
336
+ packingType: inventory.packingType,
337
+ actualPackQty: inventory.qty,
338
+ actualPackUomValue: inventory.uomValue,
339
+ uom: inventory.uom,
340
+ product: inventory.product,
341
+ productDetail: inventory.productDetail,
342
+ unloadedBy: inventory.creator,
343
+ unloadedAt: inventory.createdAt,
344
+ putawayBy: inventory.creator,
345
+ putawayAt: inventory.createdAt,
346
+ type: constants_1.ORDER_TYPES.ARRIVAL_NOTICE,
347
+ arrivalNotice: pendingArrivalNotice,
348
+ inventory,
349
+ creator: user,
350
+ updater: user
351
+ });
352
+ await orderInventoryRepo.save(orderInventory);
353
+ }
354
+ await inventoryRepo.save(inventories);
355
+ const grnRepo = tx.getRepository(goods_receival_note_1.GoodsReceivalNote);
356
+ const orderNo = order_no_generator_1.OrderNoGenerator.goodsReceiveNote();
357
+ const grn = {
358
+ refNo: pendingArrivalNotice.name,
359
+ name: orderNo,
360
+ bizplace: pendingArrivalNotice.bizplace,
361
+ domain,
362
+ status: constants_1.GRN_STATUS.PENDING_RECEIVE,
363
+ creator: user,
364
+ updater: user,
365
+ arrivalNotice: pendingArrivalNotice
366
+ };
367
+ await grnRepo.save(grn);
368
+ return pendingArrivalNotice;
369
+ }
100
370
  async addEditArrivalNoticeProducts(context, ganNo, approvedAddEditProducts, newOrderProducts, existingOrderProducts) {
101
371
  var _a;
102
372
  const { user, domain, tx } = context.state;
@@ -125,6 +395,9 @@ let ArrivalNoticeMutation = class ArrivalNoticeMutation {
125
395
  .set({
126
396
  batchId: op.batchId,
127
397
  batchIdRef: op.batchIdRef,
398
+ expDate: op.expDate,
399
+ warehouse: op.warehouse ? { id: op.warehouse.id } : null,
400
+ location: op.location ? { id: op.location.id } : null,
128
401
  manufactureDate: op.manufactureDate,
129
402
  packQty: op.packQty,
130
403
  packingType: op.packingType,
@@ -360,6 +633,27 @@ __decorate([
360
633
  __metadata("design:paramtypes", [String, arrival_notice_types_1.ArrivalNoticePatch, Object]),
361
634
  __metadata("design:returntype", Promise)
362
635
  ], ArrivalNoticeMutation.prototype, "rejectArrivalNotice", null);
636
+ __decorate([
637
+ (0, type_graphql_1.Directive)('@privilege(category: "order_warehouse", privilege: "mutation")'),
638
+ (0, type_graphql_1.Directive)('@transaction'),
639
+ (0, type_graphql_1.Mutation)(returns => arrival_notice_1.ArrivalNotice),
640
+ __param(0, (0, type_graphql_1.Ctx)()),
641
+ __param(1, (0, type_graphql_1.Arg)('arrivalNotice', type => arrival_notice_types_1.NewArrivalNotice)),
642
+ __param(2, (0, type_graphql_1.Arg)('files', type => [graphql_upload_1.GraphQLUpload], { nullable: true })),
643
+ __metadata("design:type", Function),
644
+ __metadata("design:paramtypes", [Object, arrival_notice_types_1.NewArrivalNotice, Array]),
645
+ __metadata("design:returntype", Promise)
646
+ ], ArrivalNoticeMutation.prototype, "submitDirectInboundArrivalNotice", null);
647
+ __decorate([
648
+ (0, type_graphql_1.Directive)('@privilege(category: "order_warehouse", privilege: "mutation")'),
649
+ (0, type_graphql_1.Directive)('@transaction'),
650
+ (0, type_graphql_1.Mutation)(returns => arrival_notice_1.ArrivalNotice),
651
+ __param(0, (0, type_graphql_1.Ctx)()),
652
+ __param(1, (0, type_graphql_1.Arg)('name')),
653
+ __metadata("design:type", Function),
654
+ __metadata("design:paramtypes", [Object, String]),
655
+ __metadata("design:returntype", Promise)
656
+ ], ArrivalNoticeMutation.prototype, "confirmDirectInboundArrivalNotice", null);
363
657
  __decorate([
364
658
  (0, type_graphql_1.Directive)('@privilege(category: "order_warehouse", privilege: "mutation")'),
365
659
  (0, type_graphql_1.Directive)('@transaction'),
@@ -476,132 +770,137 @@ async function generateArrivalNoticeFunction(_, arrivalNotice, fromPo, files, co
476
770
  let myBizplace;
477
771
  let orderNo = '';
478
772
  const settingRepo = (tx === null || tx === void 0 ? void 0 : tx.getRepository(setting_base_1.Setting)) || (0, typeorm_1.getRepository)(setting_base_1.Setting);
479
- if (arrivalNotice.bizplace)
480
- myBizplace = arrivalNotice.bizplace;
481
- else if (arrivalNotice.customerBizplaceId) {
482
- const permittedBizplaces = await (0, biz_base_1.getPermittedBizplaces)(domain, user);
483
- let foundPermittedBizplace = permittedBizplaces.find(biz => biz.id == arrivalNotice.customerBizplaceId);
484
- if (!foundPermittedBizplace)
485
- throw new Error(`This user does not permitted for this company`);
486
- myBizplace = arrivalNotice.customerBizplaceId;
487
- }
488
- else if (arrivalNotice.partnerBizplaceId) {
489
- const permittedBizplaces = await (0, biz_base_1.getPermittedBizplaces)(domain, user);
490
- let foundPermittedBizplace = permittedBizplaces.find(biz => biz.id == arrivalNotice.partnerBizplaceId);
491
- if (!foundPermittedBizplace)
492
- throw new Error(`This user does not permitted for this company`);
493
- myBizplace = arrivalNotice.partnerBizplaceId;
494
- }
495
- else if (arrivalNotice.warehouseId)
496
- myBizplace = await (0, biz_base_1.getOutletBizplace)(arrivalNotice.warehouseId);
497
- else
498
- myBizplace = await (0, biz_base_1.getMyBizplace)(domain, user);
499
- // Add validation for decimal quantities
500
- for (let patch of orderProducts) {
501
- // Get product details to check isInventoryDecimal
502
- const product = (await tx.getRepository(product_base_1.Product).findOne({
503
- where: { id: patch.product.id }
504
- }));
505
- if (!product) {
506
- throw new Error(`Product not found for ID: ${patch.product.id}`);
773
+ try {
774
+ if (arrivalNotice.bizplace)
775
+ myBizplace = arrivalNotice.bizplace;
776
+ else if (arrivalNotice.customerBizplaceId) {
777
+ const permittedBizplaces = await (0, biz_base_1.getPermittedBizplaces)(domain, user);
778
+ let foundPermittedBizplace = permittedBizplaces.find(biz => biz.id == arrivalNotice.customerBizplaceId);
779
+ if (!foundPermittedBizplace)
780
+ throw new Error(`This user does not permitted for this company`);
781
+ myBizplace = arrivalNotice.customerBizplaceId;
507
782
  }
508
- // Validate packQty based on isInventoryDecimal flag
509
- const validatePackQty = (qty) => {
510
- if (qty === null || qty === undefined)
511
- return true;
512
- const numQty = Number(qty);
513
- if (isNaN(numQty))
514
- return false;
515
- if (product.isInventoryDecimal) {
516
- // For decimal products, check if decimal places <= 3
517
- const decimalPlaces = (numQty.toString().split('.')[1] || '').length;
518
- return decimalPlaces <= 3;
519
- }
520
- else {
521
- // For non-decimal products, check if it's a whole number
522
- return numQty === Math.floor(numQty);
523
- }
524
- };
525
- // Validate only packQty
526
- if (!validatePackQty(patch.packQty)) {
527
- throw new Error(`Invalid pack quantity for product ${product.name} (SKU: ${product.sku}). ${product.isInventoryDecimal
528
- ? 'Decimal quantities must have at most 3 decimal places'
529
- : 'Only whole numbers are allowed'}`);
783
+ else if (arrivalNotice.partnerBizplaceId) {
784
+ const permittedBizplaces = await (0, biz_base_1.getPermittedBizplaces)(domain, user);
785
+ let foundPermittedBizplace = permittedBizplaces.find(biz => biz.id == arrivalNotice.partnerBizplaceId);
786
+ if (!foundPermittedBizplace)
787
+ throw new Error(`This user does not permitted for this company`);
788
+ myBizplace = arrivalNotice.partnerBizplaceId;
530
789
  }
531
- // Check for existing LotID in Inventory
532
- let foundInventoryPallet = await tx.getRepository(warehouse_base_1.Inventory).findOne({
533
- where: {
534
- domain,
535
- palletId: patch.palletId
790
+ else if (arrivalNotice.warehouseId)
791
+ myBizplace = await (0, biz_base_1.getOutletBizplace)(arrivalNotice.warehouseId);
792
+ else
793
+ myBizplace = await (0, biz_base_1.getMyBizplace)(domain, user);
794
+ // Add validation for decimal quantities
795
+ for (let patch of orderProducts) {
796
+ // Get product details to check isInventoryDecimal
797
+ const product = (await tx.getRepository(product_base_1.Product).findOne({
798
+ where: { id: patch.product.id }
799
+ }));
800
+ if (!product) {
801
+ throw new Error(`Product not found for ID: ${patch.product.id}`);
536
802
  }
537
- });
538
- if (patch.palletId) {
539
- // Check for existing LotID in OrderProduct
540
- let foundOrderProductsPallet = await tx.getRepository(order_product_1.OrderProduct).find({
803
+ // Validate packQty based on isInventoryDecimal flag
804
+ const validatePackQty = (qty) => {
805
+ if (qty === null || qty === undefined)
806
+ return true;
807
+ const numQty = Number(qty);
808
+ if (isNaN(numQty))
809
+ return false;
810
+ if (product.isInventoryDecimal) {
811
+ // For decimal products, check if decimal places <= 3
812
+ const decimalPlaces = (numQty.toString().split('.')[1] || '').length;
813
+ return decimalPlaces <= 3;
814
+ }
815
+ else {
816
+ // For non-decimal products, check if it's a whole number
817
+ return numQty === Math.floor(numQty);
818
+ }
819
+ };
820
+ // Validate only packQty
821
+ if (!validatePackQty(patch.packQty)) {
822
+ throw new Error(`Invalid pack quantity for product ${product.name} (SKU: ${product.sku}). ${product.isInventoryDecimal
823
+ ? 'Decimal quantities must have at most 3 decimal places'
824
+ : 'Only whole numbers are allowed'}`);
825
+ }
826
+ // Check for existing LotID in Inventory
827
+ let foundInventoryPallet = await tx.getRepository(warehouse_base_1.Inventory).findOne({
541
828
  where: {
542
829
  domain,
543
830
  palletId: patch.palletId
544
831
  }
545
832
  });
546
- // Check for existing LotID in ArrivalNotice
547
- let arrivalNotices = await Promise.all(foundOrderProductsPallet.map(async (product) => {
548
- return await tx.getRepository(arrival_notice_1.ArrivalNotice).findOne({
833
+ if (patch.palletId) {
834
+ // Check for existing LotID in OrderProduct
835
+ let foundOrderProductsPallet = await tx.getRepository(order_product_1.OrderProduct).find({
549
836
  where: {
550
- id: product.arrivalNoticeId
837
+ domain,
838
+ palletId: patch.palletId
551
839
  }
552
840
  });
553
- }));
554
- //Allow the reuse if PalletID if all the entered products has at least one of the conditions
555
- let allProductsValid = foundOrderProductsPallet.every((product, index) => {
556
- let arrivalNotice = arrivalNotices[index];
557
- return product.status === 'REJECTED' || product.issue || (arrivalNotice && arrivalNotice.status === 'CANCELLED');
558
- });
559
- if (!allProductsValid || foundInventoryPallet) {
560
- throw new Error(i18next_1.default.t('Lot ID is already in use. Please enter a new Lot ID.'));
841
+ // Check for existing LotID in ArrivalNotice
842
+ let arrivalNotices = await Promise.all(foundOrderProductsPallet.map(async (product) => {
843
+ return await tx.getRepository(arrival_notice_1.ArrivalNotice).findOne({
844
+ where: {
845
+ id: product.arrivalNoticeId
846
+ }
847
+ });
848
+ }));
849
+ //Allow the reuse if PalletID if all the entered products has at least one of the conditions
850
+ let allProductsValid = foundOrderProductsPallet.every((product, index) => {
851
+ let arrivalNotice = arrivalNotices[index];
852
+ return (product.status === 'REJECTED' || product.issue || (arrivalNotice && arrivalNotice.status === 'CANCELLED'));
853
+ });
854
+ if (!allProductsValid || foundInventoryPallet) {
855
+ throw new Error(i18next_1.default.t('Lot ID is already in use. Please enter a new Lot ID.'));
856
+ }
561
857
  }
562
858
  }
563
- }
564
- // find GAN number rule setting
565
- const ganNoSetting = await settingRepo.findOne({
566
- where: {
567
- domain,
568
- name: constants_1.ORDER_NUMBER_SETTING_KEY.GAN_NUMBER_RULE
569
- }
570
- });
571
- if (ganNoSetting) {
572
- orderNo = await (0, id_rule_base_1.generateId)({ domain, type: constants_1.ORDER_NUMBER_RULE_TYPE.GAN_NUMBER, seed: {} });
573
- }
574
- else {
575
- orderNo = order_no_generator_1.OrderNoGenerator.arrivalNotice();
576
- }
577
- // 1. Create arrival notice
578
- const createdArrivalNotice = await tx.getRepository(arrival_notice_1.ArrivalNotice).save(Object.assign(Object.assign({}, arrivalNotice), { name: orderNo, domain, bizplace: myBizplace, looseItem: (arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.looseItem) ? arrivalNotice.looseItem : false, status: fromPo ? constants_1.ORDER_STATUS.INTRANSIT : constants_1.ORDER_STATUS.PENDING, creator: user, updater: user }));
579
- // 2. Create arrival notice product
580
- await addArrivalNoticeProducts(domain, createdArrivalNotice, orderProducts.map((op) => {
581
- return Object.assign(Object.assign({}, op), { status: fromPo ? constants_1.ORDER_PRODUCT_STATUS.INTRANSIT : constants_1.ORDER_PRODUCT_STATUS.PENDING });
582
- }), user, tx);
583
- await (0, job_sheet_mutation_1.generateJobSheet)(domain, user, createdArrivalNotice, tx);
584
- // 3. Create arrival notice vas
585
- if (orderVass === null || orderVass === void 0 ? void 0 : orderVass.length) {
586
- orderVass = await Promise.all(orderVass.map(async (ov) => {
587
- if (ov.targetProduct) {
588
- ov.targetProduct = await tx.getRepository(product_base_1.Product).findOne(ov.targetProduct.id);
859
+ // find GAN number rule setting
860
+ const ganNoSetting = await settingRepo.findOne({
861
+ where: {
862
+ domain,
863
+ name: constants_1.ORDER_NUMBER_SETTING_KEY.GAN_NUMBER_RULE
589
864
  }
590
- return Object.assign(Object.assign({}, ov), { domain, bizplace: myBizplace, name: order_no_generator_1.OrderNoGenerator.orderVas(), vas: await tx.getRepository(vas_1.Vas).findOne({ domain, id: ov.vas.id }), type: constants_1.ORDER_TYPES.ARRIVAL_NOTICE, arrivalNotice: createdArrivalNotice, status: fromPo ? constants_1.ORDER_VAS_STATUS.INTRANSIT : constants_1.ORDER_VAS_STATUS.PENDING, creator: user, updater: user });
591
- }));
592
- await tx.getRepository(order_vas_1.OrderVas).save(orderVass);
593
- }
594
- if (files === null || files === void 0 ? void 0 : files.length) {
595
- const attachments = files.map(attachment => {
596
- return {
597
- file: attachment,
598
- refBy: createdArrivalNotice.id,
599
- category: attachment_type_1.ATTACHMENT_TYPE.GAN
600
- };
601
865
  });
602
- await (0, attachment_base_1.createAttachments)(_, { attachments }, context);
866
+ if (ganNoSetting) {
867
+ orderNo = await (0, id_rule_base_1.generateId)({ domain, type: constants_1.ORDER_NUMBER_RULE_TYPE.GAN_NUMBER, seed: {} });
868
+ }
869
+ else {
870
+ orderNo = order_no_generator_1.OrderNoGenerator.arrivalNotice();
871
+ }
872
+ // 1. Create arrival notice
873
+ const createdArrivalNotice = await tx.getRepository(arrival_notice_1.ArrivalNotice).save(Object.assign(Object.assign({}, arrivalNotice), { name: orderNo, domain, bizplace: myBizplace, looseItem: (arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.looseItem) ? arrivalNotice.looseItem : false, status: fromPo ? constants_1.ORDER_STATUS.INTRANSIT : constants_1.ORDER_STATUS.PENDING, creator: user, updater: user }));
874
+ // 2. Create arrival notice product
875
+ await addArrivalNoticeProducts(domain, createdArrivalNotice, orderProducts.map((op) => {
876
+ return Object.assign(Object.assign({}, op), { status: fromPo ? constants_1.ORDER_PRODUCT_STATUS.INTRANSIT : constants_1.ORDER_PRODUCT_STATUS.PENDING });
877
+ }), user, tx);
878
+ await (0, job_sheet_mutation_1.generateJobSheet)(domain, user, createdArrivalNotice, tx);
879
+ // 3. Create arrival notice vas
880
+ if (orderVass === null || orderVass === void 0 ? void 0 : orderVass.length) {
881
+ orderVass = await Promise.all(orderVass.map(async (ov) => {
882
+ if (ov.targetProduct) {
883
+ ov.targetProduct = await tx.getRepository(product_base_1.Product).findOne(ov.targetProduct.id);
884
+ }
885
+ return Object.assign(Object.assign({}, ov), { domain, bizplace: myBizplace, name: order_no_generator_1.OrderNoGenerator.orderVas(), vas: await tx.getRepository(vas_1.Vas).findOne({ domain, id: ov.vas.id }), type: constants_1.ORDER_TYPES.ARRIVAL_NOTICE, arrivalNotice: createdArrivalNotice, status: fromPo ? constants_1.ORDER_VAS_STATUS.INTRANSIT : constants_1.ORDER_VAS_STATUS.PENDING, creator: user, updater: user });
886
+ }));
887
+ await tx.getRepository(order_vas_1.OrderVas).save(orderVass);
888
+ }
889
+ if (files === null || files === void 0 ? void 0 : files.length) {
890
+ const attachments = files.map(attachment => {
891
+ return {
892
+ file: attachment,
893
+ refBy: createdArrivalNotice.id,
894
+ category: attachment_type_1.ATTACHMENT_TYPE.GAN
895
+ };
896
+ });
897
+ await (0, attachment_base_1.createAttachments)(_, { attachments }, context);
898
+ }
899
+ return createdArrivalNotice;
900
+ }
901
+ catch (error) {
902
+ throw new Error(error.message);
603
903
  }
604
- return createdArrivalNotice;
605
904
  }
606
905
  exports.generateArrivalNoticeFunction = generateArrivalNoticeFunction;
607
906
  async function confirmArrivalNoticeFunction(name, context, tx) {
@@ -797,6 +1096,7 @@ async function receiveArrivalNoticeFunction(_, name, context) {
797
1096
  }
798
1097
  // 4. Update status of arrival notice (PENDING_RECEIVE => INTRANSIT)
799
1098
  let rcvArrivalNotice = await tx.getRepository(arrival_notice_1.ArrivalNotice).save(Object.assign(Object.assign({}, foundArrivalNotice), { status: anStatus, acceptedBy: user, acceptedAt: new Date(), updater: user }));
1099
+ (0, integration_base_1.webhookHandler)(rcvArrivalNotice, { id: rcvArrivalNotice.bizplace }, integration_base_1.WebhookEventsEnum.ArrivalNoticeUpdated);
800
1100
  return foundArrivalNotice;
801
1101
  }
802
1102
  catch (e) {
@@ -840,6 +1140,7 @@ async function checkArrivedNoticeFunction(name, context, tx) {
840
1140
  }
841
1141
  // 4. Update status of arrival notice (INTRANSIT => ARRIVED)
842
1142
  await tx.getRepository(arrival_notice_1.ArrivalNotice).save(Object.assign(Object.assign({}, foundArrivalNotice), { status: constants_1.ORDER_STATUS.ARRIVED, updater: user }));
1143
+ (0, integration_base_1.webhookHandler)(foundArrivalNotice, { id: foundArrivalNotice.bizplace }, integration_base_1.WebhookEventsEnum.ArrivalNoticeUpdated);
843
1144
  // notification logics
844
1145
  const users = await (0, biz_base_1.getDomainUsers)(foundArrivalNotice === null || foundArrivalNotice === void 0 ? void 0 : foundArrivalNotice.bizplace, tx);
845
1146
  if ((users === null || users === void 0 ? void 0 : users.length) && ((_a = context.header) === null || _a === void 0 ? void 0 : _a.referer)) {
@@ -908,6 +1209,7 @@ async function rejectArrivalNotice(tx, name, remark, context) {
908
1209
  foundArrivalNotice.status = constants_1.ORDER_STATUS.REJECTED;
909
1210
  foundArrivalNotice.updater = user;
910
1211
  await tx.getRepository(arrival_notice_1.ArrivalNotice).save(foundArrivalNotice);
1212
+ (0, integration_base_1.webhookHandler)(foundArrivalNotice, { id: foundArrivalNotice.bizplace }, integration_base_1.WebhookEventsEnum.ArrivalNoticeUpdated);
911
1213
  // notification logics
912
1214
  const users = await (0, biz_base_1.getDomainUsers)(foundArrivalNotice === null || foundArrivalNotice === void 0 ? void 0 : foundArrivalNotice.bizplace, tx);
913
1215
  // send notification to Customer Users
@@ -931,7 +1233,7 @@ async function rejectArrivalNotice(tx, name, remark, context) {
931
1233
  }
932
1234
  exports.rejectArrivalNotice = rejectArrivalNotice;
933
1235
  async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts, user, tx) {
934
- var _a, _b;
1236
+ var _a, _b, _c, _d, _e;
935
1237
  const orderProductRepo = (tx === null || tx === void 0 ? void 0 : tx.getRepository(order_product_1.OrderProduct)) || (0, typeorm_1.getRepository)(order_product_1.OrderProduct);
936
1238
  if (!(arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.bizplace) || !((_a = arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.orderProducts) === null || _a === void 0 ? void 0 : _a.length)) {
937
1239
  arrivalNotice = await tx.getRepository(arrival_notice_1.ArrivalNotice).findOne({
@@ -946,6 +1248,8 @@ async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts,
946
1248
  name: order_no_generator_1.OrderNoGenerator.orderProduct(),
947
1249
  product_id: op.product.id,
948
1250
  product_detail_id: op.productDetail.id,
1251
+ warehouse_id: ((_b = op.warehouse) === null || _b === void 0 ? void 0 : _b.id) || null,
1252
+ location_id: ((_c = op.location) === null || _c === void 0 ? void 0 : _c.id) || null,
949
1253
  batch_id: op.batchId,
950
1254
  batch_id_ref: op.batchIdRef,
951
1255
  packing_type: op.packingType,
@@ -958,6 +1262,7 @@ async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts,
958
1262
  pallet_id: op.palletId,
959
1263
  unit_price: op.unitPrice,
960
1264
  remark: op.remark,
1265
+ exp_date: (_d = op.expDate) !== null && _d !== void 0 ? _d : null,
961
1266
  manufacture_date: op.manufactureDate,
962
1267
  status: op.status,
963
1268
  adjusted_batch_id: op.adjustedBatchId,
@@ -970,20 +1275,66 @@ async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts,
970
1275
  adjusted_pallet_qty: op.adjustedPalletQty,
971
1276
  adjusted_unit_price: op.adjustedUnitPrice,
972
1277
  domain_id: domain.id,
973
- bizplace_id: (arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.bizplaceId) || ((_b = arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.bizplace) === null || _b === void 0 ? void 0 : _b.id) || (arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.bizplace),
1278
+ bizplace_id: (arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.bizplaceId) || ((_e = arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.bizplace) === null || _e === void 0 ? void 0 : _e.id) || (arrivalNotice === null || arrivalNotice === void 0 ? void 0 : arrivalNotice.bizplace),
974
1279
  arrival_notice_id: arrivalNotice.id,
975
1280
  creator_id: user.id,
976
1281
  updater_id: user.id
977
1282
  });
978
1283
  }
979
1284
  await orderProductRepo.query(`
980
- INSERT INTO order_products ("name", "product_detail_id", "product_id", "batch_id", "batch_id_ref", "packing_type", "packing_size", "uom", "uom_value", "pack_qty", "total_uom_value", "pallet_qty", "pallet_id", "unit_price", "remark", "manufacture_date", "status",
981
- "adjusted_batch_id", "adjusted_batch_id_ref", "adjusted_packing_type", "adjusted_uom_value", "adjusted_uom", "adjusted_pack_qty", "adjusted_total_uom_value", "adjusted_pallet_qty", "adjusted_unit_price",
982
- "domain_id", "bizplace_id", "arrival_notice_id", "creator_id", "updater_id")
983
- SELECT "name", "product_detail_id", "product_id", "batch_id", "batch_id_ref", "packing_type", "packing_size", "uom", "uom_value", "pack_qty", "total_uom_value", "pallet_qty", "pallet_id", "unit_price", "remark", "manufacture_date", "status",
984
- "adjusted_batch_id", "adjusted_batch_id_ref", "adjusted_packing_type", "adjusted_uom_value", "adjusted_uom", "adjusted_pack_qty", "adjusted_total_uom_value", "adjusted_pallet_qty", "adjusted_unit_price",
985
- "domain_id", "bizplace_id", "arrival_notice_id", "creator_id", "updater_id"
986
- FROM JSON_POPULATE_RECORDSET(NULL::order_products, $1) op
1285
+ INSERT INTO order_products (
1286
+ "name", "product_detail_id", "product_id",
1287
+ "warehouse_id", "location_id",
1288
+ "batch_id", "batch_id_ref", "packing_type",
1289
+ "packing_size", "uom", "uom_value",
1290
+ "pack_qty", "total_uom_value", "pallet_qty",
1291
+ "pallet_id", "unit_price", "remark",
1292
+ "exp_date",
1293
+ "manufacture_date", "status", "adjusted_batch_id",
1294
+ "adjusted_batch_id_ref", "adjusted_packing_type",
1295
+ "adjusted_uom_value", "adjusted_uom",
1296
+ "adjusted_pack_qty", "adjusted_total_uom_value",
1297
+ "adjusted_pallet_qty", "adjusted_unit_price",
1298
+ "domain_id", "bizplace_id", "arrival_notice_id",
1299
+ "creator_id", "updater_id"
1300
+ )
1301
+ SELECT
1302
+ "name",
1303
+ "product_detail_id",
1304
+ "product_id",
1305
+ "warehouse_id",
1306
+ "location_id",
1307
+ "batch_id",
1308
+ "batch_id_ref",
1309
+ "packing_type",
1310
+ "packing_size",
1311
+ "uom",
1312
+ "uom_value",
1313
+ "pack_qty",
1314
+ "total_uom_value",
1315
+ "pallet_qty",
1316
+ "pallet_id",
1317
+ "unit_price",
1318
+ "remark",
1319
+ "exp_date",
1320
+ "manufacture_date",
1321
+ "status",
1322
+ "adjusted_batch_id",
1323
+ "adjusted_batch_id_ref",
1324
+ "adjusted_packing_type",
1325
+ "adjusted_uom_value",
1326
+ "adjusted_uom",
1327
+ "adjusted_pack_qty",
1328
+ "adjusted_total_uom_value",
1329
+ "adjusted_pallet_qty",
1330
+ "adjusted_unit_price",
1331
+ "domain_id",
1332
+ "bizplace_id",
1333
+ "arrival_notice_id",
1334
+ "creator_id",
1335
+ "updater_id"
1336
+ FROM
1337
+ JSON_POPULATE_RECORDSET(NULL :: order_products, $1) op
987
1338
  `, [JSON.stringify(createdOrderProducts)]);
988
1339
  }
989
1340
  exports.addArrivalNoticeProducts = addArrivalNoticeProducts;
@@ -1082,4 +1433,21 @@ function formRawArrivalNotices(arrivalNotice, errorMsg) {
1082
1433
  }
1083
1434
  return rawArrivalNotices;
1084
1435
  }
1436
+ function mergeDuplicateRow(arr, groupByKey, qty) {
1437
+ return arr.reduce((acc, currentItem) => {
1438
+ const getNestedValue = (obj, path) => {
1439
+ return path.split('.').reduce((o, p) => (o ? o[p] : undefined), obj);
1440
+ };
1441
+ const compositeKey = groupByKey.map(key => getNestedValue(currentItem, key)).join('::');
1442
+ if (acc.has(compositeKey)) {
1443
+ const existingItem = acc.get(compositeKey);
1444
+ existingItem[qty] = parseFloat(existingItem[qty]) + parseFloat(currentItem[qty]);
1445
+ existingItem['palletQty'] = parseFloat(existingItem['palletQty']) + parseFloat(currentItem['palletQty']);
1446
+ existingItem['totalUomValue'] = (parseFloat(existingItem['totalUomValue']) + parseFloat(currentItem['totalUomValue'])).toString();
1447
+ }
1448
+ else
1449
+ acc.set(compositeKey, Object.assign({}, currentItem));
1450
+ return acc;
1451
+ }, new Map());
1452
+ }
1085
1453
  //# sourceMappingURL=arrival-notice-mutation.js.map