-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
72 lines (65 loc) · 3.14 KB
/
index.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
import { exportToPdf } from "./controllers/export-to-pdf";
import { listDocuments } from "./controllers/list-documents";
import { getLastTimestamp, writeProgressFile } from "./controllers/progress-file";
import { Command } from 'commander';
const program = new Command();
program
.name('erpnext-documents-export')
.description('CLI to export ERPNext documents periodically')
.option('-u, --url <url>', 'ERPNext URL')
.option('-k, --key <key>', 'API key')
.option('-s, --secret <secret>', 'API secret');
program.command('watch')
.description('watch for changes in ERPNext documents')
.argument('<doctype>', 'DocType to watch')
.option('-t, --target-dir <dir>', 'target directory to save files', './')
.option('-f, --print-format <format>', 'format to export')
.option('-d, --date-field <field>', 'date field to use', 'posting_date')
.option('-ds, --docstatus <status>', 'docstatus to filter on')
.option('-ot, --output-template <template>', 'output filename template e.g. "{customer_name} - {name}"', '{name}')
.option('--include-json', 'also export JSON file')
.action(async (doctype: string, options: any) => {
while (true) {
try {
const lastTimestamp = await getLastTimestamp(options.targetDir);
const documents = await listDocuments({
url: program.opts().url,
key: program.opts().key,
secret: program.opts().secret,
doctype: doctype,
lastTimestamp,
docstatus: options.docstatus
});
let newLastTimestamp = lastTimestamp;
for (const doc of documents) {
try {
const exportedDocument = await exportToPdf({
url: program.opts().url,
key: program.opts().key,
secret: program.opts().secret,
doctype: doctype,
name: doc.name,
dateField: options.dateField,
targetDir: options.targetDir,
printFormat: options.printFormat,
outputTemplate: options.outputTemplate,
includeJson: options.includeJson,
});
if (exportedDocument !== null && (newLastTimestamp === null || exportedDocument.modified > newLastTimestamp)) {
newLastTimestamp = exportedDocument.modified;
await writeProgressFile(newLastTimestamp, options.targetDir);
}
} catch (e) {
console.error("Failed to export document", doc.name);
console.error(e);
}
}
} catch (e) {
console.error("Failed to list documents");
console.error(e);
}
// Sleep for 10 seconds
await new Promise((resolve) => setTimeout(resolve, 10000));
}
});
program.parse();