-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathDocNumGenForRange.ts
More file actions
79 lines (64 loc) · 2.62 KB
/
DocNumGenForRange.ts
File metadata and controls
79 lines (64 loc) · 2.62 KB
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
function main(workbook: ExcelScript.Workbook, inputString: string): string {
// Temporary placeholder for testing
const incoming = {
docType: 'form',
documentName: 'cilx.png'
}
inputString = JSON.stringify(incoming);
// End temp testing area
// Object to hold key prefixes for each document type
const PREFIX = {
form: 'F',
'work instruction': 'W'
}
// Length of the numeric part of the key
const KEYLENGTH = 6;
// Parse the incoming string as object
const input:RequestData = JSON.parse(inputString);
// Reject invalid request
if (input.docType.toLowerCase() !== 'form' &&
input.docType.toLowerCase() !== 'work instruction') {
throw `Invalid type sent to the script: ${input.docType}. Should be one of the following: ${Object.keys(PREFIX)}`
}
// Get existing data in the sheet
const sheet = workbook.getWorksheet('PlainSheet'); /* plain range sheet */
const range = sheet.getUsedRange();
const data = range.getValues() as string[][];
// Filter rows to match the incoming type and then extract the document number column (index 0) and then sort it.
const selectIds = data.filter((value) => {
return value[1].toLowerCase() === input.docType.toLowerCase();
}).map((row) => row[0]).sort();
// Get the max document Id for the type
const maxId = selectIds[selectIds.length-1];
// Extract numeric part
const numPart = maxId.substring(1);
const nextNum = Number(numPart) + 1;
// If we ever reach the max key numbrer, throw an error
if (nextNum >= (10 ** KEYLENGTH)) {
throw `Key sequence of ${nextNum} out of range for type: ${input.docType}.`
}
// Get the correct prefix value
const prefixVal: string = PREFIX[input.docType.toLowerCase()] as string;
// Compute next key value
const nextKey = prefixVal + '0'.repeat(KEYLENGTH).substring(0, KEYLENGTH - String(nextNum).length) + String(nextNum);
// Get last row and compute next row address
const last = range.getLastRow();
const target = last.getOffsetRange(1, 0);
// Add a row with incoming data plus the computed key value
target.setValues([
[
nextKey,
/* Capitalize the document type */
input.docType[0].toUpperCase() + input.docType.toLowerCase().slice(1),
input.documentName
]
])
console.log(`Added row: ${[nextKey, input.docType, input.documentName]}`)
// Return the key value recorded in Excel
return nextKey;
}
// Incoming data structure
interface RequestData {
docType: string
documentName: string
}