@things-factory/sales-base 4.3.656 → 4.3.660

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) {
@@ -931,7 +1230,7 @@ async function rejectArrivalNotice(tx, name, remark, context) {
931
1230
  }
932
1231
  exports.rejectArrivalNotice = rejectArrivalNotice;
933
1232
  async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts, user, tx) {
934
- var _a, _b;
1233
+ var _a, _b, _c, _d, _e;
935
1234
  const orderProductRepo = (tx === null || tx === void 0 ? void 0 : tx.getRepository(order_product_1.OrderProduct)) || (0, typeorm_1.getRepository)(order_product_1.OrderProduct);
936
1235
  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
1236
  arrivalNotice = await tx.getRepository(arrival_notice_1.ArrivalNotice).findOne({
@@ -946,6 +1245,8 @@ async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts,
946
1245
  name: order_no_generator_1.OrderNoGenerator.orderProduct(),
947
1246
  product_id: op.product.id,
948
1247
  product_detail_id: op.productDetail.id,
1248
+ warehouse_id: ((_b = op.warehouse) === null || _b === void 0 ? void 0 : _b.id) || null,
1249
+ location_id: ((_c = op.location) === null || _c === void 0 ? void 0 : _c.id) || null,
949
1250
  batch_id: op.batchId,
950
1251
  batch_id_ref: op.batchIdRef,
951
1252
  packing_type: op.packingType,
@@ -958,6 +1259,7 @@ async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts,
958
1259
  pallet_id: op.palletId,
959
1260
  unit_price: op.unitPrice,
960
1261
  remark: op.remark,
1262
+ exp_date: (_d = op.expDate) !== null && _d !== void 0 ? _d : null,
961
1263
  manufacture_date: op.manufactureDate,
962
1264
  status: op.status,
963
1265
  adjusted_batch_id: op.adjustedBatchId,
@@ -970,20 +1272,66 @@ async function addArrivalNoticeProducts(domain, arrivalNotice, newOrderProducts,
970
1272
  adjusted_pallet_qty: op.adjustedPalletQty,
971
1273
  adjusted_unit_price: op.adjustedUnitPrice,
972
1274
  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),
1275
+ 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
1276
  arrival_notice_id: arrivalNotice.id,
975
1277
  creator_id: user.id,
976
1278
  updater_id: user.id
977
1279
  });
978
1280
  }
979
1281
  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
1282
+ INSERT INTO order_products (
1283
+ "name", "product_detail_id", "product_id",
1284
+ "warehouse_id", "location_id",
1285
+ "batch_id", "batch_id_ref", "packing_type",
1286
+ "packing_size", "uom", "uom_value",
1287
+ "pack_qty", "total_uom_value", "pallet_qty",
1288
+ "pallet_id", "unit_price", "remark",
1289
+ "exp_date",
1290
+ "manufacture_date", "status", "adjusted_batch_id",
1291
+ "adjusted_batch_id_ref", "adjusted_packing_type",
1292
+ "adjusted_uom_value", "adjusted_uom",
1293
+ "adjusted_pack_qty", "adjusted_total_uom_value",
1294
+ "adjusted_pallet_qty", "adjusted_unit_price",
1295
+ "domain_id", "bizplace_id", "arrival_notice_id",
1296
+ "creator_id", "updater_id"
1297
+ )
1298
+ SELECT
1299
+ "name",
1300
+ "product_detail_id",
1301
+ "product_id",
1302
+ "warehouse_id",
1303
+ "location_id",
1304
+ "batch_id",
1305
+ "batch_id_ref",
1306
+ "packing_type",
1307
+ "packing_size",
1308
+ "uom",
1309
+ "uom_value",
1310
+ "pack_qty",
1311
+ "total_uom_value",
1312
+ "pallet_qty",
1313
+ "pallet_id",
1314
+ "unit_price",
1315
+ "remark",
1316
+ "exp_date",
1317
+ "manufacture_date",
1318
+ "status",
1319
+ "adjusted_batch_id",
1320
+ "adjusted_batch_id_ref",
1321
+ "adjusted_packing_type",
1322
+ "adjusted_uom_value",
1323
+ "adjusted_uom",
1324
+ "adjusted_pack_qty",
1325
+ "adjusted_total_uom_value",
1326
+ "adjusted_pallet_qty",
1327
+ "adjusted_unit_price",
1328
+ "domain_id",
1329
+ "bizplace_id",
1330
+ "arrival_notice_id",
1331
+ "creator_id",
1332
+ "updater_id"
1333
+ FROM
1334
+ JSON_POPULATE_RECORDSET(NULL :: order_products, $1) op
987
1335
  `, [JSON.stringify(createdOrderProducts)]);
988
1336
  }
989
1337
  exports.addArrivalNoticeProducts = addArrivalNoticeProducts;
@@ -1082,4 +1430,21 @@ function formRawArrivalNotices(arrivalNotice, errorMsg) {
1082
1430
  }
1083
1431
  return rawArrivalNotices;
1084
1432
  }
1433
+ function mergeDuplicateRow(arr, groupByKey, qty) {
1434
+ return arr.reduce((acc, currentItem) => {
1435
+ const getNestedValue = (obj, path) => {
1436
+ return path.split('.').reduce((o, p) => (o ? o[p] : undefined), obj);
1437
+ };
1438
+ const compositeKey = groupByKey.map(key => getNestedValue(currentItem, key)).join('::');
1439
+ if (acc.has(compositeKey)) {
1440
+ const existingItem = acc.get(compositeKey);
1441
+ existingItem[qty] = parseFloat(existingItem[qty]) + parseFloat(currentItem[qty]);
1442
+ existingItem['palletQty'] = parseFloat(existingItem['palletQty']) + parseFloat(currentItem['palletQty']);
1443
+ existingItem['totalUomValue'] = (parseFloat(existingItem['totalUomValue']) + parseFloat(currentItem['totalUomValue'])).toString();
1444
+ }
1445
+ else
1446
+ acc.set(compositeKey, Object.assign({}, currentItem));
1447
+ return acc;
1448
+ }, new Map());
1449
+ }
1085
1450
  //# sourceMappingURL=arrival-notice-mutation.js.map