ofsc-utility 1.0.31 → 1.0.33

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.
@@ -56,4 +56,13 @@ export declare function generateHash(item: {
56
56
  * @returns
57
57
  */
58
58
  export declare function downloadAllEventsOfDLastTwoMinutes(clientId: string, clientSecret: string, instanceUrl: string, subscriptionId: string): Promise<any[]>;
59
+ /**
60
+ * Events of last one hour
61
+ * @param clientId
62
+ * @param clientSecret
63
+ * @param instanceUrl
64
+ * @param subscriptionId
65
+ * @returns
66
+ */
67
+ export declare function downloadAllEventsOfLastOneHour(clientId: string, clientSecret: string, instanceUrl: string, subscriptionId: string): Promise<any[]>;
59
68
  export {};
@@ -8,6 +8,7 @@ exports.downloadAllEventsOfDay = downloadAllEventsOfDay;
8
8
  exports.downloadAllEventsOfDayCSV = downloadAllEventsOfDayCSV;
9
9
  exports.generateHash = generateHash;
10
10
  exports.downloadAllEventsOfDLastTwoMinutes = downloadAllEventsOfDLastTwoMinutes;
11
+ exports.downloadAllEventsOfLastOneHour = downloadAllEventsOfLastOneHour;
11
12
  const node_crypto_1 = __importDefault(require("node:crypto"));
12
13
  const path_1 = __importDefault(require("path"));
13
14
  const index_1 = require("../oauthTokenService/index");
@@ -363,3 +364,92 @@ async function downloadAllEventsOfDLastTwoMinutes(clientId, clientSecret, instan
363
364
  }
364
365
  return events;
365
366
  }
367
+ /**
368
+ * Events of last one hour
369
+ * @param clientId
370
+ * @param clientSecret
371
+ * @param instanceUrl
372
+ * @param subscriptionId
373
+ * @returns
374
+ */
375
+ async function downloadAllEventsOfLastOneHour(clientId, clientSecret, instanceUrl, subscriptionId) {
376
+ /**
377
+ * Download events from the last ~180 seconds and return them as an
378
+ * array.
379
+ *
380
+ * Differences from `downloadAllEventsOfDayCSV`:
381
+ * - The `since` timestamp is computed using `getTimeBefore180SecondsAlt`.
382
+ * - Validates the generated timestamp with `validateDateTimeStrict`.
383
+ * - For each fetched item, this function attaches a `uniqueId` field
384
+ * generated by `generateHash` (used for deduplication or tracing).
385
+ *
386
+ * Usage: lightweight polling helper to retrieve recent events for
387
+ * short-lived processing or monitoring.
388
+ *
389
+ * @param clientId - OAuth client id.
390
+ * @param clientSecret - OAuth client secret.
391
+ * @param instanceUrl - Instance host.
392
+ * @param subscriptionId - Subscription id for events.
393
+ * @returns Array of recent event objects.
394
+ */
395
+ // All collected events
396
+ const events = [];
397
+ const since = (0, utilities_1.getTimeBefore3600SecondsAlt)();
398
+ let isValidate = (0, index_2.validateDateTimeStrict)(since);
399
+ if (!isValidate.isValid) {
400
+ throw new Error(isValidate.error);
401
+ }
402
+ // Build initial request URL
403
+ const baseUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/events`;
404
+ const initialUrl = `${baseUrl}?subscriptionId=${encodeURIComponent(subscriptionId)}&since=${encodeURIComponent(since)}`;
405
+ console.log("sinceDate", since);
406
+ let token = await (0, index_1.getOAuthToken)(clientId, clientSecret, instanceUrl);
407
+ // Get first page
408
+ let firstPage = await fetchEventsPage(initialUrl, token, clientId, clientSecret, instanceUrl);
409
+ token = firstPage.token;
410
+ let nextPage = firstPage.data.nextPage;
411
+ let found = firstPage.data.found;
412
+ // Controls infinite loop
413
+ let lastSeenPage = nextPage;
414
+ let repeatedPageCount = 0;
415
+ // Loop through pages
416
+ while (found && nextPage) {
417
+ const pageUrl = new URL(baseUrl);
418
+ pageUrl.search = new URLSearchParams({
419
+ subscriptionId,
420
+ page: nextPage,
421
+ limit: "1000",
422
+ }).toString();
423
+ const finalUrl = pageUrl.toString();
424
+ const result = await fetchEventsPage(finalUrl, token, clientId, clientSecret, instanceUrl);
425
+ token = result.token;
426
+ const page = result.data;
427
+ found = page.found;
428
+ nextPage = page.nextPage;
429
+ console.error("nextPage", nextPage, "Records:", page.items?.length, "Time:", page.items?.[0]?.time);
430
+ // Prevent infinite looping
431
+ if (nextPage === lastSeenPage) {
432
+ repeatedPageCount++;
433
+ if (repeatedPageCount > 15) {
434
+ console.warn("⚠️ Pagination repeating same page more than 15 times. Stopping.");
435
+ break;
436
+ }
437
+ }
438
+ else {
439
+ lastSeenPage = nextPage;
440
+ repeatedPageCount = 0;
441
+ }
442
+ // Add events
443
+ if (!page.items) {
444
+ console.warn("⚠️ No items found in page. Stopping.");
445
+ break;
446
+ }
447
+ for (let k of page.items) {
448
+ k["uniqueId"] = generateHash(k);
449
+ k["Change"] = k.activityChanges || k.inventoryChanges || k.requestChanges || k.userChanges || {};
450
+ k["Id"] = k.activityDetails?.activityId || k.resourceDetails?.resourceId || `${k.userDetails?.login}(${k.userDetails?.status})` || '-';
451
+ events.push(k);
452
+ }
453
+ }
454
+ return events;
455
+ }
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export * as User from './users';
10
10
  export * as Utilities from './utilities';
11
11
  export * as WorkZone from './workZones';
12
12
  export * from './types';
13
- export { generateAllOnHandInventoryOfAllResourcesCSV } from './inventory';
13
+ export { generateAllOnHandInventoryOfAllResources, generateAllOnHandInventoryOfAllResourcesCSV } from './inventory';
14
14
  export { getOAuthToken } from './oauthTokenService';
15
15
  export { downloadWorkZoneCSV } from './workZones';
16
16
  export { AllResources, downloadAllResourcesCSV, getworkSkillsOfResource } from './resources';
@@ -18,7 +18,7 @@ export { downloadAllUsersCSV, generateUsersCollaborationCSV } from './users';
18
18
  export { downloadAllInventoryTypesCSV, getInventoryTypesDetail, updateCreateInventoryType } from './inventoryTypes';
19
19
  export { getActivitybyId, getAllActivities } from './activities';
20
20
  export { createActivityCustomerInventories, getActivityCustomerInventories } from './activityInventories';
21
- export { downloadAllEventsOfDay, downloadAllEventsOfDayCSV } from './events';
21
+ export { downloadAllEventsOfDay, downloadAllEventsOfDayCSV, downloadAllEventsOfDLastTwoMinutes, downloadAllEventsOfLastOneHour } from './events';
22
22
  export { createExcelFile } from './utilities';
23
23
  export { createConfigurationFile } from './metadata';
24
24
  declare const OfscUtility: {
@@ -50,6 +50,7 @@ declare const OfscUtility: {
50
50
  };
51
51
  downloadAllEventsOfDayCSV: any;
52
52
  downloadAllEventsOfDay: any;
53
+ downloadAllEventsOfLastOneHour: any;
53
54
  generateUsersCollaborationCSV: any;
54
55
  generateAllOnHandInventoryOfAllResourcesCSV: any;
55
56
  getActivitybyId: any;
package/dist/index.js CHANGED
@@ -36,7 +36,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
36
36
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.createConfigurationFile = exports.createExcelFile = exports.downloadAllEventsOfDayCSV = exports.downloadAllEventsOfDay = exports.getActivityCustomerInventories = exports.createActivityCustomerInventories = exports.getAllActivities = exports.getActivitybyId = exports.updateCreateInventoryType = exports.getInventoryTypesDetail = exports.downloadAllInventoryTypesCSV = exports.generateUsersCollaborationCSV = exports.downloadAllUsersCSV = exports.getworkSkillsOfResource = exports.downloadAllResourcesCSV = exports.AllResources = exports.downloadWorkZoneCSV = exports.getOAuthToken = exports.generateAllOnHandInventoryOfAllResourcesCSV = exports.WorkZone = exports.Utilities = exports.User = exports.Resource = exports.OauthTokenService = exports.CreateConfigurationFile = exports.InventoryType = exports.Inventory = exports.Events = exports.ActivityInventories = exports.Activity = void 0;
39
+ exports.createConfigurationFile = exports.createExcelFile = exports.downloadAllEventsOfLastOneHour = exports.downloadAllEventsOfDLastTwoMinutes = exports.downloadAllEventsOfDayCSV = exports.downloadAllEventsOfDay = exports.getActivityCustomerInventories = exports.createActivityCustomerInventories = exports.getAllActivities = exports.getActivitybyId = exports.updateCreateInventoryType = exports.getInventoryTypesDetail = exports.downloadAllInventoryTypesCSV = exports.generateUsersCollaborationCSV = exports.downloadAllUsersCSV = exports.getworkSkillsOfResource = exports.downloadAllResourcesCSV = exports.AllResources = exports.downloadWorkZoneCSV = exports.getOAuthToken = exports.generateAllOnHandInventoryOfAllResourcesCSV = exports.generateAllOnHandInventoryOfAllResources = exports.WorkZone = exports.Utilities = exports.User = exports.Resource = exports.OauthTokenService = exports.CreateConfigurationFile = exports.InventoryType = exports.Inventory = exports.Events = exports.ActivityInventories = exports.Activity = void 0;
40
40
  // Export all methods grouped by category
41
41
  exports.Activity = __importStar(require("./activities"));
42
42
  exports.ActivityInventories = __importStar(require("./activityInventories"));
@@ -52,6 +52,7 @@ exports.WorkZone = __importStar(require("./workZones"));
52
52
  // Export types
53
53
  __exportStar(require("./types"), exports);
54
54
  var inventory_1 = require("./inventory");
55
+ Object.defineProperty(exports, "generateAllOnHandInventoryOfAllResources", { enumerable: true, get: function () { return inventory_1.generateAllOnHandInventoryOfAllResources; } });
55
56
  Object.defineProperty(exports, "generateAllOnHandInventoryOfAllResourcesCSV", { enumerable: true, get: function () { return inventory_1.generateAllOnHandInventoryOfAllResourcesCSV; } });
56
57
  var oauthTokenService_1 = require("./oauthTokenService");
57
58
  Object.defineProperty(exports, "getOAuthToken", { enumerable: true, get: function () { return oauthTokenService_1.getOAuthToken; } });
@@ -77,6 +78,8 @@ Object.defineProperty(exports, "getActivityCustomerInventories", { enumerable: t
77
78
  var events_1 = require("./events");
78
79
  Object.defineProperty(exports, "downloadAllEventsOfDay", { enumerable: true, get: function () { return events_1.downloadAllEventsOfDay; } });
79
80
  Object.defineProperty(exports, "downloadAllEventsOfDayCSV", { enumerable: true, get: function () { return events_1.downloadAllEventsOfDayCSV; } });
81
+ Object.defineProperty(exports, "downloadAllEventsOfDLastTwoMinutes", { enumerable: true, get: function () { return events_1.downloadAllEventsOfDLastTwoMinutes; } });
82
+ Object.defineProperty(exports, "downloadAllEventsOfLastOneHour", { enumerable: true, get: function () { return events_1.downloadAllEventsOfLastOneHour; } });
80
83
  var utilities_1 = require("./utilities");
81
84
  Object.defineProperty(exports, "createExcelFile", { enumerable: true, get: function () { return utilities_1.createExcelFile; } });
82
85
  var metadata_1 = require("./metadata");
@@ -111,6 +114,7 @@ const OfscUtility = {
111
114
  },
112
115
  downloadAllEventsOfDayCSV: require('./events').downloadAllEventsOfDayCSV,
113
116
  downloadAllEventsOfDay: require('./events').downloadAllEventsOfDay,
117
+ downloadAllEventsOfLastOneHour: require('./events').downloadAllEventsOfLastOneHour,
114
118
  generateUsersCollaborationCSV: require('./users').generateUsersCollaborationCSV,
115
119
  generateAllOnHandInventoryOfAllResourcesCSV: require('./inventory').generateAllOnHandInventoryOfAllResourcesCSV,
116
120
  getActivitybyId: require('./activities').getActivitybyId,
@@ -1 +1,5 @@
1
1
  export declare function generateAllOnHandInventoryOfAllResourcesCSV(clientId: string, clientSecret: string, instanceUrl: string): Promise<void>;
2
+ export declare function generateAllOnHandInventoryOfAllResources(clientId: string, clientSecret: string, instanceUrl: string): Promise<{
3
+ data: any[];
4
+ props: string[];
5
+ }>;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.generateAllOnHandInventoryOfAllResourcesCSV = generateAllOnHandInventoryOfAllResourcesCSV;
7
+ exports.generateAllOnHandInventoryOfAllResources = generateAllOnHandInventoryOfAllResources;
7
8
  const path_1 = __importDefault(require("path"));
8
9
  const utilities_1 = require("../utilities");
9
10
  async function generateAllOnHandInventoryOfAllResourcesCSV(clientId, clientSecret, instanceUrl) {
@@ -77,3 +78,79 @@ async function generateAllOnHandInventoryOfAllResourcesCSV(clientId, clientSecre
77
78
  (0, utilities_1.saveCsv)(rows, filename);
78
79
  console.log(`📁 CSV saved: ${fullPath}`);
79
80
  }
81
+ async function generateAllOnHandInventoryOfAllResources(clientId, clientSecret, instanceUrl) {
82
+ let offset = 0;
83
+ const limit = 100;
84
+ const allResources = [];
85
+ let token = "";
86
+ console.log("🚀 Starting all Resources Inventories export...");
87
+ console.log("--------------------------------------------------");
88
+ while (true) {
89
+ const resourcesUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/resources/?offset=${offset}&limit=${limit}`;
90
+ console.log(`➡️ Fetching resources offset=${offset}`);
91
+ const res = await (0, utilities_1.fetchWithRetry)(resourcesUrl, clientId, clientSecret, instanceUrl, token);
92
+ token = res.token;
93
+ const data = res.data;
94
+ if (!data?.items?.length) {
95
+ console.warn("⚠ No resource items returned. Breaking.");
96
+ break;
97
+ }
98
+ allResources.push(...data.items);
99
+ console.log(` ✔ Received ${data.items.length} resources (Total: ${allResources.length})`);
100
+ if (offset + limit >= data.totalResults)
101
+ break;
102
+ offset += limit;
103
+ }
104
+ console.log("--------------------------------------------------");
105
+ console.log(`Total resources to process: ${allResources.length}`);
106
+ console.log("--------------------------------------------------");
107
+ // 2. Fetch on hand inventories for each resource
108
+ const rows = [];
109
+ for (const [index, resource] of allResources.entries()) {
110
+ console.log(`${index} 👤 Fetching Inventories for ${resource.resourceId}`);
111
+ if (resource.status !== "active") {
112
+ console.log(` ⚠ Skipping inactive resource ${resource.resourceId}`);
113
+ continue;
114
+ }
115
+ offset = 0;
116
+ while (true) {
117
+ const invUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/resources/${encodeURIComponent(resource.resourceId)}/inventories/?offset=${offset}&limit=${limit}`;
118
+ try {
119
+ const res = await (0, utilities_1.fetchWithRetry)(invUrl, clientId, clientSecret, instanceUrl, token);
120
+ token = res.token;
121
+ const itemsData = res.data;
122
+ const items = itemsData?.items ?? [];
123
+ if (!items || items.length === 0) {
124
+ console.log(` ⚠ No Inventories found for ${resource.resourceId}`);
125
+ break;
126
+ }
127
+ for (const inv of items) {
128
+ delete inv.links;
129
+ delete inv.status;
130
+ rows.push({ resourceName: resource.name, resourceType: resource.resourceType, resourceTimeZone: resource.timeZoneIANA, ...inv, });
131
+ }
132
+ console.log(` ✔ Found ${items.length} Inventories`);
133
+ if (offset + limit >= itemsData.totalResults)
134
+ break;
135
+ offset += limit;
136
+ }
137
+ catch (err) {
138
+ console.error(`❌ Error fetching Inventories for ${resource.resourceId}:`, err);
139
+ console.log(` ⚠ Skipping invUrl ${invUrl}`);
140
+ }
141
+ }
142
+ }
143
+ console.log("--------------------------------------------------");
144
+ console.log(`Total rows: ${rows.length}`);
145
+ console.log("--------------------------------------------------");
146
+ const props = [...rows.reduce((set, row) => {
147
+ if (row && typeof row === "object") {
148
+ Object.keys(row).forEach((key) => set.add(key));
149
+ }
150
+ return set;
151
+ }, new Set())];
152
+ return {
153
+ data: rows,
154
+ props,
155
+ };
156
+ }
@@ -29,4 +29,5 @@ interface ValidationResult {
29
29
  */
30
30
  export declare function validateDateTimeStrict(dateTimeStr: string): ValidationResult;
31
31
  export declare function getTimeBefore180SecondsAlt(): string;
32
+ export declare function getTimeBefore3600SecondsAlt(): string;
32
33
  export {};
@@ -42,6 +42,7 @@ exports.xmlNodeToObjects = xmlNodeToObjects;
42
42
  exports.createExcelFile = createExcelFile;
43
43
  exports.validateDateTimeStrict = validateDateTimeStrict;
44
44
  exports.getTimeBefore180SecondsAlt = getTimeBefore180SecondsAlt;
45
+ exports.getTimeBefore3600SecondsAlt = getTimeBefore3600SecondsAlt;
45
46
  const XLSX = __importStar(require("xlsx-js-style"));
46
47
  const xmldom_1 = require("xmldom");
47
48
  const oauthTokenService_1 = require("../oauthTokenService");
@@ -310,3 +311,10 @@ function getTimeBefore180SecondsAlt() {
310
311
  .replace('T', ' ')
311
312
  .substring(0, 19);
312
313
  }
314
+ function getTimeBefore3600SecondsAlt() {
315
+ const timeBefore = new Date(Date.now() - 3600000); // 3600 * 1000 = 3600000
316
+ // Convert to ISO string and format
317
+ return timeBefore.toISOString()
318
+ .replace('T', ' ')
319
+ .substring(0, 19);
320
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofsc-utility",
3
- "version": "1.0.31",
3
+ "version": "1.0.33",
4
4
  "description": "A wrapper for Oracle Field Service REST API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/readme.md CHANGED
@@ -144,6 +144,52 @@ await ofs.downloadAllUsersCSV(
144
144
  );
145
145
  ```
146
146
 
147
+ ### Resource related methods
148
+
149
+ ```js
150
+ await ofs.generateAllOnHandInventoryOfAllResourcesCSV(
151
+ process.env.CLIENT_ID,
152
+ process.env.CLIENT_SECRET,
153
+ process.env.INSTANCE_NAME,
154
+ );
155
+ ```
156
+
157
+ This helper fetches all active resources and writes their on-hand inventory rows to a CSV file.
158
+
159
+ ```js
160
+ const inventoryResult = await ofs.generateAllOnHandInventoryOfAllResources(
161
+ process.env.CLIENT_ID,
162
+ process.env.CLIENT_SECRET,
163
+ process.env.INSTANCE_NAME,
164
+ );
165
+
166
+ console.log(`Loaded ${inventoryResult.data.length} inventory rows`);
167
+ console.log("Available table columns:", inventoryResult.props);
168
+ ```
169
+
170
+ This method fetches active resources and returns an object containing:
171
+
172
+ - `data`: an array of inventory row objects
173
+ - `props`: an array of unique keys found across all row objects
174
+
175
+ The `props` array can be used as your dynamic table columns. For example:
176
+
177
+ ```js
178
+ const columns = inventoryResult.props;
179
+ const rows = inventoryResult.data;
180
+
181
+ columns.forEach((col) => {
182
+ console.log(`Column: ${col}`);
183
+ });
184
+
185
+ rows.forEach((row) => {
186
+ const cells = columns.map((col) => row[col]);
187
+ console.log(cells);
188
+ });
189
+ ```
190
+
191
+ This gives you a dynamic table definition based on the actual inventory row fields returned by OFSC.
192
+
147
193
  ### Activity and inventory helpers
148
194
 
149
195
  ```js
@@ -237,6 +283,8 @@ Top-level exports include:
237
283
  - `downloadWorkZoneCSV`
238
284
  - `downloadAllResourcesCSV`
239
285
  - `downloadAllUsersCSV`
286
+ - `generateAllOnHandInventoryOfAllResourcesCSV`
287
+ - `generateAllOnHandInventoryOfAllResources`
240
288
  - `downloadAllInventoryTypesCSV`
241
289
  - `getInventoryTypesDetail`
242
290
  - `updateCreateInventoryType`