sos-inventory-db 1.0.0
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.
- package/LICENSE +23 -0
- package/README.md +226 -0
- package/dist/index.cjs +216 -0
- package/dist/index.mjs +224 -0
- package/package.json +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Copyright (c) 2024–2026 Chris Rowley
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# **sos-inventory-db**
|
|
2
|
+
|
|
3
|
+
A schema‑driven relational database model for **SOS Inventory**, including:
|
|
4
|
+
|
|
5
|
+
- Fully documented API contract definitions
|
|
6
|
+
- Deterministic ingestion of *all* SOS objects
|
|
7
|
+
- Multi‑engine database support (SQLite, PostgreSQL, MariaDB, MySQL, SQL Server)
|
|
8
|
+
- A single, stable entry point: **`downloadSOS()`**
|
|
9
|
+
- Clean, normalized relational tables generated from real SOS payloads
|
|
10
|
+
|
|
11
|
+
This package gives you a **local, queryable mirror** of your SOS Inventory data — built from the *actual* API payloads, not the inconsistent documentation.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## **Features**
|
|
16
|
+
|
|
17
|
+
- 🚀 **One function**: `downloadSOS(params)`
|
|
18
|
+
- 🧱 **Schema‑driven**: every table is defined in `db/definitions.js`
|
|
19
|
+
- 🔄 **Deterministic ingestion**: same results across all engines
|
|
20
|
+
- 🗄️ **Multi‑database support**:
|
|
21
|
+
- SQLite (default, zero config)
|
|
22
|
+
- PostgreSQL
|
|
23
|
+
- MariaDB
|
|
24
|
+
- MySQL
|
|
25
|
+
- SQL Server
|
|
26
|
+
- 📦 **Dual‑module build**: CommonJS + ESM
|
|
27
|
+
- 🧪 **Optional DB drivers** — install only what you need
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## **Installation**
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm install sos-inventory-db
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Optional: install the driver for your database engine:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm install better-sqlite3
|
|
41
|
+
npm install pg
|
|
42
|
+
npm install mariadb
|
|
43
|
+
npm install mysql2
|
|
44
|
+
npm install mssql
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## **Quickstart**
|
|
50
|
+
|
|
51
|
+
### ESM
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
import downloadSOS from 'sos-inventory-db'
|
|
55
|
+
// or: const downloadSOS = require('sos-inventory-db')
|
|
56
|
+
|
|
57
|
+
await downloadSOS({
|
|
58
|
+
database: {
|
|
59
|
+
engine: 'sqlite',
|
|
60
|
+
filename: './sos.db'
|
|
61
|
+
},
|
|
62
|
+
sosAuthorization: process.env.SOS_AUTH
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### CommonJS
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
const downloadSOS = require('sos-inventory-db')
|
|
70
|
+
|
|
71
|
+
downloadSOS({
|
|
72
|
+
database: {
|
|
73
|
+
engine: 'sqlite',
|
|
74
|
+
filename: './sos.db'
|
|
75
|
+
},
|
|
76
|
+
sosAuthorization: process.env.SOS_AUTH
|
|
77
|
+
})
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
This will:
|
|
81
|
+
|
|
82
|
+
- Create all tables defined in `db/definitions.js`
|
|
83
|
+
- Fetch all SOS Inventory objects
|
|
84
|
+
- Normalize them into relational tables
|
|
85
|
+
- Insert them into your chosen database engine
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## **Engine Configuration**
|
|
90
|
+
|
|
91
|
+
`sos-inventory-db` accepts a `database` object describing the engine and connection parameters.
|
|
92
|
+
|
|
93
|
+
Here is the full interface:
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
const testDatabases = {
|
|
97
|
+
sqlite: {
|
|
98
|
+
engine: 'sqlite',
|
|
99
|
+
filename: 'db/wdm.db'
|
|
100
|
+
},
|
|
101
|
+
mariadb: {
|
|
102
|
+
engine: 'mariadb',
|
|
103
|
+
host: process.env.MARIADB_HOST,
|
|
104
|
+
port: process.env.MARIADB_PORT,
|
|
105
|
+
user: process.env.MARIADB_USER,
|
|
106
|
+
password: process.env.MARIADB_PASSWORD,
|
|
107
|
+
database: process.env.MARIADB_DATABASE
|
|
108
|
+
},
|
|
109
|
+
postgres: {
|
|
110
|
+
engine: 'postgres',
|
|
111
|
+
host: process.env.POSTGRESQL_HOST,
|
|
112
|
+
port: process.env.POSTGRESQL_PORT,
|
|
113
|
+
user: process.env.POSTGRESQL_USER,
|
|
114
|
+
password: process.env.POSTGRESQL_PASSWORD,
|
|
115
|
+
database: process.env.POSTGRESQL_DATABASE
|
|
116
|
+
},
|
|
117
|
+
mssql: {
|
|
118
|
+
engine: 'mssql',
|
|
119
|
+
server: process.env.MSSQL_SERVER,
|
|
120
|
+
port: Number(process.env.MSSQL_PORT),
|
|
121
|
+
authentication: {
|
|
122
|
+
type: 'default',
|
|
123
|
+
options: {
|
|
124
|
+
userName: process.env.MSSQL_USER,
|
|
125
|
+
password: process.env.MSSQL_PASSWORD
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
options: {
|
|
129
|
+
database: process.env.MSSQL_DATABASE,
|
|
130
|
+
encrypt: true,
|
|
131
|
+
trustServerCertificate: true,
|
|
132
|
+
enableArithAbort: true
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Pass one of these objects to `downloadSOS()`:
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
await downloadSOS({
|
|
142
|
+
database: testDatabases.postgres,
|
|
143
|
+
sosAuthorization: process.env.SOS_AUTH
|
|
144
|
+
})
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## **Authentication**
|
|
150
|
+
|
|
151
|
+
You must provide a valid SOS Inventory API token:
|
|
152
|
+
|
|
153
|
+
```js
|
|
154
|
+
await downloadSOS({
|
|
155
|
+
database,
|
|
156
|
+
sosAuthorization: 'Bearer <your-token-here>'
|
|
157
|
+
})
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Or via environment variable:
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
export SOS_AUTH="Bearer <token>"
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## **What Gets Created**
|
|
169
|
+
|
|
170
|
+
`sos-inventory-db` builds a complete relational mirror of your SOS Inventory account, including:
|
|
171
|
+
|
|
172
|
+
- Items
|
|
173
|
+
- Item BOMs
|
|
174
|
+
- Customers
|
|
175
|
+
- Vendors
|
|
176
|
+
- Sales Orders
|
|
177
|
+
- Purchase Orders
|
|
178
|
+
- Invoices
|
|
179
|
+
- Payments
|
|
180
|
+
- Locations
|
|
181
|
+
- Categories
|
|
182
|
+
- Adjustments
|
|
183
|
+
- And all supporting lookup tables
|
|
184
|
+
|
|
185
|
+
Every table is defined in:
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
db/definitions.js
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
This file is the single source of truth for:
|
|
192
|
+
|
|
193
|
+
- Table names
|
|
194
|
+
- Field types
|
|
195
|
+
- Nullability
|
|
196
|
+
- Primary keys
|
|
197
|
+
- Reference mappings
|
|
198
|
+
- Read‑only fields
|
|
199
|
+
- API contract definitions
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
## **Why This Exists**
|
|
204
|
+
|
|
205
|
+
SOS Inventory’s API documentation is:
|
|
206
|
+
|
|
207
|
+
- incomplete
|
|
208
|
+
- inconsistent
|
|
209
|
+
- sometimes incorrect
|
|
210
|
+
- and often out of sync with real payloads
|
|
211
|
+
|
|
212
|
+
This package solves that by:
|
|
213
|
+
|
|
214
|
+
- capturing the *actual* API responses
|
|
215
|
+
- documenting the real schema
|
|
216
|
+
- normalizing everything into relational tables
|
|
217
|
+
- providing a deterministic ingestion engine
|
|
218
|
+
- supporting multiple SQL backends
|
|
219
|
+
|
|
220
|
+
The result is a stable, queryable, local mirror of your SOS data.
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## **License**
|
|
225
|
+
|
|
226
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const openDb = require("./db/database.js");
|
|
3
|
+
const createTable = require("./db/create-table.js");
|
|
4
|
+
const insertRow = require("./db/insert-row.js");
|
|
5
|
+
const { tables, supportTables } = require("./db/definitions.js");
|
|
6
|
+
function formatRuntime(ms) {
|
|
7
|
+
const totalSeconds = Math.floor(ms / 1e3);
|
|
8
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
9
|
+
const minutes = Math.floor(totalSeconds % 3600 / 60);
|
|
10
|
+
const seconds = totalSeconds % 60;
|
|
11
|
+
return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
|
|
12
|
+
}
|
|
13
|
+
async function sosApi(url, method, authorization, retries = 5) {
|
|
14
|
+
console.log(url);
|
|
15
|
+
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
16
|
+
try {
|
|
17
|
+
const res = await fetch(url, {
|
|
18
|
+
method,
|
|
19
|
+
headers: {
|
|
20
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
21
|
+
Accept: "*/*",
|
|
22
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
23
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
24
|
+
Host: "api.sosinventory.com",
|
|
25
|
+
Authorization: authorization
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
if (!res.ok) {
|
|
29
|
+
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
|
30
|
+
}
|
|
31
|
+
return await res.json();
|
|
32
|
+
} catch (err) {
|
|
33
|
+
if (attempt === retries) throw err;
|
|
34
|
+
const delay = 250 * attempt;
|
|
35
|
+
console.log(`Retry ${attempt}/${retries} after error: ${err.message}`);
|
|
36
|
+
console.log(url);
|
|
37
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function downloadTable(params, engine, table) {
|
|
42
|
+
const ctResult = await createTable(engine, table);
|
|
43
|
+
if (!ctResult.ok) return ctResult;
|
|
44
|
+
const retries = params.retries ?? 5;
|
|
45
|
+
let offset = 1;
|
|
46
|
+
await engine.begin();
|
|
47
|
+
while (true) {
|
|
48
|
+
const result = await sosApi(
|
|
49
|
+
`https://api.sosinventory.com${table.api.query.endpoint}?start=${offset}&maxresults=200`,
|
|
50
|
+
table.api.query.method,
|
|
51
|
+
params.sosAuthorization,
|
|
52
|
+
retries
|
|
53
|
+
);
|
|
54
|
+
if (result.status !== "ok") {
|
|
55
|
+
await engine.rollback();
|
|
56
|
+
return { ok: false, message: result.message || "SOS API returned non-ok status" };
|
|
57
|
+
}
|
|
58
|
+
if (!Array.isArray(result.data)) {
|
|
59
|
+
await engine.rollback();
|
|
60
|
+
return { ok: false, message: "SOS API returned invalid data array" };
|
|
61
|
+
}
|
|
62
|
+
if (typeof result.count !== "number" || typeof result.totalCount !== "number") {
|
|
63
|
+
await engine.rollback();
|
|
64
|
+
return { ok: false, message: "SOS API returned invalid pagination fields" };
|
|
65
|
+
}
|
|
66
|
+
for (const record of result.data) {
|
|
67
|
+
delete record.keys;
|
|
68
|
+
delete record.values;
|
|
69
|
+
const irResult = await insertRow(engine, table, record);
|
|
70
|
+
if (!irResult.ok) {
|
|
71
|
+
await engine.rollback();
|
|
72
|
+
return { ok: false, message: irResult };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
offset += result.count;
|
|
76
|
+
if (offset > result.totalCount) break;
|
|
77
|
+
}
|
|
78
|
+
await engine.commit();
|
|
79
|
+
return { ok: true };
|
|
80
|
+
}
|
|
81
|
+
async function handleSupportTable(engine, table) {
|
|
82
|
+
await createTable(engine, table);
|
|
83
|
+
const supportMap = /* @__PURE__ */ new Map();
|
|
84
|
+
for (const sourceTable of table.sourceTables) {
|
|
85
|
+
const rows = await engine.query(
|
|
86
|
+
`SELECT DISTINCT ${engine.q(table.sourceField)} FROM ${engine.q(sourceTable)} WHERE ${engine.q(table.sourceField)} IS NOT NULL`,
|
|
87
|
+
[],
|
|
88
|
+
true
|
|
89
|
+
);
|
|
90
|
+
for (const row of rows) {
|
|
91
|
+
let obj;
|
|
92
|
+
try {
|
|
93
|
+
obj = row[table.sourceField];
|
|
94
|
+
if (typeof obj !== "object") obj = JSON.parse(obj);
|
|
95
|
+
} catch (err) {
|
|
96
|
+
console.error(`Invalid JSON in ${table.name}:`, row[table.sourceField]);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (!obj || typeof obj !== "object") continue;
|
|
100
|
+
const key = obj.id ?? obj.value ?? obj.code ?? obj.name;
|
|
101
|
+
if (!key) continue;
|
|
102
|
+
if (!supportMap.has(key)) {
|
|
103
|
+
supportMap.set(key, {
|
|
104
|
+
id: obj.id ?? obj.value ?? obj.code,
|
|
105
|
+
name: obj.name ?? obj.code ?? obj.value
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
for (const value of supportMap.values()) {
|
|
111
|
+
await insertRow(engine, table, value);
|
|
112
|
+
}
|
|
113
|
+
return { ok: true };
|
|
114
|
+
}
|
|
115
|
+
async function handleItemBoms(params, engine, table) {
|
|
116
|
+
await createTable(engine, table);
|
|
117
|
+
const items = await engine.query("select id from items where type IN ('Assembly', 'Item Group')", [], true);
|
|
118
|
+
const retries = params.retries ?? 5;
|
|
119
|
+
for (const item of items) {
|
|
120
|
+
const result = await sosApi(`https://api.sosinventory.com/api/v2/item/${item.id}/bom`, "GET", params.sosAuthorization, retries);
|
|
121
|
+
if (!result.data) continue;
|
|
122
|
+
if (result.data.lines.length === 0) continue;
|
|
123
|
+
const lines = result.data.lines;
|
|
124
|
+
for (const line of lines) {
|
|
125
|
+
const id = Number(line.lineId);
|
|
126
|
+
delete line.lineId;
|
|
127
|
+
const record = {
|
|
128
|
+
id,
|
|
129
|
+
itemId: item.id,
|
|
130
|
+
...line
|
|
131
|
+
};
|
|
132
|
+
await insertRow(engine, table, record);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { ok: true };
|
|
136
|
+
}
|
|
137
|
+
async function downloadSOS(params) {
|
|
138
|
+
if (!params.database.engine) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
message: "Missing required parameter: params.database.engine",
|
|
142
|
+
error: new Error("params.database.engine is required"),
|
|
143
|
+
extra: null
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
if (!params.sosAuthorization) {
|
|
147
|
+
return {
|
|
148
|
+
ok: false,
|
|
149
|
+
message: "Missing required parameter: params.sosAuthorization",
|
|
150
|
+
error: new Error("params.sosAuthorization is required"),
|
|
151
|
+
extra: null
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
const start = Date.now();
|
|
155
|
+
const engine = await openDb(params.database);
|
|
156
|
+
const referenceTables = tables.filter((table) => table.reference === true);
|
|
157
|
+
for (const table of referenceTables) {
|
|
158
|
+
const result = await downloadTable(params, engine, table);
|
|
159
|
+
if (!result.ok) {
|
|
160
|
+
if (engine.close) await engine.close();
|
|
161
|
+
return {
|
|
162
|
+
ok: false,
|
|
163
|
+
message: `downloadTable failed for ${table.name}`,
|
|
164
|
+
error: result.error || new Error("Unknown downloadTable error"),
|
|
165
|
+
extra: { table: table.name, result }
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const primaryTables = tables.filter((table) => table.primary === true);
|
|
170
|
+
for (const table of primaryTables) {
|
|
171
|
+
const result = await downloadTable(params, engine, table);
|
|
172
|
+
if (!result.ok) {
|
|
173
|
+
if (engine.close) await engine.close();
|
|
174
|
+
return {
|
|
175
|
+
ok: false,
|
|
176
|
+
message: `downloadTable failed for ${table.name}`,
|
|
177
|
+
error: result.error || new Error("Unknown downloadTable error"),
|
|
178
|
+
extra: { table: table.name, result }
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const table of supportTables) {
|
|
183
|
+
if (table.name === "itemBoms") {
|
|
184
|
+
const bomResult = await handleItemBoms(params, engine, table);
|
|
185
|
+
if (!bomResult.ok) {
|
|
186
|
+
if (engine.close) await engine.close();
|
|
187
|
+
return {
|
|
188
|
+
ok: false,
|
|
189
|
+
message: "handleItemBoms failed",
|
|
190
|
+
error: bomResult.error || new Error("Unknown item BOM handler error"),
|
|
191
|
+
extra: { table: table.name, result: bomResult }
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
} else {
|
|
195
|
+
const refResult = await handleSupportTable(engine, table);
|
|
196
|
+
if (!refResult.ok) {
|
|
197
|
+
if (engine.close) await engine.close();
|
|
198
|
+
return {
|
|
199
|
+
ok: false,
|
|
200
|
+
message: "handleSupportTable failed",
|
|
201
|
+
error: refResult.error || new Error("Unknown support table handler error"),
|
|
202
|
+
extra: { table: table.name, result: refResult }
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (engine.close) await engine.close();
|
|
208
|
+
const runtime = formatRuntime(Date.now() - start);
|
|
209
|
+
return {
|
|
210
|
+
ok: true,
|
|
211
|
+
message: "downloadSOS completed successfully",
|
|
212
|
+
error: null,
|
|
213
|
+
extra: { runtime }
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
module.exports = downloadSOS;
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
2
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
3
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
4
|
+
};
|
|
5
|
+
var require_index = __commonJS({
|
|
6
|
+
"index.js"(exports, module) {
|
|
7
|
+
const openDb = require("./db/database.js");
|
|
8
|
+
const createTable = require("./db/create-table.js");
|
|
9
|
+
const insertRow = require("./db/insert-row.js");
|
|
10
|
+
const { tables, supportTables } = require("./db/definitions.js");
|
|
11
|
+
function formatRuntime(ms) {
|
|
12
|
+
const totalSeconds = Math.floor(ms / 1e3);
|
|
13
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
14
|
+
const minutes = Math.floor(totalSeconds % 3600 / 60);
|
|
15
|
+
const seconds = totalSeconds % 60;
|
|
16
|
+
return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
|
|
17
|
+
}
|
|
18
|
+
async function sosApi(url, method, authorization, retries = 5) {
|
|
19
|
+
console.log(url);
|
|
20
|
+
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
21
|
+
try {
|
|
22
|
+
const res = await fetch(url, {
|
|
23
|
+
method,
|
|
24
|
+
headers: {
|
|
25
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
26
|
+
Accept: "*/*",
|
|
27
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
28
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
29
|
+
Host: "api.sosinventory.com",
|
|
30
|
+
Authorization: authorization
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
|
35
|
+
}
|
|
36
|
+
return await res.json();
|
|
37
|
+
} catch (err) {
|
|
38
|
+
if (attempt === retries) throw err;
|
|
39
|
+
const delay = 250 * attempt;
|
|
40
|
+
console.log(`Retry ${attempt}/${retries} after error: ${err.message}`);
|
|
41
|
+
console.log(url);
|
|
42
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function downloadTable(params, engine, table) {
|
|
47
|
+
const ctResult = await createTable(engine, table);
|
|
48
|
+
if (!ctResult.ok) return ctResult;
|
|
49
|
+
const retries = params.retries ?? 5;
|
|
50
|
+
let offset = 1;
|
|
51
|
+
await engine.begin();
|
|
52
|
+
while (true) {
|
|
53
|
+
const result = await sosApi(
|
|
54
|
+
`https://api.sosinventory.com${table.api.query.endpoint}?start=${offset}&maxresults=200`,
|
|
55
|
+
table.api.query.method,
|
|
56
|
+
params.sosAuthorization,
|
|
57
|
+
retries
|
|
58
|
+
);
|
|
59
|
+
if (result.status !== "ok") {
|
|
60
|
+
await engine.rollback();
|
|
61
|
+
return { ok: false, message: result.message || "SOS API returned non-ok status" };
|
|
62
|
+
}
|
|
63
|
+
if (!Array.isArray(result.data)) {
|
|
64
|
+
await engine.rollback();
|
|
65
|
+
return { ok: false, message: "SOS API returned invalid data array" };
|
|
66
|
+
}
|
|
67
|
+
if (typeof result.count !== "number" || typeof result.totalCount !== "number") {
|
|
68
|
+
await engine.rollback();
|
|
69
|
+
return { ok: false, message: "SOS API returned invalid pagination fields" };
|
|
70
|
+
}
|
|
71
|
+
for (const record of result.data) {
|
|
72
|
+
delete record.keys;
|
|
73
|
+
delete record.values;
|
|
74
|
+
const irResult = await insertRow(engine, table, record);
|
|
75
|
+
if (!irResult.ok) {
|
|
76
|
+
await engine.rollback();
|
|
77
|
+
return { ok: false, message: irResult };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
offset += result.count;
|
|
81
|
+
if (offset > result.totalCount) break;
|
|
82
|
+
}
|
|
83
|
+
await engine.commit();
|
|
84
|
+
return { ok: true };
|
|
85
|
+
}
|
|
86
|
+
async function handleSupportTable(engine, table) {
|
|
87
|
+
await createTable(engine, table);
|
|
88
|
+
const supportMap = /* @__PURE__ */ new Map();
|
|
89
|
+
for (const sourceTable of table.sourceTables) {
|
|
90
|
+
const rows = await engine.query(
|
|
91
|
+
`SELECT DISTINCT ${engine.q(table.sourceField)} FROM ${engine.q(sourceTable)} WHERE ${engine.q(table.sourceField)} IS NOT NULL`,
|
|
92
|
+
[],
|
|
93
|
+
true
|
|
94
|
+
);
|
|
95
|
+
for (const row of rows) {
|
|
96
|
+
let obj;
|
|
97
|
+
try {
|
|
98
|
+
obj = row[table.sourceField];
|
|
99
|
+
if (typeof obj !== "object") obj = JSON.parse(obj);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
console.error(`Invalid JSON in ${table.name}:`, row[table.sourceField]);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (!obj || typeof obj !== "object") continue;
|
|
105
|
+
const key = obj.id ?? obj.value ?? obj.code ?? obj.name;
|
|
106
|
+
if (!key) continue;
|
|
107
|
+
if (!supportMap.has(key)) {
|
|
108
|
+
supportMap.set(key, {
|
|
109
|
+
id: obj.id ?? obj.value ?? obj.code,
|
|
110
|
+
name: obj.name ?? obj.code ?? obj.value
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (const value of supportMap.values()) {
|
|
116
|
+
await insertRow(engine, table, value);
|
|
117
|
+
}
|
|
118
|
+
return { ok: true };
|
|
119
|
+
}
|
|
120
|
+
async function handleItemBoms(params, engine, table) {
|
|
121
|
+
await createTable(engine, table);
|
|
122
|
+
const items = await engine.query("select id from items where type IN ('Assembly', 'Item Group')", [], true);
|
|
123
|
+
const retries = params.retries ?? 5;
|
|
124
|
+
for (const item of items) {
|
|
125
|
+
const result = await sosApi(`https://api.sosinventory.com/api/v2/item/${item.id}/bom`, "GET", params.sosAuthorization, retries);
|
|
126
|
+
if (!result.data) continue;
|
|
127
|
+
if (result.data.lines.length === 0) continue;
|
|
128
|
+
const lines = result.data.lines;
|
|
129
|
+
for (const line of lines) {
|
|
130
|
+
const id = Number(line.lineId);
|
|
131
|
+
delete line.lineId;
|
|
132
|
+
const record = {
|
|
133
|
+
id,
|
|
134
|
+
itemId: item.id,
|
|
135
|
+
...line
|
|
136
|
+
};
|
|
137
|
+
await insertRow(engine, table, record);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return { ok: true };
|
|
141
|
+
}
|
|
142
|
+
async function downloadSOS(params) {
|
|
143
|
+
if (!params.database.engine) {
|
|
144
|
+
return {
|
|
145
|
+
ok: false,
|
|
146
|
+
message: "Missing required parameter: params.database.engine",
|
|
147
|
+
error: new Error("params.database.engine is required"),
|
|
148
|
+
extra: null
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if (!params.sosAuthorization) {
|
|
152
|
+
return {
|
|
153
|
+
ok: false,
|
|
154
|
+
message: "Missing required parameter: params.sosAuthorization",
|
|
155
|
+
error: new Error("params.sosAuthorization is required"),
|
|
156
|
+
extra: null
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
const start = Date.now();
|
|
160
|
+
const engine = await openDb(params.database);
|
|
161
|
+
const referenceTables = tables.filter((table) => table.reference === true);
|
|
162
|
+
for (const table of referenceTables) {
|
|
163
|
+
const result = await downloadTable(params, engine, table);
|
|
164
|
+
if (!result.ok) {
|
|
165
|
+
if (engine.close) await engine.close();
|
|
166
|
+
return {
|
|
167
|
+
ok: false,
|
|
168
|
+
message: `downloadTable failed for ${table.name}`,
|
|
169
|
+
error: result.error || new Error("Unknown downloadTable error"),
|
|
170
|
+
extra: { table: table.name, result }
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const primaryTables = tables.filter((table) => table.primary === true);
|
|
175
|
+
for (const table of primaryTables) {
|
|
176
|
+
const result = await downloadTable(params, engine, table);
|
|
177
|
+
if (!result.ok) {
|
|
178
|
+
if (engine.close) await engine.close();
|
|
179
|
+
return {
|
|
180
|
+
ok: false,
|
|
181
|
+
message: `downloadTable failed for ${table.name}`,
|
|
182
|
+
error: result.error || new Error("Unknown downloadTable error"),
|
|
183
|
+
extra: { table: table.name, result }
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
for (const table of supportTables) {
|
|
188
|
+
if (table.name === "itemBoms") {
|
|
189
|
+
const bomResult = await handleItemBoms(params, engine, table);
|
|
190
|
+
if (!bomResult.ok) {
|
|
191
|
+
if (engine.close) await engine.close();
|
|
192
|
+
return {
|
|
193
|
+
ok: false,
|
|
194
|
+
message: "handleItemBoms failed",
|
|
195
|
+
error: bomResult.error || new Error("Unknown item BOM handler error"),
|
|
196
|
+
extra: { table: table.name, result: bomResult }
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
} else {
|
|
200
|
+
const refResult = await handleSupportTable(engine, table);
|
|
201
|
+
if (!refResult.ok) {
|
|
202
|
+
if (engine.close) await engine.close();
|
|
203
|
+
return {
|
|
204
|
+
ok: false,
|
|
205
|
+
message: "handleSupportTable failed",
|
|
206
|
+
error: refResult.error || new Error("Unknown support table handler error"),
|
|
207
|
+
extra: { table: table.name, result: refResult }
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (engine.close) await engine.close();
|
|
213
|
+
const runtime = formatRuntime(Date.now() - start);
|
|
214
|
+
return {
|
|
215
|
+
ok: true,
|
|
216
|
+
message: "downloadSOS completed successfully",
|
|
217
|
+
error: null,
|
|
218
|
+
extra: { runtime }
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
module.exports = downloadSOS;
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
export default require_index();
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sos-inventory-db",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A schema‑driven relational database model for SOS Inventory, including full API contract definitions and ingestion support for SQLite, PostgreSQL, MariaDB, MySQL, and SQL Server.",
|
|
5
|
+
"type": "commonjs",
|
|
6
|
+
|
|
7
|
+
"main": "./dist/index.cjs",
|
|
8
|
+
"exports": {
|
|
9
|
+
"import": "./dist/index.mjs",
|
|
10
|
+
"require": "./dist/index.cjs"
|
|
11
|
+
},
|
|
12
|
+
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "node build.js",
|
|
21
|
+
"test": "node test/sos-download-test.js"
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
"keywords": [
|
|
25
|
+
"sos-inventory",
|
|
26
|
+
"sos inventory",
|
|
27
|
+
"inventory",
|
|
28
|
+
"api",
|
|
29
|
+
"etl",
|
|
30
|
+
"data-ingestion",
|
|
31
|
+
"database",
|
|
32
|
+
"sqlite",
|
|
33
|
+
"postgresql",
|
|
34
|
+
"mysql",
|
|
35
|
+
"mariadb",
|
|
36
|
+
"sqlserver",
|
|
37
|
+
"schema",
|
|
38
|
+
"sync",
|
|
39
|
+
"mirror",
|
|
40
|
+
"downloader"
|
|
41
|
+
],
|
|
42
|
+
"author": "Chris Rowley",
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"optionalDependencies": {
|
|
45
|
+
"better-sqlite3": "^12.8.0",
|
|
46
|
+
"mariadb": "^3.5.2",
|
|
47
|
+
"mssql": "^12.2.1",
|
|
48
|
+
"mysql2": "^3.20.0",
|
|
49
|
+
"pg": "^8.20.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"dotenv": "^17.3.1",
|
|
53
|
+
"esbuild": "^0.27.7",
|
|
54
|
+
"eslint": "^10.1.0",
|
|
55
|
+
"globals": "^17.4.0"
|
|
56
|
+
}
|
|
57
|
+
}
|