@machinemetrics/mm-erp-sdk 0.1.6-beta.2 → 0.1.7-beta.1
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/dist/{config-WKwu1mMo.js → config-qat9zgOl.js} +2 -2
- package/dist/{config-WKwu1mMo.js.map → config-qat9zgOl.js.map} +1 -1
- package/dist/{connector-factory-DHmMYsRs.js → connector-factory-C2czCs9v.js} +2 -2
- package/dist/{connector-factory-DHmMYsRs.js.map → connector-factory-C2czCs9v.js.map} +1 -1
- package/dist/{hashed-cache-manager-CtDhFqj6.js → hashed-cache-manager-CzyFSt2B.js} +4 -4
- package/dist/{hashed-cache-manager-CtDhFqj6.js.map → hashed-cache-manager-CzyFSt2B.js.map} +1 -1
- package/dist/{index-aci_wdcn.js → index-B9wo8pld.js} +2 -2
- package/dist/{index-aci_wdcn.js.map → index-B9wo8pld.js.map} +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/{logger-hqtl8hFM.js → logger-Db8CkwR6.js} +924 -966
- package/dist/logger-Db8CkwR6.js.map +1 -0
- package/dist/mm-erp-sdk.js +275 -17
- package/dist/mm-erp-sdk.js.map +1 -1
- package/dist/services/data-sync-service/data-sync-service.d.ts.map +1 -1
- package/dist/services/data-sync-service/jobs/clean-up-expired-cache.js +4 -4
- package/dist/services/data-sync-service/jobs/from-erp.d.ts.map +1 -1
- package/dist/services/data-sync-service/jobs/from-erp.js +25 -8
- package/dist/services/data-sync-service/jobs/from-erp.js.map +1 -1
- package/dist/services/data-sync-service/jobs/retry-failed-labor-tickets.js +3 -3
- package/dist/services/data-sync-service/jobs/run-migrations.js +1 -1
- package/dist/services/data-sync-service/jobs/to-erp.d.ts.map +1 -1
- package/dist/services/data-sync-service/jobs/to-erp.js +24 -7
- package/dist/services/data-sync-service/jobs/to-erp.js.map +1 -1
- package/dist/services/psql-erp-service/configuration.d.ts +10 -0
- package/dist/services/psql-erp-service/configuration.d.ts.map +1 -0
- package/dist/services/psql-erp-service/index.d.ts +19 -0
- package/dist/services/psql-erp-service/index.d.ts.map +1 -0
- package/dist/services/psql-erp-service/internal/psql-config.d.ts +28 -0
- package/dist/services/psql-erp-service/internal/psql-config.d.ts.map +1 -0
- package/dist/services/psql-erp-service/internal/psql-labor-ticket-operations.d.ts +40 -0
- package/dist/services/psql-erp-service/internal/psql-labor-ticket-operations.d.ts.map +1 -0
- package/dist/services/psql-erp-service/internal/types/psql-types.d.ts +15 -0
- package/dist/services/psql-erp-service/internal/types/psql-types.d.ts.map +1 -0
- package/dist/services/psql-erp-service/psql-helpers.d.ts +32 -0
- package/dist/services/psql-erp-service/psql-helpers.d.ts.map +1 -0
- package/dist/services/psql-erp-service/psql-service.d.ts +36 -0
- package/dist/services/psql-erp-service/psql-service.d.ts.map +1 -0
- package/dist/types/erp-types.d.ts +2 -1
- package/dist/types/erp-types.d.ts.map +1 -1
- package/dist/utils/standard-process-drivers/labor-ticket-erp-synchronizer.d.ts.map +1 -1
- package/package.json +3 -1
- package/src/index.ts +27 -5
- package/src/services/data-sync-service/data-sync-service.ts +43 -3
- package/src/services/data-sync-service/jobs/from-erp.ts +35 -6
- package/src/services/data-sync-service/jobs/to-erp.ts +35 -5
- package/src/services/psql-erp-service/configuration.ts +9 -0
- package/src/services/psql-erp-service/index.ts +28 -0
- package/src/services/psql-erp-service/internal/psql-config.ts +13 -0
- package/src/services/psql-erp-service/internal/psql-labor-ticket-operations.ts +58 -0
- package/src/services/psql-erp-service/internal/types/psql-types.ts +17 -0
- package/src/services/psql-erp-service/psql-helpers.ts +90 -0
- package/src/services/psql-erp-service/psql-service.ts +178 -0
- package/src/types/erp-types.ts +1 -0
- package/src/utils/standard-process-drivers/labor-ticket-erp-synchronizer.ts +1 -2
- package/dist/logger-hqtl8hFM.js.map +0 -1
|
@@ -7,6 +7,18 @@ import { createConnectorFromPath } from "../../../utils/connector-factory";
|
|
|
7
7
|
// Configure the logger with the correct log level
|
|
8
8
|
logger.level = process.env.LOG_LEVEL || "info";
|
|
9
9
|
|
|
10
|
+
// Enable garbage collection on exit if available
|
|
11
|
+
if (global.gc) {
|
|
12
|
+
process.on("exit", () => {
|
|
13
|
+
logger.debug("from-erp: Running garbage collection on exit");
|
|
14
|
+
try {
|
|
15
|
+
global.gc?.();
|
|
16
|
+
} catch (e) {
|
|
17
|
+
// Ignore GC errors
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
10
22
|
const main = async () => {
|
|
11
23
|
try {
|
|
12
24
|
logger.info('Worker for job "from-erp" online');
|
|
@@ -14,7 +26,7 @@ const main = async () => {
|
|
|
14
26
|
|
|
15
27
|
// Get the connector path from the environment variable
|
|
16
28
|
const connectorPath = process.env.CONNECTOR_PATH;
|
|
17
|
-
|
|
29
|
+
|
|
18
30
|
if (!connectorPath) {
|
|
19
31
|
throw new Error("Connector path not provided in environment variables");
|
|
20
32
|
}
|
|
@@ -28,6 +40,23 @@ const main = async () => {
|
|
|
28
40
|
|
|
29
41
|
await connector.syncFromERPCompleted();
|
|
30
42
|
logger.info("==========Completed from-erp job cycle==========");
|
|
43
|
+
|
|
44
|
+
// Cleanup before worker exit
|
|
45
|
+
logger.debug("from-erp: Starting cleanup sequence");
|
|
46
|
+
|
|
47
|
+
// Trigger garbage collection if available
|
|
48
|
+
if (global.gc) {
|
|
49
|
+
logger.debug("from-erp: Running manual garbage collection");
|
|
50
|
+
try {
|
|
51
|
+
global.gc?.();
|
|
52
|
+
} catch (e) {
|
|
53
|
+
logger.debug("from-erp: GC not available or failed");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Small delay to allow any pending operations to complete
|
|
58
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
59
|
+
logger.debug("from-erp: Cleanup sequence completed");
|
|
31
60
|
} catch (error) {
|
|
32
61
|
const errorDetails = {
|
|
33
62
|
message: error instanceof Error ? error.message : String(error),
|
|
@@ -46,10 +75,10 @@ const main = async () => {
|
|
|
46
75
|
// Cross-platform module detection fix for Bree compatibility
|
|
47
76
|
// Windows: process.argv[1] uses backslashes, import.meta.url uses forward slashes
|
|
48
77
|
// Linux/Mac: both use forward slashes, so this normalization is safe
|
|
49
|
-
const normalizedArgv1 = process.argv[1].replace(/\\/g,
|
|
50
|
-
const fileUrl = normalizedArgv1.startsWith(
|
|
51
|
-
`file://${normalizedArgv1}`
|
|
52
|
-
`file:///${normalizedArgv1}`;
|
|
78
|
+
const normalizedArgv1 = process.argv[1].replace(/\\/g, "/");
|
|
79
|
+
const fileUrl = normalizedArgv1.startsWith("/")
|
|
80
|
+
? `file://${normalizedArgv1}` // Unix: file:// + /path = file:///path
|
|
81
|
+
: `file:///${normalizedArgv1}`; // Windows: file:/// + C:/path = file:///C:/path
|
|
53
82
|
const isMainModule = import.meta.url === fileUrl;
|
|
54
83
|
|
|
55
84
|
if (isMainModule) {
|
|
@@ -61,4 +90,4 @@ if (isMainModule) {
|
|
|
61
90
|
}
|
|
62
91
|
}
|
|
63
92
|
|
|
64
|
-
export default main;
|
|
93
|
+
export default main;
|
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
import "dotenv/config";
|
|
2
2
|
|
|
3
|
-
import logger from "
|
|
3
|
+
import logger from "../../../services/reporting-service/logger";
|
|
4
|
+
import { SQLiteCoordinator } from "../../sqlite-service";
|
|
4
5
|
import { createConnectorFromPath } from "../../../utils/connector-factory";
|
|
5
6
|
|
|
6
7
|
// Configure the logger with the correct log level
|
|
7
8
|
logger.level = process.env.LOG_LEVEL || "info";
|
|
8
9
|
|
|
10
|
+
// Enable garbage collection on exit if available
|
|
11
|
+
if (global.gc) {
|
|
12
|
+
process.on("exit", () => {
|
|
13
|
+
logger.debug("to-erp: Running garbage collection on exit");
|
|
14
|
+
try {
|
|
15
|
+
global.gc?.();
|
|
16
|
+
} catch (e) {
|
|
17
|
+
// Ignore GC errors
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
9
22
|
const main = async () => {
|
|
10
23
|
try {
|
|
11
24
|
logger.info('Worker for job "to-erp" online');
|
|
@@ -25,6 +38,23 @@ const main = async () => {
|
|
|
25
38
|
await connector.syncToERPCompleted();
|
|
26
39
|
|
|
27
40
|
logger.info("==========Completed to-erp job cycle==========");
|
|
41
|
+
|
|
42
|
+
// Cleanup before worker exit
|
|
43
|
+
logger.debug("to-erp: Starting cleanup sequence");
|
|
44
|
+
|
|
45
|
+
// Trigger garbage collection if available
|
|
46
|
+
if (global.gc) {
|
|
47
|
+
logger.debug("to-erp: Running manual garbage collection");
|
|
48
|
+
try {
|
|
49
|
+
global.gc?.();
|
|
50
|
+
} catch (e) {
|
|
51
|
+
logger.debug("to-erp: GC not available or failed");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Small delay to allow any pending operations to complete
|
|
56
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
57
|
+
logger.debug("to-erp: Cleanup sequence completed");
|
|
28
58
|
} catch (error) {
|
|
29
59
|
const errorDetails = {
|
|
30
60
|
message: error instanceof Error ? error.message : String(error),
|
|
@@ -47,10 +77,10 @@ const main = async () => {
|
|
|
47
77
|
// Cross-platform module detection fix for Bree compatibility
|
|
48
78
|
// Windows: process.argv[1] uses backslashes, import.meta.url uses forward slashes
|
|
49
79
|
// Linux/Mac: both use forward slashes, so this normalization is safe
|
|
50
|
-
const normalizedArgv1 = process.argv[1].replace(/\\/g,
|
|
51
|
-
const fileUrl = normalizedArgv1.startsWith(
|
|
52
|
-
`file://${normalizedArgv1}`
|
|
53
|
-
`file:///${normalizedArgv1}`;
|
|
80
|
+
const normalizedArgv1 = process.argv[1].replace(/\\/g, "/");
|
|
81
|
+
const fileUrl = normalizedArgv1.startsWith("/")
|
|
82
|
+
? `file://${normalizedArgv1}` // Unix: file:// + /path = file:///path
|
|
83
|
+
: `file:///${normalizedArgv1}`; // Windows: file:/// + C:/path = file:///C:/path
|
|
54
84
|
const isMainModule = import.meta.url === fileUrl;
|
|
55
85
|
|
|
56
86
|
if (isMainModule) {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { PsqlService } from "./psql-service";
|
|
2
|
+
import { PsqlLaborTicketOperations } from "./internal/psql-labor-ticket-operations";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A class to manage interactions with PSQL (Pervasive) databases via ODBC
|
|
6
|
+
*/
|
|
7
|
+
export { PsqlService };
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Labor ticket operations for PSQL (Phase 2)
|
|
11
|
+
*/
|
|
12
|
+
export { PsqlLaborTicketOperations };
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Configuration interface for PSQL connections
|
|
16
|
+
*/
|
|
17
|
+
export type { PsqlConfiguration } from "./configuration";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Helper functions for PSQL data formatting
|
|
21
|
+
*/
|
|
22
|
+
export {
|
|
23
|
+
formatPsqlDate,
|
|
24
|
+
formatPsqlTime,
|
|
25
|
+
combinePsqlDateTime,
|
|
26
|
+
isPsqlDateEmpty,
|
|
27
|
+
cleanPsqlCharField,
|
|
28
|
+
} from "./psql-helpers";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
export const PsqlConfigSchema = z.object({
|
|
4
|
+
host: z.string().nonempty("Host is required."),
|
|
5
|
+
port: z.string().nonempty("Port is required."),
|
|
6
|
+
database: z.string().nonempty("Database name is required."),
|
|
7
|
+
username: z.string().nonempty("Username is required."),
|
|
8
|
+
password: z.string().nonempty("Password is required."),
|
|
9
|
+
connectionTimeout: z.string().optional().default("15000"),
|
|
10
|
+
requestTimeout: z.string().optional().default("15000"),
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export type PsqlConfig = z.infer<typeof PsqlConfigSchema>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PSQL Labor Ticket Operations
|
|
3
|
+
*
|
|
4
|
+
* Phase 2: This will handle INSERT/UPDATE/DELETE operations for labor tickets
|
|
5
|
+
* Phase 1: Placeholder - throws errors if called
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { PsqlService } from "../psql-service";
|
|
9
|
+
import { MMReceiveLaborTicket } from "../../../services/mm-api-service";
|
|
10
|
+
import logger from "../../reporting-service/logger";
|
|
11
|
+
|
|
12
|
+
export class PsqlLaborTicketOperations {
|
|
13
|
+
constructor(private service: PsqlService) {}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Create labor ticket in START_LABOR table
|
|
17
|
+
*
|
|
18
|
+
* Phase 2 Implementation Notes:
|
|
19
|
+
* - Will use prepared statements with parameter binding
|
|
20
|
+
* - Insert into START_LABOR table
|
|
21
|
+
* - Return GUID as erpUid
|
|
22
|
+
*
|
|
23
|
+
* @param laborTicket Labor ticket from MachineMetrics
|
|
24
|
+
* @returns Labor ticket and ERP unique ID
|
|
25
|
+
*/
|
|
26
|
+
async createLaborTicket(
|
|
27
|
+
laborTicket: MMReceiveLaborTicket
|
|
28
|
+
): Promise<{ laborTicket: MMReceiveLaborTicket; erpUid: string }> {
|
|
29
|
+
logger.warn(
|
|
30
|
+
"PsqlLaborTicketOperations.createLaborTicket not yet implemented (Phase 2)"
|
|
31
|
+
);
|
|
32
|
+
throw new Error(
|
|
33
|
+
"Labor ticket creation not implemented for PSQL. This is a Phase 2 feature."
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Update labor ticket (move from START_LABOR to COMPLETED_LABOR)
|
|
39
|
+
*
|
|
40
|
+
* Phase 2 Implementation Notes:
|
|
41
|
+
* - Insert into COMPLETED_LABOR
|
|
42
|
+
* - Delete from START_LABOR
|
|
43
|
+
* - Should be done in a transaction
|
|
44
|
+
*
|
|
45
|
+
* @param laborTicket Labor ticket to update
|
|
46
|
+
* @returns Updated labor ticket
|
|
47
|
+
*/
|
|
48
|
+
async updateLaborTicket(
|
|
49
|
+
laborTicket: MMReceiveLaborTicket
|
|
50
|
+
): Promise<MMReceiveLaborTicket> {
|
|
51
|
+
logger.warn(
|
|
52
|
+
"PsqlLaborTicketOperations.updateLaborTicket not yet implemented (Phase 2)"
|
|
53
|
+
);
|
|
54
|
+
throw new Error(
|
|
55
|
+
"Labor ticket update not implemented for PSQL. This is a Phase 2 feature."
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PSQL-specific type definitions
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export interface PsqlConnectionOptions {
|
|
6
|
+
connectionString: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface OdbcError {
|
|
10
|
+
state: string;
|
|
11
|
+
message: string;
|
|
12
|
+
code?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface OdbcErrorResponse extends Error {
|
|
16
|
+
odbcErrors?: OdbcError[];
|
|
17
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper functions for PSQL/Pervasive database operations
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Formats a date from PSQL YYMMDD format to ISO date string
|
|
7
|
+
* @param psqlDate Date in YYMMDD format (e.g., "250105" for Jan 5, 2025)
|
|
8
|
+
* @returns ISO date string (e.g., "2025-01-05") or null if invalid
|
|
9
|
+
*/
|
|
10
|
+
export function formatPsqlDate(psqlDate: string): string | null {
|
|
11
|
+
if (!psqlDate || psqlDate === "000000" || psqlDate.trim() === "") {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
try {
|
|
16
|
+
const year = parseInt(psqlDate.substring(0, 2), 10);
|
|
17
|
+
const month = parseInt(psqlDate.substring(2, 4), 10);
|
|
18
|
+
const day = parseInt(psqlDate.substring(4, 6), 10);
|
|
19
|
+
|
|
20
|
+
// Convert 2-digit year to 4-digit (assuming 2000s)
|
|
21
|
+
const fullYear = year + 2000;
|
|
22
|
+
|
|
23
|
+
// Basic validation
|
|
24
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const date = new Date(fullYear, month - 1, day);
|
|
29
|
+
return date.toISOString().split("T")[0];
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Formats a time from PSQL HHMM format to HH:MM:SS
|
|
37
|
+
* @param psqlTime Time in HHMM format (e.g., "1430" for 2:30 PM)
|
|
38
|
+
* @returns Time string in HH:MM:SS format or null if invalid
|
|
39
|
+
*/
|
|
40
|
+
export function formatPsqlTime(psqlTime: string): string | null {
|
|
41
|
+
if (!psqlTime || psqlTime.trim() === "") {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
const hours = psqlTime.substring(0, 2);
|
|
47
|
+
const minutes = psqlTime.substring(2, 4);
|
|
48
|
+
return `${hours}:${minutes}:00`;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Combines PSQL date and time into ISO datetime string
|
|
56
|
+
* @param psqlDate Date in YYMMDD format
|
|
57
|
+
* @param psqlTime Time in HHMM format
|
|
58
|
+
* @returns ISO datetime string or null if invalid
|
|
59
|
+
*/
|
|
60
|
+
export function combinePsqlDateTime(
|
|
61
|
+
psqlDate: string,
|
|
62
|
+
psqlTime: string
|
|
63
|
+
): string | null {
|
|
64
|
+
const date = formatPsqlDate(psqlDate);
|
|
65
|
+
const time = formatPsqlTime(psqlTime);
|
|
66
|
+
|
|
67
|
+
if (!date || !time) {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return `${date}T${time}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Helper to check if a PSQL date is "empty" (000000 or blank)
|
|
76
|
+
*/
|
|
77
|
+
export function isPsqlDateEmpty(psqlDate: string): boolean {
|
|
78
|
+
return !psqlDate || psqlDate === "000000" || psqlDate.trim() === "";
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Clean and trim PSQL CHAR field (removes trailing spaces)
|
|
83
|
+
* PSQL CHAR fields are fixed-width and padded with spaces
|
|
84
|
+
*/
|
|
85
|
+
export function cleanPsqlCharField(value: string | null | undefined): string {
|
|
86
|
+
if (value === null || value === undefined) {
|
|
87
|
+
return "";
|
|
88
|
+
}
|
|
89
|
+
return String(value).trim();
|
|
90
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import odbc from "odbc";
|
|
2
|
+
import { PsqlConfiguration } from "./configuration";
|
|
3
|
+
import { ERPResponse } from "../../types/erp-types";
|
|
4
|
+
import { OdbcErrorResponse } from "./internal/types/psql-types";
|
|
5
|
+
import logger from "../reporting-service/logger";
|
|
6
|
+
|
|
7
|
+
type PagingParams = {
|
|
8
|
+
limit?: number;
|
|
9
|
+
offset?: number;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export class PsqlService {
|
|
13
|
+
private config: PsqlConfiguration;
|
|
14
|
+
|
|
15
|
+
constructor(config: PsqlConfiguration) {
|
|
16
|
+
this.config = config;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// REMOVED: dispose() method - not needed anymore
|
|
20
|
+
// REMOVED: connection property - not needed anymore
|
|
21
|
+
// REMOVED: openConnection() method - not needed anymore
|
|
22
|
+
// REMOVED: closeConnection() method - not needed anymore
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Build PSQL ODBC connection string
|
|
26
|
+
* CRITICAL: ServerName must use IP.PORT format (e.g., 10.4.0.11.1583)
|
|
27
|
+
*/
|
|
28
|
+
private buildConnectionString(): string {
|
|
29
|
+
const serverName = `${this.config.host}.${this.config.port}`;
|
|
30
|
+
|
|
31
|
+
return (
|
|
32
|
+
[
|
|
33
|
+
"Driver={Pervasive ODBC Interface}",
|
|
34
|
+
`ServerName=${serverName}`,
|
|
35
|
+
`DBQ=${this.config.database}`,
|
|
36
|
+
`UID=${this.config.username}`,
|
|
37
|
+
`PWD=${this.config.password}`,
|
|
38
|
+
"AutoDoubleQuote=0",
|
|
39
|
+
].join(";") + ";"
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Execute a query and return the results
|
|
45
|
+
* Creates a fresh connection for each query to avoid handle corruption
|
|
46
|
+
*
|
|
47
|
+
* @param query The SQL query to execute
|
|
48
|
+
* @param params Query parameters (currently unused for PSQL read operations)
|
|
49
|
+
* @param paging Optional paging parameters
|
|
50
|
+
* @returns The entities fetched from the database, along with paging information
|
|
51
|
+
*/
|
|
52
|
+
public async executePreparedStatement(
|
|
53
|
+
query: string,
|
|
54
|
+
params: Record<string, string> = {},
|
|
55
|
+
paging?: PagingParams
|
|
56
|
+
): Promise<ERPResponse | undefined> {
|
|
57
|
+
let connection: odbc.Connection | null = null;
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
// Create fresh connection for THIS query only
|
|
61
|
+
const connStr = this.buildConnectionString();
|
|
62
|
+
logger.debug("Creating fresh PSQL connection for query");
|
|
63
|
+
connection = await odbc.connect(connStr);
|
|
64
|
+
|
|
65
|
+
if (Object.keys(params).length > 0) {
|
|
66
|
+
logger.warn(
|
|
67
|
+
"PsqlService: Query parameters provided but parameter binding not yet implemented. " +
|
|
68
|
+
"Using direct query execution. This is acceptable for Phase 1 read operations."
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const records = await connection.query(query);
|
|
73
|
+
const allRecords = PsqlService.recordsetToRecords(records);
|
|
74
|
+
const rowsFetched = allRecords.length;
|
|
75
|
+
|
|
76
|
+
// Apply paging if requested
|
|
77
|
+
const pagedData =
|
|
78
|
+
paging?.offset !== undefined || paging?.limit !== undefined
|
|
79
|
+
? allRecords.slice(
|
|
80
|
+
paging.offset || 0,
|
|
81
|
+
(paging.offset || 0) + (paging.limit || allRecords.length)
|
|
82
|
+
)
|
|
83
|
+
: allRecords;
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
data: pagedData,
|
|
87
|
+
paging: {
|
|
88
|
+
count: rowsFetched,
|
|
89
|
+
limit: paging?.limit || 0,
|
|
90
|
+
offset: paging?.offset || 0,
|
|
91
|
+
nextPage:
|
|
92
|
+
paging?.limit && (paging.offset || 0) + paging.limit < rowsFetched
|
|
93
|
+
? String((paging.offset || 0) + paging.limit)
|
|
94
|
+
: undefined,
|
|
95
|
+
previousPage: paging?.offset
|
|
96
|
+
? String(Math.max(0, (paging.offset || 0) - (paging.limit || 10)))
|
|
97
|
+
: undefined,
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
} catch (error) {
|
|
101
|
+
const errorInfo = error as OdbcErrorResponse;
|
|
102
|
+
logger.error("Error fetching data from PSQL", {
|
|
103
|
+
error: errorInfo.message,
|
|
104
|
+
odbcErrors: errorInfo.odbcErrors,
|
|
105
|
+
query: query.substring(0, 200), // Log first 200 chars of query
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
throw this.handleOdbcError(errorInfo);
|
|
109
|
+
} finally {
|
|
110
|
+
// CRITICAL: Always close connection, even on error
|
|
111
|
+
if (connection) {
|
|
112
|
+
try {
|
|
113
|
+
await connection.close();
|
|
114
|
+
logger.debug("PSQL connection closed successfully");
|
|
115
|
+
} catch (err) {
|
|
116
|
+
// Don't throw on close errors, just log
|
|
117
|
+
logger.warn("Error closing PSQL connection (non-fatal)", {
|
|
118
|
+
error: err,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Transform ODBC result set to array of Record<string, string> instances.
|
|
127
|
+
* IMPORTANT: PSQL CHAR fields are often padded with spaces - we trim them
|
|
128
|
+
*/
|
|
129
|
+
public static recordsetToRecords(recordset: any[]): Record<string, string>[] {
|
|
130
|
+
if (!Array.isArray(recordset)) {
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const data: Record<string, string>[] = recordset.map((row) => {
|
|
135
|
+
const transformedRow: Record<string, string> = {};
|
|
136
|
+
Object.keys(row).forEach((key) => {
|
|
137
|
+
const value = row[key];
|
|
138
|
+
transformedRow[key] =
|
|
139
|
+
value !== null && value !== undefined ? String(value).trim() : "";
|
|
140
|
+
});
|
|
141
|
+
return transformedRow;
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
return data;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Handle ODBC errors and provide meaningful messages
|
|
149
|
+
*/
|
|
150
|
+
private handleOdbcError(error: OdbcErrorResponse): Error {
|
|
151
|
+
const odbcError = error.odbcErrors?.[0];
|
|
152
|
+
const errorCode = odbcError?.state;
|
|
153
|
+
const message = odbcError?.message || error.message;
|
|
154
|
+
|
|
155
|
+
switch (errorCode) {
|
|
156
|
+
case "08S01":
|
|
157
|
+
return new Error(
|
|
158
|
+
"PSQL connection failed. Check: " +
|
|
159
|
+
"1) PVSW environment variable set to /usr/local/psql/etc/pvsw.ini, " +
|
|
160
|
+
"2) Network connectivity to ports 1583/3351, " +
|
|
161
|
+
"3) ODBC configuration files in /usr/local/psql/etc/ and /etc/. " +
|
|
162
|
+
`Original error: ${message}`
|
|
163
|
+
);
|
|
164
|
+
case "28000":
|
|
165
|
+
return new Error(
|
|
166
|
+
`PSQL authentication failed. Check username/password. Original error: ${message}`
|
|
167
|
+
);
|
|
168
|
+
case "42000":
|
|
169
|
+
return new Error(`PSQL SQL syntax error. Original error: ${message}`);
|
|
170
|
+
case "42S02":
|
|
171
|
+
return new Error(
|
|
172
|
+
`PSQL table or view not found. Check table names in query. Original error: ${message}`
|
|
173
|
+
);
|
|
174
|
+
default:
|
|
175
|
+
return new Error(`PSQL error (${errorCode || "unknown"}): ${message}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
package/src/types/erp-types.ts
CHANGED
|
@@ -57,8 +57,7 @@ export class LaborTicketERPSynchronizer {
|
|
|
57
57
|
// the checkpoint to ensure there is no gap of time for the next sync.
|
|
58
58
|
const mostRecentUpdate = laborTicketsUpdates.reduce(
|
|
59
59
|
(latest: string | null, ticket: MMReceiveLaborTicket) => {
|
|
60
|
-
if (!ticket.updatedAt) return latest;
|
|
61
|
-
if (!latest) return ticket.updatedAt;
|
|
60
|
+
if (!latest || !ticket.updatedAt) return latest;
|
|
62
61
|
return new Date(ticket.updatedAt) > new Date(latest)
|
|
63
62
|
? ticket.updatedAt
|
|
64
63
|
: latest;
|