ofsc-utility 1.0.9 → 1.0.10

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.
@@ -63,8 +63,9 @@ async function createActivityCustomerInventories(clientId, clientSecret, instanc
63
63
  },
64
64
  body: JSON.stringify(payload)
65
65
  });
66
- if (!res.ok) {
67
- throw new Error(`❌ POST failed: ${res.status} ${res.statusText}`);
68
- }
66
+ // if (!res.ok) {
67
+ // return await res.json();
68
+ // throw new Error(`❌ POST failed: ${res.status} ${res.statusText}`);
69
+ // }
69
70
  return await res.json();
70
71
  }
@@ -0,0 +1,7 @@
1
+ type AnyObject = {
2
+ [key: string]: any;
3
+ };
4
+ export declare function flattenObject(obj: AnyObject, parentKey?: string, result?: AnyObject): AnyObject;
5
+ export declare function downloadAllEventsOfDay(clientId: string, clientSecret: string, instanceUrl: string, subscriptionId: string, sinceDate: string, onlyData: boolean): Promise<any[]>;
6
+ export declare function downloadAllEventsOfDayCSV(clientId: string, clientSecret: string, instanceUrl: string, subscriptionId: string, sinceDate: string, onlyData: boolean): Promise<any[]>;
7
+ export {};
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.flattenObject = flattenObject;
7
+ exports.downloadAllEventsOfDay = downloadAllEventsOfDay;
8
+ exports.downloadAllEventsOfDayCSV = downloadAllEventsOfDayCSV;
9
+ const path_1 = __importDefault(require("path"));
10
+ const index_1 = require("../oauthTokenService/index");
11
+ const utilities_1 = require("../utilities");
12
+ function flattenObject(obj, parentKey = "", result = {}) {
13
+ for (const key in obj) {
14
+ const newKey = parentKey ? `${parentKey}_${key}` : key;
15
+ if (typeof obj[key] === "object" &&
16
+ obj[key] !== null &&
17
+ !Array.isArray(obj[key])) {
18
+ flattenObject(obj[key], newKey, result);
19
+ }
20
+ else {
21
+ result[newKey] = obj[key];
22
+ }
23
+ }
24
+ return result;
25
+ }
26
+ async function fetchEventsPage(url, token, clientId, clientSecret, instanceUrl) {
27
+ const res = await (0, utilities_1.fetchWithRetry)(url, clientId, clientSecret, instanceUrl, token);
28
+ return {
29
+ token: res.token,
30
+ data: res.data
31
+ };
32
+ }
33
+ function processEventItems(items, sinceDate, output) {
34
+ for (const item of items) {
35
+ const eventTime = item.time;
36
+ // Stop if date changes
37
+ if (!eventTime.startsWith(sinceDate)) {
38
+ console.log("Stopping at different event date:", eventTime);
39
+ return false;
40
+ }
41
+ // Add activityId as first level field
42
+ const activityId = item.activityDetails?.activityId ?? null;
43
+ output.push({ activityId, ...item });
44
+ }
45
+ return true;
46
+ }
47
+ async function downloadAllEventsOfDay(clientId, clientSecret, instanceUrl, subscriptionId, sinceDate, onlyData) {
48
+ console.log("Downloading events...OnlyData:", onlyData);
49
+ let data = await downloadAllEventsOfDayCSV(clientId, clientSecret, instanceUrl, subscriptionId, sinceDate, onlyData);
50
+ return data;
51
+ }
52
+ async function downloadAllEventsOfDayCSV(clientId, clientSecret, instanceUrl, subscriptionId, sinceDate, onlyData) {
53
+ // All collected events
54
+ const events = [];
55
+ // Build initial request URL
56
+ const baseUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/events`;
57
+ const initialUrl = `${baseUrl}?subscriptionId=${encodeURIComponent(subscriptionId)}&since=${encodeURIComponent(sinceDate + " 00:00:00")}`;
58
+ let token = await (0, index_1.getOAuthToken)(clientId, clientSecret, instanceUrl);
59
+ // Get first page
60
+ let firstPage = await fetchEventsPage(initialUrl, token, clientId, clientSecret, instanceUrl);
61
+ token = firstPage.token;
62
+ let nextPage = firstPage.data.nextPage;
63
+ let found = firstPage.data.found;
64
+ // Controls infinite loop
65
+ let lastSeenPage = nextPage;
66
+ let repeatedPageCount = 0;
67
+ // Loop through pages
68
+ while (found && nextPage) {
69
+ const pageUrl = new URL(baseUrl);
70
+ pageUrl.search = new URLSearchParams({
71
+ subscriptionId,
72
+ page: nextPage,
73
+ limit: "1000",
74
+ }).toString();
75
+ const finalUrl = pageUrl.toString();
76
+ const result = await fetchEventsPage(finalUrl, token, clientId, clientSecret, instanceUrl);
77
+ token = result.token;
78
+ const page = result.data;
79
+ found = page.found;
80
+ nextPage = page.nextPage;
81
+ console.error("nextPage", nextPage, "Records:", page.items?.length, "Time:", page.items?.[0]?.time);
82
+ // Prevent infinite looping
83
+ if (nextPage === lastSeenPage) {
84
+ repeatedPageCount++;
85
+ if (repeatedPageCount > 10) {
86
+ console.warn("⚠️ Pagination repeating same page more than 10 times. Stopping.");
87
+ break;
88
+ }
89
+ }
90
+ else {
91
+ lastSeenPage = nextPage;
92
+ repeatedPageCount = 0;
93
+ }
94
+ // Add events
95
+ if (page.items) {
96
+ if (!processEventItems(page.items, sinceDate, events)) {
97
+ break;
98
+ }
99
+ }
100
+ else {
101
+ console.warn("⚠️ No items found in page. Stopping.");
102
+ break;
103
+ }
104
+ }
105
+ // Save CSV
106
+ const ts = Math.floor(Date.now() / 1000);
107
+ const filename = `events-${sinceDate}_${ts}.csv`;
108
+ const fullPath = path_1.default.resolve(filename);
109
+ if (!onlyData) {
110
+ (0, utilities_1.saveCsv)(events, fullPath);
111
+ console.log(`✅ Saved ${events.length} events to: ${fullPath}`);
112
+ }
113
+ return events;
114
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * as Activity from './activities';
2
2
  export * as ActivityInventories from './activityInventories';
3
+ export * as Events from './events';
3
4
  export * as InventoryType from './inventoryTypes';
4
5
  export * as OauthTokenService from './oauthTokenService';
5
6
  export * as Resource from './resources';
@@ -14,6 +15,7 @@ export { downloadAllUsersCSV } from './users';
14
15
  export { downloadAllInventoryTypesCSV, getInventoryTypesDetail, updateCreateInventoryType } from './inventoryTypes';
15
16
  export { getAllActivities } from './activities';
16
17
  export { createActivityCustomerInventories, getActivityCustomerInventories } from './activityInventories';
18
+ export { downloadAllEventsOfDay, downloadAllEventsOfDayCSV } from './events';
17
19
  declare const OfscUtility: {
18
20
  getOAuthToken: any;
19
21
  downloadWorkZoneCSV: any;
@@ -25,5 +27,7 @@ declare const OfscUtility: {
25
27
  getAllActivities: any;
26
28
  getActivityCustomerInventories: any;
27
29
  createActivityCustomerInventories: any;
30
+ downloadAllEventsOfDayCSV: any;
31
+ downloadAllEventsOfDay: any;
28
32
  };
29
33
  export default OfscUtility;
package/dist/index.js CHANGED
@@ -36,10 +36,11 @@ 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.getActivityCustomerInventories = exports.createActivityCustomerInventories = exports.getAllActivities = exports.updateCreateInventoryType = exports.getInventoryTypesDetail = exports.downloadAllInventoryTypesCSV = exports.downloadAllUsersCSV = exports.downloadAllResourcesCSV = exports.downloadWorkZoneCSV = exports.getOAuthToken = exports.WorkZone = exports.CSV = exports.User = exports.Resource = exports.OauthTokenService = exports.InventoryType = exports.ActivityInventories = exports.Activity = void 0;
39
+ exports.downloadAllEventsOfDayCSV = exports.downloadAllEventsOfDay = exports.getActivityCustomerInventories = exports.createActivityCustomerInventories = exports.getAllActivities = exports.updateCreateInventoryType = exports.getInventoryTypesDetail = exports.downloadAllInventoryTypesCSV = exports.downloadAllUsersCSV = exports.downloadAllResourcesCSV = exports.downloadWorkZoneCSV = exports.getOAuthToken = exports.WorkZone = exports.CSV = exports.User = exports.Resource = exports.OauthTokenService = exports.InventoryType = 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"));
43
+ exports.Events = __importStar(require("./events"));
43
44
  exports.InventoryType = __importStar(require("./inventoryTypes"));
44
45
  exports.OauthTokenService = __importStar(require("./oauthTokenService"));
45
46
  exports.Resource = __importStar(require("./resources"));
@@ -66,6 +67,9 @@ Object.defineProperty(exports, "getAllActivities", { enumerable: true, get: func
66
67
  var activityInventories_1 = require("./activityInventories");
67
68
  Object.defineProperty(exports, "createActivityCustomerInventories", { enumerable: true, get: function () { return activityInventories_1.createActivityCustomerInventories; } });
68
69
  Object.defineProperty(exports, "getActivityCustomerInventories", { enumerable: true, get: function () { return activityInventories_1.getActivityCustomerInventories; } });
70
+ var events_1 = require("./events");
71
+ Object.defineProperty(exports, "downloadAllEventsOfDay", { enumerable: true, get: function () { return events_1.downloadAllEventsOfDay; } });
72
+ Object.defineProperty(exports, "downloadAllEventsOfDayCSV", { enumerable: true, get: function () { return events_1.downloadAllEventsOfDayCSV; } });
69
73
  // Default export with all functionality
70
74
  const OfscUtility = {
71
75
  getOAuthToken: require('./oauthTokenService').getOAuthToken,
@@ -77,6 +81,8 @@ const OfscUtility = {
77
81
  updateInventoryType: require('./inventoryTypes').updateInventoryType,
78
82
  getAllActivities: require('./activities').getAllActivities,
79
83
  getActivityCustomerInventories: require('./activityInventories').getActivityCustomerInventories,
80
- createActivityCustomerInventories: require('./activityInventories').createActivityCustomerInventories
84
+ createActivityCustomerInventories: require('./activityInventories').createActivityCustomerInventories,
85
+ downloadAllEventsOfDayCSV: require('./events').downloadAllEventsOfDayCSV,
86
+ downloadAllEventsOfDay: require('./events').downloadAllEventsOfDay
81
87
  };
82
88
  exports.default = OfscUtility;
package/dist/types.d.ts CHANGED
@@ -39,3 +39,8 @@ export interface InventoryTypePayload {
39
39
  quantityPrecision: number;
40
40
  translations: InventoryTranslation[];
41
41
  }
42
+ export interface EventResponse {
43
+ found?: boolean;
44
+ nextPage?: string;
45
+ items?: any[];
46
+ }
@@ -74,6 +74,9 @@ function saveCsv(rows, filePath) {
74
74
  function escapeCsvValue(value) {
75
75
  if (value == null)
76
76
  return "";
77
+ if (typeof value === "object") {
78
+ value = JSON.stringify(value);
79
+ }
77
80
  const str = String(value);
78
81
  // Wrap in quotes if needed
79
82
  if (str.includes(",") || str.includes('"') || str.includes("\n")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofsc-utility",
3
- "version": "1.0.9",
3
+ "version": "1.0.10",
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
@@ -25,10 +25,11 @@ Please see the code snippet below.
25
25
 
26
26
  #### csv
27
27
 
28
- downloadWorkZoneCSV("clientId", "clientSecret", "instanceId")
29
- downloadAllResourcesCSV("clientId", "clientSecret", "instanceId")
30
- downloadAllUsersCSV("clientId", "clientSecret", "instanceId")
31
- downloadAllInventoryTypesCSV("clientId", "clientSecret", "instanceId")
28
+ downloadWorkZoneCSV(process.env.clientID, process.env.clientSecreat, process.env.instanceId)
29
+ downloadAllResourcesCSV(process.env.clientID, process.env.clientSecreat, process.env.instanceId)
30
+ downloadAllUsersCSV(process.env.clientID, process.env.clientSecreat, process.env.instanceId)
31
+ downloadAllInventoryTypesCSV(process.env.clientID, process.env.clientSecreat, process.env.instanceId)
32
+ downloadAllEventsOfDayCSV(process.env.clientID, process.env.clientSecreat, process.env.instanceId, process.env.subscriptionId,"2025-12-05")
32
33
 
33
34
  #### records
34
35
 
@@ -38,6 +39,7 @@ Please see the code snippet below.
38
39
  getAllActivities("clientId", "clientSecret", "instanceId"."resources","dateFrom","dateTo","q","fields")
39
40
  getActivityCustomerInventories("clientId", "clientSecret", "instanceId"."activityId")
40
41
  createActivityCustomerInventories( "clientId", "clientSecret", "instanceId"."activityId","payload")
42
+ downloadAllEventsOfDay(process.env.clientID, process.env.clientSecreat, process.env.instanceId, process.env.subscriptionId,"2025-12-05")
41
43
 
42
44
  ## Usage
43
45
 
@@ -168,6 +170,17 @@ ofs.getActivityCustomerInventories("CLIENT_ID", "CLIENT_SECRET", "INSTANCE_URL",
168
170
  });
169
171
  ```
170
172
 
173
+ ```js
174
+ const ofs = require("ofsc-utility");
175
+ ofs.Events.downloadAllEventsOfDayCSV(
176
+ process.env.clientID,
177
+ process.env.clientSecreat,
178
+ process.env.instanceId,
179
+ process.env.subscriptionId,
180
+ "2025-12-05"
181
+ );
182
+ ```
183
+
171
184
  ## License
172
185
 
173
186
  MIT