Varun10000 Claude Fable 5 commited on
Commit
be50eca
Β·
1 Parent(s): 9006385

PDF via pdfkit (pure JS, works in sandboxed hosts); artifacts file into case folder; size-case fix in cost estimator

Browse files
Files changed (5) hide show
  1. box-service.js +7 -1
  2. case-report.html +1 -1
  3. package-lock.json +201 -0
  4. package.json +1 -0
  5. server.js +127 -16
box-service.js CHANGED
@@ -804,7 +804,13 @@ function createBoxService({ configStore }) {
804
  }
805
 
806
  const report = caseRecord?.report || {};
807
- const folderId = report.boxFolderId || status.caseRootFolderId || status.intakeFolderId;
 
 
 
 
 
 
808
  const buffer = Buffer.isBuffer(content) ? content : Buffer.from(String(content ?? ''), 'utf8');
809
 
810
  const upload = await uploadBufferToBox({
 
804
  }
805
 
806
  const report = caseRecord?.report || {};
807
+ // Prefer the case's own folder (Potholes/{ward}/Case-{id}) so artifacts like
808
+ // after-photos live WITH the case, not loose in the intake root.
809
+ let folderId = report.boxFolderId || '';
810
+ if (!folderId) {
811
+ try { folderId = await findCaseFolderId(caseId || caseRecord?.caseId, caseRecord, boxConfig) || ''; } catch (_) {}
812
+ }
813
+ if (!folderId) folderId = status.caseRootFolderId || status.intakeFolderId;
814
  const buffer = Buffer.isBuffer(content) ? content : Buffer.from(String(content ?? ''), 'utf8');
815
 
816
  const upload = await uploadBufferToBox({
case-report.html CHANGED
@@ -116,7 +116,7 @@
116
  const dash = (v) => (v === 0 || v) ? v : 'β€”';
117
 
118
  function estimateRepairCost(size, severityScore, address) {
119
- const base = { Small: 140, Medium: 260, Large: 480 }[size] || 0;
120
  if (!base) return { base: 0, severity: 0, traffic: 0, total: 0 };
121
  const score = Math.max(0, Math.min(100, num(severityScore) || 50));
122
  const severity = Math.round((score / 100) * 80);
 
116
  const dash = (v) => (v === 0 || v) ? v : 'β€”';
117
 
118
  function estimateRepairCost(size, severityScore, address) {
119
+ const base = { small: 140, medium: 260, large: 480 }[String(size || '').trim().toLowerCase()] || 0;
120
  if (!base) return { base: 0, severity: 0, traffic: 0, total: 0 };
121
  const score = Math.max(0, Math.min(100, num(severityScore) || 50));
122
  const severity = Math.round((score / 100) * 80);
package-lock.json CHANGED
@@ -11,9 +11,34 @@
11
  "dependencies": {
12
  "@supabase/supabase-js": "^2.108.2",
13
  "jose": "^6.2.3",
 
14
  "pg": "^8.22.0"
15
  }
16
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  "node_modules/@supabase/auth-js": {
18
  "version": "2.108.2",
19
  "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.108.2.tgz",
@@ -98,6 +123,91 @@
98
  "node": ">=20.0.0"
99
  }
100
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  "node_modules/iceberg-js": {
102
  "version": "0.8.1",
103
  "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
@@ -116,6 +226,51 @@
116
  "url": "https://github.com/sponsors/panva"
117
  }
118
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  "node_modules/pg": {
120
  "version": "8.22.0",
121
  "resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
@@ -205,6 +360,14 @@
205
  "split2": "^4.1.0"
206
  }
207
  },
 
 
 
 
 
 
 
 
208
  "node_modules/postgres-array": {
209
  "version": "2.0.0",
210
  "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
@@ -244,6 +407,12 @@
244
  "node": ">=0.10.0"
245
  }
246
  },
 
 
 
 
 
 
247
  "node_modules/split2": {
248
  "version": "4.2.0",
249
  "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
@@ -253,12 +422,44 @@
253
  "node": ">= 10.x"
254
  }
255
  },
 
 
 
 
 
 
256
  "node_modules/tslib": {
257
  "version": "2.8.1",
258
  "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
259
  "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
260
  "license": "0BSD"
261
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  "node_modules/xtend": {
263
  "version": "4.0.2",
264
  "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
 
11
  "dependencies": {
12
  "@supabase/supabase-js": "^2.108.2",
13
  "jose": "^6.2.3",
14
+ "pdfkit": "^0.19.1",
15
  "pg": "^8.22.0"
16
  }
17
  },
18
+ "node_modules/@noble/ciphers": {
19
+ "version": "1.3.0",
20
+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
21
+ "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
22
+ "license": "MIT",
23
+ "engines": {
24
+ "node": "^14.21.3 || >=16"
25
+ },
26
+ "funding": {
27
+ "url": "https://paulmillr.com/funding/"
28
+ }
29
+ },
30
+ "node_modules/@noble/hashes": {
31
+ "version": "1.8.0",
32
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
33
+ "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
34
+ "license": "MIT",
35
+ "engines": {
36
+ "node": "^14.21.3 || >=16"
37
+ },
38
+ "funding": {
39
+ "url": "https://paulmillr.com/funding/"
40
+ }
41
+ },
42
  "node_modules/@supabase/auth-js": {
43
  "version": "2.108.2",
44
  "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.108.2.tgz",
 
123
  "node": ">=20.0.0"
124
  }
125
  },
126
+ "node_modules/@swc/helpers": {
127
+ "version": "0.5.23",
128
+ "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
129
+ "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==",
130
+ "license": "Apache-2.0",
131
+ "dependencies": {
132
+ "tslib": "^2.8.0"
133
+ }
134
+ },
135
+ "node_modules/base64-js": {
136
+ "version": "1.5.1",
137
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
138
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
139
+ "funding": [
140
+ {
141
+ "type": "github",
142
+ "url": "https://github.com/sponsors/feross"
143
+ },
144
+ {
145
+ "type": "patreon",
146
+ "url": "https://www.patreon.com/feross"
147
+ },
148
+ {
149
+ "type": "consulting",
150
+ "url": "https://feross.org/support"
151
+ }
152
+ ],
153
+ "license": "MIT"
154
+ },
155
+ "node_modules/brotli": {
156
+ "version": "1.3.3",
157
+ "resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
158
+ "integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
159
+ "license": "MIT",
160
+ "dependencies": {
161
+ "base64-js": "^1.1.2"
162
+ }
163
+ },
164
+ "node_modules/browserify-zlib": {
165
+ "version": "0.2.0",
166
+ "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz",
167
+ "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==",
168
+ "license": "MIT",
169
+ "dependencies": {
170
+ "pako": "~1.0.5"
171
+ }
172
+ },
173
+ "node_modules/clone": {
174
+ "version": "2.1.2",
175
+ "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
176
+ "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
177
+ "license": "MIT",
178
+ "engines": {
179
+ "node": ">=0.8"
180
+ }
181
+ },
182
+ "node_modules/dfa": {
183
+ "version": "1.2.0",
184
+ "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
185
+ "integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
186
+ "license": "MIT"
187
+ },
188
+ "node_modules/fast-deep-equal": {
189
+ "version": "3.1.3",
190
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
191
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
192
+ "license": "MIT"
193
+ },
194
+ "node_modules/fontkit": {
195
+ "version": "2.0.4",
196
+ "resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
197
+ "integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
198
+ "license": "MIT",
199
+ "dependencies": {
200
+ "@swc/helpers": "^0.5.12",
201
+ "brotli": "^1.3.2",
202
+ "clone": "^2.1.2",
203
+ "dfa": "^1.2.0",
204
+ "fast-deep-equal": "^3.1.3",
205
+ "restructure": "^3.0.0",
206
+ "tiny-inflate": "^1.0.3",
207
+ "unicode-properties": "^1.4.0",
208
+ "unicode-trie": "^2.0.0"
209
+ }
210
+ },
211
  "node_modules/iceberg-js": {
212
  "version": "0.8.1",
213
  "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
 
226
  "url": "https://github.com/sponsors/panva"
227
  }
228
  },
229
+ "node_modules/js-md5": {
230
+ "version": "0.8.3",
231
+ "resolved": "https://registry.npmjs.org/js-md5/-/js-md5-0.8.3.tgz",
232
+ "integrity": "sha512-qR0HB5uP6wCuRMrWPTrkMaev7MJZwJuuw4fnwAzRgP4J4/F8RwtodOKpGp4XpqsLBFzzgqIO42efFAyz2Et6KQ==",
233
+ "license": "MIT"
234
+ },
235
+ "node_modules/linebreak": {
236
+ "version": "1.1.0",
237
+ "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
238
+ "integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
239
+ "license": "MIT",
240
+ "dependencies": {
241
+ "base64-js": "0.0.8",
242
+ "unicode-trie": "^2.0.0"
243
+ }
244
+ },
245
+ "node_modules/linebreak/node_modules/base64-js": {
246
+ "version": "0.0.8",
247
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
248
+ "integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
249
+ "license": "MIT",
250
+ "engines": {
251
+ "node": ">= 0.4"
252
+ }
253
+ },
254
+ "node_modules/pako": {
255
+ "version": "1.0.11",
256
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
257
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
258
+ "license": "(MIT AND Zlib)"
259
+ },
260
+ "node_modules/pdfkit": {
261
+ "version": "0.19.1",
262
+ "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.19.1.tgz",
263
+ "integrity": "sha512-6Gzk+wDwTs4VSxsR5rCMTnIl5nlmkye1oWB0l2hDB1EX6ZNSIBroKQEv+2+fPPn+stVjyqzmsqRJVDfB9fo5DA==",
264
+ "license": "MIT",
265
+ "dependencies": {
266
+ "@noble/ciphers": "^1.0.0",
267
+ "@noble/hashes": "^1.6.0",
268
+ "fontkit": "^2.0.4",
269
+ "js-md5": "^0.8.3",
270
+ "linebreak": "^1.1.0",
271
+ "png-js": "^1.1.0"
272
+ }
273
+ },
274
  "node_modules/pg": {
275
  "version": "8.22.0",
276
  "resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
 
360
  "split2": "^4.1.0"
361
  }
362
  },
363
+ "node_modules/png-js": {
364
+ "version": "1.1.0",
365
+ "resolved": "https://registry.npmjs.org/png-js/-/png-js-1.1.0.tgz",
366
+ "integrity": "sha512-PM/uYGzGdNSzqeOgly68+6wKQDL1SY0a/N+OEa/+br6LnHWOAJB0Npiamnodfq3jd2LS/i2fMeOKSAILjA+m5Q==",
367
+ "dependencies": {
368
+ "browserify-zlib": "^0.2.0"
369
+ }
370
+ },
371
  "node_modules/postgres-array": {
372
  "version": "2.0.0",
373
  "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
 
407
  "node": ">=0.10.0"
408
  }
409
  },
410
+ "node_modules/restructure": {
411
+ "version": "3.0.2",
412
+ "resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
413
+ "integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
414
+ "license": "MIT"
415
+ },
416
  "node_modules/split2": {
417
  "version": "4.2.0",
418
  "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
 
422
  "node": ">= 10.x"
423
  }
424
  },
425
+ "node_modules/tiny-inflate": {
426
+ "version": "1.0.3",
427
+ "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
428
+ "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
429
+ "license": "MIT"
430
+ },
431
  "node_modules/tslib": {
432
  "version": "2.8.1",
433
  "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
434
  "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
435
  "license": "0BSD"
436
  },
437
+ "node_modules/unicode-properties": {
438
+ "version": "1.4.1",
439
+ "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
440
+ "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
441
+ "license": "MIT",
442
+ "dependencies": {
443
+ "base64-js": "^1.3.0",
444
+ "unicode-trie": "^2.0.0"
445
+ }
446
+ },
447
+ "node_modules/unicode-trie": {
448
+ "version": "2.0.0",
449
+ "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
450
+ "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
451
+ "license": "MIT",
452
+ "dependencies": {
453
+ "pako": "^0.2.5",
454
+ "tiny-inflate": "^1.0.0"
455
+ }
456
+ },
457
+ "node_modules/unicode-trie/node_modules/pako": {
458
+ "version": "0.2.9",
459
+ "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
460
+ "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
461
+ "license": "MIT"
462
+ },
463
  "node_modules/xtend": {
464
  "version": "4.0.2",
465
  "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
package.json CHANGED
@@ -14,6 +14,7 @@
14
  "dependencies": {
15
  "@supabase/supabase-js": "^2.108.2",
16
  "jose": "^6.2.3",
 
17
  "pg": "^8.22.0"
18
  }
19
  }
 
14
  "dependencies": {
15
  "@supabase/supabase-js": "^2.108.2",
16
  "jose": "^6.2.3",
17
+ "pdfkit": "^0.19.1",
18
  "pg": "^8.22.0"
19
  }
20
  }
server.js CHANGED
@@ -1043,8 +1043,8 @@ Proceed to the assigned stop in route order, complete the repair, capture after-
1043
  // Estimated repair cost from size + severity + road class (mirrors the Ops Review
1044
  // dashboard estimator) so the report can compare estimated vs. actual spend.
1045
  function estimateRepairCost(size, severityScore, address) {
1046
- const baseBySize = { Small: 140, Medium: 260, Large: 480 };
1047
- const base = baseBySize[size] || 0;
1048
  if (!base) return { base: 0, severity: 0, traffic: 0, total: 0 };
1049
  const score = Math.max(0, Math.min(100, Number(severityScore) || 50));
1050
  const severity = Math.round((score / 100) * 80);
@@ -1385,8 +1385,111 @@ function renderBeforeAfterHtml(spec, images = []) {
1385
  </body></html>`;
1386
  }
1387
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1388
  // Generate the before/after report as a PDF (photos + all data) into the Closeout
1389
- // Reports folder. Falls back to the .docx generator if PDF rendering is unavailable.
 
1390
  async function generateBeforeAfterReport({ caseId, caseRecord }) {
1391
  const report = caseRecord.report || {};
1392
  const images = [];
@@ -1395,7 +1498,7 @@ async function generateBeforeAfterReport({ caseId, caseRecord }) {
1395
  if (!id) return;
1396
  try {
1397
  const f = await boxService.getFileContent(id);
1398
- images.push({ dataUri: `data:image/jpeg;base64,${Buffer.from(f.body).toString('base64')}`, caption });
1399
  } catch (e) {
1400
  console.warn('[before-after pdf] photo fetch failed', id, e.message);
1401
  }
@@ -1403,21 +1506,28 @@ async function generateBeforeAfterReport({ caseId, caseRecord }) {
1403
  await addPhoto(report.photoFileId, 'Before β€” Reported Condition');
1404
  await addPhoto(report.afterPhotoFileId, 'After β€” Completed Repair');
1405
 
 
 
 
1406
  try {
1407
- const spec = buildBeforeAfterDocSpec(caseRecord, []);
1408
- const pdf = await htmlToPdf(renderBeforeAfterHtml(spec, images));
1409
- const fileName = `${caseId}_before_after_report.pdf`;
1410
- const result = await boxService.uploadCloseoutReport({
1411
- caseId,
1412
- fileName,
1413
- content: pdf,
1414
- contentType: 'application/pdf',
1415
- });
1416
- return { ...result, fileName, embeddedImages: images.length, format: 'pdf' };
1417
  } catch (e) {
1418
- console.warn('[before-after] PDF generation failed, falling back to .docx:', e.message);
1419
- return await generateBeforeAfterDoc({ caseId, caseRecord });
 
 
 
 
 
1420
  }
 
 
 
 
 
 
 
 
1421
  }
1422
 
1423
  // ── Box case-list cache ───────────────────────────────────────────────────────
@@ -2649,6 +2759,7 @@ async function handleApiRequest(req, res, reqUrl) {
2649
  // Photo + AI fields so the before/after report is complete even when the
2650
  // hosted store started fresh (they live in the sidecar / Box folder).
2651
  photoFileId: pick(r.photoFileId, sc.photoFileId, boxMeta && boxMeta.photoFileId),
 
2652
  aiResult: pick(r.aiResult, sc.aiResult, boxMeta && boxMeta.potholeSize),
2653
  aiPrediction: pick(r.aiPrediction, sc.aiPrediction),
2654
  aiReviewStatus: pick(r.aiReviewStatus, sc.aiReviewStatus, boxMeta && boxMeta.aiReviewStatus),
 
1043
  // Estimated repair cost from size + severity + road class (mirrors the Ops Review
1044
  // dashboard estimator) so the report can compare estimated vs. actual spend.
1045
  function estimateRepairCost(size, severityScore, address) {
1046
+ const baseBySize = { small: 140, medium: 260, large: 480 };
1047
+ const base = baseBySize[String(size || '').trim().toLowerCase()] || 0;
1048
  if (!base) return { base: 0, severity: 0, traffic: 0, total: 0 };
1049
  const score = Math.max(0, Math.min(100, Number(severityScore) || 50));
1050
  const severity = Math.round((score / 100) * 80);
 
1385
  </body></html>`;
1386
  }
1387
 
1388
+ // Render the before/after report spec to PDF with pdfkit β€” pure JavaScript, no
1389
+ // external browser/renderer binaries, so it works identically on any host
1390
+ // (including sandboxed containers where Chromium/wkhtmltopdf cannot run).
1391
+ function renderBeforeAfterPdfKit(spec, images = []) {
1392
+ const PDFDocument = require('pdfkit');
1393
+ return new Promise((resolve, reject) => {
1394
+ const NAVY = '#003a85', INK = '#0b2545', GREY = '#5b6b85', LINE = '#dbe6f5', ROW = '#eef2f8';
1395
+ const M = 46; // page margin
1396
+ const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: M, left: M, right: M } });
1397
+ const W = doc.page.width - M * 2; // usable width
1398
+ const chunks = [];
1399
+ doc.on('data', (c) => chunks.push(c));
1400
+ doc.on('end', () => resolve(Buffer.concat(chunks)));
1401
+ doc.on('error', reject);
1402
+
1403
+ const ensureRoom = (h) => {
1404
+ if (doc.y + h > doc.page.height - M) { doc.addPage(); }
1405
+ };
1406
+
1407
+ const sectionHeader = (label) => {
1408
+ ensureRoom(40);
1409
+ doc.moveDown(0.9);
1410
+ doc.font('Helvetica-Bold').fontSize(9).fillColor(GREY)
1411
+ .text(String(label).toUpperCase(), M, doc.y, { characterSpacing: 0.8 });
1412
+ const y = doc.y + 3;
1413
+ doc.moveTo(M, y).lineTo(M + W, y).lineWidth(1).strokeColor(LINE).stroke();
1414
+ doc.y = y + 8;
1415
+ };
1416
+
1417
+ const kvRow = (label, value) => {
1418
+ const labW = Math.round(W * 0.36);
1419
+ const valW = W - labW - 10;
1420
+ const val = (value === undefined || value === null || String(value).trim() === '') ? 'β€”' : String(value);
1421
+ doc.font('Helvetica-Bold').fontSize(9);
1422
+ const h = Math.max(
1423
+ doc.heightOfString(String(label), { width: labW }),
1424
+ doc.heightOfString(val, { width: valW }),
1425
+ ) + 8;
1426
+ ensureRoom(h + 2);
1427
+ const y = doc.y;
1428
+ doc.fillColor(GREY).text(String(label), M + 4, y + 4, { width: labW });
1429
+ doc.fillColor(INK).text(val, M + labW + 10, y + 4, { width: valW });
1430
+ const ly = y + h;
1431
+ doc.moveTo(M, ly).lineTo(M + W, ly).lineWidth(0.5).strokeColor(ROW).stroke();
1432
+ doc.y = ly + 1;
1433
+ };
1434
+
1435
+ // ── Title block ──
1436
+ doc.font('Helvetica-Bold').fontSize(20).fillColor(NAVY).text(spec.title || 'Before / After Report', M, doc.y);
1437
+ doc.moveDown(0.15);
1438
+ doc.font('Helvetica').fontSize(10).fillColor(GREY).text(spec.subtitle || '');
1439
+ doc.moveDown(0.3);
1440
+ const metaLine = (spec.meta || []).map(([l, v]) => `${l}: ${v}`).join(' Β· ');
1441
+ doc.font('Helvetica').fontSize(8.5).fillColor(GREY).text(metaLine);
1442
+
1443
+ // ── Photos side-by-side ──
1444
+ const photos = images.filter((im) => im && im.buffer);
1445
+ if (photos.length) {
1446
+ sectionHeader('Before / After Photos');
1447
+ const gap = 14;
1448
+ const cellW = photos.length === 1 ? W : Math.floor((W - gap) / 2);
1449
+ const imgH = 175;
1450
+ ensureRoom(imgH + 30);
1451
+ const y0 = doc.y;
1452
+ photos.slice(0, 2).forEach((p, i) => {
1453
+ const x = M + i * (cellW + gap);
1454
+ try {
1455
+ doc.save();
1456
+ doc.roundedRect(x, y0, cellW, imgH, 5).clip();
1457
+ doc.image(p.buffer, x, y0, { cover: [cellW, imgH], align: 'center', valign: 'center' });
1458
+ doc.restore();
1459
+ doc.roundedRect(x, y0, cellW, imgH, 5).lineWidth(1).strokeColor(LINE).stroke();
1460
+ } catch (e) {
1461
+ doc.font('Helvetica').fontSize(9).fillColor(GREY).text('[photo could not be embedded]', x, y0 + imgH / 2, { width: cellW, align: 'center' });
1462
+ }
1463
+ doc.font('Helvetica-Bold').fontSize(8).fillColor(GREY)
1464
+ .text(String(p.caption || '').toUpperCase(), x, y0 + imgH + 7, { width: cellW, align: 'center', characterSpacing: 0.6 });
1465
+ });
1466
+ doc.y = y0 + imgH + 24;
1467
+ }
1468
+
1469
+ // ── Data sections ──
1470
+ for (const section of (spec.sections || [])) {
1471
+ sectionHeader(section.heading);
1472
+ for (const [label, value] of (section.fields || [])) kvRow(label, value);
1473
+ }
1474
+
1475
+ // ── Field notes ──
1476
+ sectionHeader('Field Notes');
1477
+ const notes = String(spec.notes || 'No field notes provided.');
1478
+ doc.font('Helvetica').fontSize(9.5);
1479
+ const nh = doc.heightOfString(notes, { width: W - 24 }) + 18;
1480
+ ensureRoom(nh);
1481
+ const ny = doc.y;
1482
+ doc.roundedRect(M, ny, W, nh, 5).fillAndStroke('#f4f8fd', LINE);
1483
+ doc.fillColor(INK).text(notes, M + 12, ny + 9, { width: W - 24 });
1484
+ doc.y = ny + nh;
1485
+
1486
+ doc.end();
1487
+ });
1488
+ }
1489
+
1490
  // Generate the before/after report as a PDF (photos + all data) into the Closeout
1491
+ // Reports folder. pdfkit is primary (works everywhere); browser renderers are the
1492
+ // fallback; the .docx generator is the last resort.
1493
  async function generateBeforeAfterReport({ caseId, caseRecord }) {
1494
  const report = caseRecord.report || {};
1495
  const images = [];
 
1498
  if (!id) return;
1499
  try {
1500
  const f = await boxService.getFileContent(id);
1501
+ images.push({ buffer: Buffer.from(f.body), dataUri: `data:image/jpeg;base64,${Buffer.from(f.body).toString('base64')}`, caption });
1502
  } catch (e) {
1503
  console.warn('[before-after pdf] photo fetch failed', id, e.message);
1504
  }
 
1506
  await addPhoto(report.photoFileId, 'Before β€” Reported Condition');
1507
  await addPhoto(report.afterPhotoFileId, 'After β€” Completed Repair');
1508
 
1509
+ const spec = buildBeforeAfterDocSpec(caseRecord, []);
1510
+ const fileName = `${caseId}_before_after_report.pdf`;
1511
+ let pdf = null;
1512
  try {
1513
+ pdf = await renderBeforeAfterPdfKit(spec, images);
 
 
 
 
 
 
 
 
 
1514
  } catch (e) {
1515
+ console.warn('[before-after] pdfkit failed, trying browser renderer:', e.message);
1516
+ try {
1517
+ pdf = await htmlToPdf(renderBeforeAfterHtml(spec, images));
1518
+ } catch (e2) {
1519
+ console.warn('[before-after] PDF generation failed, falling back to .docx:', e2.message);
1520
+ return await generateBeforeAfterDoc({ caseId, caseRecord });
1521
+ }
1522
  }
1523
+
1524
+ const result = await boxService.uploadCloseoutReport({
1525
+ caseId,
1526
+ fileName,
1527
+ content: pdf,
1528
+ contentType: 'application/pdf',
1529
+ });
1530
+ return { ...result, fileName, embeddedImages: images.length, format: 'pdf' };
1531
  }
1532
 
1533
  // ── Box case-list cache ───────────────────────────────────────────────────────
 
2759
  // Photo + AI fields so the before/after report is complete even when the
2760
  // hosted store started fresh (they live in the sidecar / Box folder).
2761
  photoFileId: pick(r.photoFileId, sc.photoFileId, boxMeta && boxMeta.photoFileId),
2762
+ afterPhotoFileId: pick(r.afterPhotoFileId, boxMeta && boxMeta.afterPhotoFileId),
2763
  aiResult: pick(r.aiResult, sc.aiResult, boxMeta && boxMeta.potholeSize),
2764
  aiPrediction: pick(r.aiPrediction, sc.aiPrediction),
2765
  aiReviewStatus: pick(r.aiReviewStatus, sc.aiReviewStatus, boxMeta && boxMeta.aiReviewStatus),