-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
525 lines (525 loc) · 22.4 KB
/
index.js
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair
/* eslint-disable max-lines */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { URL } from 'node:url';
import FasterUrlBuilder from '@cityssm/faster-url-builder';
import puppeteerLaunch from '@cityssm/puppeteer-launch';
import { secondsToMillis } from '@cityssm/to-millis';
import { dateToString } from '@cityssm/utils-datetime';
import Debug from 'debug';
import { DEBUG_NAMESPACE } from './debug.config.js';
import { minimumRecommendedTimeoutSeconds, reportExportTypes } from './lookups.js';
import { applyReportFilters } from './puppeteer.helpers.js';
import { defaultDelayMillis, delay, longDelayMillis } from './utilities.js';
const debug = Debug(`${DEBUG_NAMESPACE}:index`);
export class FasterReportExporter {
fasterUrlBuilder;
#fasterUserName;
#fasterPassword;
#downloadFolderPath = os.tmpdir();
#useHeadlessBrowser = true;
#timeoutMillis = secondsToMillis(
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
Math.max(90, minimumRecommendedTimeoutSeconds));
#timeZone = 'Eastern';
/**
* Initializes the FasterReportExporter.
* @param fasterTenantOrBaseUrl - The subdomain of the FASTER Web URL before ".fasterwebcloud.com"
* or the full domain and path including "/FASTER"
* @param fasterUserName - The user name
* @param fasterPassword - The password
* @param options - Options
*/
constructor(fasterTenantOrBaseUrl, fasterUserName, fasterPassword, options = {}) {
this.fasterUrlBuilder = new FasterUrlBuilder(fasterTenantOrBaseUrl);
this.#fasterUserName = fasterUserName;
this.#fasterPassword = fasterPassword;
if (options.downloadFolderPath !== undefined) {
this.setDownloadFolderPath(options.downloadFolderPath);
}
if (options.timeoutMillis !== undefined) {
this.setTimeoutMillis(options.timeoutMillis);
}
if (options.showBrowserWindow !== undefined && options.showBrowserWindow) {
this.showBrowserWindow();
}
if (options.timeZone !== undefined) {
this.#timeZone = options.timeZone;
}
}
/**
* Sets the folder where downloaded reports are saved.
* @param downloadFolderPath - The folder where downloaded reports are saved.
*/
setDownloadFolderPath(downloadFolderPath) {
// eslint-disable-next-line security/detect-non-literal-fs-filename
if (!fs.existsSync(downloadFolderPath)) {
throw new Error(`Download folder path does not exist: ${downloadFolderPath}`);
}
this.#downloadFolderPath = downloadFolderPath;
}
/**
* Changes the timeout for loading the browser and navigating between pages.
* @param timeoutMillis - Number of milliseconds.
*/
setTimeoutMillis(timeoutMillis) {
this.#timeoutMillis = timeoutMillis;
if (timeoutMillis < secondsToMillis(minimumRecommendedTimeoutSeconds)) {
debug(`Warning: Timeouts less than ${minimumRecommendedTimeoutSeconds}s are not recommended.`);
}
}
/**
* Switches off headless mode, making the browser window visible.
* Useful for debugging.
*/
showBrowserWindow() {
this.#useHeadlessBrowser = false;
}
/**
* Changes the time zone parameter used in reports.
* @param timezone - The preferred report time zone.
*/
setTimeZone(timezone) {
this.#timeZone = timezone;
}
/**
* Gets a browser and page that are logged into FASTER.
* @returns browser and page, be sure to close the browser when done.
*/
async _getLoggedInFasterPage() {
// eslint-disable-next-line @typescript-eslint/init-declarations
let browser;
try {
browser = await puppeteerLaunch({
browser: 'chrome',
protocol: 'cdp',
headless: this.#useHeadlessBrowser,
timeout: this.#timeoutMillis
});
/*
* Load Faster
*/
debug('Logging into FASTER...');
const page = await browser.newPage();
await page.goto(this.fasterUrlBuilder.baseUrl, {
timeout: this.#timeoutMillis
});
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
/*
* Log in if need be
*/
const loginFormElement = await page.$('#form_Signin');
if (loginFormElement !== null) {
debug('Filling out login form...');
const userNameElement = await loginFormElement.$('#LoginControl_UserName');
if (userNameElement === null) {
throw new Error('Unable to locate user name field.');
}
await userNameElement.type(this.#fasterUserName);
const passwordElement = await loginFormElement.$('#LoginControl_Password');
if (passwordElement === null) {
throw new Error('Unable to locate password field.');
}
await passwordElement.type(this.#fasterPassword);
const submitButtonElement = await loginFormElement.$('#LoginControl_SignInButton_input');
if (submitButtonElement === null) {
throw new Error('Unable to locate # button.');
}
await submitButtonElement.scrollIntoView();
await submitButtonElement.click();
await delay();
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
if (page.url().toLowerCase().includes('release/releasenotes.aspx')) {
debug('Release notes page, continuing...');
// eslint-disable-next-line @cspell/spellchecker
const continueButtonElement = await page.$('#OKRadButon_input');
if (continueButtonElement !== null) {
await continueButtonElement.scrollIntoView();
await continueButtonElement.click();
await delay();
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
}
}
}
debug('Finished logging in.');
return {
browser,
page
};
}
catch (error) {
try {
await browser?.close();
}
catch { }
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw error;
}
}
// eslint-disable-next-line @typescript-eslint/max-params
async #navigateToFasterReportPage(browser, page, reportKey, reportParameters, reportFilters) {
try {
/*
* Navigate to report
*/
const reportUrl = new URL(this.fasterUrlBuilder.reportViewerUrl);
reportUrl.searchParams.set('R', reportKey);
for (const [parameterKey, parameterValue] of Object.entries(reportParameters)) {
reportUrl.searchParams.set(parameterKey, parameterValue);
}
await page.goto(reportUrl.href, {
timeout: this.#timeoutMillis
});
await delay();
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
if (reportFilters !== undefined) {
await applyReportFilters(page, reportFilters, {
timeoutMillis: this.#timeoutMillis
});
}
return {
browser,
page
};
}
catch (error) {
try {
await browser.close();
}
catch { }
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw error;
}
}
/**
* Exports a FASTER report to a file.
* @param browser - Puppeteer browser
* @param page - Puppeteer page on a report page
* @param exportType - Output file type
* @returns - Path to the exported file.
*/
async #exportFasterReport(browser, page, exportType = 'PDF') {
await page.bringToFront();
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
debug(`Report Page Title: ${await page.title()}`);
// eslint-disable-next-line @typescript-eslint/no-misused-promises, no-async-promise-executor, promise/avoid-new
return await new Promise(async (resolve) => {
let downloadStarted = false;
try {
/*
* Catch the download
*/
const cdpSession = await browser.target().createCDPSession();
await cdpSession.send('Browser.setDownloadBehavior', {
behavior: 'allowAndName',
downloadPath: this.#downloadFolderPath,
eventsEnabled: true
});
cdpSession.on('Browser.downloadProgress', (event) => {
if (event.state === 'completed') {
debug('Download complete.');
const downloadedFilePath = path.join(this.#downloadFolderPath, event.guid);
// eslint-disable-next-line security/detect-object-injection
const newFilePath = `${downloadedFilePath}.${reportExportTypes[exportType]}`;
// eslint-disable-next-line security/detect-non-literal-fs-filename
fs.rename(downloadedFilePath, newFilePath, (error) => {
if (error === null) {
debug(`File: ${newFilePath}`);
resolve(newFilePath);
}
else {
debug(`File: ${downloadedFilePath}`);
resolve(downloadedFilePath);
}
});
downloadStarted = false;
}
else if (event.state === 'canceled') {
downloadStarted = false;
throw new Error('Download cancelled.');
}
});
/*
* Print to PDF
*/
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
debug(`Finding the print button for "${exportType}"...`);
const printOptionsMenuElement = await page.waitForSelector('#RvDetails_ctl05_ctl04_ctl00_ButtonLink', { timeout: this.#timeoutMillis });
if (printOptionsMenuElement === null) {
throw new Error('Unable to locate print options. Consider extending the timeout millis.');
}
await printOptionsMenuElement.click();
await delay(longDelayMillis);
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
const printOptionElement = await page.waitForSelector(`#RvDetails_ctl05_ctl04_ctl00_Menu a[title^='${exportType}']`, { timeout: this.#timeoutMillis });
if (printOptionElement === null) {
throw new Error(`Unable to locate "${exportType}" print type.`);
}
debug(`Print button found for "${exportType}"...`);
await delay();
downloadStarted = true;
await printOptionElement.scrollIntoView();
await printOptionElement.click();
debug('Print selected.');
await delay(longDelayMillis);
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
let retries = this.#timeoutMillis / defaultDelayMillis;
// eslint-disable-next-line no-unmodified-loop-condition, @typescript-eslint/no-unnecessary-condition
while (downloadStarted && retries > 0) {
await delay();
retries--;
}
}
finally {
try {
await browser.close();
}
catch { }
}
});
}
/**
* Exports a Part Order Print (W299) report for a given order number.
* @param orderNumber - The order number.
* @param exportType - The export type.
* @returns The path to the exported report.
*/
async exportPartOrderPrint(orderNumber, exportType) {
const { browser, page } = await this._getLoggedInFasterPage();
await this.#navigateToFasterReportPage(browser, page, '/Part Order Print/W299 - OrderPrint', {
OrderID: orderNumber.toString(),
ReportType: 'S',
Domain: 'Inventory'
}, {
'Time Zone': this.#timeZone
});
return await this.#exportFasterReport(browser, page, exportType);
}
/**
* Exports an Inventory Report (W200).
* @param exportType - The export type.
* @returns The path to the exported report.
*/
async exportInventory(exportType) {
const { browser, page } = await this._getLoggedInFasterPage();
await this.#navigateToFasterReportPage(browser, page, '/Inventory/W200 - Inventory Report', {
ReportType: 'S',
Domain: 'Inventory',
Parent: 'Reports'
}, {
'Time Zone': this.#timeZone,
'Grouping within Storeroom': 'Item Category'
});
return await this.#exportFasterReport(browser, page, exportType);
}
/**
* Export an Asset Master List (W114) report.
* @param exportType - The export type.
* @returns The path to the exported report.
*/
async exportAssetList(exportType) {
const { browser, page } = await this._getLoggedInFasterPage();
await this.#navigateToFasterReportPage(browser, page, '/Assets/W114 - Asset Master List', {
ReportType: 'S',
Domain: 'Assets',
Parent: 'Reports'
}, {
'Time Zone': this.#timeZone,
'Primary Grouping': 'Organization',
'Secondary Grouping': 'Department'
});
return await this.#exportFasterReport(browser, page, exportType);
}
/**
* Export a Work Order Details by Work Order Number (W300N) report.
* @param minWorkOrderNumber - Minimum work order number.
* @param maxWorkOrderNumber - Maximum work order number.
* @param exportType - The export type.
* @returns The path to the exported report.
*/
async exportWorkOrderDetails(minWorkOrderNumber, maxWorkOrderNumber, exportType) {
const minWorkOrderNumberString = minWorkOrderNumber.toString();
const maxWorkOrderNumberString = (maxWorkOrderNumber ?? minWorkOrderNumber).toString();
const { browser, page } = await this._getLoggedInFasterPage();
await this.#navigateToFasterReportPage(browser, page,
// eslint-disable-next-line no-secrets/no-secrets
'/Maintenance/W300n - WorkOrderDetailsByWONumber', {
ReportType: 'S',
Domain: 'Maintenance',
Parent: 'Reports'
}, {
'Time Zone': this.#timeZone,
'Beginning Work Order Number': minWorkOrderNumberString,
'Ending Work Order Number': maxWorkOrderNumberString
});
return await this.#exportFasterReport(browser, page, exportType);
}
async #exportWorkOrderPrint(workOrderNumber, exportType, printButtonSelector) {
const { browser, page } = await this._getLoggedInFasterPage();
try {
await page.goto(this.fasterUrlBuilder.workOrderUrl(workOrderNumber), {
timeout: this.#timeoutMillis
});
await delay();
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
const printElement = await page.waitForSelector(printButtonSelector, {
timeout: this.#timeoutMillis
});
if (printElement === null) {
throw new Error('Unable to locate print link.');
}
await printElement.scrollIntoView();
await printElement.click();
const reportViewerTarget = await browser.waitForTarget((target) => target.url().toLowerCase().includes('reportviewer.aspx'), {
timeout: this.#timeoutMillis
});
const newPage = await reportViewerTarget.asPage();
await delay();
await newPage.bringToFront();
await delay();
await newPage.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
return await this.#exportFasterReport(browser, newPage, exportType);
}
catch (error) {
try {
await browser.close();
}
catch { }
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw error;
}
}
/**
* Exports the Customer Print (W398) for a given work order.
* @param workOrderNumber - The work order number.
* @param exportType - The export type.
* @returns The path to the exported report.
*/
async exportWorkOrderCustomerPrint(workOrderNumber, exportType = 'PDF') {
return await this.#exportWorkOrderPrint(workOrderNumber, exportType,
// eslint-disable-next-line no-secrets/no-secrets
'#ctl00_ContentPlaceHolder_Content_MasterWorkOrderDetailMenu_CustomerPrintLinkButton');
}
/**
* Exports the Technician Print (W399) for a given work order.
* @param workOrderNumber - The work order number.
* @param exportType - The export type.
* @returns The path to the exported report.
*/
async exportWorkOrderTechnicianPrint(workOrderNumber, exportType = 'PDF') {
return await this.#exportWorkOrderPrint(workOrderNumber, exportType,
// eslint-disable-next-line no-secrets/no-secrets
'#ctl00_ContentPlaceHolder_Content_MasterWorkOrderDetailMenu_WorkOrderPrintLinkButton');
}
/**
* Exports the Message Logger (W603) report.
* @param startDate - The start date
* @param endDate - The end date
* @param exportType - The export type
* @returns The path to the exported report.
*/
async exportMessageLogger(startDate = new Date(), endDate = new Date(), exportType) {
const { browser, page } = await this._getLoggedInFasterPage();
await this.#navigateToFasterReportPage(browser, page, '/Setup/W603 - Message Logger', {
ReportType: 'S',
Domain: 'Setup',
Parent: 'Reports'
}, {
'Time Zone': this.#timeZone,
'Start Date': dateToString(startDate),
'End Date': dateToString(endDate)
});
return await this.#exportFasterReport(browser, page, exportType);
}
/**
* Exports a scheduled report by name.
* Helpful for exporting reports with complex parameters.
* @param scheduleName - Schedule name
* @param startDate - The start date
* @param endDate - The end date
* @param exportType - The export type
* @returns The path to the exported report.
*/
async exportScheduledReport(scheduleName, startDate = new Date(), endDate = new Date(), exportType) {
let { browser, page } = await this._getLoggedInFasterPage();
try {
await page.goto(this.fasterUrlBuilder.scheduledReportsUrl, {
timeout: this.#timeoutMillis
});
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
// Find the report row
const scheduledReportsTableRowElements = await page.$$(
// eslint-disable-next-line no-secrets/no-secrets
'#ctl00_ContentPlaceHolder_Content_ScheduleRadDock_C_ScheduleRadGrid_ctl00 tbody tr');
for (const scheduledReportsTableRowElement of scheduledReportsTableRowElements) {
const reportNameElement = await scheduledReportsTableRowElement.$('td:nth-child(2) div span');
if (reportNameElement === null) {
continue;
}
const reportNameText = await reportNameElement.evaluate((cell) => cell.textContent?.trim());
if (reportNameText === scheduleName) {
debug(`Scheduled report found: ${scheduleName}`);
const actionLinkElements = await scheduledReportsTableRowElement.$$('td:nth-child(1) a');
for (const actionLinkElement of actionLinkElements) {
const actionLinkText = await actionLinkElement.evaluate((cell) => cell.textContent);
if (actionLinkText === 'Parameter') {
debug(`Opening report: ${scheduleName}`);
await actionLinkElement.click();
await delay();
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
const browserPages = await browser.pages();
page = browserPages.at(-1);
await page.bringToFront();
await delay();
await page.waitForNetworkIdle({
timeout: this.#timeoutMillis
});
await applyReportFilters(page, {
'Start Date': dateToString(startDate),
'End Date': dateToString(endDate)
}, {
timeoutMillis: this.#timeoutMillis
});
break;
}
}
}
}
}
catch (error) {
try {
await browser.close();
}
catch { }
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw error;
}
return await this.#exportFasterReport(browser, page, exportType);
}
}