@machinemetrics/mm-erp-sdk 0.1.9-beta.1 → 0.1.9-beta.2
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/README.md +5 -0
- package/dist/{config-CvA-mFWF.js → config-Bax6Ofp5.js} +2 -2
- package/dist/{config-CvA-mFWF.js.map → config-Bax6Ofp5.js.map} +1 -1
- package/dist/{connector-factory-BPm2GVVF.js → connector-factory-BaMIlES8.js} +2 -2
- package/dist/{connector-factory-BPm2GVVF.js.map → connector-factory-BaMIlES8.js.map} +1 -1
- package/dist/{hashed-cache-manager-B15NN8hK.js → hashed-cache-manager-C1u9jQgY.js} +4 -4
- package/dist/{hashed-cache-manager-B15NN8hK.js.map → hashed-cache-manager-C1u9jQgY.js.map} +1 -1
- package/dist/{index-D8qO1NyK.js → index-BkVlW0ZW.js} +2 -2
- package/dist/{index-D8qO1NyK.js.map → index-BkVlW0ZW.js.map} +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/{logger-BWw0_z9q.js → logger-DW5fyhVS.js} +114 -78
- package/dist/logger-DW5fyhVS.js.map +1 -0
- package/dist/mm-erp-sdk.js +7 -716
- 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 +12 -5
- 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 +4 -7
- package/dist/services/data-sync-service/jobs/to-erp.js.map +1 -1
- package/dist/services/mm-api-service/index.d.ts +0 -7
- package/dist/services/mm-api-service/index.d.ts.map +1 -1
- package/dist/services/mm-api-service/mm-api-service.d.ts +0 -6
- package/dist/services/mm-api-service/mm-api-service.d.ts.map +1 -1
- package/dist/services/reporting-service/logger.d.ts.map +1 -1
- package/dist/utils/index.d.ts +0 -5
- package/dist/utils/index.d.ts.map +1 -1
- package/package.json +2 -5
- package/src/index.ts +0 -3
- package/src/services/data-sync-service/data-sync-service.ts +0 -10
- package/src/services/data-sync-service/jobs/from-erp.ts +7 -2
- package/src/services/data-sync-service/jobs/to-erp.ts +1 -5
- package/src/services/mm-api-service/index.ts +0 -8
- package/src/services/mm-api-service/mm-api-service.ts +2 -19
- package/src/services/reporting-service/logger.ts +111 -81
- package/src/utils/index.ts +0 -6
- package/dist/logger-BWw0_z9q.js.map +0 -1
- package/dist/services/data-sync-service/nats-labor-ticket-listener.d.ts +0 -30
- package/dist/services/data-sync-service/nats-labor-ticket-listener.d.ts.map +0 -1
- package/dist/services/mm-api-service/company-info.d.ts +0 -13
- package/dist/services/mm-api-service/company-info.d.ts.map +0 -1
- package/dist/services/nats-service/nats-service.d.ts +0 -114
- package/dist/services/nats-service/nats-service.d.ts.map +0 -1
- package/dist/services/nats-service/test-nats-subscriber.d.ts +0 -6
- package/dist/services/nats-service/test-nats-subscriber.d.ts.map +0 -1
- package/dist/utils/error-formatter.d.ts +0 -19
- package/dist/utils/error-formatter.d.ts.map +0 -1
- package/src/services/data-sync-service/nats-labor-ticket-listener.ts +0 -341
- package/src/services/mm-api-service/company-info.ts +0 -87
- package/src/services/nats-service/nats-service.ts +0 -351
- package/src/services/nats-service/test-nats-subscriber.ts +0 -96
- package/src/utils/error-formatter.ts +0 -205
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Manages NATS-based real-time labor ticket processing
|
|
3
|
-
*/
|
|
4
|
-
export declare class NatsLaborTicketListener {
|
|
5
|
-
private connector;
|
|
6
|
-
private natsService?;
|
|
7
|
-
constructor(connector: any);
|
|
8
|
-
/**
|
|
9
|
-
* Start listening for labor ticket events via NATS
|
|
10
|
-
*/
|
|
11
|
-
start(): Promise<void>;
|
|
12
|
-
/**
|
|
13
|
-
* Register health check handler - responds immediately to let Dashboard know connector is online
|
|
14
|
-
*/
|
|
15
|
-
private registerHealthCheckHandler;
|
|
16
|
-
/**
|
|
17
|
-
* Register labor ticket processing handler
|
|
18
|
-
*/
|
|
19
|
-
private registerLaborTicketHandler;
|
|
20
|
-
/**
|
|
21
|
-
* Process labor ticket in ERP and then create MM entities with ERP ID attached
|
|
22
|
-
*/
|
|
23
|
-
private processLaborTicket;
|
|
24
|
-
/**
|
|
25
|
-
* Update checkpoint to prevent to-erp polling job from reprocessing this ticket
|
|
26
|
-
* Only updates if the new timestamp is later than the current checkpoint (prevents moving backwards)
|
|
27
|
-
*/
|
|
28
|
-
private updateCheckpoint;
|
|
29
|
-
}
|
|
30
|
-
//# sourceMappingURL=nats-labor-ticket-listener.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nats-labor-ticket-listener.d.ts","sourceRoot":"","sources":["../../../src/services/data-sync-service/nats-labor-ticket-listener.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,qBAAa,uBAAuB;IAClC,OAAO,CAAC,SAAS,CAAM;IACvB,OAAO,CAAC,WAAW,CAAC,CAAc;gBAEtB,SAAS,EAAE,GAAG;IAI1B;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA0C5B;;OAEG;IACH,OAAO,CAAC,0BAA0B;IAoBlC;;OAEG;IACH,OAAO,CAAC,0BAA0B;IA8GlC;;OAEG;YACW,kBAAkB;IA6FhC;;;OAGG;YACW,gBAAgB;CAyC/B"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export interface CompanyInfo {
|
|
2
|
-
timezone: string;
|
|
3
|
-
locationRef: string;
|
|
4
|
-
companyId: string;
|
|
5
|
-
}
|
|
6
|
-
/**
|
|
7
|
-
* Fetches company information from /accounts/current endpoint
|
|
8
|
-
* Results are cached to avoid repeated API calls
|
|
9
|
-
* @returns Promise<CompanyInfo> Company information including timezone, locationRef, and companyId
|
|
10
|
-
* @throws Error if unable to fetch company information
|
|
11
|
-
*/
|
|
12
|
-
export declare const getCompanyInfo: () => Promise<CompanyInfo>;
|
|
13
|
-
//# sourceMappingURL=company-info.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"company-info.d.ts","sourceRoot":"","sources":["../../../src/services/mm-api-service/company-info.ts"],"names":[],"mappings":"AAWA,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,eAAO,MAAM,cAAc,QAAa,OAAO,CAAC,WAAW,CA8D1D,CAAC"}
|
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NATS Service - Central connection and subscription management
|
|
3
|
-
* Allows connectors to register handlers for different NATS subjects
|
|
4
|
-
*/
|
|
5
|
-
export interface NatsMessageHandler {
|
|
6
|
-
/**
|
|
7
|
-
* Handler function for NATS messages
|
|
8
|
-
* - Return a value to reply (if msg has reply subject)
|
|
9
|
-
* - Return void/undefined for pub-sub (no reply)
|
|
10
|
-
*/
|
|
11
|
-
handle: (data: any, subject: string) => Promise<any | void>;
|
|
12
|
-
}
|
|
13
|
-
export interface NatsHandlerRegistration {
|
|
14
|
-
/**
|
|
15
|
-
* Subject pattern to subscribe to (supports wildcards: *, >)
|
|
16
|
-
* Examples:
|
|
17
|
-
* - "mm.14.epic01.labor-ticket.*" (single level wildcard)
|
|
18
|
-
* - "mm.14.epic01.erp.>" (multi-level wildcard)
|
|
19
|
-
*/
|
|
20
|
-
subject: string;
|
|
21
|
-
/**
|
|
22
|
-
* Handler for this subject
|
|
23
|
-
*/
|
|
24
|
-
handler: NatsMessageHandler;
|
|
25
|
-
/**
|
|
26
|
-
* Optional description for logging/debugging
|
|
27
|
-
*/
|
|
28
|
-
description?: string;
|
|
29
|
-
}
|
|
30
|
-
export interface NatsServiceConfig {
|
|
31
|
-
/**
|
|
32
|
-
* NATS server URLs
|
|
33
|
-
*/
|
|
34
|
-
servers: string | string[];
|
|
35
|
-
/**
|
|
36
|
-
* Connection name (for monitoring)
|
|
37
|
-
*/
|
|
38
|
-
name: string;
|
|
39
|
-
/**
|
|
40
|
-
* Location reference (for subject namespacing)
|
|
41
|
-
*/
|
|
42
|
-
locationRef: string;
|
|
43
|
-
/**
|
|
44
|
-
* ERP type (epicor, infor, etc.)
|
|
45
|
-
*/
|
|
46
|
-
erpType: string;
|
|
47
|
-
/**
|
|
48
|
-
* Enable/disable NATS
|
|
49
|
-
*/
|
|
50
|
-
enabled: boolean;
|
|
51
|
-
/**
|
|
52
|
-
* Auto-reconnect settings
|
|
53
|
-
*/
|
|
54
|
-
reconnect?: boolean;
|
|
55
|
-
maxReconnectAttempts?: number;
|
|
56
|
-
reconnectTimeWait?: number;
|
|
57
|
-
}
|
|
58
|
-
export declare class NatsService {
|
|
59
|
-
private connection;
|
|
60
|
-
private subscriptions;
|
|
61
|
-
private config;
|
|
62
|
-
private handlers;
|
|
63
|
-
private statusPublishTimer;
|
|
64
|
-
constructor(config: NatsServiceConfig);
|
|
65
|
-
/**
|
|
66
|
-
* Register a handler for a specific subject pattern
|
|
67
|
-
*/
|
|
68
|
-
registerHandler(registration: NatsHandlerRegistration): void;
|
|
69
|
-
/**
|
|
70
|
-
* Connect to NATS and start all registered handlers
|
|
71
|
-
*/
|
|
72
|
-
connect(): Promise<void>;
|
|
73
|
-
/**
|
|
74
|
-
* Start a single handler (subscribe to its subject)
|
|
75
|
-
*/
|
|
76
|
-
private startHandler;
|
|
77
|
-
/**
|
|
78
|
-
* Publish a message to a subject (for pub/sub)
|
|
79
|
-
*/
|
|
80
|
-
publish(subject: string, data: any): Promise<void>;
|
|
81
|
-
/**
|
|
82
|
-
* Send a request and wait for reply (for request-reply)
|
|
83
|
-
*/
|
|
84
|
-
request(subject: string, data: any, timeoutMs?: number): Promise<any>;
|
|
85
|
-
/**
|
|
86
|
-
* Check if connected to NATS
|
|
87
|
-
*/
|
|
88
|
-
isConnected(): boolean;
|
|
89
|
-
/**
|
|
90
|
-
* Start automatic status publishing (every 30 seconds)
|
|
91
|
-
*/
|
|
92
|
-
private startStatusPublishing;
|
|
93
|
-
/**
|
|
94
|
-
* Publish connector status
|
|
95
|
-
*/
|
|
96
|
-
private publishStatus;
|
|
97
|
-
/**
|
|
98
|
-
* Monitor connection status
|
|
99
|
-
*/
|
|
100
|
-
private monitorConnection;
|
|
101
|
-
/**
|
|
102
|
-
* Setup graceful shutdown
|
|
103
|
-
*/
|
|
104
|
-
private setupShutdown;
|
|
105
|
-
/**
|
|
106
|
-
* Disconnect from NATS
|
|
107
|
-
*/
|
|
108
|
-
disconnect(): Promise<void>;
|
|
109
|
-
/**
|
|
110
|
-
* Get the location reference
|
|
111
|
-
*/
|
|
112
|
-
getLocationRef(): string;
|
|
113
|
-
}
|
|
114
|
-
//# sourceMappingURL=nats-service.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nats-service.d.ts","sourceRoot":"","sources":["../../../src/services/nats-service/nats-service.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,MAAM,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;CAC7D;AAED,MAAM,WAAW,uBAAuB;IACtC;;;;;OAKG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,OAAO,EAAE,kBAAkB,CAAC;IAE5B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,qBAAa,WAAW;IACtB,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,aAAa,CAAwC;IAC7D,OAAO,CAAC,MAAM,CAAoB;IAClC,OAAO,CAAC,QAAQ,CAAiC;IACjD,OAAO,CAAC,kBAAkB,CAA+B;gBAE7C,MAAM,EAAE,iBAAiB;IAIrC;;OAEG;IACH,eAAe,CAAC,YAAY,EAAE,uBAAuB,GAAG,IAAI;IAQ5D;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA4C9B;;OAEG;YACW,YAAY;IA+D1B;;OAEG;IACG,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;IAWxD;;OAEG;IACG,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,GAAE,MAAc,GAAG,OAAO,CAAC,GAAG,CAAC;IAqBlF;;OAEG;IACH,WAAW,IAAI,OAAO;IAItB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAY7B;;OAEG;YACW,aAAa;IAoB3B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAgBzB;;OAEG;IACH,OAAO,CAAC,aAAa;IAWrB;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBjC;;OAEG;IACH,cAAc,IAAI,MAAM;CAGzB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"test-nats-subscriber.d.ts","sourceRoot":"","sources":["../../../src/services/nats-service/test-nats-subscriber.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Error formatter utility for standardizing error messages across connectors
|
|
3
|
-
* Extracts human-readable messages from various error types (axios, custom errors, etc.)
|
|
4
|
-
*/
|
|
5
|
-
export interface FormattedError {
|
|
6
|
-
message: string;
|
|
7
|
-
code: string;
|
|
8
|
-
httpStatus?: number;
|
|
9
|
-
metadata?: Record<string, any>;
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Extract meaningful error message from various error types
|
|
13
|
-
*/
|
|
14
|
-
export declare function formatError(error: any): FormattedError;
|
|
15
|
-
/**
|
|
16
|
-
* Format error for logging (shorter, cleaner version)
|
|
17
|
-
*/
|
|
18
|
-
export declare function formatErrorForLogging(error: any): string;
|
|
19
|
-
//# sourceMappingURL=error-formatter.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-formatter.d.ts","sourceRoot":"","sources":["../../src/utils/error-formatter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAChC;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,GAAG,GAAG,cAAc,CA6CtD;AAkID;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM,CAUxD"}
|
|
@@ -1,341 +0,0 @@
|
|
|
1
|
-
import logger from "../reporting-service/logger";
|
|
2
|
-
import { formatError } from "../../utils/error-formatter";
|
|
3
|
-
import { NatsService } from "../nats-service/nats-service";
|
|
4
|
-
import { MMReceiveLaborTicket, MMApiClient, getCompanyInfo } from "../mm-api-service";
|
|
5
|
-
import { SQLiteCoordinator } from "../sqlite-service";
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Manages NATS-based real-time labor ticket processing
|
|
9
|
-
*/
|
|
10
|
-
export class NatsLaborTicketListener {
|
|
11
|
-
private connector: any;
|
|
12
|
-
private natsService?: NatsService;
|
|
13
|
-
|
|
14
|
-
constructor(connector: any) {
|
|
15
|
-
this.connector = connector;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Start listening for labor ticket events via NATS
|
|
20
|
-
*/
|
|
21
|
-
async start(): Promise<void> {
|
|
22
|
-
try {
|
|
23
|
-
// Fetch company info from MM API (includes locationRef)
|
|
24
|
-
const companyInfo = await getCompanyInfo();
|
|
25
|
-
const erpType = this.connector.type || "unknown";
|
|
26
|
-
|
|
27
|
-
logger.info("Starting NATS listener for labor tickets", {
|
|
28
|
-
locationRef: companyInfo.locationRef,
|
|
29
|
-
companyId: companyInfo.companyId,
|
|
30
|
-
erpType,
|
|
31
|
-
servers: process.env.NATS_SERVERS || "nats://localhost:4222",
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
this.natsService = new NatsService({
|
|
35
|
-
servers: process.env.NATS_SERVERS || "nats://localhost:4222",
|
|
36
|
-
name: `${erpType}-connector`,
|
|
37
|
-
locationRef: companyInfo.locationRef,
|
|
38
|
-
erpType,
|
|
39
|
-
enabled: true,
|
|
40
|
-
reconnect: true,
|
|
41
|
-
maxReconnectAttempts: -1,
|
|
42
|
-
reconnectTimeWait: 2000,
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
// Register health check handler
|
|
46
|
-
this.registerHealthCheckHandler(companyInfo.locationRef, erpType);
|
|
47
|
-
|
|
48
|
-
// Register labor ticket handler
|
|
49
|
-
this.registerLaborTicketHandler(companyInfo.locationRef, erpType);
|
|
50
|
-
|
|
51
|
-
// Connect to NATS
|
|
52
|
-
await this.natsService.connect();
|
|
53
|
-
|
|
54
|
-
logger.info("NATS listener started successfully", {
|
|
55
|
-
subject: `mm.14.${companyInfo.locationRef}.labor-ticket.*`,
|
|
56
|
-
});
|
|
57
|
-
} catch (error) {
|
|
58
|
-
logger.error("Failed to start NATS listener", { error });
|
|
59
|
-
// Don't throw - allow REST polling to continue
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Register health check handler - responds immediately to let Dashboard know connector is online
|
|
65
|
-
*/
|
|
66
|
-
private registerHealthCheckHandler(locationRef: string, erpType: string): void {
|
|
67
|
-
if (!this.natsService) return;
|
|
68
|
-
|
|
69
|
-
this.natsService.registerHandler({
|
|
70
|
-
subject: `mm.14.${locationRef}.erp.health`,
|
|
71
|
-
description: "Health check - responds immediately to indicate connector is online",
|
|
72
|
-
handler: {
|
|
73
|
-
handle: async () => {
|
|
74
|
-
logger.debug("Health check received, sending pong");
|
|
75
|
-
return {
|
|
76
|
-
status: "online",
|
|
77
|
-
timestamp: new Date().toISOString(),
|
|
78
|
-
locationRef,
|
|
79
|
-
erpType,
|
|
80
|
-
};
|
|
81
|
-
},
|
|
82
|
-
},
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Register labor ticket processing handler
|
|
88
|
-
*/
|
|
89
|
-
private registerLaborTicketHandler(locationRef: string, erpType: string): void {
|
|
90
|
-
if (!this.natsService) return;
|
|
91
|
-
|
|
92
|
-
this.natsService.registerHandler({
|
|
93
|
-
subject: `mm.14.${locationRef}.labor-ticket.*`,
|
|
94
|
-
description: "Process labor tickets in real-time from NATS",
|
|
95
|
-
handler: {
|
|
96
|
-
handle: async ({ data }: any, subject: string) => {
|
|
97
|
-
const action = subject.split(".").pop();
|
|
98
|
-
const { actionPayload } = data;
|
|
99
|
-
const startTime = Date.now();
|
|
100
|
-
const { laborTicketRef } = actionPayload;
|
|
101
|
-
|
|
102
|
-
logger.info("Received labor ticket via NATS", {
|
|
103
|
-
action,
|
|
104
|
-
requestId: data.requestId,
|
|
105
|
-
laborTicketRef,
|
|
106
|
-
});
|
|
107
|
-
|
|
108
|
-
// Use the same lock as to-erp job to prevent concurrent processing
|
|
109
|
-
return await SQLiteCoordinator.executeWithLock("to-erp", async () => {
|
|
110
|
-
try {
|
|
111
|
-
let laborTicketData;
|
|
112
|
-
|
|
113
|
-
if (laborTicketRef) {
|
|
114
|
-
// Fetch the full labor ticket data using the laborTicketRef
|
|
115
|
-
const mmApiClient = new MMApiClient();
|
|
116
|
-
const laborTicket = await mmApiClient.fetchLaborTicketByRef(laborTicketRef);
|
|
117
|
-
|
|
118
|
-
logger.info("Fetched labor ticket data from MM API", {
|
|
119
|
-
laborTicketRef,
|
|
120
|
-
laborTicketId: laborTicket.laborTicketId,
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
// Merge changed fields from actionPayload to ensure we process the actual changes
|
|
124
|
-
laborTicketData = {
|
|
125
|
-
...laborTicket,
|
|
126
|
-
...actionPayload,
|
|
127
|
-
};
|
|
128
|
-
} else {
|
|
129
|
-
// No laborTicketRef provided, use the actionPayload directly
|
|
130
|
-
logger.info("No laborTicketRef provided, using actionPayload directly", {
|
|
131
|
-
requestId: data.requestId,
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
laborTicketData = actionPayload;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
const mergedLaborTicket = new MMReceiveLaborTicket(laborTicketData);
|
|
138
|
-
|
|
139
|
-
// Process labor ticket: ERP operation first, then create MM entities with ERP ID
|
|
140
|
-
const result = await this.processLaborTicket(
|
|
141
|
-
mergedLaborTicket,
|
|
142
|
-
action || "unknown"
|
|
143
|
-
);
|
|
144
|
-
|
|
145
|
-
// Update checkpoint to prevent to-erp polling job from reprocessing this ticket
|
|
146
|
-
await this.updateCheckpoint(erpType, result);
|
|
147
|
-
|
|
148
|
-
// Return response with full labor ticket data for immediate frontend state update
|
|
149
|
-
return {
|
|
150
|
-
status: "success",
|
|
151
|
-
requestId: data.requestId,
|
|
152
|
-
action,
|
|
153
|
-
timestamp: new Date().toISOString(),
|
|
154
|
-
processingTimeMs: Date.now() - startTime,
|
|
155
|
-
laborTicketRef: result.laborTicketRef,
|
|
156
|
-
laborTicket: result.laborTicket,
|
|
157
|
-
};
|
|
158
|
-
} catch (error) {
|
|
159
|
-
// Check if error was already formatted in inner catch block
|
|
160
|
-
const formattedError = (error as any)?._formatted || formatError(error);
|
|
161
|
-
|
|
162
|
-
// Debug logging
|
|
163
|
-
logger.debug("Error details", {
|
|
164
|
-
hasFormatted: !!(error as any)?._formatted,
|
|
165
|
-
isAxiosError: (error as any)?.isAxiosError,
|
|
166
|
-
errorMessage: (error as any)?.message,
|
|
167
|
-
responseStatus: (error as any)?.response?.status,
|
|
168
|
-
responseData: (error as any)?.response?.data,
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
logger.error("Error handling labor ticket from NATS", {
|
|
172
|
-
error: formattedError.message,
|
|
173
|
-
code: formattedError.code,
|
|
174
|
-
requestId: data.requestId,
|
|
175
|
-
laborTicketRef,
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
return {
|
|
179
|
-
status: "error",
|
|
180
|
-
requestId: data.requestId,
|
|
181
|
-
action,
|
|
182
|
-
timestamp: new Date().toISOString(),
|
|
183
|
-
processingTimeMs: Date.now() - startTime,
|
|
184
|
-
error: {
|
|
185
|
-
message: formattedError.message,
|
|
186
|
-
code: formattedError.code,
|
|
187
|
-
httpStatus: formattedError.httpStatus,
|
|
188
|
-
metadata: formattedError.metadata,
|
|
189
|
-
laborTicketRef,
|
|
190
|
-
},
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
});
|
|
194
|
-
},
|
|
195
|
-
},
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* Process labor ticket in ERP and then create MM entities with ERP ID attached
|
|
201
|
-
*/
|
|
202
|
-
private async processLaborTicket(
|
|
203
|
-
laborTicket: MMReceiveLaborTicket,
|
|
204
|
-
action: string
|
|
205
|
-
): Promise<{ laborTicketRef: string; laborTicket: any }> {
|
|
206
|
-
const { MMEntityProcessor } = await import("../../utils/standard-process-drivers/mm-entity-processor");
|
|
207
|
-
const { ERPObjType } = await import("../../types/erp-types");
|
|
208
|
-
const { MMSendLaborTicket } = await import("../mm-api-service");
|
|
209
|
-
|
|
210
|
-
logger.info("Processing labor ticket: ERP first, then MM creation", {
|
|
211
|
-
laborTicketRef: laborTicket.laborTicketRef,
|
|
212
|
-
action,
|
|
213
|
-
hasLaborTicketId: !!laborTicket.laborTicketId,
|
|
214
|
-
});
|
|
215
|
-
|
|
216
|
-
try {
|
|
217
|
-
let erpResult;
|
|
218
|
-
|
|
219
|
-
if (action === "create" || !laborTicket.laborTicketId) {
|
|
220
|
-
// Create new labor ticket in ERP
|
|
221
|
-
erpResult = await this.connector.createLaborTicketInERP(laborTicket);
|
|
222
|
-
logger.info("Successfully created labor ticket in ERP", {
|
|
223
|
-
laborTicketRef: laborTicket.laborTicketRef,
|
|
224
|
-
erpUid: erpResult.erpUid,
|
|
225
|
-
});
|
|
226
|
-
} else {
|
|
227
|
-
// Update existing labor ticket in ERP
|
|
228
|
-
erpResult = { laborTicket: await this.connector.updateLaborTicketInERP(laborTicket) };
|
|
229
|
-
logger.info("Successfully updated labor ticket in ERP", {
|
|
230
|
-
laborTicketRef: laborTicket.laborTicketRef,
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// Now update MM entities with ERP ID attached
|
|
235
|
-
const laborTicketForMM = { ...laborTicket };
|
|
236
|
-
if (erpResult.erpUid) {
|
|
237
|
-
laborTicketForMM.laborTicketId = erpResult.erpUid;
|
|
238
|
-
|
|
239
|
-
// If this was a create (no initial laborTicketId) with a laborTicketRef,
|
|
240
|
-
// patch the existing orphaned MM record with the new ERP ID first
|
|
241
|
-
if (!laborTicket.laborTicketId && laborTicketForMM.laborTicketRef) {
|
|
242
|
-
const mmApiClient = new MMApiClient();
|
|
243
|
-
await mmApiClient.updateLaborTicketIdByRef(
|
|
244
|
-
laborTicketForMM.laborTicketRef,
|
|
245
|
-
erpResult.erpUid
|
|
246
|
-
);
|
|
247
|
-
|
|
248
|
-
logger.info("Patched existing MM labor ticket with new ERP ID", {
|
|
249
|
-
laborTicketRef: laborTicketForMM.laborTicketRef,
|
|
250
|
-
laborTicketId: erpResult.erpUid,
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// Set state based on clockOut before writing to MM
|
|
256
|
-
laborTicketForMM.state = laborTicketForMM.clockOut ? "CLOSED" : "OPEN";
|
|
257
|
-
|
|
258
|
-
// Write all fields to MM (this updates the existing record now that it has laborTicketId)
|
|
259
|
-
const mmLaborTicket = MMSendLaborTicket.fromPlainObject(laborTicketForMM as any);
|
|
260
|
-
|
|
261
|
-
const mmResult = await MMEntityProcessor.writeEntities(
|
|
262
|
-
ERPObjType.LABOR_TICKETS,
|
|
263
|
-
[mmLaborTicket],
|
|
264
|
-
null // No caching for real-time operations
|
|
265
|
-
);
|
|
266
|
-
|
|
267
|
-
logger.info("Successfully updated MM entities after ERP operation", {
|
|
268
|
-
laborTicketRef: laborTicketForMM.laborTicketRef,
|
|
269
|
-
laborTicketId: laborTicketForMM.laborTicketId,
|
|
270
|
-
entitiesCreated: mmResult.upsertedEntities,
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
return {
|
|
274
|
-
laborTicketRef: laborTicketForMM.laborTicketRef!,
|
|
275
|
-
laborTicket: laborTicketForMM,
|
|
276
|
-
};
|
|
277
|
-
} catch (error) {
|
|
278
|
-
// Format error to preserve meaningful message
|
|
279
|
-
const formattedError = formatError(error);
|
|
280
|
-
|
|
281
|
-
logger.error("Failed to process labor ticket with MM creation", {
|
|
282
|
-
laborTicketRef: laborTicket.laborTicketRef,
|
|
283
|
-
action,
|
|
284
|
-
error: formattedError.message,
|
|
285
|
-
code: formattedError.code,
|
|
286
|
-
});
|
|
287
|
-
|
|
288
|
-
// Create enhanced error to propagate
|
|
289
|
-
const enhancedError: any = error;
|
|
290
|
-
enhancedError._formatted = formattedError;
|
|
291
|
-
throw enhancedError;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
/**
|
|
296
|
-
* Update checkpoint to prevent to-erp polling job from reprocessing this ticket
|
|
297
|
-
* Only updates if the new timestamp is later than the current checkpoint (prevents moving backwards)
|
|
298
|
-
*/
|
|
299
|
-
private async updateCheckpoint(
|
|
300
|
-
erpType: string,
|
|
301
|
-
result: { laborTicketRef: string; laborTicket: any }
|
|
302
|
-
): Promise<void> {
|
|
303
|
-
const mmApiClient = new MMApiClient();
|
|
304
|
-
const currentCheckpoint = await mmApiClient.getCheckpoint({
|
|
305
|
-
system: erpType,
|
|
306
|
-
table: "labor_tickets",
|
|
307
|
-
checkpointType: "export",
|
|
308
|
-
checkpointValue: {
|
|
309
|
-
timestamp: "",
|
|
310
|
-
},
|
|
311
|
-
});
|
|
312
|
-
|
|
313
|
-
const currentTimestamp = (currentCheckpoint as any)?.timestamp;
|
|
314
|
-
const newTimestamp = result.laborTicket.updatedAt || new Date().toISOString();
|
|
315
|
-
|
|
316
|
-
// Only update checkpoint if new timestamp is later than current (prevents moving backwards)
|
|
317
|
-
if (!currentTimestamp || new Date(newTimestamp) > new Date(currentTimestamp)) {
|
|
318
|
-
await mmApiClient.saveCheckpoint({
|
|
319
|
-
system: erpType,
|
|
320
|
-
table: "labor_tickets",
|
|
321
|
-
checkpointType: "export",
|
|
322
|
-
checkpointValue: {
|
|
323
|
-
timestamp: newTimestamp,
|
|
324
|
-
},
|
|
325
|
-
});
|
|
326
|
-
|
|
327
|
-
logger.debug("Updated export checkpoint after NATS processing", {
|
|
328
|
-
laborTicketRef: result.laborTicketRef,
|
|
329
|
-
previousCheckpoint: currentTimestamp,
|
|
330
|
-
newCheckpoint: newTimestamp,
|
|
331
|
-
});
|
|
332
|
-
} else {
|
|
333
|
-
logger.debug("Skipped checkpoint update (timestamp not newer)", {
|
|
334
|
-
laborTicketRef: result.laborTicketRef,
|
|
335
|
-
currentCheckpoint: currentTimestamp,
|
|
336
|
-
ticketTimestamp: newTimestamp,
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { CoreConfiguration } from "../data-sync-service/configuration-manager";
|
|
2
|
-
import { HTTPClientFactory } from "../../utils/http-client";
|
|
3
|
-
import { logger } from "../reporting-service";
|
|
4
|
-
|
|
5
|
-
// Cache for company info to avoid repeated API calls
|
|
6
|
-
let companyInfoCache: {
|
|
7
|
-
timezone: string;
|
|
8
|
-
locationRef: string;
|
|
9
|
-
companyId: string;
|
|
10
|
-
} | null = null;
|
|
11
|
-
|
|
12
|
-
export interface CompanyInfo {
|
|
13
|
-
timezone: string;
|
|
14
|
-
locationRef: string;
|
|
15
|
-
companyId: string;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Fetches company information from /accounts/current endpoint
|
|
20
|
-
* Results are cached to avoid repeated API calls
|
|
21
|
-
* @returns Promise<CompanyInfo> Company information including timezone, locationRef, and companyId
|
|
22
|
-
* @throws Error if unable to fetch company information
|
|
23
|
-
*/
|
|
24
|
-
export const getCompanyInfo = async (): Promise<CompanyInfo> => {
|
|
25
|
-
// Return cached value if available
|
|
26
|
-
if (companyInfoCache) {
|
|
27
|
-
return companyInfoCache;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
try {
|
|
31
|
-
// Get the configuration
|
|
32
|
-
const config = CoreConfiguration.inst();
|
|
33
|
-
const apiUrl = config.mmApiBaseUrl;
|
|
34
|
-
const authToken = config.mmApiAuthToken;
|
|
35
|
-
|
|
36
|
-
if (!apiUrl || !authToken) {
|
|
37
|
-
throw new Error("Missing required configuration for company info fetch");
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Create HTTP client
|
|
41
|
-
const client = HTTPClientFactory.getInstance({
|
|
42
|
-
baseUrl: apiUrl,
|
|
43
|
-
retryAttempts: config.mmApiRetryAttempts,
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
// Fetch user/company information from the API
|
|
47
|
-
const response = await client.request<{
|
|
48
|
-
company: {
|
|
49
|
-
timezone: string;
|
|
50
|
-
id: string;
|
|
51
|
-
};
|
|
52
|
-
locationRef: number;
|
|
53
|
-
}>({
|
|
54
|
-
url: "/accounts/current?includeLocation=true",
|
|
55
|
-
method: "GET",
|
|
56
|
-
headers: {
|
|
57
|
-
Authorization: `Bearer ${authToken}`,
|
|
58
|
-
},
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
const userInfo = response.data;
|
|
62
|
-
if (!userInfo?.company) {
|
|
63
|
-
throw new Error("Unable to retrieve company information from API");
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Debug: Log what we actually got from the API
|
|
67
|
-
logger.info("Fetched company info from /accounts/current", {
|
|
68
|
-
locationRef: userInfo.locationRef,
|
|
69
|
-
companyId: userInfo.company.id,
|
|
70
|
-
timezone: userInfo.company.timezone,
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
// Cache and return company info - locationRef is at top level, not in company
|
|
74
|
-
companyInfoCache = {
|
|
75
|
-
timezone: userInfo.company.timezone,
|
|
76
|
-
locationRef: String(userInfo.locationRef), // Convert number to string
|
|
77
|
-
companyId: userInfo.company.id,
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
return companyInfoCache;
|
|
81
|
-
} catch (error) {
|
|
82
|
-
throw new Error(
|
|
83
|
-
`Failed to get company info: ${error instanceof Error ? error.message : "Unknown error"}`
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
|