ofsc-utility 1.0.8 → 1.0.9

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.
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Fetches all customer inventories related to the given activity.
3
+ *
4
+ * @param {string} clientId - The OFSC client ID.
5
+ * @param {string} clientSecret - The OFSC client secret.
6
+ * @param {string} instanceUrl - The OFSC instance URL.
7
+ * @param {string} activityId - The ID of the activity to fetch customer inventories for.
8
+ *
9
+ * @returns {Promise<any[]>} A promise which resolves to an array of customer inventory objects.
10
+ */
11
+ export declare function getActivityCustomerInventories(clientId: string, clientSecret: string, instanceUrl: string, activityId: string): Promise<any[]>;
12
+ /**
13
+ * Creates a new customer inventory related to the given activity.
14
+ *
15
+ * @param {string} clientId - The OFSC client ID.
16
+ * @param {string} clientSecret - The OFSC client secret.
17
+ * @param {string} instanceUrl - The OFSC instance URL.
18
+ * @param {string} activityId - The ID of the activity to create a customer inventory for.
19
+ * @param {object} payload - The customer inventory payload.
20
+ *
21
+ * @returns {Promise<object>} A promise which resolves to the created customer inventory object.
22
+ */
23
+ export declare function createActivityCustomerInventories(clientId: string, clientSecret: string, instanceUrl: string, activityId: string, payload: {}): Promise<{}>;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getActivityCustomerInventories = getActivityCustomerInventories;
4
+ exports.createActivityCustomerInventories = createActivityCustomerInventories;
5
+ const oauthTokenService_1 = require("../oauthTokenService");
6
+ const utilities_1 = require("../utilities");
7
+ /**
8
+ * Fetches all customer inventories related to the given activity.
9
+ *
10
+ * @param {string} clientId - The OFSC client ID.
11
+ * @param {string} clientSecret - The OFSC client secret.
12
+ * @param {string} instanceUrl - The OFSC instance URL.
13
+ * @param {string} activityId - The ID of the activity to fetch customer inventories for.
14
+ *
15
+ * @returns {Promise<any[]>} A promise which resolves to an array of customer inventory objects.
16
+ */
17
+ async function getActivityCustomerInventories(clientId, clientSecret, instanceUrl, activityId) {
18
+ const limit = 100;
19
+ let offset = 0;
20
+ let token = await (0, oauthTokenService_1.getOAuthToken)(clientId, clientSecret, instanceUrl);
21
+ const allItems = [];
22
+ const fetchCustomerInventories = async (offset) => {
23
+ const params = new URLSearchParams({
24
+ offset: offset.toString(),
25
+ limit: limit.toString()
26
+ });
27
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/activities/${activityId}/customerInventories?${params}`;
28
+ console.log(`➡️ Fetching offset=${offset}, limit=${limit}`);
29
+ const response = await (0, utilities_1.fetchWithRetry)(url, clientId, clientSecret, instanceUrl, token);
30
+ token = response.token;
31
+ const data = response.data;
32
+ if (!data.items || data.items.length === 0) {
33
+ // console.log("✔ No more items found. Stopping pagination.");
34
+ return;
35
+ }
36
+ allItems.push(...data.items);
37
+ console.log(` ✔ Received ${data.items.length} items (Total: ${allItems.length}) for activity ${activityId}`);
38
+ await fetchCustomerInventories(offset + limit);
39
+ };
40
+ await fetchCustomerInventories(offset);
41
+ return allItems;
42
+ }
43
+ /**
44
+ * Creates a new customer inventory related to the given activity.
45
+ *
46
+ * @param {string} clientId - The OFSC client ID.
47
+ * @param {string} clientSecret - The OFSC client secret.
48
+ * @param {string} instanceUrl - The OFSC instance URL.
49
+ * @param {string} activityId - The ID of the activity to create a customer inventory for.
50
+ * @param {object} payload - The customer inventory payload.
51
+ *
52
+ * @returns {Promise<object>} A promise which resolves to the created customer inventory object.
53
+ */
54
+ async function createActivityCustomerInventories(clientId, clientSecret, instanceUrl, activityId, payload) {
55
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/activities/${activityId}/customerInventories`;
56
+ const token = await (0, oauthTokenService_1.getOAuthToken)(clientId, clientSecret, instanceUrl);
57
+ const res = await fetch(url, {
58
+ method: "POST",
59
+ headers: {
60
+ Authorization: `Bearer ${token}`,
61
+ Accept: "application/json",
62
+ "Content-Type": "application/json"
63
+ },
64
+ body: JSON.stringify(payload)
65
+ });
66
+ if (!res.ok) {
67
+ throw new Error(`❌ POST failed: ${res.status} ${res.statusText}`);
68
+ }
69
+ return await res.json();
70
+ }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export * as Activity from './activities';
2
+ export * as ActivityInventories from './activityInventories';
2
3
  export * as InventoryType from './inventoryTypes';
3
4
  export * as OauthTokenService from './oauthTokenService';
4
5
  export * as Resource from './resources';
5
6
  export * as User from './users';
7
+ export * as CSV from './utilities';
6
8
  export * as WorkZone from './workZones';
7
9
  export * from './types';
8
10
  export { getOAuthToken } from './oauthTokenService';
@@ -11,6 +13,7 @@ export { downloadAllResourcesCSV } from './resources';
11
13
  export { downloadAllUsersCSV } from './users';
12
14
  export { downloadAllInventoryTypesCSV, getInventoryTypesDetail, updateCreateInventoryType } from './inventoryTypes';
13
15
  export { getAllActivities } from './activities';
16
+ export { createActivityCustomerInventories, getActivityCustomerInventories } from './activityInventories';
14
17
  declare const OfscUtility: {
15
18
  getOAuthToken: any;
16
19
  downloadWorkZoneCSV: any;
@@ -20,5 +23,7 @@ declare const OfscUtility: {
20
23
  getInventoryTypesDetail: any;
21
24
  updateInventoryType: any;
22
25
  getAllActivities: any;
26
+ getActivityCustomerInventories: any;
27
+ createActivityCustomerInventories: any;
23
28
  };
24
29
  export default OfscUtility;
package/dist/index.js CHANGED
@@ -36,13 +36,15 @@ 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.getAllActivities = exports.updateCreateInventoryType = exports.getInventoryTypesDetail = exports.downloadAllInventoryTypesCSV = exports.downloadAllUsersCSV = exports.downloadAllResourcesCSV = exports.downloadWorkZoneCSV = exports.getOAuthToken = exports.WorkZone = exports.User = exports.Resource = exports.OauthTokenService = exports.InventoryType = exports.Activity = void 0;
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;
40
40
  // Export all methods grouped by category
41
41
  exports.Activity = __importStar(require("./activities"));
42
+ exports.ActivityInventories = __importStar(require("./activityInventories"));
42
43
  exports.InventoryType = __importStar(require("./inventoryTypes"));
43
44
  exports.OauthTokenService = __importStar(require("./oauthTokenService"));
44
45
  exports.Resource = __importStar(require("./resources"));
45
46
  exports.User = __importStar(require("./users"));
47
+ exports.CSV = __importStar(require("./utilities"));
46
48
  exports.WorkZone = __importStar(require("./workZones"));
47
49
  // Export types
48
50
  __exportStar(require("./types"), exports);
@@ -61,9 +63,11 @@ Object.defineProperty(exports, "getInventoryTypesDetail", { enumerable: true, ge
61
63
  Object.defineProperty(exports, "updateCreateInventoryType", { enumerable: true, get: function () { return inventoryTypes_1.updateCreateInventoryType; } });
62
64
  var activities_1 = require("./activities");
63
65
  Object.defineProperty(exports, "getAllActivities", { enumerable: true, get: function () { return activities_1.getAllActivities; } });
66
+ var activityInventories_1 = require("./activityInventories");
67
+ Object.defineProperty(exports, "createActivityCustomerInventories", { enumerable: true, get: function () { return activityInventories_1.createActivityCustomerInventories; } });
68
+ Object.defineProperty(exports, "getActivityCustomerInventories", { enumerable: true, get: function () { return activityInventories_1.getActivityCustomerInventories; } });
64
69
  // Default export with all functionality
65
70
  const OfscUtility = {
66
- // Case converters
67
71
  getOAuthToken: require('./oauthTokenService').getOAuthToken,
68
72
  downloadWorkZoneCSV: require('./workZones').downloadWorkZoneCSV,
69
73
  downloadAllResourcesCSV: require('./resources').downloadAllResourcesCSV,
@@ -71,6 +75,8 @@ const OfscUtility = {
71
75
  downloadAllInventoryTypesCSV: require('./inventoryTypes').downloadAllInventoryTypesCSV,
72
76
  getInventoryTypesDetail: require('./inventoryTypes').getInventoryTypesDetail,
73
77
  updateInventoryType: require('./inventoryTypes').updateInventoryType,
74
- getAllActivities: require('./activities').getAllActivities
78
+ getAllActivities: require('./activities').getAllActivities,
79
+ getActivityCustomerInventories: require('./activityInventories').getActivityCustomerInventories,
80
+ createActivityCustomerInventories: require('./activityInventories').createActivityCustomerInventories
75
81
  };
76
82
  exports.default = OfscUtility;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Fetches a URL with retry logic for expired tokens.
3
+ *
4
+ * @param {string} url - The URL to fetch.
5
+ * @param {string} clientId - The OFSC client ID.
6
+ * @param {string} clientSecret - The OFSC client secret.
7
+ * @param {string} instanceUrl - The OFSC instance URL.
8
+ * @param {string} token - The current OAuth token.
9
+ *
10
+ * @returns {Promise<{ data: any; token: string }>} A promise which resolves to an object containing the parsed JSON data and the latest OAuth token.
11
+ */
12
+ export declare const fetchWithRetry: (url: string, clientId: string, clientSecret: string, instanceUrl: string, token: string) => Promise<{
13
+ data: any;
14
+ token: string;
15
+ }>;
16
+ export declare function saveCsv<T extends Record<string, any>>(rows: T[], filePath: string): void;
@@ -1 +1,83 @@
1
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.fetchWithRetry = void 0;
7
+ exports.saveCsv = saveCsv;
8
+ const oauthTokenService_1 = require("../oauthTokenService");
9
+ /**
10
+ * Fetches a URL with retry logic for expired tokens.
11
+ *
12
+ * @param {string} url - The URL to fetch.
13
+ * @param {string} clientId - The OFSC client ID.
14
+ * @param {string} clientSecret - The OFSC client secret.
15
+ * @param {string} instanceUrl - The OFSC instance URL.
16
+ * @param {string} token - The current OAuth token.
17
+ *
18
+ * @returns {Promise<{ data: any; token: string }>} A promise which resolves to an object containing the parsed JSON data and the latest OAuth token.
19
+ */
20
+ const fetchWithRetry = async (url, clientId, clientSecret, instanceUrl, token) => {
21
+ const doFetch = async (bearer) => {
22
+ return fetch(url, {
23
+ method: "GET",
24
+ headers: {
25
+ Authorization: `Bearer ${bearer}`,
26
+ Accept: "application/json"
27
+ }
28
+ });
29
+ };
30
+ // Try with the current token
31
+ let res = await doFetch(token);
32
+ // If 401 → renew and retry
33
+ if (res.status === 401) {
34
+ console.warn("⚠️ Token expired — renewing token…");
35
+ token = await (0, oauthTokenService_1.getOAuthToken)(clientId, clientSecret, instanceUrl);
36
+ res = await doFetch(token);
37
+ }
38
+ // If still not OK → fail
39
+ if (!res.ok) {
40
+ const body = await res.text();
41
+ throw new Error(`❌ Request failed: ${res.status} ${res.statusText}\n${body}`);
42
+ }
43
+ // Return parsed JSON + latest token
44
+ return {
45
+ data: await res.json(),
46
+ token
47
+ };
48
+ };
49
+ exports.fetchWithRetry = fetchWithRetry;
50
+ const fs_1 = __importDefault(require("fs"));
51
+ const path_1 = __importDefault(require("path"));
52
+ function saveCsv(rows, filePath) {
53
+ if (!rows || rows.length === 0) {
54
+ throw new Error("CSV creation failed: no rows provided.");
55
+ }
56
+ // Extract headers from the first row
57
+ const headers = Object.keys(rows[0]);
58
+ // Build CSV content
59
+ const csvLines = [
60
+ headers.join(","), // header row
61
+ ...rows.map(row => headers.map(h => escapeCsvValue(row[h])).join(","))
62
+ ];
63
+ const csvContent = csvLines.join("\n");
64
+ // Ensure directory exists
65
+ const dir = path_1.default.dirname(filePath);
66
+ if (!fs_1.default.existsSync(dir)) {
67
+ fs_1.default.mkdirSync(dir, { recursive: true });
68
+ }
69
+ // Write the file
70
+ fs_1.default.writeFileSync(filePath, csvContent);
71
+ console.log(`CSV saved: ${filePath}`);
72
+ }
73
+ // Escape CSV fields
74
+ function escapeCsvValue(value) {
75
+ if (value == null)
76
+ return "";
77
+ const str = String(value);
78
+ // Wrap in quotes if needed
79
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
80
+ return `"${str.replace(/"/g, '""')}"`;
81
+ }
82
+ return str;
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofsc-utility",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
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
@@ -21,41 +21,36 @@ npm install ofsc-utility
21
21
 
22
22
  ### Download
23
23
 
24
- Please see the code snippet below.
24
+ Please see the code snippet below.
25
25
 
26
- #### csv
26
+ #### csv
27
27
 
28
28
  downloadWorkZoneCSV("clientId", "clientSecret", "instanceId")
29
29
  downloadAllResourcesCSV("clientId", "clientSecret", "instanceId")
30
30
  downloadAllUsersCSV("clientId", "clientSecret", "instanceId")
31
31
  downloadAllInventoryTypesCSV("clientId", "clientSecret", "instanceId")
32
-
33
-
34
- #### records
32
+
33
+ #### records
35
34
 
36
35
  getOAuthToken("clientId", "clientSecret", "instanceId")
37
36
  getInventoryTypesDetail("clientId", "clientSecret", "instanceId"."inventory_label")
38
37
  updateCreateInventoryType("clientId", "clientSecret", "instanceId"."inventory_label")
39
38
  getAllActivities("clientId", "clientSecret", "instanceId"."resources","dateFrom","dateTo","q","fields")
40
-
41
-
39
+ getActivityCustomerInventories("clientId", "clientSecret", "instanceId"."activityId")
40
+ createActivityCustomerInventories( "clientId", "clientSecret", "instanceId"."activityId","payload")
42
41
 
43
42
  ## Usage
44
43
 
45
- downloadWorkZoneCSV("bot", "XXXXXXXXX", "compXXX.test")
44
+ downloadWorkZoneCSV("bot", "XXXXXXXXX", "compXXX.test")
46
45
 
47
46
  ### CommonJS
48
47
 
49
48
  ```js
50
-
51
- async function run (){
52
- let data = await ofs.InventoryType.getInventoryTypesDetail(
53
- "clientId", "clientSecret", "instanceId", "inventory_label");
54
- console.error(data);
49
+ async function run() {
50
+ let data = await ofs.InventoryType.getInventoryTypesDetail("clientId", "clientSecret", "instanceId", "inventory_label");
51
+ console.error(data);
55
52
  }
56
53
  run();
57
-
58
-
59
54
  ```
60
55
 
61
56
  ```js
@@ -110,44 +105,37 @@ ofs
110
105
  ```
111
106
 
112
107
  ```js
113
- const ofs = require('ofsc-utility');
108
+ const ofs = require("ofsc-utility");
114
109
 
115
110
  async function run() {
116
- const payload = {
117
- label: "inventory_label",
111
+ const payload = {
112
+ label: "inventory_label",
113
+ name: "Ordered Part",
114
+ unitOfMeasurement: "ea",
115
+ active: true,
116
+ nonSerialized: true,
117
+ modelProperty: "part_item_number_rev",
118
+ quantityPrecision: 0,
119
+ translations: [
120
+ {
121
+ language: "en",
118
122
  name: "Ordered Part",
119
123
  unitOfMeasurement: "ea",
120
- active: true,
121
- nonSerialized: true,
122
- modelProperty: "part_item_number_rev",
123
- quantityPrecision: 0,
124
- translations: [
125
- {
126
- language: "en",
127
- name: "Ordered Part",
128
- unitOfMeasurement: "ea",
129
- languageISO: "en-US"
130
- }
131
- ]
132
- };
133
-
134
- try {
135
- const result = await updateCreateInventoryType(
136
- "CLIENT_ID",
137
- "CLIENT_SECRET",
138
- "INSTANCE_URL",
139
- "inventory_label",
140
- payload
141
- );
142
-
143
- console.log("Updated:", result);
144
- } catch (err) {
145
- console.error(err);
146
- }
124
+ languageISO: "en-US",
125
+ },
126
+ ],
127
+ };
128
+
129
+ try {
130
+ const result = await updateCreateInventoryType("CLIENT_ID", "CLIENT_SECRET", "INSTANCE_URL", "inventory_label", payload);
131
+
132
+ console.log("Updated:", result);
133
+ } catch (err) {
134
+ console.error(err);
135
+ }
147
136
  }
148
137
 
149
138
  run();
150
-
151
139
  ```
152
140
 
153
141
  ```js
@@ -174,6 +162,12 @@ async function run() {
174
162
  run();
175
163
  ```
176
164
 
165
+ ```js
166
+ ofs.getActivityCustomerInventories("CLIENT_ID", "CLIENT_SECRET", "INSTANCE_URL", "activityId").then((data) => {
167
+ console.log(data);
168
+ });
169
+ ```
170
+
177
171
  ## License
178
172
 
179
173
  MIT