ofsc-utility 1.0.18 → 1.0.20

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.
@@ -4,4 +4,13 @@ type AnyObject = {
4
4
  export declare function flattenObject(obj: AnyObject, parentKey?: string, result?: AnyObject): AnyObject;
5
5
  export declare function downloadAllEventsOfDay(clientId: string, clientSecret: string, instanceUrl: string, subscriptionId: string, sinceDate: string, onlyData: boolean): Promise<any[]>;
6
6
  export declare function downloadAllEventsOfDayCSV(clientId: string, clientSecret: string, instanceUrl: string, subscriptionId: string, sinceDate: string, onlyData: boolean): Promise<any[]>;
7
+ /**
8
+ * Events of last two minutes
9
+ * @param clientId
10
+ * @param clientSecret
11
+ * @param instanceUrl
12
+ * @param subscriptionId
13
+ * @returns
14
+ */
15
+ export declare function downloadAllEventsOfDLastTwoMinutes(clientId: string, clientSecret: string, instanceUrl: string, subscriptionId: string): Promise<any[]>;
7
16
  export {};
@@ -6,9 +6,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.flattenObject = flattenObject;
7
7
  exports.downloadAllEventsOfDay = downloadAllEventsOfDay;
8
8
  exports.downloadAllEventsOfDayCSV = downloadAllEventsOfDayCSV;
9
+ exports.downloadAllEventsOfDLastTwoMinutes = downloadAllEventsOfDLastTwoMinutes;
9
10
  const path_1 = __importDefault(require("path"));
10
11
  const index_1 = require("../oauthTokenService/index");
11
12
  const utilities_1 = require("../utilities");
13
+ const index_2 = require("../utilities/index");
12
14
  function flattenObject(obj, parentKey = "", result = {}) {
13
15
  for (const key in obj) {
14
16
  const newKey = parentKey ? `${parentKey}_${key}` : key;
@@ -124,3 +126,70 @@ async function downloadAllEventsOfDayCSV(clientId, clientSecret, instanceUrl, su
124
126
  }
125
127
  return events;
126
128
  }
129
+ /**
130
+ * Events of last two minutes
131
+ * @param clientId
132
+ * @param clientSecret
133
+ * @param instanceUrl
134
+ * @param subscriptionId
135
+ * @returns
136
+ */
137
+ async function downloadAllEventsOfDLastTwoMinutes(clientId, clientSecret, instanceUrl, subscriptionId) {
138
+ // All collected events
139
+ const events = [];
140
+ const since = (0, index_2.getTimeBefore180SecondsAlt)();
141
+ let isValidate = (0, index_2.validateDateTimeStrict)(since);
142
+ if (!isValidate.isValid) {
143
+ throw new Error(isValidate.error);
144
+ }
145
+ // Build initial request URL
146
+ const baseUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/events`;
147
+ const initialUrl = `${baseUrl}?subscriptionId=${encodeURIComponent(subscriptionId)}&since=${encodeURIComponent(since)}`;
148
+ console.log("sinceDate", since);
149
+ let token = await (0, index_1.getOAuthToken)(clientId, clientSecret, instanceUrl);
150
+ // Get first page
151
+ let firstPage = await fetchEventsPage(initialUrl, token, clientId, clientSecret, instanceUrl);
152
+ token = firstPage.token;
153
+ let nextPage = firstPage.data.nextPage;
154
+ let found = firstPage.data.found;
155
+ // Controls infinite loop
156
+ let lastSeenPage = nextPage;
157
+ let repeatedPageCount = 0;
158
+ // Loop through pages
159
+ while (found && nextPage) {
160
+ const pageUrl = new URL(baseUrl);
161
+ pageUrl.search = new URLSearchParams({
162
+ subscriptionId,
163
+ page: nextPage,
164
+ limit: "1000",
165
+ }).toString();
166
+ const finalUrl = pageUrl.toString();
167
+ const result = await fetchEventsPage(finalUrl, token, clientId, clientSecret, instanceUrl);
168
+ token = result.token;
169
+ const page = result.data;
170
+ found = page.found;
171
+ nextPage = page.nextPage;
172
+ console.error("nextPage", nextPage, "Records:", page.items?.length, "Time:", page.items?.[0]?.time);
173
+ // Prevent infinite looping
174
+ if (nextPage === lastSeenPage) {
175
+ repeatedPageCount++;
176
+ if (repeatedPageCount > 10) {
177
+ console.warn("⚠️ Pagination repeating same page more than 10 times. Stopping.");
178
+ break;
179
+ }
180
+ }
181
+ else {
182
+ lastSeenPage = nextPage;
183
+ repeatedPageCount = 0;
184
+ }
185
+ // Add events
186
+ if (!page.items) {
187
+ console.warn("⚠️ No items found in page. Stopping.");
188
+ break;
189
+ }
190
+ for (let k of page.items) {
191
+ events.push(k);
192
+ }
193
+ }
194
+ return events;
195
+ }
@@ -11,7 +11,7 @@ async function getCapacityMetaData(clientId, clientSecret, instanceUrl, token =
11
11
  const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscMetadata/v1/capacityAreas?offset=${offset}&limit=${limit}`;
12
12
  const res = await (0, utilities_1.fetchWithRetry)(url, clientId, clientSecret, instanceUrl, token);
13
13
  token = res.token;
14
- responsedata = [...responsedata, ...res.data.items];
14
+ responsedata = [...responsedata, ...res.data?.items || []];
15
15
  if (!res.data.hasMore)
16
16
  break;
17
17
  offset = res.data.offset + limit;
@@ -46,7 +46,7 @@ async function capacitycategoriesOfacapacityArea(clientId, clientSecret, instanc
46
46
  const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscMetadata/v1/capacityAreas/${capacityArea.label}/capacityCategories`;
47
47
  const res = await (0, utilities_1.fetchWithRetry)(url, clientId, clientSecret, instanceUrl, token);
48
48
  token = res.token;
49
- for (const category of res.data.items) {
49
+ for (const category of res.data?.items || []) {
50
50
  data.push({
51
51
  "capacityArea": capacityArea.label,
52
52
  "Capacity Category": category.name,
@@ -18,4 +18,15 @@ export declare function xmlNodeToObjects(xmlString: string, parentNodeName: stri
18
18
  type SheetRow = Record<string, unknown>;
19
19
  type SheetsData = Record<string, SheetRow[]>;
20
20
  export declare function createExcelFile(sheetsData: SheetsData, filename?: string): void;
21
+ interface ValidationResult {
22
+ isValid: boolean;
23
+ error?: string;
24
+ }
25
+ /**
26
+ * Validate Date String Format must be YYYY-MM-DD HH:MM:SS
27
+ * @param dateTimeStr :string
28
+ * @returns
29
+ */
30
+ export declare function validateDateTimeStrict(dateTimeStr: string): ValidationResult;
31
+ export declare function getTimeBefore180SecondsAlt(): string;
21
32
  export {};
@@ -40,6 +40,8 @@ exports.fetchWithRetry = void 0;
40
40
  exports.saveCsv = saveCsv;
41
41
  exports.xmlNodeToObjects = xmlNodeToObjects;
42
42
  exports.createExcelFile = createExcelFile;
43
+ exports.validateDateTimeStrict = validateDateTimeStrict;
44
+ exports.getTimeBefore180SecondsAlt = getTimeBefore180SecondsAlt;
43
45
  const XLSX = __importStar(require("xlsx-js-style"));
44
46
  const xmldom_1 = require("xmldom");
45
47
  const oauthTokenService_1 = require("../oauthTokenService");
@@ -271,3 +273,40 @@ function createExcelFile(sheetsData, filename = 'file.xlsx') {
271
273
  XLSX.writeFile(workbook, filename);
272
274
  console.log(`✓ Excel file created: ${filename}`);
273
275
  }
276
+ /**
277
+ * Validate Date String Format must be YYYY-MM-DD HH:MM:SS
278
+ * @param dateTimeStr :string
279
+ * @returns
280
+ */
281
+ function validateDateTimeStrict(dateTimeStr) {
282
+ const regex = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
283
+ const match = dateTimeStr.match(regex);
284
+ if (!match) {
285
+ return { isValid: false, error: 'Format must be YYYY-MM-DD HH:MM:SS' };
286
+ }
287
+ const [, year, month, day, hours, minutes, seconds] = match.map(Number);
288
+ if (month < 1 || month > 12) {
289
+ return { isValid: false, error: 'Month must be between 1 and 12' };
290
+ }
291
+ const daysInMonth = new Date(year, month, 0).getDate();
292
+ if (day < 1 || day > daysInMonth) {
293
+ return { isValid: false, error: `Day must be between 1 and ${daysInMonth}` };
294
+ }
295
+ if (hours < 0 || hours > 23) {
296
+ return { isValid: false, error: 'Hours must be between 0 and 23' };
297
+ }
298
+ if (minutes < 0 || minutes > 59) {
299
+ return { isValid: false, error: 'Minutes must be between 0 and 59' };
300
+ }
301
+ if (seconds < 0 || seconds > 59) {
302
+ return { isValid: false, error: 'Seconds must be between 0 and 59' };
303
+ }
304
+ return { isValid: true };
305
+ }
306
+ function getTimeBefore180SecondsAlt() {
307
+ const timeBefore = new Date(Date.now() - 180000); // 180 * 1000 = 180000
308
+ // Convert to ISO string and format
309
+ return timeBefore.toISOString()
310
+ .replace('T', ' ')
311
+ .substring(0, 19);
312
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofsc-utility",
3
- "version": "1.0.18",
3
+ "version": "1.0.20",
4
4
  "description": "A wrapper for Oracle Field Service REST API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",