-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexternal-submission-service.js
More file actions
279 lines (260 loc) · 7.65 KB
/
external-submission-service.js
File metadata and controls
279 lines (260 loc) · 7.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import { config } from '../../../config.js'
const HTTP_OK = 200
export const SUBMISSION_STATUS = {
PENDING: 'pending',
SUCCESS: 'success',
FAILED: 'failed'
}
/**
* ExternalSubmissionService
*
* Sends a prepared proposal payload to the external AIMS PD / Pipeline REST
* API and records the outcome in `pafs_proposal_submissions`.
*
* The service is intentionally stateless — each call is independent so that
* the admin resend path can use the same code as the initial submission.
*/
export class ExternalSubmissionService {
constructor(prisma, logger) {
this.prisma = prisma
this.logger = logger
this.enabled = config.get('externalSubmission.enabled')
this.baseUrl = config.get('externalSubmission.baseUrl')
this.endpoint = config.get('externalSubmission.endpoint')
this.accessCode = config.get('externalSubmission.accessCode')
this.timeout = config.get('externalSubmission.timeout')
}
/**
* Send the proposal payload to the external system.
*
* Always records an attempt row in pafs_proposal_submissions regardless of
* outcome so the admin panel can show the history.
*
* @param {Object} options
* @param {bigint|number} options.projectId - DB project id
* @param {string} options.referenceNumber - Project reference number
* @param {Object} options.payload - Built proposal payload object
* @param {boolean} [options.isResend=false] - true for admin-triggered resends
* @returns {Promise<{success: boolean, httpStatus?: number, error?: string}>}
*/
async send({ projectId, referenceNumber, payload, isResend = false }) {
if (!this.enabled) {
this.logger.warn(
{ referenceNumber },
'External submission disabled — skipping send'
)
await this._recordAttempt({
projectId,
referenceNumber,
status: SUBMISSION_STATUS.FAILED,
httpStatusCode: null,
errorMessage: 'External submission is disabled',
responseBody: null,
requestPayload: this._scrubPayload(payload),
isResend
})
return { success: false, error: 'External submission is disabled' }
}
let httpStatus = null
let responseText = null
try {
;({ httpStatus, responseText } = await this._executeRequest(
payload,
referenceNumber
))
if (httpStatus !== HTTP_OK) {
return await this._handleFailure({
projectId,
referenceNumber,
httpStatus,
responseText,
payload,
isResend
})
}
return await this._handleSuccess({
projectId,
referenceNumber,
httpStatus,
responseText,
payload,
isResend
})
} catch (error) {
const errorMessage =
error.name === 'AbortError'
? `Request timed out after ${this.timeout}ms`
: error.message
this.logger.error(
{ referenceNumber, error: errorMessage },
'External submission request failed'
)
await this._recordAttempt({
projectId,
referenceNumber,
status: SUBMISSION_STATUS.FAILED,
httpStatusCode: httpStatus,
errorMessage,
responseBody: responseText,
requestPayload: this._scrubPayload(payload),
isResend
})
return { success: false, error: errorMessage }
}
}
/**
* Execute the HTTP POST request with a timeout.
* Returns the HTTP status code and response body text.
* @private
*/
async _executeRequest(payload, referenceNumber) {
const url = new URL(`${this.baseUrl}${this.endpoint}`)
url.searchParams.set('code', this.accessCode)
this.logger.info(
{ referenceNumber, url: `${this.baseUrl}${this.endpoint}` },
'Sending proposal to external system'
)
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), this.timeout)
let response
try {
response = await fetch(url.toString(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: controller.signal
})
} finally {
clearTimeout(timer)
}
const responseText = await response.text().catch(() => null)
return { httpStatus: response.status, responseText }
}
/**
* Handle a non-OK HTTP response — record failure and return result.
* @private
*/
async _handleFailure({
projectId,
referenceNumber,
httpStatus,
responseText,
payload,
isResend
}) {
this.logger.warn(
{ referenceNumber, httpStatus },
'External submission returned non-OK HTTP status'
)
await this._recordAttempt({
projectId,
referenceNumber,
status: SUBMISSION_STATUS.FAILED,
httpStatusCode: httpStatus,
errorMessage: `HTTP ${httpStatus}`,
responseBody: responseText,
requestPayload: this._scrubPayload(payload),
isResend
})
return { success: false, httpStatus, error: `HTTP ${httpStatus}` }
}
/**
* Handle a successful HTTP response — record success, stamp pol date, return result.
* @private
*/
async _handleSuccess({
projectId,
referenceNumber,
httpStatus,
responseText,
payload,
isResend
}) {
this.logger.info(
{ referenceNumber, httpStatus },
'Proposal sent to external system successfully'
)
await this._recordAttempt({
projectId,
referenceNumber,
status: SUBMISSION_STATUS.SUCCESS,
httpStatusCode: httpStatus,
errorMessage: null,
responseBody: responseText,
requestPayload: this._scrubPayload(payload),
isResend
})
await this.markSubmittedToPol(referenceNumber)
return { success: true, httpStatus }
}
/**
* Persist a submission attempt to pafs_proposal_submissions.
* @private
*/
/**
* Return a copy of the payload with the shapefile base64 stripped.
* The binary data can be multi-megabytes — the S3 key on the project record
* is sufficient to retrieve the file when needed.
* @private
*/
_scrubPayload(payload) {
if (!payload) {
return null
}
if (!payload.shapefile) {
return payload
}
return { ...payload, shapefile: '[base64_omitted]' }
}
async _recordAttempt({
projectId,
referenceNumber,
status,
httpStatusCode,
errorMessage,
responseBody,
requestPayload = null,
isResend
}) {
try {
await this.prisma.pafs_proposal_submissions.create({
data: {
project_id: BigInt(projectId),
reference_number: referenceNumber,
status,
http_status_code: httpStatusCode,
error_message: errorMessage,
response_body: responseBody,
request_payload: requestPayload,
is_resend: isResend,
attempted_at: new Date(),
created_at: new Date()
}
})
} catch (dbError) {
// Recording failure must not block the caller — log and continue.
this.logger.error(
{ referenceNumber, error: dbError.message },
'Failed to record submission attempt in database'
)
}
}
/**
* Update submitted_to_pol timestamp on the project record.
* Public so callers (e.g. admin mark-submitted-to-pol endpoint) can reuse
* this without duplicating the Prisma call.
*/
async markSubmittedToPol(referenceNumber) {
try {
await this.prisma.pafs_core_projects.updateMany({
where: { reference_number: referenceNumber },
data: { submitted_to_pol: new Date() }
})
} catch (dbError) {
this.logger.error(
{ referenceNumber, error: dbError.message },
'Failed to update submitted_to_pol on project'
)
}
}
}