-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_retail_replenishment_items.ts
431 lines (394 loc) · 10.8 KB
/
get_retail_replenishment_items.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
* @NModuleScope SameAccount
*/
import { EntryPoints } from 'N/types';
import * as runtime from 'N/runtime';
import * as serverWidget from 'N/ui/serverWidget';
import * as search from 'N/search';
import * as file from 'N/file';
import * as log from 'N/log';
import * as message from 'N/ui/message';
import * as spTransferOrder from './createTransferOrder';
import { ServerResponse } from 'N/https';
/**
* A Suitelet to get retail replenishment items and create a transfer order.
*/
interface Item {
id: string;
sku: string;
name: string;
storeQuantityAvailable: string;
storeQuantityMin: string;
storeQuantityMax: string;
warehouseItemID: string;
warehouseQuantityAvailable: string;
quantityNeeded: string;
}
export const onRequest: EntryPoints.Suitelet.onRequest = (
context: EntryPoints.Suitelet.onRequestContext
) => {
const request = context.request;
const response = context.response;
if (request.method == 'GET') {
onGet(response);
} else {
onPost(response);
}
};
/**
* Handles the Get Request
*/
const onGet = (response: ServerResponse) => {
const items = getReplenishment();
const page = createPage(items);
response.writePage(page);
};
/**
* Handles the Post Request
*/
const onPost = (response: ServerResponse) => {
const items = getReplenishment();
// create CSV and save to file cabinet
const csvFileId = createCSV(items);
// create transfer order
const memo = 'Retail Store - ' + todaysDate();
const transferOrderId = spTransferOrder.create(3, 1, items, memo);
// create form
const form = serverWidget.createForm({
title:
'Retail Replenishment - ' + todaysDate() + ' | Total: ' + items.length,
});
form.addPageInitMessage({
type: message.Type.CONFIRMATION,
title: 'SUCCESS!',
message: 'Transfer Order Created!',
});
form.addField({
id: 'custpage_message',
type: serverWidget.FieldType.INLINEHTML,
label: ' ',
}).defaultValue =
'Transfer Order created: <a href="https://system.netsuite.com/app/accounting/transactions/trnfrord.nl?id=' +
transferOrderId +
'&whence=" target="_blank">' +
transferOrderId +
'</a>.';
response.writePage(form);
};
/**
* Creates the retail replenishment results list.
*/
const getReplenishment = () => {
// Load saved search
const retailReplenishmentSavedSearch = runtime
.getCurrentScript()
.getParameter({ name: 'custscript_retail_replenishment_search' });
const retailStoreSearch = search.load({
id: String(retailReplenishmentSavedSearch),
});
const pagedData = retailStoreSearch.runPaged({
pageSize: 1000,
});
const itemResults = [];
pagedData.pageRanges.forEach(pageRange => {
const page = pagedData.fetch({ index: pageRange.index });
page.data.forEach(result => {
itemResults.push(result);
});
});
log.debug({
title: 'RESULTS FOUND!',
details: JSON.stringify(itemResults.length),
});
// get ids to use with main warehouse item search
const ids = [];
for (let i in itemResults) {
// push id
ids.push(itemResults[i].id);
}
log.debug({
title: 'REPLENISHMENT ITEM IDS',
details: JSON.stringify(ids),
});
// create main warehouse item search and return object
const itemSearchValues = mainWarehouseSearch(ids);
log.debug({
title: 'MAIN WAREHOUSE ITEM SEARCH OBJECT',
details: JSON.stringify(itemSearchValues),
});
// build array of objects for csv
// create a copy and parse
const retailStoreResults = JSON.stringify(itemResults);
const retailStoreResultsJSON = JSON.parse(retailStoreResults);
const items = [];
for (let j in retailStoreResultsJSON) {
const item = retailStoreResultsJSON[j];
log.debug({
title: 'RESULT',
details: item,
});
const itemName = item.values.displayname;
const sku = item.values.custitem_sp_item_sku;
// get warehouse available from item search object
const warehouseQuantityAvailable =
itemSearchValues[item.id].warehouseAvailable;
// calculate
const storeQuantityAvailable = parseInt(item.values.formulanumeric);
const storeQuantityMin = item.values.formulanumeric_4;
const storeQuantityMax = parseInt(item.values.formulanumeric_1);
let quantityNeeded = storeQuantityMax - storeQuantityAvailable;
if (warehouseQuantityAvailable != '' && warehouseQuantityAvailable > 0) {
if (quantityNeeded > warehouseQuantityAvailable) {
quantityNeeded = warehouseQuantityAvailable;
}
const replenish = {
id: item.id,
sku: sku,
name: itemName.replace(',', ''),
storeQuantityAvailable: storeQuantityAvailable,
storeQuantityMin: storeQuantityMin,
storeQuantityMax: storeQuantityMax,
warehouseItemID: itemSearchValues[j],
warehouseQuantityAvailable: warehouseQuantityAvailable,
quantityNeeded: quantityNeeded,
};
const itemToReplenish = replenish;
items.push(itemToReplenish);
}
}
return items;
};
/**
* Creates an item search and retrieves the Main Warehouse
* Location Availability for each item.
*/
const mainWarehouseSearch = (ids: number[]) => {
const itemSearch = search.create({
type: 'item',
columns: ['locationquantityavailable'],
});
itemSearch.filters = [
search.createFilter({
name: 'inventorylocation',
operator: search.Operator.IS,
values: '1', // main warehouse
}),
search.createFilter({
name: 'internalid',
operator: search.Operator.IS,
values: ids,
}),
];
const itemSearchResultSet = itemSearch.run();
const itemSearchResults = itemSearchResultSet.getRange({
start: 0,
end: 1000,
});
// make a copy & parse
let itemSearchValues = JSON.stringify(itemSearchResults);
itemSearchValues = JSON.parse(itemSearchValues);
// create the object
return createItemSearchObj(itemSearchValues);
};
/**
* Creates Main Warehouse Location Availability Object,
* uses the internal id of the item as the key.
*/
const createItemSearchObj = items => {
const obj = {};
for (let i in items) {
const item = items[i];
const warehouseAvailable = parseInt(item.values.locationquantityavailable);
obj[item.id] = {
warehouseAvailable: warehouseAvailable,
};
}
return obj;
};
/**
* Creates a CSV file to be used to import and create a Transfer Order for
* Retail Store Item Replenishment.
*/
const createCSV = (items: Item[]) => {
const dir = Number(
runtime
.getCurrentScript()
.getParameter({ name: 'custscript_retail_replenishment_dir' })
);
const today = todaysDate();
const rnd = generateRandomString();
// create the csv file
const csvFile = file.create({
name: 'retail-store-replenishment-' + today + '_' + rnd + '.csv',
contents:
'transferName,id,sku,name,storeQuantityAvailable,storeQuantityMax,' +
'warehouseQuantityAvailable,quantityNeeded,date\n',
folder: dir,
fileType: file.Type.CSV,
});
// add the data
for (let i in items) {
var item = items[i];
csvFile.appendLine({
value:
'Retail Store - ' +
today +
',' +
item.id +
',' +
item.sku +
',' +
item.name +
',' +
item.storeQuantityAvailable +
',' +
item.storeQuantityMax +
',' +
item.warehouseQuantityAvailable +
',' +
item.quantityNeeded +
',' +
today,
});
}
// save the file
const csvFileId = csvFile.save();
return csvFileId;
};
/**
* Generates today's date in format DD/MM/YYYY
*/
const todaysDate = () => {
const today = new Date();
let dd: string | number = today.getDate();
let mm: string | number = today.getMonth() + 1;
const yyyy: string | number = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
return mm + '/' + dd + '/' + yyyy;
};
/**
* Generates a random string to be used during
* CSV file naming as to not overwrite existing file.
*/
const generateRandomString = () => {
return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
);
};
/**
* Creates a list widget for the results page
*/
const createPage = (items: Item[]) => {
log.debug({
title: 'CREATING PAGE',
details: 'There are ' + items.length,
});
const form = serverWidget.createForm({
title:
'Retail Replenishment - ' + todaysDate() + ' | Total: ' + items.length,
});
form.addSubmitButton({
label: 'Create Transfer Order',
});
const sublist = form.addSublist({
id: 'custpage_retial_replenishment_sublist',
type: serverWidget.SublistType.LIST,
label: 'Retail Replenishment',
});
sublist.addField({
id: 'custpage_field_id',
type: serverWidget.FieldType.TEXT,
label: 'ID',
});
sublist.addField({
id: 'custpage_field_sku',
type: serverWidget.FieldType.TEXT,
label: 'SKU',
});
sublist.addField({
id: 'custpage_field_name',
type: serverWidget.FieldType.TEXT,
label: 'Name',
});
sublist.addField({
id: 'custpage_field_store_qty_available',
type: serverWidget.FieldType.TEXT,
label: 'Store Qty Available',
});
sublist.addField({
id: 'custpage_field_store_qty_min',
type: serverWidget.FieldType.TEXT,
label: 'Store Qty Min',
});
sublist.addField({
id: 'custpage_field_store_qty_max',
type: serverWidget.FieldType.TEXT,
label: 'Store Qty Max',
});
sublist.addField({
id: 'custpage_field_warehouse_qty_available',
type: serverWidget.FieldType.TEXT,
label: 'Warehouse Qty Available',
});
sublist.addField({
id: 'custpage_field_qty_needed',
type: serverWidget.FieldType.TEXT,
label: 'Qty Needed',
});
for (let i = 0; i < items.length; i++) {
const item = items[i];
log.debug({
title: 'Item: ' + i,
details: item.id,
});
sublist.setSublistValue({
id: 'custpage_field_id',
line: i,
value: item.id,
});
sublist.setSublistValue({
id: 'custpage_field_sku',
line: i,
value: item.sku,
});
sublist.setSublistValue({
id: 'custpage_field_name',
line: i,
value: item.name,
});
sublist.setSublistValue({
id: 'custpage_field_store_qty_available',
line: i,
value: String(item.storeQuantityAvailable),
});
sublist.setSublistValue({
id: 'custpage_field_store_qty_min',
line: i,
value: String(item.storeQuantityMin),
});
sublist.setSublistValue({
id: 'custpage_field_store_qty_max',
line: i,
value: String(item.storeQuantityMax),
});
sublist.setSublistValue({
id: 'custpage_field_warehouse_qty_available',
line: i,
value: String(item.warehouseQuantityAvailable),
});
sublist.setSublistValue({
id: 'custpage_field_qty_needed',
line: i,
value: String(item.quantityNeeded),
});
}
return form;
};