@managesome/eposmatic-toolkit 0.4.89 → 0.4.92

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 (66) hide show
  1. package/esm/constants/ENUMS.js +1 -0
  2. package/esm/constants/enums/storage.js +23 -0
  3. package/esm/helpers/index.js +1 -0
  4. package/esm/helpers/order/generate-warehouse-internal-movement.js +3 -0
  5. package/esm/helpers/storage/index.js +1 -0
  6. package/esm/helpers/storage/upload-paths.js +384 -0
  7. package/esm/helpers/store/common-warehouse-internal-movement-actions.js +124 -4
  8. package/esm/helpers/utils/discount-amounts.js +64 -0
  9. package/esm/helpers/utils/index.js +2 -0
  10. package/esm/helpers/utils/internal-movement-items.js +30 -0
  11. package/esm/helpers/utils/tenant-purchase-order-engine.js +10 -18
  12. package/esm/helpers/utils/warehouse-purchase-order-engine.js +10 -18
  13. package/esm/schemas/models/index.js +1 -0
  14. package/esm/schemas/models/pending_uploads.js +102 -0
  15. package/esm/schemas/models/warehouse_internal_movements.js +54 -0
  16. package/esm/schemas/types/index.js +1 -0
  17. package/esm/schemas/types/pending_uploads.js +1 -0
  18. package/lib/constants/ENUMS.d.ts +1 -0
  19. package/lib/constants/ENUMS.js +1 -0
  20. package/lib/constants/enums/storage.d.ts +21 -0
  21. package/lib/constants/enums/storage.js +26 -0
  22. package/lib/helpers/index.d.ts +1 -0
  23. package/lib/helpers/index.js +1 -0
  24. package/lib/helpers/order/generate-warehouse-internal-movement.js +3 -0
  25. package/lib/helpers/storage/index.d.ts +1 -0
  26. package/lib/helpers/storage/index.js +17 -0
  27. package/lib/helpers/storage/upload-paths.d.ts +117 -0
  28. package/lib/helpers/storage/upload-paths.js +394 -0
  29. package/lib/helpers/store/common-warehouse-internal-movement-actions.d.ts +33 -1
  30. package/lib/helpers/store/common-warehouse-internal-movement-actions.js +126 -3
  31. package/lib/helpers/utils/discount-amounts.d.ts +50 -0
  32. package/lib/helpers/utils/discount-amounts.js +69 -0
  33. package/lib/helpers/utils/index.d.ts +2 -0
  34. package/lib/helpers/utils/index.js +2 -0
  35. package/lib/helpers/utils/internal-movement-items.d.ts +35 -0
  36. package/lib/helpers/utils/internal-movement-items.js +36 -0
  37. package/lib/helpers/utils/tenant-purchase-order-engine.js +9 -17
  38. package/lib/helpers/utils/warehouse-purchase-order-engine.js +9 -17
  39. package/lib/schemas/models/index.d.ts +1 -0
  40. package/lib/schemas/models/index.js +1 -0
  41. package/lib/schemas/models/inventories.d.ts +3 -3
  42. package/lib/schemas/models/inventory_transactions.d.ts +3 -3
  43. package/lib/schemas/models/item_transactions.d.ts +3 -3
  44. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +3 -3
  45. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +3 -3
  46. package/lib/schemas/models/orders.d.ts +120 -120
  47. package/lib/schemas/models/pending_uploads.d.ts +118 -0
  48. package/lib/schemas/models/pending_uploads.js +105 -0
  49. package/lib/schemas/models/tenant_hr_employees.d.ts +3 -3
  50. package/lib/schemas/models/tenant_inventory_department_transactions.d.ts +3 -3
  51. package/lib/schemas/models/tenant_inventory_department_utilities.d.ts +3 -3
  52. package/lib/schemas/models/warehouse_internal_movements.d.ts +570 -0
  53. package/lib/schemas/models/warehouse_internal_movements.js +54 -0
  54. package/lib/schemas/models/warehouse_inventory_transactions.d.ts +3 -3
  55. package/lib/schemas/models/warehouse_item_transactions.d.ts +3 -3
  56. package/lib/schemas/models/warehouse_items.d.ts +3 -3
  57. package/lib/schemas/types/index.d.ts +1 -0
  58. package/lib/schemas/types/index.js +1 -0
  59. package/lib/schemas/types/pending_uploads.d.ts +30 -0
  60. package/lib/schemas/types/pending_uploads.js +2 -0
  61. package/lib/schemas/types/warehouse_internal_movements.d.ts +17 -1
  62. package/lib/tests/pending-uploads-schema.test.d.ts +1 -0
  63. package/lib/tests/pending-uploads-schema.test.js +79 -0
  64. package/lib/tests/storage-upload-paths.test.d.ts +1 -0
  65. package/lib/tests/storage-upload-paths.test.js +198 -0
  66. package/package.json +1 -1
@@ -15,5 +15,6 @@ export * from './enums/order';
15
15
  export * from './enums/payments';
16
16
  export * from './enums/platform';
17
17
  export * from './enums/printing';
18
+ export * from './enums/storage';
18
19
  export * from './enums/users';
19
20
  export * from './enums/wallet';
@@ -0,0 +1,23 @@
1
+ export var PENDING_UPLOAD_REF_TYPE_ENUM;
2
+ (function (PENDING_UPLOAD_REF_TYPE_ENUM) {
3
+ PENDING_UPLOAD_REF_TYPE_ENUM["TENANT"] = "TENANT";
4
+ PENDING_UPLOAD_REF_TYPE_ENUM["BRAND"] = "BRAND";
5
+ PENDING_UPLOAD_REF_TYPE_ENUM["WAREHOUSE"] = "WAREHOUSE";
6
+ PENDING_UPLOAD_REF_TYPE_ENUM["EMPLOYEE"] = "EMPLOYEE";
7
+ PENDING_UPLOAD_REF_TYPE_ENUM["DELIVERY"] = "DELIVERY";
8
+ PENDING_UPLOAD_REF_TYPE_ENUM["RIDER"] = "RIDER";
9
+ PENDING_UPLOAD_REF_TYPE_ENUM["RESTAURANT"] = "RESTAURANT";
10
+ PENDING_UPLOAD_REF_TYPE_ENUM["EXPENSE"] = "EXPENSE";
11
+ })(PENDING_UPLOAD_REF_TYPE_ENUM || (PENDING_UPLOAD_REF_TYPE_ENUM = {}));
12
+ export const ALL_PENDING_UPLOAD_REF_TYPES = Object.values(PENDING_UPLOAD_REF_TYPE_ENUM);
13
+ /**
14
+ * Delivery proof stage. Enum values are upper-case by enum convention;
15
+ * the path builder lower-cases them into the storage leaf
16
+ * (`pickup_food_image_url.<ext>` / `dropoff_food_image_url.<ext>`).
17
+ */
18
+ export var PENDING_UPLOAD_STAGE_ENUM;
19
+ (function (PENDING_UPLOAD_STAGE_ENUM) {
20
+ PENDING_UPLOAD_STAGE_ENUM["PICKUP"] = "PICKUP";
21
+ PENDING_UPLOAD_STAGE_ENUM["DROPOFF"] = "DROPOFF";
22
+ })(PENDING_UPLOAD_STAGE_ENUM || (PENDING_UPLOAD_STAGE_ENUM = {}));
23
+ export const ALL_PENDING_UPLOAD_STAGES = Object.values(PENDING_UPLOAD_STAGE_ENUM);
@@ -8,6 +8,7 @@ export * from './rider-reports';
8
8
  export * from './order';
9
9
  export * from './pra';
10
10
  export * from './srb';
11
+ export * from './storage';
11
12
  export * from './store';
12
13
  export * from './types';
13
14
  export * from './utils';
@@ -17,6 +17,9 @@ export function generateWarehouseInternalMovementIteration(movement, partial = t
17
17
  is_gst_inclusive: movement.is_gst_inclusive,
18
18
  gst: movement.gst,
19
19
  gst_amount: movement.gst_amount,
20
+ order_discount_details: movement.order_discount_details,
21
+ total_discount_applied: movement.total_discount_applied,
22
+ exclude_discount_from_gst: movement.exclude_discount_from_gst,
20
23
  labor_charges: movement.labor_charges,
21
24
  labor_charges_amount: movement.labor_charges_amount,
22
25
  is_labor_charges_percentage: movement.is_labor_charges_percentage,
@@ -0,0 +1 @@
1
+ export * from './upload-paths';
@@ -0,0 +1,384 @@
1
+ /**
2
+ * Server-owned Cloud Storage upload path registry.
3
+ *
4
+ * The client sends a `kind` plus entity ids and file metadata. This module is
5
+ * the only place that turns those inputs into a bucket-relative object path.
6
+ * Nothing here performs I/O, so both backend services can import it and the
7
+ * toolkit build stays usable in browser contexts.
8
+ *
9
+ * Security invariants:
10
+ * - every kind is in a closed registry;
11
+ * - every client-supplied id is a single, validated path segment;
12
+ * - only `images/` and `documents/` roots are reachable;
13
+ * - the final path is re-validated after construction.
14
+ */
15
+ import { PENDING_UPLOAD_REF_TYPE_ENUM, PENDING_UPLOAD_STAGE_ENUM } from '../../constants/enums/storage';
16
+ export const IMAGE_MAX_BYTES = 5 * 1024 * 1024;
17
+ export const DOCUMENT_MAX_BYTES = 10 * 1024 * 1024;
18
+ export const IMAGE_MIME_EXTENSIONS = {
19
+ 'image/avif': 'avif',
20
+ 'image/gif': 'gif',
21
+ 'image/heic': 'heic',
22
+ 'image/heif': 'heif',
23
+ 'image/jpeg': 'jpeg',
24
+ 'image/jpg': 'jpeg',
25
+ 'image/png': 'png',
26
+ 'image/vnd.microsoft.icon': 'ico',
27
+ 'image/webp': 'webp',
28
+ 'image/x-icon': 'ico',
29
+ };
30
+ export const DOCUMENT_MIME_EXTENSIONS = {
31
+ 'application/msword': ['doc'],
32
+ 'application/pdf': ['pdf'],
33
+ 'application/vnd.ms-excel': ['xls'],
34
+ 'application/vnd.ms-powerpoint': ['ppt'],
35
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': ['pptx'],
36
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['xlsx'],
37
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['docx'],
38
+ 'image/heic': ['heic'],
39
+ 'image/jpeg': ['jpg', 'jpeg'],
40
+ 'image/png': ['png'],
41
+ 'image/webp': ['webp'],
42
+ 'text/csv': ['csv'],
43
+ 'text/plain': ['txt'],
44
+ };
45
+ export const STORAGE_UPLOAD_KIND = {
46
+ BRAND_CATEGORY_BANNER: 'brand.category_banner',
47
+ BRAND_CATEGORY_IMAGE: 'brand.category',
48
+ BRAND_HALF_HALF_IMAGE: 'brand.halfhalf',
49
+ BRAND_IMAGE: 'brand.image',
50
+ BRAND_ITEM_IMAGE: 'brand.item',
51
+ BRAND_OFFER_IMAGE: 'brand.offer',
52
+ BRAND_SPECIAL_IMAGE: 'brand.special',
53
+ BRAND_WAREHOUSE_CATEGORY_IMAGE: 'brand.warehouse.category',
54
+ BRAND_WAREHOUSE_ITEM_IMAGE: 'brand.warehouse.item',
55
+ DELIVERY_PROOF: 'delivery.proof',
56
+ DOCUMENT_HR: 'document.hr',
57
+ DOCUMENT_POLICY: 'document.policy',
58
+ INTERNAL_EXPENSE_IMAGE: 'internal.expense',
59
+ INTERNAL_RESTAURANT_IMAGE: 'internal.restaurant',
60
+ RIDER_IMAGE: 'rider.image',
61
+ TENANT_DEPARTMENT_IMAGE: 'tenant.department',
62
+ TENANT_DIGITAL_MENU: 'tenant.digital_menu',
63
+ TENANT_EXPENSE_IMAGE: 'tenant.expense',
64
+ TENANT_IMAGE: 'tenant.image',
65
+ TENANT_INVENTORY_IMAGE: 'tenant.inventory',
66
+ TENANT_MARKETING_IMAGE: 'tenant.marketing',
67
+ TENANT_SLIDER: 'tenant.slider',
68
+ TENANT_STAFF_IMAGE: 'tenant.staff',
69
+ TENANT_WEB_COVER: 'tenant.web_cover',
70
+ TENANT_WEB_FAVICON: 'tenant.web_favicon',
71
+ WAREHOUSE_EXPENSE_IMAGE: 'warehouse.expense',
72
+ WAREHOUSE_IMAGE: 'warehouse.image',
73
+ WAREHOUSE_INVENTORY_IMAGE: 'warehouse.inventory',
74
+ WAREHOUSE_STAFF_IMAGE: 'warehouse.staff',
75
+ };
76
+ export class StorageUploadValidationError extends Error {
77
+ constructor(code, message) {
78
+ super(message);
79
+ this.name = 'StorageUploadValidationError';
80
+ this.code = code;
81
+ }
82
+ }
83
+ const ID_FIELDS = [
84
+ 'brand_id',
85
+ 'tenant_id',
86
+ 'warehouse_id',
87
+ 'employee_id',
88
+ 'delivery_id',
89
+ 'record_id',
90
+ 'resource_id',
91
+ ];
92
+ const SEGMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
93
+ const FINAL_PATH_PATTERN = /^[A-Za-z0-9._/-]+$/;
94
+ const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
95
+ function fail(code, message) {
96
+ throw new StorageUploadValidationError(code, message);
97
+ }
98
+ function requireId(ids, field) {
99
+ const value = ids[field];
100
+ if (typeof value !== 'string' || value.length === 0) {
101
+ fail('MISSING_FIELD', `Missing required storage id: ${field}`);
102
+ }
103
+ return value;
104
+ }
105
+ function assertSegment(value, field) {
106
+ if (typeof value !== 'string' || !SEGMENT_PATTERN.test(value) || value.includes('..')) {
107
+ fail('INVALID_ID', `Invalid storage path segment for ${field}`);
108
+ }
109
+ }
110
+ function assertFinalPath(path) {
111
+ if (!path.startsWith('images/') && !path.startsWith('documents/')) {
112
+ fail('INVALID_PATH', 'Storage path must start with images/ or documents/');
113
+ }
114
+ if (path.length === 0 || path.length > 1024) {
115
+ fail('INVALID_PATH', 'Storage path length is out of bounds');
116
+ }
117
+ if (path.includes('//') || path.includes('..') || path.includes('?') || path.includes('#')) {
118
+ fail('INVALID_PATH', 'Storage path contains a forbidden sequence');
119
+ }
120
+ if (!FINAL_PATH_PATTERN.test(path)) {
121
+ fail('INVALID_PATH', 'Storage path contains forbidden characters');
122
+ }
123
+ }
124
+ function assertStage(stage) {
125
+ if (stage === PENDING_UPLOAD_STAGE_ENUM.PICKUP || stage === PENDING_UPLOAD_STAGE_ENUM.DROPOFF) {
126
+ return stage;
127
+ }
128
+ return fail('INVALID_STAGE', 'stage must be PICKUP or DROPOFF');
129
+ }
130
+ function assertUuid(uuid) {
131
+ if (typeof uuid !== 'string' || !UUID_V4_PATTERN.test(uuid)) {
132
+ fail('INVALID_UUID', 'A valid server-generated UUID is required for this kind');
133
+ }
134
+ }
135
+ export function normalizeStorageMime(mime) {
136
+ if (typeof mime !== 'string') {
137
+ fail('INVALID_MIME', 'mime must be a string');
138
+ }
139
+ return mime.split(';')[0].trim().toLowerCase();
140
+ }
141
+ function imageExtension(mime) {
142
+ const extension = IMAGE_MIME_EXTENSIONS[mime];
143
+ if (!extension) {
144
+ fail('INVALID_MIME', `Unsupported image mime type: ${mime}`);
145
+ }
146
+ return extension;
147
+ }
148
+ function filenameExtension(filename, mime) {
149
+ const allowed = DOCUMENT_MIME_EXTENSIONS[mime];
150
+ if (!allowed) {
151
+ fail('INVALID_MIME', `Unsupported document mime type: ${mime}`);
152
+ }
153
+ const cleaned = filename.split('?')[0].split('#')[0].replace(/\\/g, '/');
154
+ const base = cleaned.slice(cleaned.lastIndexOf('/') + 1);
155
+ if (!base || base.startsWith('.') || base.includes('..')) {
156
+ fail('INVALID_FILENAME', 'Invalid document filename');
157
+ }
158
+ const match = /\.([A-Za-z0-9]{1,8})$/.exec(base);
159
+ if (!match) {
160
+ fail('INVALID_FILENAME', 'Document filename has no usable extension');
161
+ }
162
+ const extension = match[1].toLowerCase();
163
+ if (!allowed.includes(extension)) {
164
+ fail('INVALID_FILENAME', `Filename extension .${extension} does not match ${mime}`);
165
+ }
166
+ return extension;
167
+ }
168
+ function resolveExtension(definition, mime, filename) {
169
+ if (definition.extension === 'mime') {
170
+ if (definition.media !== 'image') {
171
+ fail('INVALID_MIME', 'Mime-derived extensions are only allowed for images');
172
+ }
173
+ return `.${imageExtension(mime)}`;
174
+ }
175
+ if (typeof filename !== 'string' || filename.length === 0) {
176
+ fail('MISSING_FIELD', 'filename is required for this kind');
177
+ }
178
+ return `.${filenameExtension(filename, mime)}`;
179
+ }
180
+ function imageDefinition(kind, owner, identities, routes, requiredIds, build, options) {
181
+ return {
182
+ kind,
183
+ routes,
184
+ owner,
185
+ identities,
186
+ media: 'image',
187
+ maxBytes: IMAGE_MAX_BYTES,
188
+ extension: 'mime',
189
+ ...options,
190
+ requiredIds,
191
+ build,
192
+ };
193
+ }
194
+ function documentDefinition(kind, requiredIds, build) {
195
+ return {
196
+ kind,
197
+ routes: ['items'],
198
+ owner: 'document',
199
+ identities: ['tenant_staff_hr'],
200
+ media: 'document',
201
+ maxBytes: DOCUMENT_MAX_BYTES,
202
+ extension: 'filename',
203
+ leaf: 'uuid',
204
+ requiredIds,
205
+ build,
206
+ };
207
+ }
208
+ const FIXED_IMAGE_NAME = 'image_url';
209
+ const recordBaseName = (ids) => requireId(ids, 'record_id');
210
+ const STORAGE_UPLOAD_DEFINITIONS = {
211
+ [STORAGE_UPLOAD_KIND.BRAND_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_IMAGE, 'brand', ['tenant_staff', 'internal'], ['items'], ['brand_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), fileName].join('/'), { baseName: () => FIXED_IMAGE_NAME, leaf: 'fixed' }),
212
+ [STORAGE_UPLOAD_KIND.BRAND_CATEGORY_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_CATEGORY_IMAGE, 'brand', ['tenant_staff', 'internal'], ['items'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'categories', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
213
+ [STORAGE_UPLOAD_KIND.BRAND_CATEGORY_BANNER]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_CATEGORY_BANNER, 'brand', ['tenant_staff', 'internal'], ['items'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'categories-banner', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
214
+ [STORAGE_UPLOAD_KIND.BRAND_ITEM_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_ITEM_IMAGE, 'brand', ['tenant_staff', 'internal'], ['items'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'items', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
215
+ [STORAGE_UPLOAD_KIND.BRAND_OFFER_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_OFFER_IMAGE, 'brand', ['tenant_staff', 'internal'], ['items'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'offers', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
216
+ [STORAGE_UPLOAD_KIND.BRAND_SPECIAL_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_SPECIAL_IMAGE, 'brand', ['tenant_staff', 'internal'], ['items'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'specials', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
217
+ [STORAGE_UPLOAD_KIND.BRAND_HALF_HALF_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_HALF_HALF_IMAGE, 'brand', ['tenant_staff', 'internal'], ['items'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'halfhalf', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
218
+ [STORAGE_UPLOAD_KIND.BRAND_WAREHOUSE_CATEGORY_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_WAREHOUSE_CATEGORY_IMAGE, 'brand', ['warehouse_staff', 'internal'], ['items', 'operations'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'warehouse-categories', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
219
+ [STORAGE_UPLOAD_KIND.BRAND_WAREHOUSE_ITEM_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.BRAND_WAREHOUSE_ITEM_IMAGE, 'brand', ['warehouse_staff', 'internal'], ['items', 'operations'], ['brand_id', 'record_id'], (ids, fileName) => ['images', 'brands', requireId(ids, 'brand_id'), 'warehouse-items', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
220
+ [STORAGE_UPLOAD_KIND.TENANT_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_IMAGE, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), fileName].join('/'), { baseName: () => FIXED_IMAGE_NAME, leaf: 'fixed' }),
221
+ [STORAGE_UPLOAD_KIND.TENANT_WEB_COVER]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_WEB_COVER, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), fileName].join('/'), { baseName: () => 'web_cover', leaf: 'fixed' }),
222
+ [STORAGE_UPLOAD_KIND.TENANT_WEB_FAVICON]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_WEB_FAVICON, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), fileName].join('/'), { baseName: () => 'web_favicon', leaf: 'fixed' }),
223
+ [STORAGE_UPLOAD_KIND.TENANT_DIGITAL_MENU]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_DIGITAL_MENU, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), 'digital-menu', fileName].join('/'), { leaf: 'uuid' }),
224
+ [STORAGE_UPLOAD_KIND.TENANT_SLIDER]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_SLIDER, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), 'sliders', fileName].join('/'), { leaf: 'uuid' }),
225
+ [STORAGE_UPLOAD_KIND.TENANT_STAFF_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_STAFF_IMAGE, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id', 'record_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), 'staff', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
226
+ [STORAGE_UPLOAD_KIND.TENANT_MARKETING_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_MARKETING_IMAGE, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id', 'record_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), 'marketing', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
227
+ [STORAGE_UPLOAD_KIND.TENANT_EXPENSE_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_EXPENSE_IMAGE, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id', 'record_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), 'expense-details', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
228
+ [STORAGE_UPLOAD_KIND.TENANT_INVENTORY_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_INVENTORY_IMAGE, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id', 'record_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), 'inventory', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
229
+ [STORAGE_UPLOAD_KIND.TENANT_DEPARTMENT_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.TENANT_DEPARTMENT_IMAGE, 'tenant', ['tenant_staff', 'internal'], ['items'], ['tenant_id', 'record_id'], (ids, fileName) => ['images', 'tenants', requireId(ids, 'tenant_id'), 'departments', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
230
+ [STORAGE_UPLOAD_KIND.WAREHOUSE_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.WAREHOUSE_IMAGE, 'warehouse', ['warehouse_staff', 'internal'], ['items', 'operations'], ['warehouse_id'], (ids, fileName) => ['images', 'warehouses', requireId(ids, 'warehouse_id'), fileName].join('/'), { baseName: () => FIXED_IMAGE_NAME, leaf: 'fixed' }),
231
+ [STORAGE_UPLOAD_KIND.WAREHOUSE_STAFF_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.WAREHOUSE_STAFF_IMAGE, 'warehouse', ['warehouse_staff', 'internal'], ['items', 'operations'], ['warehouse_id', 'record_id'], (ids, fileName) => ['images', 'warehouses', requireId(ids, 'warehouse_id'), 'staff', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
232
+ [STORAGE_UPLOAD_KIND.WAREHOUSE_INVENTORY_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.WAREHOUSE_INVENTORY_IMAGE, 'warehouse', ['warehouse_staff', 'internal'], ['items', 'operations'], ['warehouse_id', 'record_id'], (ids, fileName) => ['images', 'warehouses', requireId(ids, 'warehouse_id'), 'inventory', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
233
+ [STORAGE_UPLOAD_KIND.WAREHOUSE_EXPENSE_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.WAREHOUSE_EXPENSE_IMAGE, 'warehouse', ['warehouse_staff', 'internal'], ['items', 'operations'], ['warehouse_id', 'record_id'], (ids, fileName) => ['images', 'warehouses', requireId(ids, 'warehouse_id'), 'warehouse-expense-details', fileName].join('/'), { baseName: recordBaseName, leaf: 'record' }),
234
+ [STORAGE_UPLOAD_KIND.DOCUMENT_HR]: documentDefinition(STORAGE_UPLOAD_KIND.DOCUMENT_HR, ['tenant_id', 'employee_id'], (ids, fileName) => [
235
+ 'documents',
236
+ 'tenants',
237
+ requireId(ids, 'tenant_id'),
238
+ 'hr-documents',
239
+ requireId(ids, 'employee_id'),
240
+ fileName,
241
+ ].join('/')),
242
+ [STORAGE_UPLOAD_KIND.DOCUMENT_POLICY]: documentDefinition(STORAGE_UPLOAD_KIND.DOCUMENT_POLICY, ['tenant_id'], (ids, fileName) => ['documents', 'tenants', requireId(ids, 'tenant_id'), 'hr-policies', fileName].join('/')),
243
+ [STORAGE_UPLOAD_KIND.INTERNAL_RESTAURANT_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.INTERNAL_RESTAURANT_IMAGE, 'internal', ['internal'], ['items'], ['resource_id'], (ids, fileName) => ['images', 'restaurants', requireId(ids, 'resource_id'), fileName].join('/'), { baseName: () => FIXED_IMAGE_NAME, leaf: 'fixed' }),
244
+ [STORAGE_UPLOAD_KIND.INTERNAL_EXPENSE_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.INTERNAL_EXPENSE_IMAGE, 'internal', ['internal'], ['items'], ['resource_id'], (ids, fileName) => ['images', 'expenses', requireId(ids, 'resource_id'), fileName].join('/'), { baseName: () => FIXED_IMAGE_NAME, leaf: 'fixed' }),
245
+ [STORAGE_UPLOAD_KIND.RIDER_IMAGE]: imageDefinition(STORAGE_UPLOAD_KIND.RIDER_IMAGE, 'rider', ['rider'], ['riders'], [], (_ids, fileName, uid) => ['images', 'riders', uid, fileName].join('/'), { baseName: () => FIXED_IMAGE_NAME, leaf: 'fixed', requiresUid: true }),
246
+ [STORAGE_UPLOAD_KIND.DELIVERY_PROOF]: imageDefinition(STORAGE_UPLOAD_KIND.DELIVERY_PROOF, 'delivery', ['delivery_rider'], ['riders'], ['delivery_id'], (ids, fileName) => ['images', 'deliveries', requireId(ids, 'delivery_id'), fileName].join('/'), {
247
+ baseName: (ids) => `${assertStage(ids.stage).toLowerCase()}_food_image_url`,
248
+ leaf: 'fixed',
249
+ requiredStage: true,
250
+ }),
251
+ };
252
+ function resolveStorageUploadRef(definition, ids, uid) {
253
+ switch (definition.owner) {
254
+ case 'brand':
255
+ return {
256
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.BRAND,
257
+ refId: requireId(ids, 'brand_id'),
258
+ };
259
+ case 'tenant':
260
+ return {
261
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.TENANT,
262
+ refId: requireId(ids, 'tenant_id'),
263
+ };
264
+ case 'warehouse':
265
+ return {
266
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.WAREHOUSE,
267
+ refId: requireId(ids, 'warehouse_id'),
268
+ };
269
+ case 'document':
270
+ return definition.kind === STORAGE_UPLOAD_KIND.DOCUMENT_HR
271
+ ? {
272
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.EMPLOYEE,
273
+ refId: requireId(ids, 'employee_id'),
274
+ }
275
+ : {
276
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.TENANT,
277
+ refId: requireId(ids, 'tenant_id'),
278
+ };
279
+ case 'internal':
280
+ return definition.kind === STORAGE_UPLOAD_KIND.INTERNAL_RESTAURANT_IMAGE
281
+ ? {
282
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.RESTAURANT,
283
+ refId: requireId(ids, 'resource_id'),
284
+ }
285
+ : {
286
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.EXPENSE,
287
+ refId: requireId(ids, 'resource_id'),
288
+ };
289
+ case 'rider':
290
+ return {
291
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.RIDER,
292
+ refId: uid,
293
+ };
294
+ case 'delivery':
295
+ return {
296
+ refType: PENDING_UPLOAD_REF_TYPE_ENUM.DELIVERY,
297
+ refId: requireId(ids, 'delivery_id'),
298
+ };
299
+ default:
300
+ return fail('INVALID_KIND', `Kind ${definition.kind} has no storage reference`);
301
+ }
302
+ }
303
+ export function isStorageUploadKind(value) {
304
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(STORAGE_UPLOAD_DEFINITIONS, value);
305
+ }
306
+ export function getStorageUploadDefinition(kind) {
307
+ if (!isStorageUploadKind(kind)) {
308
+ fail('INVALID_KIND', `Unknown storage upload kind: ${String(kind)}`);
309
+ }
310
+ return STORAGE_UPLOAD_DEFINITIONS[kind];
311
+ }
312
+ export function getStorageUploadKinds() {
313
+ return Object.values(STORAGE_UPLOAD_KIND);
314
+ }
315
+ export function getStorageUploadKindsForRoute(route) {
316
+ return getStorageUploadKinds().filter((kind) => STORAGE_UPLOAD_DEFINITIONS[kind].routes.includes(route));
317
+ }
318
+ /**
319
+ * Builds the bucket-relative object path for a validated upload request.
320
+ *
321
+ * Throws `StorageUploadValidationError` for every caller error. The route
322
+ * should map that error to HTTP 400 (or 415 for an unsupported MIME).
323
+ */
324
+ export function buildStorageUploadPath(input) {
325
+ const definition = getStorageUploadDefinition(input.kind);
326
+ const ids = input.ids ?? {};
327
+ const mime = normalizeStorageMime(input.mime);
328
+ if (!mime) {
329
+ fail('INVALID_MIME', 'mime is required');
330
+ }
331
+ for (const field of ID_FIELDS) {
332
+ const value = ids[field];
333
+ if (value !== undefined) {
334
+ if (typeof value !== 'string') {
335
+ fail('INVALID_ID', `Invalid storage path segment for ${field}`);
336
+ }
337
+ assertSegment(value, field);
338
+ }
339
+ }
340
+ if (ids.stage !== undefined) {
341
+ assertStage(ids.stage);
342
+ }
343
+ for (const field of definition.requiredIds) {
344
+ requireId(ids, field);
345
+ }
346
+ if (definition.requiredStage && ids.stage === undefined) {
347
+ fail('MISSING_FIELD', 'stage is required for this kind');
348
+ }
349
+ if (definition.requiresUid) {
350
+ if (!input.uid) {
351
+ fail('MISSING_FIELD', 'uid is required for this kind');
352
+ }
353
+ assertSegment(input.uid, 'uid');
354
+ }
355
+ const extension = resolveExtension(definition, mime, input.filename);
356
+ let base;
357
+ if (definition.leaf === 'uuid') {
358
+ if (!input.uuid) {
359
+ fail('MISSING_FIELD', 'uuid is required for this kind');
360
+ }
361
+ assertUuid(input.uuid);
362
+ base = input.uuid;
363
+ }
364
+ else {
365
+ if (!definition.baseName) {
366
+ fail('INVALID_KIND', `Kind ${definition.kind} has no base name`);
367
+ }
368
+ base = definition.baseName(ids);
369
+ }
370
+ assertSegment(base, 'file name');
371
+ const fileName = `${base}${extension}`;
372
+ const ref = resolveStorageUploadRef(definition, ids, input.uid ?? '');
373
+ assertSegment(ref.refId, 'ref_id');
374
+ const path = definition.build(ids, fileName, input.uid ?? '');
375
+ assertFinalPath(path);
376
+ return {
377
+ path,
378
+ extension,
379
+ maxBytes: definition.maxBytes,
380
+ contentType: mime,
381
+ refType: ref.refType,
382
+ refId: ref.refId,
383
+ };
384
+ }
@@ -1,5 +1,31 @@
1
- import { convertDecimalToInt, convertIntToDecimal, getCardChargesAndAmountCollected, getPercentageAmount, parseFloatCeil, parseNum, } from '../utils';
1
+ import { convertDecimalToInt, convertIntToDecimal, getCardChargesAndAmountCollected, getPercentageAmount, parseFloatCeil, parseNum, getItemDiscountAmount, getOrderDiscountAmount, withDiscountTotal, } from '../utils';
2
2
  import { getOrderPaymentsCardDetailsWithPrice } from './common-order-actions';
3
+ /**
4
+ * Resolved money value of one movement line's discount.
5
+ *
6
+ * Mirrors `getWarehousePurchaseOrderItemDiscountAmount`: a flat
7
+ * `special_discount` is PER UNIT (so it scales with quantity) and a percentage
8
+ * applies to the line's gross value. The result is clamped to the line total.
9
+ */
10
+ export function getWarehouseInternalMovementItemDiscountAmount(item) {
11
+ // Shared rule with warehouse/tenant POs; this wrapper keeps the movement
12
+ // cart's currency-decimal rounding.
13
+ return parseNum(getItemDiscountAmount({
14
+ grossAmount: parseNum((item.unit_price ?? 0) * (item.quantity ?? 0)),
15
+ quantity: item.quantity,
16
+ details: item.item_discount_details,
17
+ }));
18
+ }
19
+ /**
20
+ * Refreshes `total_discount` on a line's discount record so it matches the
21
+ * line's current price/quantity, preserving every other field.
22
+ */
23
+ export function withResolvedWarehouseInternalMovementItemDiscountTotal(item) {
24
+ const details = item.item_discount_details;
25
+ if (!details)
26
+ return null;
27
+ return withDiscountTotal(details, getWarehouseInternalMovementItemDiscountAmount(item));
28
+ }
3
29
  /**
4
30
  * Convert unit_price on every internal movement item.
5
31
  */
@@ -9,8 +35,27 @@ export function getWarehouseInternalMovementItemsWithPrice(items, convertToPrice
9
35
  return items.map((item) => ({
10
36
  ...item,
11
37
  unit_price: item.unit_price != null ? convertToPrice(item.unit_price) : undefined,
38
+ ...(item.item_discount_details != null
39
+ ? {
40
+ item_discount_details: getWarehouseInternalMovementItemDiscountDetailsWithPrice(item.item_discount_details, convertToPrice),
41
+ }
42
+ : {}),
12
43
  }));
13
44
  }
45
+ /**
46
+ * Scale a line discount record. A percentage is not a price, so only the fixed
47
+ * per-unit amount and the resolved total are converted.
48
+ */
49
+ function getWarehouseInternalMovementItemDiscountDetailsWithPrice(discount, convertToPrice) {
50
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
51
+ return {
52
+ ...discount,
53
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
54
+ ? { special_discount: convertToPrice(special_discount) }
55
+ : {}),
56
+ total_discount: convertToPrice(total_discount ?? 0),
57
+ };
58
+ }
14
59
  /**
15
60
  * Convert monetary fields on payments array.
16
61
  */
@@ -33,6 +78,22 @@ export function getWarehouseInternalMovementIterationsWithPrice(iterations, writ
33
78
  return [];
34
79
  return iterations.map((iteration) => getWarehouseInternalMovementWithPrice(iteration, writeable));
35
80
  }
81
+ /**
82
+ * Convert the order-level discount record. A percentage is not a price, so only
83
+ * the resolved money value (and a fixed `special_discount`) are scaled.
84
+ */
85
+ function getWarehouseInternalMovementDiscountDetailsWithPrice(discount, convertToPrice) {
86
+ if (!discount)
87
+ return null;
88
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
89
+ return {
90
+ ...discount,
91
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
92
+ ? { special_discount: convertToPrice(special_discount) }
93
+ : {}),
94
+ total_discount: convertToPrice(total_discount ?? 0),
95
+ };
96
+ }
36
97
  /**
37
98
  * Convert all monetary fields on an internal movement.
38
99
  *
@@ -53,6 +114,14 @@ export function getWarehouseInternalMovementWithPrice(order, writeable) {
53
114
  ...(order.amount_collected != null ? { amount_collected: convertToPrice(order.amount_collected) } : {}),
54
115
  ...(order.amount_earned != null ? { amount_earned: convertToPrice(order.amount_earned) } : {}),
55
116
  ...(order.gst != null ? { gst: convertToPrice(order.gst) } : {}),
117
+ ...(order.order_discount_details != null
118
+ ? {
119
+ order_discount_details: getWarehouseInternalMovementDiscountDetailsWithPrice(order.order_discount_details, convertToPrice),
120
+ }
121
+ : {}),
122
+ ...(order.total_discount_applied != null
123
+ ? { total_discount_applied: convertToPrice(order.total_discount_applied) }
124
+ : {}),
56
125
  ...(order.labor_charges != null && order.is_labor_charges_percentage !== true
57
126
  ? { labor_charges: convertToPrice(order.labor_charges) }
58
127
  : {}),
@@ -75,25 +144,70 @@ export function getWarehouseInternalMovementWithPrice(order, writeable) {
75
144
  : {}),
76
145
  };
77
146
  }
147
+ /**
148
+ * Resolve the order-level discount of an internal movement against its items
149
+ * subtotal. Mirrors `getWarehousePurchaseOrderOrderDiscountDetails`.
150
+ *
151
+ * `special_discount` is a percentage when `is_special_discount_percentage` is
152
+ * true and a flat money amount otherwise. The resolved value is clamped to the
153
+ * subtotal, so a movement can never go negative.
154
+ */
155
+ export function getWarehouseInternalMovementOrderDiscountDetails(discountDetails, baseAmount) {
156
+ if (!discountDetails) {
157
+ return { order_discount_details: null, total_discount_applied: 0 };
158
+ }
159
+ const totalDiscount = parseNum(getOrderDiscountAmount({
160
+ baseAmount,
161
+ details: discountDetails,
162
+ }));
163
+ if (totalDiscount <= 0) {
164
+ return { order_discount_details: null, total_discount_applied: 0 };
165
+ }
166
+ return {
167
+ order_discount_details: withDiscountTotal(discountDetails, totalDiscount),
168
+ total_discount_applied: totalDiscount,
169
+ };
170
+ }
78
171
  /**
79
172
  * Recalculate financial totals for an internal movement — mirrors
80
173
  * `calculateCartWarehousePurchaseOrderInfoAndSyncData` but for the flat
81
174
  * `items` array instead of nested `categories`.
175
+ *
176
+ * Each line's item discount is taken off first, then the order-level discount
177
+ * is applied to the resulting subtotal. GST and percentage charges are
178
+ * calculated on the discounted value. When `exclude_discount_from_gst` is true
179
+ * the order discount is taken off after GST instead.
82
180
  */
83
181
  export function calculateCartInternalMovementInfoAndSyncData(data) {
84
- const subtotal = (data.items ?? []).reduce((sum, item) => sum + parseNum((item.unit_price ?? 0) * (item.quantity ?? 0)), 0);
182
+ let subtotal = 0;
183
+ const items = (data.items ?? []).map((item) => {
184
+ const grossAmount = parseNum((item.unit_price ?? 0) * (item.quantity ?? 0));
185
+ const itemDiscountAmount = getWarehouseInternalMovementItemDiscountAmount(item);
186
+ subtotal += parseNum(Math.max(0, grossAmount - itemDiscountAmount));
187
+ return {
188
+ ...item,
189
+ item_discount_details: withResolvedWarehouseInternalMovementItemDiscountTotal(item),
190
+ };
191
+ });
192
+ subtotal = parseNum(subtotal);
193
+ const { order_discount_details, total_discount_applied } = getWarehouseInternalMovementOrderDiscountDetails(data.order_discount_details, subtotal);
194
+ const applyGSTOnOriginalPrice = data.exclude_discount_from_gst === true;
85
195
  let grand_total = subtotal;
196
+ if (!applyGSTOnOriginalPrice) {
197
+ grand_total -= total_discount_applied;
198
+ }
199
+ const postDiscountSubtotal = parseNum(Math.max(0, subtotal - total_discount_applied));
86
200
  let gst_amount = 0;
87
201
  const gst = data.gst ?? 0;
88
202
  // Order-level charges (labor, freight): entered per movement, either a fixed
89
- // amount or a percentage of the items subtotal. `is_*_charges_taxable`
203
+ // amount or a percentage of the post-discount items subtotal. `is_*_charges_taxable`
90
204
  // (snapshot of the warehouse setting) decides the placement: taxable => added
91
205
  // BEFORE GST, untaxed => added after it.
92
206
  const getOrderCharge = (value, isPercentage) => {
93
207
  const entered = parseNum(Math.max(0, value ?? 0));
94
208
  return {
95
209
  entered,
96
- amount: isPercentage ? parseNum(getPercentageAmount(subtotal, entered)) : entered,
210
+ amount: isPercentage ? parseNum(getPercentageAmount(postDiscountSubtotal, entered)) : entered,
97
211
  };
98
212
  };
99
213
  const labor = getOrderCharge(data.labor_charges, data.is_labor_charges_percentage);
@@ -115,6 +229,9 @@ export function calculateCartInternalMovementInfoAndSyncData(data) {
115
229
  gst_amount = getPercentageAmount(grand_total, gst);
116
230
  grand_total += gst_amount;
117
231
  }
232
+ if (applyGSTOnOriginalPrice) {
233
+ grand_total -= total_discount_applied;
234
+ }
118
235
  const untaxedCharges = (isLaborTaxable ? 0 : labor_charges_amount) + (isFreightTaxable ? 0 : freight_charges_amount);
119
236
  if (untaxedCharges > 0) {
120
237
  grand_total += untaxedCharges;
@@ -124,8 +241,11 @@ export function calculateCartInternalMovementInfoAndSyncData(data) {
124
241
  grand_total = parseNum(grand_total);
125
242
  return {
126
243
  ...data,
244
+ items,
127
245
  grand_total,
128
246
  gst_amount,
247
+ order_discount_details,
248
+ total_discount_applied,
129
249
  labor_charges,
130
250
  labor_charges_amount,
131
251
  freight_charges,