@things-factory/warehouse-base 4.3.671 → 4.3.673

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.
Files changed (191) hide show
  1. package/dist-server/constants/adjustment-code.js +13 -0
  2. package/dist-server/constants/adjustment-code.js.map +1 -0
  3. package/dist-server/constants/index.js +23 -0
  4. package/dist-server/constants/index.js.map +1 -0
  5. package/dist-server/constants/inventory.js +74 -0
  6. package/dist-server/constants/inventory.js.map +1 -0
  7. package/dist-server/constants/location.js +19 -0
  8. package/dist-server/constants/location.js.map +1 -0
  9. package/dist-server/constants/pallet.js +13 -0
  10. package/dist-server/constants/pallet.js.map +1 -0
  11. package/dist-server/constants/rule-type.js +8 -0
  12. package/dist-server/constants/rule-type.js.map +1 -0
  13. package/dist-server/constants/tote.js +9 -0
  14. package/dist-server/constants/tote.js.map +1 -0
  15. package/dist-server/controllers/ecommerce/ecommerce-controller.js +125 -0
  16. package/dist-server/controllers/ecommerce/ecommerce-controller.js.map +1 -0
  17. package/dist-server/controllers/ecommerce/index.js +22 -0
  18. package/dist-server/controllers/ecommerce/index.js.map +1 -0
  19. package/dist-server/controllers/ecommerce/pos-controller.js +65 -0
  20. package/dist-server/controllers/ecommerce/pos-controller.js.map +1 -0
  21. package/dist-server/controllers/ecommerce/powrup-controller.js +87 -0
  22. package/dist-server/controllers/ecommerce/powrup-controller.js.map +1 -0
  23. package/dist-server/controllers/ecommerce/sellercraft-controller.js +85 -0
  24. package/dist-server/controllers/ecommerce/sellercraft-controller.js.map +1 -0
  25. package/dist-server/controllers/ecommerce/webspert-controller.js +131 -0
  26. package/dist-server/controllers/ecommerce/webspert-controller.js.map +1 -0
  27. package/dist-server/controllers/index.js +19 -0
  28. package/dist-server/controllers/index.js.map +1 -0
  29. package/dist-server/controllers/warehouse-controller.js +143 -0
  30. package/dist-server/controllers/warehouse-controller.js.map +1 -0
  31. package/dist-server/index.js +35 -0
  32. package/dist-server/index.js.map +1 -0
  33. package/dist-server/middlewares/index.js +1 -0
  34. package/dist-server/middlewares/index.js.map +1 -0
  35. package/dist-server/migrations/index.js +12 -0
  36. package/dist-server/migrations/index.js.map +1 -0
  37. package/dist-server/service/index.js +96 -0
  38. package/dist-server/service/index.js.map +1 -0
  39. package/dist-server/service/inventory/index.js +9 -0
  40. package/dist-server/service/inventory/index.js.map +1 -0
  41. package/dist-server/service/inventory/inventory-mutation.js +414 -0
  42. package/dist-server/service/inventory/inventory-mutation.js.map +1 -0
  43. package/dist-server/service/inventory/inventory-query.js +1211 -0
  44. package/dist-server/service/inventory/inventory-query.js.map +1 -0
  45. package/dist-server/service/inventory/inventory-types.js +478 -0
  46. package/dist-server/service/inventory/inventory-types.js.map +1 -0
  47. package/dist-server/service/inventory/inventory.js +569 -0
  48. package/dist-server/service/inventory/inventory.js.map +1 -0
  49. package/dist-server/service/inventory-change/index.js +9 -0
  50. package/dist-server/service/inventory-change/index.js.map +1 -0
  51. package/dist-server/service/inventory-change/inventory-change-mutation.js +1188 -0
  52. package/dist-server/service/inventory-change/inventory-change-mutation.js.map +1 -0
  53. package/dist-server/service/inventory-change/inventory-change-query.js +150 -0
  54. package/dist-server/service/inventory-change/inventory-change-query.js.map +1 -0
  55. package/dist-server/service/inventory-change/inventory-change-types.js +73 -0
  56. package/dist-server/service/inventory-change/inventory-change-types.js.map +1 -0
  57. package/dist-server/service/inventory-change/inventory-change.js +225 -0
  58. package/dist-server/service/inventory-change/inventory-change.js.map +1 -0
  59. package/dist-server/service/inventory-history/index.js +9 -0
  60. package/dist-server/service/inventory-history/index.js.map +1 -0
  61. package/dist-server/service/inventory-history/inventory-history-mutation.js +121 -0
  62. package/dist-server/service/inventory-history/inventory-history-mutation.js.map +1 -0
  63. package/dist-server/service/inventory-history/inventory-history-query.js +1694 -0
  64. package/dist-server/service/inventory-history/inventory-history-query.js.map +1 -0
  65. package/dist-server/service/inventory-history/inventory-history-types.js +626 -0
  66. package/dist-server/service/inventory-history/inventory-history-types.js.map +1 -0
  67. package/dist-server/service/inventory-history/inventory-history.js +238 -0
  68. package/dist-server/service/inventory-history/inventory-history.js.map +1 -0
  69. package/dist-server/service/inventory-item/index.js +9 -0
  70. package/dist-server/service/inventory-item/index.js.map +1 -0
  71. package/dist-server/service/inventory-item/inventory-item-mutation.js +274 -0
  72. package/dist-server/service/inventory-item/inventory-item-mutation.js.map +1 -0
  73. package/dist-server/service/inventory-item/inventory-item-query.js +265 -0
  74. package/dist-server/service/inventory-item/inventory-item-query.js.map +1 -0
  75. package/dist-server/service/inventory-item/inventory-item-type.js +127 -0
  76. package/dist-server/service/inventory-item/inventory-item-type.js.map +1 -0
  77. package/dist-server/service/inventory-item/inventory-item.js +146 -0
  78. package/dist-server/service/inventory-item/inventory-item.js.map +1 -0
  79. package/dist-server/service/inventory-item-change/index.js +9 -0
  80. package/dist-server/service/inventory-item-change/index.js.map +1 -0
  81. package/dist-server/service/inventory-item-change/inventory-item-change-mutation.js +121 -0
  82. package/dist-server/service/inventory-item-change/inventory-item-change-mutation.js.map +1 -0
  83. package/dist-server/service/inventory-item-change/inventory-item-change-query.js +87 -0
  84. package/dist-server/service/inventory-item-change/inventory-item-change-query.js.map +1 -0
  85. package/dist-server/service/inventory-item-change/inventory-item-change-type.js +107 -0
  86. package/dist-server/service/inventory-item-change/inventory-item-change-type.js.map +1 -0
  87. package/dist-server/service/inventory-item-change/inventory-item-change.js +110 -0
  88. package/dist-server/service/inventory-item-change/inventory-item-change.js.map +1 -0
  89. package/dist-server/service/inventory-product/index.js +9 -0
  90. package/dist-server/service/inventory-product/index.js.map +1 -0
  91. package/dist-server/service/inventory-product/inventory-product-mutation.js +120 -0
  92. package/dist-server/service/inventory-product/inventory-product-mutation.js.map +1 -0
  93. package/dist-server/service/inventory-product/inventory-product-query.js +87 -0
  94. package/dist-server/service/inventory-product/inventory-product-query.js.map +1 -0
  95. package/dist-server/service/inventory-product/inventory-product-type.js +95 -0
  96. package/dist-server/service/inventory-product/inventory-product-type.js.map +1 -0
  97. package/dist-server/service/inventory-product/inventory-product.js +112 -0
  98. package/dist-server/service/inventory-product/inventory-product.js.map +1 -0
  99. package/dist-server/service/location/index.js +9 -0
  100. package/dist-server/service/location/index.js.map +1 -0
  101. package/dist-server/service/location/location-mutation.js +279 -0
  102. package/dist-server/service/location/location-mutation.js.map +1 -0
  103. package/dist-server/service/location/location-query.js +321 -0
  104. package/dist-server/service/location/location-query.js.map +1 -0
  105. package/dist-server/service/location/location-types.js +296 -0
  106. package/dist-server/service/location/location-types.js.map +1 -0
  107. package/dist-server/service/location/location.js +146 -0
  108. package/dist-server/service/location/location.js.map +1 -0
  109. package/dist-server/service/movement/index.js +9 -0
  110. package/dist-server/service/movement/index.js.map +1 -0
  111. package/dist-server/service/movement/movement-mutation.js +80 -0
  112. package/dist-server/service/movement/movement-mutation.js.map +1 -0
  113. package/dist-server/service/movement/movement-query.js +286 -0
  114. package/dist-server/service/movement/movement-query.js.map +1 -0
  115. package/dist-server/service/movement/movement-types.js +117 -0
  116. package/dist-server/service/movement/movement-types.js.map +1 -0
  117. package/dist-server/service/movement/movement.js +101 -0
  118. package/dist-server/service/movement/movement.js.map +1 -0
  119. package/dist-server/service/pallet/index.js +9 -0
  120. package/dist-server/service/pallet/index.js.map +1 -0
  121. package/dist-server/service/pallet/pallet-mutation.js +194 -0
  122. package/dist-server/service/pallet/pallet-mutation.js.map +1 -0
  123. package/dist-server/service/pallet/pallet-query.js +164 -0
  124. package/dist-server/service/pallet/pallet-query.js.map +1 -0
  125. package/dist-server/service/pallet/pallet-types.js +109 -0
  126. package/dist-server/service/pallet/pallet-types.js.map +1 -0
  127. package/dist-server/service/pallet/pallet.js +112 -0
  128. package/dist-server/service/pallet/pallet.js.map +1 -0
  129. package/dist-server/service/pallet-count/index.js +9 -0
  130. package/dist-server/service/pallet-count/index.js.map +1 -0
  131. package/dist-server/service/pallet-count/pallet-count-mutation.js +153 -0
  132. package/dist-server/service/pallet-count/pallet-count-mutation.js.map +1 -0
  133. package/dist-server/service/pallet-count/pallet-count-query.js +86 -0
  134. package/dist-server/service/pallet-count/pallet-count-query.js.map +1 -0
  135. package/dist-server/service/pallet-count/pallet-count-types.js +65 -0
  136. package/dist-server/service/pallet-count/pallet-count-types.js.map +1 -0
  137. package/dist-server/service/pallet-count/pallet-count.js +89 -0
  138. package/dist-server/service/pallet-count/pallet-count.js.map +1 -0
  139. package/dist-server/service/pallet-history/index.js +9 -0
  140. package/dist-server/service/pallet-history/index.js.map +1 -0
  141. package/dist-server/service/pallet-history/pallet-history-mutation.js +120 -0
  142. package/dist-server/service/pallet-history/pallet-history-mutation.js.map +1 -0
  143. package/dist-server/service/pallet-history/pallet-history-query.js +87 -0
  144. package/dist-server/service/pallet-history/pallet-history-query.js.map +1 -0
  145. package/dist-server/service/pallet-history/pallet-history-types.js +65 -0
  146. package/dist-server/service/pallet-history/pallet-history-types.js.map +1 -0
  147. package/dist-server/service/pallet-history/pallet-history.js +107 -0
  148. package/dist-server/service/pallet-history/pallet-history.js.map +1 -0
  149. package/dist-server/service/product-detail-stock/index.js +9 -0
  150. package/dist-server/service/product-detail-stock/index.js.map +1 -0
  151. package/dist-server/service/product-detail-stock/product-detail-stock-mutation.js +120 -0
  152. package/dist-server/service/product-detail-stock/product-detail-stock-mutation.js.map +1 -0
  153. package/dist-server/service/product-detail-stock/product-detail-stock-query.js +66 -0
  154. package/dist-server/service/product-detail-stock/product-detail-stock-query.js.map +1 -0
  155. package/dist-server/service/product-detail-stock/product-detail-stock-types.js +57 -0
  156. package/dist-server/service/product-detail-stock/product-detail-stock-types.js.map +1 -0
  157. package/dist-server/service/product-detail-stock/product-detail-stock.js +90 -0
  158. package/dist-server/service/product-detail-stock/product-detail-stock.js.map +1 -0
  159. package/dist-server/service/reduced-inventory-history/index.js +6 -0
  160. package/dist-server/service/reduced-inventory-history/index.js.map +1 -0
  161. package/dist-server/service/reduced-inventory-history/reduced-inventory-history.js +133 -0
  162. package/dist-server/service/reduced-inventory-history/reduced-inventory-history.js.map +1 -0
  163. package/dist-server/service/tote/index.js +9 -0
  164. package/dist-server/service/tote/index.js.map +1 -0
  165. package/dist-server/service/tote/tote-mutation.js +192 -0
  166. package/dist-server/service/tote/tote-mutation.js.map +1 -0
  167. package/dist-server/service/tote/tote-query.js +162 -0
  168. package/dist-server/service/tote/tote-query.js.map +1 -0
  169. package/dist-server/service/tote/tote-types.js +75 -0
  170. package/dist-server/service/tote/tote-types.js.map +1 -0
  171. package/dist-server/service/tote/tote.js +98 -0
  172. package/dist-server/service/tote/tote.js.map +1 -0
  173. package/dist-server/service/warehouse/index.js +9 -0
  174. package/dist-server/service/warehouse/index.js.map +1 -0
  175. package/dist-server/service/warehouse/warehouse-mutation.js +148 -0
  176. package/dist-server/service/warehouse/warehouse-mutation.js.map +1 -0
  177. package/dist-server/service/warehouse/warehouse-query.js +91 -0
  178. package/dist-server/service/warehouse/warehouse-query.js.map +1 -0
  179. package/dist-server/service/warehouse/warehouse-types.js +82 -0
  180. package/dist-server/service/warehouse/warehouse-types.js.map +1 -0
  181. package/dist-server/service/warehouse/warehouse.js +114 -0
  182. package/dist-server/service/warehouse/warehouse.js.map +1 -0
  183. package/dist-server/utils/datetime-util.js +61 -0
  184. package/dist-server/utils/datetime-util.js.map +1 -0
  185. package/dist-server/utils/index.js +20 -0
  186. package/dist-server/utils/index.js.map +1 -0
  187. package/dist-server/utils/inventory-no-generator.js +17 -0
  188. package/dist-server/utils/inventory-no-generator.js.map +1 -0
  189. package/dist-server/utils/inventory-util.js +413 -0
  190. package/dist-server/utils/inventory-util.js.map +1 -0
  191. package/package.json +10 -10
@@ -0,0 +1,1211 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var _a, _b, _c, _d;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.inventoriesByStrategy = exports.InventoryQuery = void 0;
17
+ const type_graphql_1 = require("type-graphql");
18
+ const typeorm_1 = require("typeorm");
19
+ const auth_base_1 = require("@things-factory/auth-base");
20
+ const biz_base_1 = require("@things-factory/biz-base");
21
+ const env_1 = require("@things-factory/env");
22
+ const product_base_1 = require("@things-factory/product-base");
23
+ const setting_base_1 = require("@things-factory/setting-base");
24
+ const shell_1 = require("@things-factory/shell");
25
+ const constants_1 = require("../../constants");
26
+ const inventory_change_1 = require("../inventory-change/inventory-change");
27
+ const inventory_1 = require("./inventory");
28
+ const inventory_types_1 = require("./inventory-types");
29
+ let InventoryQuery = class InventoryQuery {
30
+ /**
31
+ * Combined single query resolver to perform extraction of data with or without pagination
32
+ * @param context
33
+ * @param filters
34
+ * @param pagination
35
+ * @param sortings
36
+ * @param locationSortingRules
37
+ * @param exportItem
38
+ * @returns
39
+ */
40
+ async inventories(context, filters, pagination, sortings, locationSortingRules, exportItem) {
41
+ const { domain, user, tx } = context.state;
42
+ const { page, limit } = pagination || {};
43
+ try {
44
+ //Define special filters
45
+ const productFilters = filters.find((filter) => filter.name == 'productInfo');
46
+ const remainOnlyParam = filters.find((filter) => filter.name == 'remainOnly');
47
+ const bizplace = filters.find((filter) => filter.name === 'bizplace');
48
+ filters = filters.filter(x => ['productInfo', 'remainOnly'].indexOf(x.name) < 0);
49
+ const params = { filters, pagination };
50
+ if (!bizplace) {
51
+ params.filters.push({
52
+ name: 'bizplace',
53
+ operator: 'in',
54
+ value: await (0, biz_base_1.getPermittedBizplaceIds)(domain, user),
55
+ relation: true
56
+ });
57
+ }
58
+ const remainOnly = (remainOnlyParam === null || remainOnlyParam === void 0 ? void 0 : remainOnlyParam.value) || false;
59
+ // Define Query data
60
+ const qb = tx.getRepository(inventory_1.Inventory).createQueryBuilder('inventory');
61
+ (0, shell_1.buildQuery)(qb, params, context);
62
+ qb.leftJoinAndSelect('inventory.bizplace', 'bizplace')
63
+ .leftJoinAndSelect('bizplace.domain', 'partnerDomain')
64
+ .leftJoinAndSelect('inventory.product', 'product')
65
+ .leftJoinAndSelect('inventory.productDetail', 'productDetail')
66
+ .leftJoinAndSelect('product.productDetails', 'productDetails', 'productDetails.id = inventory.product_detail_id')
67
+ .leftJoinAndSelect('inventory.warehouse', 'warehouse')
68
+ .leftJoinAndSelect('inventory.location', 'location')
69
+ .leftJoinAndSelect('inventory.creator', 'creator')
70
+ .leftJoinAndSelect('inventory.updater', 'updater')
71
+ // To get aggregated serial number in csv and total number of stored serial number
72
+ .leftJoinAndSelect(subQuery => {
73
+ return subQuery
74
+ .select('inventoryItems.inventory_id', 'inventory_item_inventory_id')
75
+ .addSelect(`SUM(case when "inventoryItems"."status" = 'STORED' then 1 else 0 end)`, 'inventory_item_count')
76
+ .addSelect(`string_agg(inventoryItems.serial_number, ', ')`, 'serial_numbers')
77
+ .from('inventory_items', 'inventoryItems')
78
+ .where(`inventoryItems.domain_id = :domainId`, { domainId: domain.id })
79
+ .andWhere(`inventoryItems.status = :ivicStatus`, { ivicStatus: constants_1.INVENTORY_STATUS.STORED })
80
+ .groupBy('inventoryItems.inventory_id');
81
+ }, 'inventoryItems', '"inventoryItems"."inventory_item_inventory_id" = "inventory"."id"');
82
+ // To get inventory with remaining qty
83
+ if (remainOnly) {
84
+ qb.andWhere('inventory.qty > 0')
85
+ .andWhere('CASE WHEN inventory.lockedQty IS NULL THEN 0 ELSE inventory.lockedQty END >= 0')
86
+ .andWhere('inventory.qty - CASE WHEN inventory.lockedQty IS NULL THEN 0 ELSE inventory.lockedQty END > 0');
87
+ }
88
+ // Filter based on multiple product parameters and allow to search in csv format
89
+ if (productFilters) {
90
+ let productFilterValue = `%${productFilters.value.toLowerCase()}%`;
91
+ qb.andWhere(qb => {
92
+ const subQuery = qb
93
+ .subQuery()
94
+ .select()
95
+ .from(product_base_1.Product, `products`)
96
+ .where(`products.id = inventory.product_id`)
97
+ .andWhere(new typeorm_1.Brackets(qb => {
98
+ qb.where('Lower(products.sku) LIKE :productInfo', { productInfo: productFilterValue })
99
+ .orWhere('Lower(products.name) LIKE :productInfo', { productInfo: productFilterValue })
100
+ .orWhere('Lower(products.description) LIKE :productInfo', { productInfo: productFilterValue })
101
+ .orWhere('Lower(products.brand) LIKE :productInfo', { productInfo: productFilterValue });
102
+ }))
103
+ .getQuery();
104
+ return `EXISTS ${subQuery}`;
105
+ });
106
+ }
107
+ // Apply sorting based on child data
108
+ if ((sortings === null || sortings === void 0 ? void 0 : sortings.length) !== 0) {
109
+ const arrChildSortData = ['bizplace', 'product', 'location', 'warehouse', 'zone'];
110
+ const sort = (sortings || []).reduce((acc, sort) => {
111
+ if (sort.name === 'sku') {
112
+ // Apply custom sorting logic for SKU
113
+ acc = Object.assign(Object.assign({}, acc), { [arrChildSortData.indexOf(sort.name) >= 0 ? sort.name + '.name' : 'product.' + sort.name]: sort.desc
114
+ ? 'DESC'
115
+ : 'ASC' });
116
+ }
117
+ else {
118
+ // Normal sorting for other fields
119
+ acc = Object.assign(Object.assign({}, acc), { [arrChildSortData.indexOf(sort.name) >= 0 ? sort.name + '.name' : 'inventory.' + sort.name]: sort.desc
120
+ ? 'DESC'
121
+ : 'ASC' });
122
+ }
123
+ return acc;
124
+ }, {});
125
+ qb.orderBy(sort);
126
+ }
127
+ if ((locationSortingRules === null || locationSortingRules === void 0 ? void 0 : locationSortingRules.length) > 0) {
128
+ locationSortingRules.forEach(rule => {
129
+ qb.addOrderBy(`location.${rule.name}`, rule.desc ? 'DESC' : 'ASC');
130
+ });
131
+ }
132
+ // Fetch all row for exporting
133
+ if (exportItem != true && page && limit) {
134
+ qb.offset((page - 1) * limit).limit(limit);
135
+ }
136
+ let items = (await qb.getRawMany()).map(item => {
137
+ return Object.assign(Object.assign({}, new inventory_1.Inventory(item)), { qty: parseFloat(item.inventory_qty) || 0, transferQty: parseFloat(item.inventory_transfer_qty) || 0, transferUomValue: parseFloat(item.inventory_transfer_uom_value) || 0, uomValue: parseFloat(item.inventory_uom_value) || 0, lockedQty: parseFloat(item.inventory_locked_qty) || 0, lockedUomValue: parseFloat(item.inventory_locked_uom_value) || 0, serialNumbers: item.serial_numbers, productDetail: {
138
+ id: item.productDetail_id,
139
+ name: item.productDetail_name,
140
+ gtin: item.productDetail_gtin
141
+ }, partnerDomain: {
142
+ id: item.bizplace_domain_id
143
+ } });
144
+ });
145
+ let total = await qb.getCount();
146
+ return {
147
+ items,
148
+ total
149
+ };
150
+ }
151
+ catch (error) {
152
+ env_1.logger.error(`inventory-query[inventories]: ${error}`);
153
+ throw error;
154
+ }
155
+ }
156
+ async inventory(palletId, context) {
157
+ const { domain } = context.state;
158
+ return await (0, typeorm_1.getRepository)(inventory_1.Inventory).findOne({
159
+ where: { domain: domain, palletId },
160
+ relations: ['domain', 'bizplace', 'product', 'location', 'warehouse', 'creator', 'updater']
161
+ });
162
+ }
163
+ async inventoryByPallet(palletId, context) {
164
+ const { domain } = context.state;
165
+ return await (0, typeorm_1.getRepository)(inventory_1.Inventory).findOne({
166
+ where: { domain, palletId, status: (0, typeorm_1.Not)((0, typeorm_1.Equal)(constants_1.INVENTORY_STATUS.TERMINATED)) },
167
+ relations: ['domain', 'bizplace', 'product', 'location', 'warehouse', 'creator', 'updater']
168
+ });
169
+ }
170
+ async inventoriesByProduct(params, context) {
171
+ try {
172
+ const { domain, user, tx } = context.state;
173
+ let permittedBizplaceIds = await (0, biz_base_1.getPermittedBizplaceIds)(domain, user);
174
+ //const partnersCompanyBizplaces: Bizplace[] = await getPartnersCompanyBizplaces(domain, user)
175
+ const page = params.pagination.page;
176
+ const limit = params.pagination.limit;
177
+ let bizplaceFilter = params.filters.find(filter => filter.name == 'bizplace');
178
+ let productFilter = params.filters.find(filter => filter.name == 'product');
179
+ let packingTypeFilter = params.filters.find(filter => filter.name == 'packingType');
180
+ let availableStockFilter = params.filters.find(filter => filter.name == 'availableStock');
181
+ let lowStockFilter = params.filters.find(filter => filter.name == 'lowStock');
182
+ let overStockFilter = params.filters.find(filter => filter.name == 'overStock');
183
+ let quarantineStockFilter = params.filters.find(filter => filter.name == 'quarantineStock');
184
+ let reserveStockFilter = params.filters.find(filter => filter.name == 'reserveStock');
185
+ let productTypeFilter = params.filters.find(filter => filter.name == 'type');
186
+ if (bizplaceFilter) {
187
+ const bizplaceQueryBuilder = (0, typeorm_1.getRepository)(biz_base_1.Bizplace).createQueryBuilder('b');
188
+ bizplaceQueryBuilder
189
+ .innerJoin('companies', 'c2', ' c2.domain_id = b.domain_id')
190
+ .innerJoin('bizplaces', 'b2', 'b2.company_id = c2.id')
191
+ .innerJoin('domains', 'd', 'd.id = b.domain_id')
192
+ .where('b2.id = :bizplaceId', { bizplaceId: bizplaceFilter.value })
193
+ .andWhere('d.ext_type <> :type', { type: 'company' });
194
+ let bizplaceList = await bizplaceQueryBuilder.getMany();
195
+ permittedBizplaceIds = [
196
+ ...permittedBizplaceIds.filter(itm => itm == bizplaceFilter.value),
197
+ ...bizplaceList.map(bz => bz.id)
198
+ //...partnersCompanyBizplaces.map(biz => biz.id)
199
+ ];
200
+ }
201
+ let bizplaceQuery = '';
202
+ if (permittedBizplaceIds.length > 0) {
203
+ bizplaceQuery = `
204
+ select bizplace_id::uuid from (VALUES ${permittedBizplaceIds.map(id => `('${id}')`).join(',')})
205
+ as bizFilter(bizplace_id)
206
+ inner join bizplaces b on b.id = bizFilter.bizplace_id::uuid
207
+ inner join domains d on d.id = b.domain_id
208
+ inner join partners p on p.partner_domain_id = d.id
209
+ where p.domain_id = '${domain.id}'
210
+ `;
211
+ }
212
+ else {
213
+ bizplaceQuery = `select null as bizplace_id`;
214
+ }
215
+ let productQuery = '';
216
+ if (productFilter) {
217
+ let productValue = productFilter.value
218
+ .toLowerCase()
219
+ .split(',')
220
+ .map(prod => {
221
+ return "'%" + prod.trim().replace(/'/g, "''") + "%'";
222
+ })
223
+ .join(',');
224
+ productQuery = `AND (
225
+ Lower("p"."name") LIKE ANY(ARRAY[${productValue}])
226
+ OR Lower("p"."sku") LIKE ANY(ARRAY[${productValue}])
227
+ OR Lower("p"."brand") LIKE ANY(ARRAY[${productValue}])
228
+ OR Lower("p"."description") LIKE ANY(ARRAY[${productValue}])
229
+ )`;
230
+ }
231
+ if (productTypeFilter) {
232
+ let productTypeValue = productTypeFilter.value
233
+ .toLowerCase()
234
+ .split(',')
235
+ .map(prod => {
236
+ return "'%" + prod.trim().replace(/'/g, "''") + "%'";
237
+ })
238
+ .join(',');
239
+ productQuery =
240
+ productQuery +
241
+ ` AND (
242
+ Lower("p"."type") LIKE ANY(ARRAY[${productTypeValue}])
243
+ )`;
244
+ }
245
+ let qtyStockQuery = '';
246
+ let availableStockQuery = '';
247
+ if (reserveStockFilter === null || reserveStockFilter === void 0 ? void 0 : reserveStockFilter.value) {
248
+ qtyStockQuery += `\nAND SUM("reserveQty") > 0`;
249
+ }
250
+ if (quarantineStockFilter === null || quarantineStockFilter === void 0 ? void 0 : quarantineStockFilter.value) {
251
+ qtyStockQuery += `\nAND SUM("quarantineQty") > 0`;
252
+ }
253
+ if (availableStockFilter === null || availableStockFilter === void 0 ? void 0 : availableStockFilter.value) {
254
+ qtyStockQuery += ` AND SUM("availableQty") + SUM("putaway_qty") > 0`;
255
+ }
256
+ if (availableStockFilter) {
257
+ availableStockQuery = ` AND SUM("availableQty") + COALESCE("putawayinv"."putaway_qty", 0) - COALESCE("pds"."unassigned_qty",0) ${(availableStockFilter === null || availableStockFilter === void 0 ? void 0 : availableStockFilter.value) ? '>' : '='} 0`;
258
+ }
259
+ if ((availableStockFilter === null || availableStockFilter === void 0 ? void 0 : availableStockFilter.value) && (quarantineStockFilter === null || quarantineStockFilter === void 0 ? void 0 : quarantineStockFilter.value)) {
260
+ qtyStockQuery = '';
261
+ qtyStockQuery += `\nAND (SUM("availableQty") > 0 \n OR SUM("quarantineQty") > 0)`;
262
+ }
263
+ if ((availableStockFilter === null || availableStockFilter === void 0 ? void 0 : availableStockFilter.value) && (reserveStockFilter === null || reserveStockFilter === void 0 ? void 0 : reserveStockFilter.value)) {
264
+ qtyStockQuery = '';
265
+ qtyStockQuery += `\nAND (SUM("availableQty") > 0 \n OR SUM("reserveQty") > 0)`;
266
+ }
267
+ if ((quarantineStockFilter === null || quarantineStockFilter === void 0 ? void 0 : quarantineStockFilter.value) && (reserveStockFilter === null || reserveStockFilter === void 0 ? void 0 : reserveStockFilter.value)) {
268
+ qtyStockQuery = '';
269
+ qtyStockQuery += `\nAND (SUM("quarantineQty") > 0 \n OR SUM("reserveQty") > 0)`;
270
+ }
271
+ let inventoryQuery = '';
272
+ if (packingTypeFilter) {
273
+ let packingTypeValue = packingTypeFilter.value
274
+ .toLowerCase()
275
+ .split(',')
276
+ .map(prod => {
277
+ return "'%" + prod.trim().replace(/'/g, "''") + "%'";
278
+ })
279
+ .join(',');
280
+ inventoryQuery =
281
+ inventoryQuery +
282
+ ` AND (
283
+ Lower("tih"."packingType") LIKE ANY(ARRAY[${packingTypeValue}])
284
+ )`;
285
+ }
286
+ let thresholdQuery = '';
287
+ if ((lowStockFilter === null || lowStockFilter === void 0 ? void 0 : lowStockFilter.value) && (overStockFilter === null || overStockFilter === void 0 ? void 0 : overStockFilter.value)) {
288
+ throw new Error('invalid filter combination');
289
+ }
290
+ else if ((lowStockFilter === null || lowStockFilter === void 0 ? void 0 : lowStockFilter.value) && !(overStockFilter === null || overStockFilter === void 0 ? void 0 : overStockFilter.value)) {
291
+ thresholdQuery = `AND SUM(COALESCE("minQty", 0)) > SUM("availableQty")`;
292
+ }
293
+ else if (!(lowStockFilter === null || lowStockFilter === void 0 ? void 0 : lowStockFilter.value) && (overStockFilter === null || overStockFilter === void 0 ? void 0 : overStockFilter.value)) {
294
+ thresholdQuery = `AND SUM(COALESCE("maxQty", 0)) > 0 AND SUM(COALESCE("maxQty", 0)) < SUM("availableQty")`;
295
+ }
296
+ // await tx.query(
297
+ // `
298
+ // CREATE TEMP TABLE order_inventories_by_products AS (
299
+ // SELECT "product_id", "packing_type", sum("release_qty") AS "total_release_qty" FROM order_inventories oi
300
+ // WHERE "type" = 'RELEASE_OF_GOODS'
301
+ // AND "domain_id" = $1
302
+ // AND "inventory_id" ISNULL
303
+ // AND "status" IN ('PENDING','PENDING_RECEIVE','PENDING_WORKSHEET','READY_TO_PICK'/*, 'PENDING_SPLIT' kiv sebab kalau pending split, ada yang dah assign tapi belum delete*/)
304
+ // GROUP BY "product_id", "packing_type"
305
+ // )`,
306
+ // [domain.id]
307
+ // )
308
+ /* old logic to calculate, monitoring new logic
309
+ (CASE WHEN "Location"."type" NOT IN ('${LOCATION_TYPE.QUARANTINE}','${LOCATION_TYPE.RESERVE}')
310
+ THEN SUM(COALESCE("Inventory"."locked_qty", 0)) ELSE 0 END) AS "releaseQty",
311
+ */
312
+ // correction on the as --> AS
313
+ await tx.query(`
314
+ create temp table temp_inv_history AS
315
+ (
316
+ select p."id" as "id", pd."id" as "productDetailId", p."sku" as "sku", p."brand" as "brand", p."name" as "name", p."type" as "type", p."description" as "description",
317
+ coalesce(i."packing_type", pd."packing_type") as "packingType", p."weight" as "weight",
318
+ pd."aux_unit_1" as "auxUnit1", pd."aux_value_1" as "auxValue1", pd."aux_unit_2" as "auxUnit2", pd."aux_value_2" as "auxValue2",
319
+ pd."aux_unit_3" as "auxUnit3", pd."aux_value_3" as "auxValue3", pd."aux_unit_4" as "auxUnit4", pd."aux_value_4" as "auxValue4",
320
+ pd."aux_unit_5" as "auxUnit5", pd."aux_value_5" as "auxValue5", coalesce(inv_bz."id", bz2."id") as "bizplaceId", coalesce(inv_bz."name", bz2."name") as "bizplaceName",
321
+ COALESCE(pdbs."min_qty", p."min_qty",0) as "minQty", COALESCE(pdbs."max_qty", p."max_qty",0) as "maxQty",
322
+ (
323
+ case when sum(coalesce(i."qty",0)) > 0 then sum(coalesce(i."unit_cost", 0) * coalesce(i."qty",0))/ sum(coalesce(i."qty",0))
324
+ else 0 end
325
+ ) as "averageUnitCost",
326
+ (
327
+ case when inv_loc."type" NOT IN ('QUARANTINE','RESERVE') and
328
+ case when i."expiration_date" is not null and p."min_outbound_shelf_life" is not null then CURRENT_DATE < i."expiration_date" - p."min_outbound_shelf_life" else true end
329
+ and i."obsolete" is false
330
+ then
331
+ case when sum(coalesce(i."qty",0)) > 0 then sum(coalesce(i."qty",0)) else 0 end
332
+ else 0 end
333
+ ) as "qty",
334
+ (
335
+ case when inv_loc."type" NOT IN ('QUARANTINE','RESERVE')
336
+ and case when i."expiration_date" is not null and p."min_outbound_shelf_life" is not null then CURRENT_DATE < i."expiration_date" - p."min_outbound_shelf_life" else true end
337
+ and i."obsolete" is false
338
+ then
339
+ case when sum(coalesce(i."qty",0)) > 0 then sum(coalesce(i."qty",0)) else 0 end - greatest(sum(COALESCE(i."locked_qty", 0)), 0)
340
+ else 0 end
341
+ ) as "availableQty",
342
+ (
343
+ case when inv_loc."type" = 'QUARANTINE'
344
+ then case when sum(coalesce(i."qty",0)) > 0
345
+ then sum(coalesce(i."qty",0))-sum(COALESCE(i."locked_qty", 0))
346
+ else 0 end
347
+ else 0 end
348
+ ) as "quarantineQty",
349
+ (
350
+ case when inv_loc."type" = 'RESERVE'
351
+ then
352
+ case when sum(coalesce(i."qty",0)) > 0
353
+ then sum(coalesce(i."qty",0))-sum(COALESCE(i."locked_qty", 0))
354
+ else 0 end
355
+ else 0 end
356
+ ) as "reserveQty",
357
+ (
358
+ case when inv_loc."type" = 'BIN'
359
+ then sum(coalesce(i."qty",0))
360
+ else 0
361
+ end
362
+ )as "binQty",
363
+ (
364
+ case when i."obsolete" is true or
365
+ case when i."expiration_date" is not null and p."min_outbound_shelf_life" is not null then CURRENT_DATE > i."expiration_date" - p."min_outbound_shelf_life" else false end
366
+ then
367
+ case when sum(coalesce(i."qty",0)) > 0 then sum(coalesce(i."qty",0)) else 0 end
368
+ else 0 end
369
+ ) as "obsoleteQty",
370
+ (
371
+ case when inv_loc."type" = 'DAMAGE'
372
+ then
373
+ case when sum(coalesce(i."qty",0)) > 0
374
+ then sum(coalesce(i."qty",0))
375
+ else 0 end
376
+ else 0 end
377
+ ) as "damageQty",
378
+ (
379
+ case when inv_loc."type" = 'STORAGE'
380
+ then
381
+ case when sum(coalesce(i."qty",0)) > 0
382
+ then sum(coalesce(i."qty",0))-sum(COALESCE(i."locked_qty", 0))
383
+ else 0 end
384
+ else 0 end
385
+ ) as "storageQty",
386
+ (
387
+ case when i."transfer_qty" > 0
388
+ then
389
+ sum(i."transfer_qty")
390
+ else 0 end
391
+ ) as "transferQty",
392
+ sum(coalesce(i."locked_qty", 0)) as "locked_qty",
393
+ pd."uom_value" as "uomValue"
394
+ from (
395
+ ${bizplaceQuery}
396
+ ) b
397
+ inner join bizplaces bz on bz.id = b.bizplace_id
398
+ inner join companies c on c.id = bz.company_id
399
+ inner join bizplaces bz2 on bz2.domain_id = c.domain_id
400
+ inner join products p on (p.bizplace_id = b.bizplace_id::uuid or p.bizplace_id = bz2.id)
401
+ inner join product_details pd on pd.product_id = p.id and pd.is_default
402
+ left join product_detail_bizplace_settings pdbs on pdbs.product_detail_id = pd.id
403
+ left join inventories i on i.bizplace_id =b.bizplace_id and i.product_id = p.id and i.qty >= 0 and i.status <> 'MISSING' and i.status <> 'PUTTING_AWAY' and
404
+ i.domain_id = $1
405
+ left join product_detail_stocks pds on pds.product_detail_id = pd.id and pds.domain_id = i.domain_id
406
+ left join bizplaces inv_bz on inv_bz.id = i.bizplace_id
407
+ left join locations inv_loc on inv_loc.id = i.location_id
408
+ where 1 = 1
409
+ ${productQuery}
410
+ group by p."id", coalesce(inv_bz."id", bz2."id"), coalesce(inv_bz."name", bz2."name"), pdbs."id", pd."id",
411
+ i."packing_type", i."packing_size", i."uom", i."transfer_qty", i."expiration_date", i."obsolete", pd."uom_value",
412
+ inv_loc."type"
413
+ )`, [domain.id]);
414
+ await tx.query(`
415
+ CREATE TEMP TABLE grouped_inventories_product AS (
416
+ SELECT "tih"."id", "sku", "brand", "name", "description", "auxUnit1", "auxValue1", "auxUnit2", "auxValue2", "auxUnit3", "auxValue3", "auxUnit4", "auxValue4", "auxUnit5", "auxValue5",
417
+ "packingType", "bizplaceId", "bizplaceName", SUM("averageUnitCost") AS "averageUnitCost", "uomValue",
418
+ SUM("minQty") AS "minQty", SUM("maxQty") AS "maxQty",
419
+ COALESCE("putawayinv"."putaway_qty", 0) AS "putawayQty",
420
+ SUM("tih"."qty") AS "qty",
421
+ SUM("quarantineQty") AS "quarantineQty",
422
+ SUM("reserveQty") AS "reserveQty",
423
+ COALESCE("opd"."total_release_qty", 0) as "draftQty",
424
+ GREATEST(SUM(COALESCE("tih"."locked_qty",0)),0) + GREATEST(COALESCE("pds"."unassigned_qty",0), 0) as "releaseQty",
425
+ COALESCE("opd"."total_release_qty", 0) - SUM("availableQty") - COALESCE("putawayinv"."putaway_qty", 0) AS "insufficientQty",
426
+ (
427
+ CASE WHEN (SUM("availableQty") + COALESCE("putawayinv"."putaway_qty", 0) - GREATEST(COALESCE("pds"."unassigned_qty",0), 0)) < 0 THEN 0
428
+ ELSE SUM("availableQty") + COALESCE("putawayinv"."putaway_qty", 0) - GREATEST(COALESCE("pds"."unassigned_qty",0), 0) END
429
+ ) AS "availableQty",
430
+ SUM("quarantineQty" + "reserveQty" + "availableQty") + COALESCE("putawayinv"."putaway_qty", 0) - COALESCE("opd"."total_release_qty", 0) AS "warehouseQty",
431
+ SUM("obsoleteQty") AS "obsoleteQty",
432
+ SUM("damageQty") AS "damageQty",
433
+ SUM("storageQty") AS "storageQty",
434
+ SUM("transferQty") AS "transferQty"
435
+ FROM "temp_inv_history" tih
436
+ LEFT JOIN
437
+ (
438
+ SELECT "op"."product_id", COALESCE(SUM("op"."release_qty")) as "total_release_qty",
439
+ "op"."packing_type", "op"."packing_size", "op"."uom"
440
+ FROM "order_products" op
441
+ INNER JOIN "draft_release_goods" drg
442
+ ON drg.id = op.draft_release_good_id
443
+ WHERE "drg"."domain_id" = $1
444
+ AND ("drg"."status" = 'DRAFT' OR "drg"."status" = 'PARTIAL RELEASED')
445
+ AND "op"."draft_release_good_id" IS NOT null
446
+ AND "op"."status" = 'DRAFT'
447
+ GROUP BY "op"."product_id","op"."packing_type" ,"op"."packing_size", "op"."uom"
448
+ ) AS "opd"
449
+ ON "tih"."id" = "opd"."product_id"
450
+ AND "tih"."packingType" = "opd"."packing_type"
451
+ LEFT JOIN
452
+ (
453
+ SELECT SUM(i.qty) as "putaway_qty", i.product_id, i.packing_type, i.packing_size, i.uom FROM "inventories" i
454
+ WHERE i.status = 'PUTTING_AWAY' and i.domain_id = $1
455
+ GROUP BY i.product_id, i.packing_type, i.packing_size, i.uom
456
+ ) AS "putawayinv" ON "tih"."id" = "putawayinv"."product_id" AND "tih"."packingType" = "putawayinv"."packing_type"
457
+ LEFT JOIN "product_detail_stocks" pds on pds.product_detail_id = "tih"."productDetailId"
458
+ GROUP BY "tih"."id", "sku", "brand", "name", "description", "packingType", "bizplaceId", "bizplaceName", "opd"."total_release_qty","putawayinv"."putaway_qty",
459
+ "auxUnit1", "auxValue1", "auxUnit2", "auxValue2", "auxUnit3", "auxValue3", "auxUnit4", "auxValue4", "auxUnit5", "auxValue5", pds.unassigned_qty, "uomValue"
460
+ HAVING 1 = 1
461
+ ${thresholdQuery}
462
+ ${availableStockQuery}
463
+ ${inventoryQuery}
464
+ )
465
+ `, [domain.id]);
466
+ const results = await tx.query(`
467
+ SELECT * FROM grouped_inventories_product
468
+ ORDER BY "bizplaceName", "sku"
469
+ OFFSET $1 LIMIT $2
470
+ `, [(page - 1) * limit, limit]);
471
+ const total = await tx.query(`SELECT COUNT(*) FROM grouped_inventories_product`);
472
+ await tx.query(`drop table temp_inv_history, grouped_inventories_product`);
473
+ return {
474
+ items: results.map((item) => {
475
+ return {
476
+ product: {
477
+ id: item.id,
478
+ name: item.name,
479
+ sku: item.sku,
480
+ brand: item.brand,
481
+ description: item.description,
482
+ minQty: item.minQty,
483
+ maxQty: item.maxQty,
484
+ auxUnit1: item.auxUnit1,
485
+ auxValue1: item.auxValue1,
486
+ auxUnit2: item.auxUnit2,
487
+ auxValue2: item.auxValue2,
488
+ auxUnit3: item.auxUnit3,
489
+ auxValue3: item.auxValue3,
490
+ auxUnit4: item.auxUnit4,
491
+ auxValue4: item.auxValue4,
492
+ auxUnit5: item.auxUnit5,
493
+ auxValue5: item.auxValue5
494
+ },
495
+ bizplace: {
496
+ id: item.bizplaceId,
497
+ name: item.bizplaceName
498
+ },
499
+ packingType: item.packingType,
500
+ averageUnitCost: item.averageUnitCost,
501
+ putawayQty: item.putawayQty,
502
+ qty: item.qty,
503
+ availableQty: item.availableQty,
504
+ insufficientQty: item.insufficientQty > 0 ? item.insufficientQty : 0,
505
+ releaseQty: item.releaseQty,
506
+ quarantineQty: item.quarantineQty,
507
+ reserveQty: item.reserveQty,
508
+ draftQty: item.draftQty,
509
+ warehouseQty: item.warehouseQty,
510
+ obsoleteQty: item.obsoleteQty,
511
+ damageQty: item.damageQty,
512
+ storageQty: item.storageQty,
513
+ transferQty: item.transferQty,
514
+ uomValue: item.uomValue
515
+ };
516
+ }),
517
+ total: total[0].count
518
+ };
519
+ }
520
+ catch (error) {
521
+ throw error;
522
+ }
523
+ }
524
+ async inventoriesByStrategy(context, worksheetId, batchId, productName, productSku, packingType, packingSize, uom, pickingStrategy, locationSortingRules, bizplaceId) {
525
+ const { domain, tx } = context.state;
526
+ const inventoryAssignmentSetting = await tx.getRepository(setting_base_1.Setting).findOne({
527
+ where: { domain, name: 'rule-for-inventory-assignment' }
528
+ });
529
+ if (!locationSortingRules && inventoryAssignmentSetting) {
530
+ locationSortingRules = [];
531
+ let locationSetting = JSON.parse(inventoryAssignmentSetting.value);
532
+ for (const key in locationSetting) {
533
+ locationSortingRules.push({ name: key, desc: locationSetting[key] == 'ASC' ? false : true });
534
+ }
535
+ }
536
+ return inventoriesByStrategy({
537
+ worksheetId,
538
+ batchId,
539
+ bizplaceId,
540
+ productName,
541
+ productSku,
542
+ packingType,
543
+ packingSize,
544
+ uom,
545
+ pickingStrategy,
546
+ locationSortingRules
547
+ }, tx);
548
+ }
549
+ async checkProductIdenticality(palletA, palletB, context) {
550
+ var _a, _b;
551
+ const { tx } = context.state;
552
+ const invRepo = tx.getRepository(inventory_1.Inventory);
553
+ const invA = await invRepo.findOne({
554
+ where: { domain: context.state.domain, palletId: palletA, status: constants_1.INVENTORY_STATUS.STORED },
555
+ relations: ['product']
556
+ });
557
+ const invB = await invRepo.findOne({
558
+ where: { domain: context.state.domain, palletId: palletB, status: constants_1.INVENTORY_STATUS.STORED },
559
+ relations: ['product']
560
+ });
561
+ return ((invA === null || invA === void 0 ? void 0 : invA.batchId) === (invB === null || invB === void 0 ? void 0 : invB.batchId) &&
562
+ ((_a = invA === null || invA === void 0 ? void 0 : invA.product) === null || _a === void 0 ? void 0 : _a.id) === ((_b = invB === null || invB === void 0 ? void 0 : invB.product) === null || _b === void 0 ? void 0 : _b.id) &&
563
+ (invA === null || invA === void 0 ? void 0 : invA.packingType) === (invB === null || invB === void 0 ? void 0 : invB.packingType));
564
+ }
565
+ async checkCartonIdenticality(cartonA, palletA, cartonB, context) {
566
+ var _a, _b;
567
+ const invRepo = (0, typeorm_1.getRepository)(inventory_1.Inventory);
568
+ const invA = await invRepo.findOne({
569
+ where: { domain: context.state.domain, palletId: palletA, cartonId: cartonA, status: constants_1.INVENTORY_STATUS.STORED },
570
+ relations: ['product']
571
+ });
572
+ const invB = await invRepo.findOne({
573
+ where: {
574
+ domain: context.state.domain,
575
+ packingType: invA.packingType,
576
+ packingSize: invA.packingSize,
577
+ product: invA.product,
578
+ cartonId: cartonB,
579
+ status: constants_1.INVENTORY_STATUS.STORED
580
+ },
581
+ relations: ['product']
582
+ });
583
+ return ((invA === null || invA === void 0 ? void 0 : invA.expirationDate) === (invB === null || invB === void 0 ? void 0 : invB.expirationDate) &&
584
+ ((_a = invA === null || invA === void 0 ? void 0 : invA.product) === null || _a === void 0 ? void 0 : _a.id) === ((_b = invB === null || invB === void 0 ? void 0 : invB.product) === null || _b === void 0 ? void 0 : _b.id) &&
585
+ (invA === null || invA === void 0 ? void 0 : invA.packingType) === (invB === null || invB === void 0 ? void 0 : invB.packingType) &&
586
+ (invA === null || invA === void 0 ? void 0 : invA.packingSize) === (invB === null || invB === void 0 ? void 0 : invB.packingSize));
587
+ }
588
+ async checkInventoryOwner(palletId, bizplaceName, context) {
589
+ try {
590
+ const invRepo = (0, typeorm_1.getRepository)(inventory_1.Inventory);
591
+ const bizRepo = (0, typeorm_1.getRepository)(biz_base_1.Bizplace);
592
+ const inventory = await invRepo.findOne({
593
+ where: { domain: context.state.domain, palletId, status: constants_1.INVENTORY_STATUS.STORED },
594
+ relations: ['bizplace']
595
+ });
596
+ if (!inventory)
597
+ throw new Error('This inventory status is not stored.');
598
+ const ownerBizplace = await bizRepo.findOne({
599
+ where: { name: bizplaceName }
600
+ });
601
+ const foundBizplace = inventory.bizplace;
602
+ return Boolean(ownerBizplace.id === foundBizplace.id);
603
+ }
604
+ catch (e) {
605
+ return false;
606
+ }
607
+ }
608
+ async checkInventoryLocation(context, cartonId, palletId, bizplaceId) {
609
+ const { domain } = context.state;
610
+ let whereClause = 'inventory.bizplace_id = :bizplaceId AND inventory.domain_id = :domainId AND inventory.status != :status';
611
+ if (cartonId) {
612
+ whereClause += ' AND inventory.cartonId = :cartonId';
613
+ }
614
+ if (palletId) {
615
+ whereClause += ' AND inventory.palletId = :palletId';
616
+ }
617
+ const qb = (0, typeorm_1.getRepository)(inventory_1.Inventory).createQueryBuilder('inventory');
618
+ qb.select(['location.name', 'product.sku'])
619
+ .innerJoin('inventory.product', 'product')
620
+ .innerJoin('inventory.location', 'location')
621
+ .innerJoin('inventory.domain', 'domain')
622
+ .innerJoin('inventory.bizplace', 'bizplace')
623
+ .where(whereClause, { cartonId, palletId, bizplaceId, domainId: domain.id, status: 'TERMINATED' });
624
+ let items = await qb.getRawMany();
625
+ items = items.map(item => {
626
+ return {
627
+ location: {
628
+ name: item.location_name
629
+ },
630
+ product: {
631
+ sku: item.product_sku
632
+ }
633
+ };
634
+ });
635
+ return { items, total: items.length };
636
+ }
637
+ async inventoriesByBundle(context, filters, pagination, sortings) {
638
+ var _a, _b;
639
+ const { domain, user } = context.state;
640
+ const params = { filters, pagination };
641
+ const productBundleId = params.filters.filter(x => x.name === 'productBundleId')[0].value;
642
+ if (!productBundleId) {
643
+ throw new Error('params product bundle is missing');
644
+ }
645
+ const bundleReleaseQty = params.filters.filter(x => x.name === 'bundleReleaseQty')[0].value;
646
+ // remove productBundleId and bundleReleaseQty from params.filters
647
+ params.filters = params.filters.filter(x => x.name !== 'productBundleId' && x.name !== 'bundleReleaseQty');
648
+ if (!params.filters.find((filter) => filter.name === 'bizplace_id')) {
649
+ params.filters.push({
650
+ name: 'bizplace_id',
651
+ operator: 'in',
652
+ value: await (0, biz_base_1.getPermittedBizplaceIds)(domain, user),
653
+ relation: true
654
+ });
655
+ }
656
+ const remainOnlyParam = (_a = params === null || params === void 0 ? void 0 : params.filters) === null || _a === void 0 ? void 0 : _a.find((f) => f.name === 'remainOnly');
657
+ let remainOnly = false;
658
+ if (typeof (remainOnlyParam === null || remainOnlyParam === void 0 ? void 0 : remainOnlyParam.value) !== 'undefined') {
659
+ remainOnly = remainOnlyParam.value;
660
+ params.filters = params.filters.filter((f) => f.name !== 'remainOnly');
661
+ }
662
+ const unlockOnlyParam = (_b = params === null || params === void 0 ? void 0 : params.filters) === null || _b === void 0 ? void 0 : _b.find((f) => f.name === 'unlockOnly');
663
+ let unlockOnly = false;
664
+ if (typeof (unlockOnlyParam === null || unlockOnlyParam === void 0 ? void 0 : unlockOnlyParam.value) !== 'undefined') {
665
+ unlockOnly = unlockOnlyParam.value;
666
+ params.filters = params.filters.filter((f) => f.name !== 'unlockOnly');
667
+ }
668
+ const productBundleSettings = await (0, typeorm_1.getRepository)(product_base_1.ProductBundleSetting).find({
669
+ where: { productBundle: productBundleId },
670
+ relations: ['product', 'productDetail', 'productBundle']
671
+ });
672
+ if (!productBundleSettings.length) {
673
+ throw new Error('product bundle settings is not found');
674
+ }
675
+ const qb = (0, typeorm_1.getRepository)(inventory_1.Inventory).createQueryBuilder('iv');
676
+ (0, shell_1.buildQuery)(qb, params, context);
677
+ qb.select('iv.product_id', 'productId')
678
+ .addSelect('iv.product_detail_id', 'productDetailId')
679
+ .addSelect('iv.batch_id', 'batchId')
680
+ .addSelect('iv.batch_id_ref', 'batchIdRef')
681
+ .addSelect('iv.packing_type', 'packingType')
682
+ .addSelect('SUM(iv.qty)', 'qty')
683
+ .addSelect('SUM(iv.locked_qty)', 'lockedQty')
684
+ .addSelect('SUM(iv.uom_value)', 'uomValue')
685
+ .addSelect('SUM(iv.locked_uom_value)', 'lockedUomValue')
686
+ .addSelect('prd.sku', 'productSku')
687
+ .addSelect('prd.name', 'productName')
688
+ .addSelect('prd.description', 'productDescription')
689
+ .addSelect('prd.type', 'productType')
690
+ .addSelect('prd.primary_unit', 'uom')
691
+ .leftJoin('iv.product', 'prd')
692
+ .leftJoin('iv.location', 'l')
693
+ .where('iv.status =:status', { status: 'STORED' })
694
+ .andWhere('l.type NOT IN(:...locationType)', { locationType: ['DAMAGE', 'RESERVE', 'QUARANTINE'] });
695
+ if (remainOnly) {
696
+ qb.andWhere('iv.qty > 0')
697
+ .andWhere('CASE WHEN iv.lockedQty IS NULL THEN 0 ELSE iv.lockedQty END >= 0')
698
+ .andWhere('iv.qty - CASE WHEN iv.lockedQty IS NULL THEN 0 ELSE iv.lockedQty END > 0');
699
+ }
700
+ if (unlockOnly) {
701
+ qb.andWhere('CASE WHEN iv.lockedQty IS NULL THEN 0 ELSE iv.lockedQty END = 0');
702
+ }
703
+ qb.andWhere('iv.product_id IN (:...productIds)', {
704
+ productIds: productBundleSettings.map(productBundle => productBundle.product.id)
705
+ })
706
+ .groupBy('iv.product_id')
707
+ .having('SUM(iv.qty) - SUM(COALESCE(iv.locked_qty, 0)) > 0')
708
+ .addGroupBy('iv.product_detail_id')
709
+ .addGroupBy('iv.batch_id')
710
+ .addGroupBy('iv.batch_id_ref')
711
+ .addGroupBy('iv.packing_type')
712
+ .addGroupBy('prd.sku')
713
+ .addGroupBy('prd.name')
714
+ .addGroupBy('prd.description')
715
+ .addGroupBy('prd.type')
716
+ .addOrderBy('prd.name')
717
+ .addGroupBy('prd.primary_unit')
718
+ .addOrderBy('iv.batch_id');
719
+ let bundleGroup = await qb.getRawMany();
720
+ bundleGroup = bundleGroup.map((item) => {
721
+ return Object.assign(Object.assign({}, item), { bundleId: productBundleId, remainQty: item.qty - (item.lockedQty ? item.lockedQty : 0), remainUomValue: item.uomValue - (item.lockedUomValue ? item.lockedUomValue : 0), uom: item.uom, bundleQty: productBundleSettings.filter(pbs => pbs.product.id === item.productId)[0].bundleQty });
722
+ });
723
+ const bundleSetting = productBundleSettings.map(pbs => {
724
+ return {
725
+ id: pbs.id,
726
+ productId: pbs.product.id,
727
+ productDetailId: pbs.productDetail.id,
728
+ bundleId: pbs.productBundle.id,
729
+ bundleQty: pbs.bundleQty,
730
+ releaseQty: bundleReleaseQty * pbs.bundleQty,
731
+ productReleaseQty: 0,
732
+ productReleaseUomValue: 0
733
+ };
734
+ });
735
+ /** ************************ **/
736
+ bundleGroup = bundleGroup
737
+ .map(group => {
738
+ const uomValue = group.remainUomValue / group.remainQty;
739
+ bundleSetting.forEach(setting => {
740
+ let assigned = false;
741
+ let releaseQty = 0;
742
+ let releaseUomValue = 0;
743
+ if (group.productId === setting.productId) {
744
+ if (setting.productReleaseQty < setting.releaseQty) {
745
+ assigned = true;
746
+ const leftQty = setting.releaseQty - setting.productReleaseQty;
747
+ releaseQty = leftQty > group.remainQty ? group.remainQty : leftQty;
748
+ releaseUomValue = Math.round(releaseQty * uomValue * 100) / 100;
749
+ setting.productReleaseQty += releaseQty;
750
+ setting.productReleaseUomValue += releaseUomValue;
751
+ }
752
+ group.assigned = assigned;
753
+ group.releaseQty = releaseQty;
754
+ group.releaseUomValue = releaseUomValue;
755
+ group.releaseUomValueWithUom = `${releaseUomValue} ${group.uom}`;
756
+ }
757
+ });
758
+ return group;
759
+ })
760
+ .filter(group => group.assigned);
761
+ /** ************************ **/
762
+ return { bundleGroup, bundleSetting };
763
+ }
764
+ async replenishmentInventories(context, filters, pagination, sortings) {
765
+ let productInfoFilter = filters.find(itm => itm.name == 'product');
766
+ let productFilterValue;
767
+ if (productInfoFilter) {
768
+ productFilterValue = productInfoFilter.value.toLowerCase().split(',').join('|');
769
+ }
770
+ let bizplaceFilter = filters.find(itm => itm.name == 'bizplace');
771
+ const qb = (0, typeorm_1.getRepository)(inventory_1.Inventory).createQueryBuilder('inv');
772
+ qb.select('p.sku', 'productSKU')
773
+ .addSelect('pd.id', 'productDetailId')
774
+ .addSelect('inv.packing_type', 'packingType')
775
+ .addSelect('inv.packing_size', 'packingSize')
776
+ .addSelect('coalesce(pd.min_qty, 0)', 'minQty')
777
+ .addSelect('coalesce(sum(inv.transfer_qty), 0)', 'transferQty')
778
+ .addSelect('coalesce(sum(case when l.type in (:...pickingLocationTypes) then inv.qty else 0 end), 0)', 'pickingShelfQty')
779
+ .addSelect('coalesce(sum(case when l.type = :storageLocationType then inv.qty else 0 end), 0)', 'storageQty')
780
+ .addSelect('biz.id', 'bizplaceId')
781
+ .addSelect('biz.name', 'bizplaceName')
782
+ .innerJoin('inv.location', 'l')
783
+ .innerJoin('inv.product', 'p')
784
+ .innerJoin('inv.productDetail', 'pd')
785
+ .leftJoin('inv.bizplace', 'biz')
786
+ .where('inv.domain_id = :domainId', { domainId: context.state.domain.id })
787
+ .andWhere('inv.status = :status', { status: 'STORED' })
788
+ .andWhere('pd.min_qty > 0');
789
+ productInfoFilter
790
+ ? qb.andWhere('(p.name ~* :productFilterValue or p.sku ~* :productFilterValue or p.description ~* :productFilterValue or p.brand ~* :productFilterValue or p.brand_sku ~* :productFilterValue)', { productFilterValue })
791
+ : '';
792
+ bizplaceFilter ? qb.andWhere('biz.id = :bizplaceId', { bizplaceId: bizplaceFilter.value }) : '';
793
+ qb.groupBy('pd.id')
794
+ .addGroupBy('p.sku')
795
+ .addGroupBy('inv.packing_type')
796
+ .addGroupBy('inv.packing_size')
797
+ .addGroupBy('pd.min_qty')
798
+ .addGroupBy('biz.id')
799
+ .addGroupBy('biz.name')
800
+ // .addGroupBy('inv.transfer_qty')
801
+ .having('coalesce(sum(case when l.type in (:...pickingLocationTypes) then inv.qty else 0 end), 0) is not null')
802
+ .andHaving('coalesce(sum(case when l.type = :storageLocationType then inv.qty else 0 end), 0) > 0')
803
+ .andHaving('coalesce("pd"."min_qty", 0) >= coalesce(sum(case when "l"."type" in (:...pickingLocationTypes) then "inv"."qty" else 0 end), 0)')
804
+ .setParameters({ pickingLocationTypes: ['SHELF', 'FLOOR'], storageLocationType: 'STORAGE' });
805
+ let items = await qb.getRawMany();
806
+ let total = items.length;
807
+ items = await qb
808
+ .offset((pagination.page - 1) * pagination.limit)
809
+ .limit(pagination.limit)
810
+ .getRawMany();
811
+ items = items.map(itm => {
812
+ itm.storageQty = itm.storageQty - itm.transferQty;
813
+ itm.transferQty = 0;
814
+ itm.transferQty = itm.minQty - itm.pickingShelfQty;
815
+ return Object.assign(Object.assign({}, itm), { bizplace: {
816
+ id: itm.bizplaceId,
817
+ name: itm.bizplaceName
818
+ } });
819
+ });
820
+ return { items, total };
821
+ }
822
+ async putawayReplenishmentInventories(context, replenishmentId, inventoryId) {
823
+ const qb = (0, typeorm_1.getRepository)(inventory_1.Inventory).createQueryBuilder('i');
824
+ qb.select('p.sku', 'productSKU')
825
+ .addSelect('i.carton_id', 'cartonId')
826
+ .addSelect('l.name', 'locationName')
827
+ .addSelect('i.qty', 'qty')
828
+ .addSelect('ri.carton_id', 'refCartonId')
829
+ .innerJoin('i.product', 'p')
830
+ .leftJoin('i.location', 'l')
831
+ .leftJoin('i.bizplace', 'biz')
832
+ .leftJoin(inventory_1.Inventory, 'ri', 'ri.id = i.ref_inventory_id')
833
+ .where('i.domain_id = :domainId', { domainId: context.state.domain.id })
834
+ .andWhere('i.ref_order_id = :replenishmentId', { replenishmentId: replenishmentId })
835
+ .andWhere('i.ref_inventory_id IN (:...inventoryId)', { inventoryId: inventoryId });
836
+ let items = await qb.getRawMany();
837
+ let total = items.length;
838
+ items = items.map(itm => {
839
+ return Object.assign(Object.assign({}, itm), { refInventory: {
840
+ cartonId: itm.refCartonId
841
+ }, location: {
842
+ name: itm.locationName
843
+ } });
844
+ });
845
+ return { items, total };
846
+ }
847
+ async domain(inventory) {
848
+ return await (0, typeorm_1.getRepository)(shell_1.Domain).findOne(inventory.domainId);
849
+ }
850
+ async updater(inventory) {
851
+ return await (0, typeorm_1.getRepository)(auth_base_1.User).findOne(inventory.updaterId);
852
+ }
853
+ async creator(inventory) {
854
+ return await (0, typeorm_1.getRepository)(auth_base_1.User).findOne(inventory.creatorId);
855
+ }
856
+ /*
857
+ move changeCount to @FieldResolver so that system don't have
858
+ to keep searching for this when user does not request for it
859
+ */
860
+ async changeCount(inventory) {
861
+ return await (0, typeorm_1.getRepository)(inventory_change_1.InventoryChange).count({
862
+ where: { inventory }
863
+ });
864
+ }
865
+ /*
866
+ "purchaseOrderNo", "orderProductRemark" and "arrivalNoticeRefNo"
867
+ are purely for Getha's lot label. @farishelmi added these here to
868
+ avoid logic changes in @inventories query
869
+ */
870
+ async purchaseOrderNo(inventory) {
871
+ var _a;
872
+ if (!inventory.refOrderId)
873
+ return '';
874
+ let items = await (0, typeorm_1.getRepository)(inventory_1.Inventory).query(`
875
+ SELECT po.name as "purchaseOrderNo" FROM arrival_notices an
876
+ LEFT JOIN purchase_orders po
877
+ ON an.purchase_order_id = po.id
878
+ WHERE an.id = '${inventory.refOrderId}'
879
+ LIMIT 1
880
+ `);
881
+ return ((_a = items[0]) === null || _a === void 0 ? void 0 : _a.purchaseOrderNo) || '';
882
+ }
883
+ async orderProductRemark(inventory) {
884
+ var _a;
885
+ if (!inventory.orderProductId)
886
+ return '';
887
+ let items = await (0, typeorm_1.getRepository)(inventory_1.Inventory).query(`
888
+ SELECT op.remark as "orderProductRemark" FROM order_products op
889
+ WHERE op.id = '${inventory.orderProductId}'
890
+ LIMIT 1
891
+ `);
892
+ return ((_a = items[0]) === null || _a === void 0 ? void 0 : _a.orderProductRemark) || '';
893
+ }
894
+ async arrivalNoticeRefNo(inventory) {
895
+ var _a;
896
+ if (!inventory.refOrderId)
897
+ return '';
898
+ let items = await (0, typeorm_1.getRepository)(inventory_1.Inventory).query(`
899
+ SELECT an.ref_no as "arrivalNoticeRefNo" FROM arrival_notices an
900
+ WHERE an.id = '${inventory.refOrderId}'
901
+ LIMIT 1
902
+ `);
903
+ return ((_a = items[0]) === null || _a === void 0 ? void 0 : _a.arrivalNoticeRefNo) || '';
904
+ }
905
+ async arrivalNoticeNo(inventory) {
906
+ var _a;
907
+ if (!inventory.refOrderId)
908
+ return '';
909
+ let items = await (0, typeorm_1.getRepository)(inventory_1.Inventory).query(`
910
+ SELECT an.name as "arrivalNoticeNo" FROM arrival_notices an
911
+ WHERE an.id = '${inventory.refOrderId}'
912
+ LIMIT 1
913
+ `);
914
+ return ((_a = items[0]) === null || _a === void 0 ? void 0 : _a.arrivalNoticeNo) || '';
915
+ }
916
+ };
917
+ __decorate([
918
+ (0, type_graphql_1.Directive)('@privilege(category: "inventory", privilege: "query")'),
919
+ (0, type_graphql_1.Directive)('@transaction'),
920
+ (0, type_graphql_1.Query)(returns => inventory_types_1.InventoryList),
921
+ __param(0, (0, type_graphql_1.Ctx)()),
922
+ __param(1, (0, type_graphql_1.Arg)('filters', type => [shell_1.Filter], { nullable: true })),
923
+ __param(2, (0, type_graphql_1.Arg)('pagination', type => shell_1.Pagination, { nullable: true })),
924
+ __param(3, (0, type_graphql_1.Arg)('sortings', type => [shell_1.Sorting], { nullable: true })),
925
+ __param(4, (0, type_graphql_1.Arg)('locationSortingRules', type => [shell_1.Sorting], { nullable: true })),
926
+ __param(5, (0, type_graphql_1.Arg)('exportItem', type => Boolean, { nullable: true })),
927
+ __metadata("design:type", Function),
928
+ __metadata("design:paramtypes", [Object, Array, typeof (_a = typeof shell_1.Pagination !== "undefined" && shell_1.Pagination) === "function" ? _a : Object, Array, Array, Boolean]),
929
+ __metadata("design:returntype", Promise)
930
+ ], InventoryQuery.prototype, "inventories", null);
931
+ __decorate([
932
+ (0, type_graphql_1.Directive)('@privilege(category: "inventory", privilege: "query")'),
933
+ (0, type_graphql_1.Query)(returns => inventory_1.Inventory),
934
+ __param(0, (0, type_graphql_1.Arg)('palletId')),
935
+ __param(1, (0, type_graphql_1.Ctx)()),
936
+ __metadata("design:type", Function),
937
+ __metadata("design:paramtypes", [String, Object]),
938
+ __metadata("design:returntype", Promise)
939
+ ], InventoryQuery.prototype, "inventory", null);
940
+ __decorate([
941
+ (0, type_graphql_1.Directive)('@privilege(category: "inventory", privilege: "query")'),
942
+ (0, type_graphql_1.Query)(returns => inventory_1.Inventory),
943
+ __param(0, (0, type_graphql_1.Arg)('palletId')),
944
+ __param(1, (0, type_graphql_1.Ctx)()),
945
+ __metadata("design:type", Function),
946
+ __metadata("design:paramtypes", [String, Object]),
947
+ __metadata("design:returntype", Promise)
948
+ ], InventoryQuery.prototype, "inventoryByPallet", null);
949
+ __decorate([
950
+ (0, type_graphql_1.Directive)('@privilege(category: "inventory", privilege: "query")'),
951
+ (0, type_graphql_1.Directive)('@transaction'),
952
+ (0, type_graphql_1.Query)(returns => inventory_types_1.InventoryList),
953
+ __param(0, (0, type_graphql_1.Args)()),
954
+ __param(1, (0, type_graphql_1.Ctx)()),
955
+ __metadata("design:type", Function),
956
+ __metadata("design:paramtypes", [typeof (_b = typeof shell_1.ListParam !== "undefined" && shell_1.ListParam) === "function" ? _b : Object, Object]),
957
+ __metadata("design:returntype", Promise)
958
+ ], InventoryQuery.prototype, "inventoriesByProduct", null);
959
+ __decorate([
960
+ (0, type_graphql_1.Directive)('@transaction'),
961
+ (0, type_graphql_1.Query)(returns => inventory_types_1.InventoryList),
962
+ __param(0, (0, type_graphql_1.Ctx)()),
963
+ __param(1, (0, type_graphql_1.Arg)('worksheetId')),
964
+ __param(2, (0, type_graphql_1.Arg)('batchId')),
965
+ __param(3, (0, type_graphql_1.Arg)('productName')),
966
+ __param(4, (0, type_graphql_1.Arg)('productSku')),
967
+ __param(5, (0, type_graphql_1.Arg)('packingType')),
968
+ __param(6, (0, type_graphql_1.Arg)('packingSize')),
969
+ __param(7, (0, type_graphql_1.Arg)('uom')),
970
+ __param(8, (0, type_graphql_1.Arg)('pickingStrategy')),
971
+ __param(9, (0, type_graphql_1.Arg)('locationSortingRules', type => [shell_1.Sorting], { nullable: true })),
972
+ __param(10, (0, type_graphql_1.Arg)('bizplaceId', { nullable: true })),
973
+ __metadata("design:type", Function),
974
+ __metadata("design:paramtypes", [Object, String, String, String, String, String, Number, String, String, Array, String]),
975
+ __metadata("design:returntype", Promise)
976
+ ], InventoryQuery.prototype, "inventoriesByStrategy", null);
977
+ __decorate([
978
+ (0, type_graphql_1.Directive)('@transaction'),
979
+ (0, type_graphql_1.Query)(returns => Boolean),
980
+ __param(0, (0, type_graphql_1.Arg)('palletA')),
981
+ __param(1, (0, type_graphql_1.Arg)('palletB')),
982
+ __param(2, (0, type_graphql_1.Ctx)()),
983
+ __metadata("design:type", Function),
984
+ __metadata("design:paramtypes", [String, String, Object]),
985
+ __metadata("design:returntype", Promise)
986
+ ], InventoryQuery.prototype, "checkProductIdenticality", null);
987
+ __decorate([
988
+ (0, type_graphql_1.Query)(returns => Boolean),
989
+ __param(0, (0, type_graphql_1.Arg)('cartonA')),
990
+ __param(1, (0, type_graphql_1.Arg)('palletA')),
991
+ __param(2, (0, type_graphql_1.Arg)('cartonB')),
992
+ __param(3, (0, type_graphql_1.Ctx)()),
993
+ __metadata("design:type", Function),
994
+ __metadata("design:paramtypes", [String, String, String, Object]),
995
+ __metadata("design:returntype", Promise)
996
+ ], InventoryQuery.prototype, "checkCartonIdenticality", null);
997
+ __decorate([
998
+ (0, type_graphql_1.Query)(returns => Boolean),
999
+ __param(0, (0, type_graphql_1.Arg)('palletId')),
1000
+ __param(1, (0, type_graphql_1.Arg)('bizplaceName')),
1001
+ __param(2, (0, type_graphql_1.Ctx)()),
1002
+ __metadata("design:type", Function),
1003
+ __metadata("design:paramtypes", [String, String, Object]),
1004
+ __metadata("design:returntype", Promise)
1005
+ ], InventoryQuery.prototype, "checkInventoryOwner", null);
1006
+ __decorate([
1007
+ (0, type_graphql_1.Query)(returns => inventory_types_1.InventoryList),
1008
+ __param(0, (0, type_graphql_1.Ctx)()),
1009
+ __param(1, (0, type_graphql_1.Arg)('cartonId', { nullable: true })),
1010
+ __param(2, (0, type_graphql_1.Arg)('palletId', { nullable: true })),
1011
+ __param(3, (0, type_graphql_1.Arg)('bizplaceId')),
1012
+ __metadata("design:type", Function),
1013
+ __metadata("design:paramtypes", [Object, String, String, String]),
1014
+ __metadata("design:returntype", Promise)
1015
+ ], InventoryQuery.prototype, "checkInventoryLocation", null);
1016
+ __decorate([
1017
+ (0, type_graphql_1.Directive)('@privilege(category: "inventory", privilege: "query")'),
1018
+ (0, type_graphql_1.Query)(returns => inventory_types_1.InventoryBundleGroupDetail),
1019
+ __param(0, (0, type_graphql_1.Ctx)()),
1020
+ __param(1, (0, type_graphql_1.Arg)('filters', type => [shell_1.Filter], { nullable: true })),
1021
+ __param(2, (0, type_graphql_1.Arg)('pagination', type => shell_1.Pagination, { nullable: true })),
1022
+ __param(3, (0, type_graphql_1.Arg)('sortings', type => [shell_1.Sorting], { nullable: true })),
1023
+ __metadata("design:type", Function),
1024
+ __metadata("design:paramtypes", [Object, Array, typeof (_c = typeof shell_1.Pagination !== "undefined" && shell_1.Pagination) === "function" ? _c : Object, Array]),
1025
+ __metadata("design:returntype", Promise)
1026
+ ], InventoryQuery.prototype, "inventoriesByBundle", null);
1027
+ __decorate([
1028
+ (0, type_graphql_1.Query)(returns => inventory_types_1.InventoryList),
1029
+ __param(0, (0, type_graphql_1.Ctx)()),
1030
+ __param(1, (0, type_graphql_1.Arg)('filters', type => [shell_1.Filter], { nullable: true })),
1031
+ __param(2, (0, type_graphql_1.Arg)('pagination', type => shell_1.Pagination, { nullable: true })),
1032
+ __param(3, (0, type_graphql_1.Arg)('sortings', type => [shell_1.Sorting], { nullable: true })),
1033
+ __metadata("design:type", Function),
1034
+ __metadata("design:paramtypes", [Object, Array, typeof (_d = typeof shell_1.Pagination !== "undefined" && shell_1.Pagination) === "function" ? _d : Object, Array]),
1035
+ __metadata("design:returntype", Promise)
1036
+ ], InventoryQuery.prototype, "replenishmentInventories", null);
1037
+ __decorate([
1038
+ (0, type_graphql_1.Query)(returns => inventory_types_1.InventoryList),
1039
+ __param(0, (0, type_graphql_1.Ctx)()),
1040
+ __param(1, (0, type_graphql_1.Arg)('replenishmentId')),
1041
+ __param(2, (0, type_graphql_1.Arg)('inventoryId', () => [String])),
1042
+ __metadata("design:type", Function),
1043
+ __metadata("design:paramtypes", [Object, String, Array]),
1044
+ __metadata("design:returntype", Promise)
1045
+ ], InventoryQuery.prototype, "putawayReplenishmentInventories", null);
1046
+ __decorate([
1047
+ (0, type_graphql_1.FieldResolver)(type => shell_1.Domain),
1048
+ __param(0, (0, type_graphql_1.Root)()),
1049
+ __metadata("design:type", Function),
1050
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1051
+ __metadata("design:returntype", Promise)
1052
+ ], InventoryQuery.prototype, "domain", null);
1053
+ __decorate([
1054
+ (0, type_graphql_1.FieldResolver)(type => auth_base_1.User),
1055
+ __param(0, (0, type_graphql_1.Root)()),
1056
+ __metadata("design:type", Function),
1057
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1058
+ __metadata("design:returntype", Promise)
1059
+ ], InventoryQuery.prototype, "updater", null);
1060
+ __decorate([
1061
+ (0, type_graphql_1.FieldResolver)(type => auth_base_1.User),
1062
+ __param(0, (0, type_graphql_1.Root)()),
1063
+ __metadata("design:type", Function),
1064
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1065
+ __metadata("design:returntype", Promise)
1066
+ ], InventoryQuery.prototype, "creator", null);
1067
+ __decorate([
1068
+ (0, type_graphql_1.FieldResolver)(type => Number),
1069
+ __param(0, (0, type_graphql_1.Root)()),
1070
+ __metadata("design:type", Function),
1071
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1072
+ __metadata("design:returntype", Promise)
1073
+ ], InventoryQuery.prototype, "changeCount", null);
1074
+ __decorate([
1075
+ (0, type_graphql_1.FieldResolver)(type => String),
1076
+ __param(0, (0, type_graphql_1.Root)()),
1077
+ __metadata("design:type", Function),
1078
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1079
+ __metadata("design:returntype", Promise)
1080
+ ], InventoryQuery.prototype, "purchaseOrderNo", null);
1081
+ __decorate([
1082
+ (0, type_graphql_1.FieldResolver)(type => String),
1083
+ __param(0, (0, type_graphql_1.Root)()),
1084
+ __metadata("design:type", Function),
1085
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1086
+ __metadata("design:returntype", Promise)
1087
+ ], InventoryQuery.prototype, "orderProductRemark", null);
1088
+ __decorate([
1089
+ (0, type_graphql_1.FieldResolver)(type => String),
1090
+ __param(0, (0, type_graphql_1.Root)()),
1091
+ __metadata("design:type", Function),
1092
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1093
+ __metadata("design:returntype", Promise)
1094
+ ], InventoryQuery.prototype, "arrivalNoticeRefNo", null);
1095
+ __decorate([
1096
+ (0, type_graphql_1.FieldResolver)(type => String),
1097
+ __param(0, (0, type_graphql_1.Root)()),
1098
+ __metadata("design:type", Function),
1099
+ __metadata("design:paramtypes", [inventory_1.Inventory]),
1100
+ __metadata("design:returntype", Promise)
1101
+ ], InventoryQuery.prototype, "arrivalNoticeNo", null);
1102
+ InventoryQuery = __decorate([
1103
+ (0, type_graphql_1.Resolver)(inventory_1.Inventory)
1104
+ ], InventoryQuery);
1105
+ exports.InventoryQuery = InventoryQuery;
1106
+ async function inventoriesByStrategy({ worksheetId, batchId, bizplaceId, productName, productSku, packingType, packingSize, uom, pickingStrategy, locationSortingRules }, trxMgr) {
1107
+ const qb = await trxMgr.getRepository(inventory_1.Inventory).createQueryBuilder('INV');
1108
+ qb.innerJoinAndSelect('INV.product', 'PROD')
1109
+ .innerJoinAndSelect('INV.location', 'LOC')
1110
+ .innerJoin('warehouse_inventory_assignment_rankings', 'WIAR', '"WIAR"."location_type" = "LOC"."type"')
1111
+ .addSelect(subQuery => subQuery
1112
+ .select('COALESCE(SUM(release_qty), 0)', 'releaseQty')
1113
+ .from('order_inventories', 'OI')
1114
+ .where('"OI"."inventory_id" = "INV"."id"')
1115
+ .andWhere("\"OI\".\"status\" IN ('PENDING', 'PENDING_RECEIVE', 'PENDING_WORKSHEET', 'PENDING_SPLIT')")
1116
+ .andWhere('"OI"."ref_worksheet_id" <> :worksheetId', { worksheetId: worksheetId }))
1117
+ .addSelect(subQuery => subQuery
1118
+ .select('COALESCE(SUM(release_uom_value), 0)', 'releaseUomValue')
1119
+ .from('order_inventories', 'OI')
1120
+ .where('"OI"."inventory_id" = "INV"."id"')
1121
+ .andWhere("\"OI\".\"status\" IN ('PENDING', 'PENDING_RECEIVE', 'PENDING_WORKSHEET', 'PENDING_SPLIT')")
1122
+ .andWhere('"OI"."ref_worksheet_id" <> :worksheetId', { worksheetId: worksheetId }))
1123
+ .andWhere('"PROD"."name" = :productName')
1124
+ .andWhere('"PROD"."sku" = :productSku')
1125
+ .andWhere('"INV"."packing_type" = :packingType')
1126
+ .andWhere('"INV"."packing_size" = :packingSize')
1127
+ .andWhere('"INV"."uom" = :uom')
1128
+ .andWhere('"INV"."status" = :status', { status: 'STORED' })
1129
+ .andWhere('"LOC"."type" NOT IN (:...locationTypes)', {
1130
+ locationTypes: [constants_1.LOCATION_TYPE.QUARANTINE, constants_1.LOCATION_TYPE.RESERVE]
1131
+ })
1132
+ .andWhere('"INV"."obsolete" = false')
1133
+ .andWhere('case when "INV"."expiration_date" is not null and "PROD"."min_outbound_shelf_life" is not null then CURRENT_DATE < "INV"."expiration_date" - "PROD"."min_outbound_shelf_life" else true end')
1134
+ .setParameters({
1135
+ productName,
1136
+ productSku,
1137
+ packingType,
1138
+ packingSize,
1139
+ uom
1140
+ });
1141
+ if (batchId !== '') {
1142
+ qb.andWhere('"INV"."batch_id" = :batchId', { batchId });
1143
+ }
1144
+ if (bizplaceId) {
1145
+ qb.andWhere('"INV"."bizplace_id" = :bizplaceId', { bizplaceId: bizplaceId });
1146
+ }
1147
+ qb.addOrderBy('"WIAR"."rank"', 'ASC');
1148
+ switch (pickingStrategy.toUpperCase()) {
1149
+ case 'FIFO':
1150
+ qb.addOrderBy('"INV"."created_at"', 'ASC');
1151
+ if ((locationSortingRules === null || locationSortingRules === void 0 ? void 0 : locationSortingRules.length) > 0) {
1152
+ locationSortingRules.forEach((rule, idx) => {
1153
+ qb.addOrderBy(`LOC.${rule.name}`, rule.desc ? 'DESC' : 'ASC');
1154
+ });
1155
+ }
1156
+ break;
1157
+ case 'LIFO':
1158
+ qb.addOrderBy('"INV"."created_at"', 'DESC');
1159
+ if ((locationSortingRules === null || locationSortingRules === void 0 ? void 0 : locationSortingRules.length) > 0) {
1160
+ locationSortingRules.forEach((rule, idx) => {
1161
+ qb.addOrderBy(`LOC.${rule.name}`, rule.desc ? 'DESC' : 'ASC');
1162
+ });
1163
+ }
1164
+ break;
1165
+ case 'FEFO':
1166
+ qb.addOrderBy('"INV"."expiration_date"', 'ASC');
1167
+ qb.addOrderBy('"INV"."created_at"', 'ASC');
1168
+ if ((locationSortingRules === null || locationSortingRules === void 0 ? void 0 : locationSortingRules.length) > 0) {
1169
+ locationSortingRules.forEach((rule, idx) => {
1170
+ qb.addOrderBy(`LOC.${rule.name}`, rule.desc ? 'DESC' : 'ASC');
1171
+ });
1172
+ }
1173
+ break;
1174
+ case 'FMFO':
1175
+ qb.addOrderBy('"INV"."manufacture_date"', 'ASC');
1176
+ qb.addOrderBy('"INV"."created_at"', 'ASC');
1177
+ if ((locationSortingRules === null || locationSortingRules === void 0 ? void 0 : locationSortingRules.length) > 0) {
1178
+ locationSortingRules.forEach((rule, idx) => {
1179
+ qb.addOrderBy(`LOC.${rule.name}`, rule.desc ? 'DESC' : 'ASC');
1180
+ });
1181
+ }
1182
+ break;
1183
+ case 'LOCATION':
1184
+ if ((locationSortingRules === null || locationSortingRules === void 0 ? void 0 : locationSortingRules.length) > 0) {
1185
+ locationSortingRules.forEach((rule, idx) => {
1186
+ idx === 0
1187
+ ? qb.addOrderBy(`LOC.${rule.name}`, rule.desc ? 'DESC' : 'ASC')
1188
+ : qb.addOrderBy(`LOC.${rule.name}`, rule.desc ? 'DESC' : 'ASC');
1189
+ });
1190
+ }
1191
+ else
1192
+ qb.addOrderBy('"LOC"."name"', 'DESC');
1193
+ break;
1194
+ }
1195
+ const { entities, raw } = await qb.getRawAndEntities();
1196
+ const items = entities
1197
+ .map((inv, idx) => {
1198
+ const qty = (inv === null || inv === void 0 ? void 0 : inv.qty) > 0 ? inv.qty : 0;
1199
+ const uomValue = (inv === null || inv === void 0 ? void 0 : inv.uomValue) > 0 ? inv.uomValue : 0;
1200
+ const lockedQty = inv.lockedQty || 0;
1201
+ const lockedUomValue = inv.lockedUomValue || 0;
1202
+ const releaseQty = parseFloat(raw[idx].releaseQty) || 0;
1203
+ const releaseUomValue = parseFloat(raw[idx].releaseUomValue) || 0;
1204
+ return Object.assign(Object.assign({}, inv), { qty: qty - lockedQty - releaseQty, uomValue: uomValue - lockedUomValue - releaseUomValue });
1205
+ })
1206
+ .filter((inv) => inv.qty);
1207
+ const total = await qb.getCount();
1208
+ return { items, total };
1209
+ }
1210
+ exports.inventoriesByStrategy = inventoriesByStrategy;
1211
+ //# sourceMappingURL=inventory-query.js.map