-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenapi.yaml
More file actions
724 lines (690 loc) · 25.6 KB
/
openapi.yaml
File metadata and controls
724 lines (690 loc) · 25.6 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
openapi: 3.0.3
info:
title: Salesforce Document Generation API
description: |
Node.js service for generating PDF, DOCX, and PPTX documents from Salesforce data.
**Key Features:**
- Interactive generation (LWC → Apex → Node)
- Batch generation (Apex Batch → Node poller)
- Template caching by ContentVersionId
- Idempotency via RequestHash
- LibreOffice-based DOCX→PDF conversion
**Authentication:**
- Inbound (Salesforce → Node): Azure AD OAuth2 client credentials
- Outbound (Node → Salesforce): JWT Bearer Flow with Integration User
See ADRs in /docs/adr/ for architectural decisions.
version: 1.0.0
contact:
name: Docgen Development Team
license:
name: Proprietary
servers:
- url: https://{environment}.azurecontainerapps.io
description: Azure Container Apps endpoint
variables:
environment:
default: docgen-prod
description: Environment name (docgen-dev, docgen-staging, docgen-prod)
tags:
- name: health
description: Health and readiness endpoints
- name: document-generation
description: Document generation endpoints
- name: worker
description: Worker poller control endpoints
paths:
/healthz:
get:
summary: Liveness probe
description: Returns 200 if the service is running. Used by Kubernetes/ACA for liveness checks.
tags:
- health
responses:
'200':
description: Service is alive
content:
application/json:
schema:
type: object
properties:
status:
type: string
enum: [ok]
example:
status: ok
/readyz:
get:
summary: Readiness probe
description: |
Returns 200 if the service is ready to handle requests (all dependencies healthy).
Returns 503 if dependencies (Salesforce, Key Vault) are unhealthy.
tags:
- health
responses:
'200':
description: Service is ready
content:
application/json:
schema:
type: object
properties:
ready:
type: boolean
checks:
type: object
properties:
salesforce:
type: boolean
keyVault:
type: boolean
example:
ready: true
checks:
salesforce: true
keyVault: true
'503':
description: Service not ready
content:
application/json:
schema:
type: object
properties:
ready:
type: boolean
checks:
type: object
example:
ready: false
checks:
salesforce: false
keyVault: true
/generate:
post:
summary: Generate a document from a Salesforce template
description: |
**Interactive document generation** endpoint. Accepts a JSON envelope with template ID,
output format, locale/timezone, and data object. Returns a download URL for the generated file.
**Flow:**
1. Validate AAD JWT (client credentials from Salesforce Named Credential)
2. Check idempotency via RequestHash (if provided)
3. Fetch template from Salesforce Files (by ContentVersionId)
4. Merge template with data using docx-templates
5. Convert DOCX→PDF via LibreOffice (if outputFormat=PDF)
6. Upload result to Salesforce Files
7. Link file to parent records (Account/Opportunity/Case)
8. Return download URL and ContentVersionId
**Data Contract:**
- Apex is responsible for building the JSON envelope
- All display values (currency, date, number) are **preformatted** by Apex with `__formatted` suffix
- Field paths follow **Salesforce API naming** (e.g., `Account.Name`, `Opportunity.TotalAmount__formatted`)
- RequestHash is computed by Apex: `sha256(templateId | outputFormat | sha256(canonical_json(data)))`
**Idempotency:**
If a RequestHash is provided and a prior request with the same hash succeeded, the existing
ContentVersionId is returned immediately without reprocessing.
**Concurrency:**
Each container instance supports up to 8 concurrent LibreOffice conversions. Additional requests
are queued.
tags:
- document-generation
security:
- oauth2: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/DocgenRequest'
examples:
minimal:
summary: Minimal valid request
value:
templateId: '068xx000000abcdXXX'
outputFileName: 'Account_Summary.pdf'
outputFormat: PDF
locale: en-GB
timezone: Europe/London
options:
storeMergedDocx: false
returnDocxToBrowser: false
data:
Account:
Name: Acme Ltd
BillingCity: London
full:
summary: Full request with all fields
value:
templateId: '068xx000000abcdXXX'
outputFileName: 'Opportunity_{{Opportunity.Name}}.pdf'
outputFormat: PDF
locale: en-GB
timezone: Europe/London
options:
storeMergedDocx: true
returnDocxToBrowser: false
parents:
AccountId: '001xx000000abcdXXX'
OpportunityId: '006xx000000xyzABC'
contact:
summary: Contact document generation
value:
templateId: '068xx000000abcdXXX'
outputFileName: 'Contact_{{Contact.Name}}.pdf'
outputFormat: PDF
locale: en-US
timezone: America/New_York
options:
storeMergedDocx: false
returnDocxToBrowser: false
parents:
ContactId: '003xx000000abcdXXX'
AccountId: '001xx000000xyzABC'
data:
Contact:
FirstName: John
LastName: Smith
Email: john.smith@example.com
Account:
Name: Acme Corporation
lead:
summary: Lead document generation
value:
templateId: '068xx000000abcdXXX'
outputFileName: 'Lead_{{Lead.Name}}.pdf'
outputFormat: PDF
locale: en-GB
timezone: Europe/London
options:
storeMergedDocx: false
returnDocxToBrowser: false
parents:
LeadId: '00Qxx000000abcdXXX'
data:
Lead:
FirstName: Jane
LastName: Doe
Company: Tech Innovations Inc
Status: Open
data:
Account:
Name: Acme Ltd
AnnualRevenue__formatted: '£1,200,000'
Opportunity:
Name: FY25 Renewal
CloseDate__formatted: '31 Oct 2025'
TotalAmount__formatted: '£250,000'
LineItems:
- Name: SKU-A
Qty: 10
UnitPrice__formatted: '£1,000'
LineTotal__formatted: '£10,000'
requestHash: 'sha256:a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6'
responses:
'200':
description: Document generated successfully
content:
application/json:
schema:
$ref: '#/components/schemas/DocgenResponse'
example:
downloadUrl: 'https://example.my.salesforce.com/sfc/servlet.shepherd/version/download/068xx000000abcdXXX'
contentVersionId: '068xx000000abcdXXX'
docxContentVersionId: '068xx000000docxYYY'
correlationId: '12345678-1234-4567-89ab-123456789012'
'202':
description: Request accepted for processing (async/batch mode)
content:
application/json:
schema:
type: object
properties:
correlationId:
type: string
format: uuid
message:
type: string
example:
correlationId: '12345678-1234-4567-89ab-123456789012'
message: 'Document generation request accepted'
'400':
description: Invalid request payload
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 400
error: Bad Request
message: "body must have required property 'templateId'"
'401':
description: Missing or invalid AAD JWT
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 401
error: Unauthorized
message: 'Missing or invalid Bearer token'
'403':
description: Token valid but insufficient permissions or wrong audience
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 403
error: Forbidden
message: 'Token audience does not match expected client ID'
'404':
description: Template not found in Salesforce
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 404
error: Not Found
message: 'Template not found'
correlationId: '12345678-1234-4567-89ab-123456789012'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 500
error: Internal Server Error
message: 'Unexpected server error'
'502':
description: Bad Gateway - LibreOffice conversion or Salesforce upload failed
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 502
error: Bad Gateway
message: 'LibreOffice conversion failed'
correlationId: '12345678-1234-4567-89ab-123456789012'
/worker/start:
post:
summary: Start the poller service
description: |
Starts the batch document generation poller. The poller runs every 15 seconds (active) or 60 seconds (idle),
fetching up to 20 QUEUED documents from Salesforce and processing them with up to 8 concurrent conversions.
**Flow:**
1. Query for QUEUED documents not locked or with expired locks
2. Lock documents sequentially (PATCH Status=PROCESSING, LockedUntil=now+2m)
3. Process documents concurrently (max 8 LibreOffice conversions)
4. Update status to SUCCEEDED/FAILED with retry backoff (1m/5m/15m)
**Adaptive Polling:**
- 15s interval when queue has work
- 60s interval when queue is idle
**Idempotent:** Returns 409 if poller is already running.
tags:
- worker
security:
- oauth2: []
responses:
'200':
description: Poller started successfully
content:
application/json:
schema:
type: object
properties:
message:
type: string
isRunning:
type: boolean
correlationId:
type: string
example:
message: 'Poller started successfully'
isRunning: true
correlationId: '12345678-1234-4567-89ab-123456789012'
'409':
description: Poller is already running
content:
application/json:
schema:
type: object
properties:
error:
type: string
correlationId:
type: string
example:
error: 'Poller is already running'
correlationId: '12345678-1234-4567-89ab-123456789012'
'401':
$ref: '#/components/responses/Unauthorized'
'500':
$ref: '#/components/responses/InternalServerError'
/worker/stop:
post:
summary: Stop the poller service
description: |
Stops the batch document generation poller gracefully. Waits for in-flight jobs to complete
before shutting down.
**Graceful Shutdown:**
- Clears polling timer
- Waits for all in-flight document processing to complete
- Updates stats and logs shutdown
**Idempotent:** Returns 200 even if poller is not running.
tags:
- worker
security:
- oauth2: []
responses:
'200':
description: Poller stopped successfully
content:
application/json:
schema:
type: object
properties:
message:
type: string
isRunning:
type: boolean
correlationId:
type: string
example:
message: 'Poller stopped successfully'
isRunning: false
correlationId: '12345678-1234-4567-89ab-123456789012'
'401':
$ref: '#/components/responses/Unauthorized'
'500':
$ref: '#/components/responses/InternalServerError'
/worker/status:
get:
summary: Get current poller status
description: |
Returns the current operational status of the poller service.
Useful for health checks and monitoring.
tags:
- worker
security:
- oauth2: []
responses:
'200':
description: Current poller status
content:
application/json:
schema:
type: object
properties:
isRunning:
type: boolean
description: Whether the poller is currently running
currentQueueDepth:
type: number
description: Number of documents found in last poll
lastPollTime:
type: string
format: date-time
nullable: true
description: Timestamp of last poll cycle
correlationId:
type: string
example:
isRunning: true
currentQueueDepth: 15
lastPollTime: '2025-11-10T10:30:45Z'
correlationId: '12345678-1234-4567-89ab-123456789012'
'401':
$ref: '#/components/responses/Unauthorized'
'500':
$ref: '#/components/responses/InternalServerError'
/worker/stats:
get:
summary: Get detailed poller statistics
description: |
Returns comprehensive statistics about poller performance and processing history.
Useful for monitoring, dashboards, and alerting.
tags:
- worker
security:
- oauth2: []
responses:
'200':
description: Detailed poller statistics
content:
application/json:
schema:
type: object
properties:
isRunning:
type: boolean
description: Whether the poller is currently running
currentQueueDepth:
type: number
description: Number of documents found in last poll
totalProcessed:
type: number
description: Total documents processed since start
totalSucceeded:
type: number
description: Total documents successfully completed
totalFailed:
type: number
description: Total documents permanently failed
totalRetries:
type: number
description: Total retry attempts across all documents
lastPollTime:
type: string
format: date-time
nullable: true
description: Timestamp of last poll cycle
uptimeSeconds:
type: number
description: Seconds since poller was started
correlationId:
type: string
example:
isRunning: true
currentQueueDepth: 15
totalProcessed: 1234
totalSucceeded: 1200
totalFailed: 34
totalRetries: 89
lastPollTime: '2025-11-10T10:30:45Z'
uptimeSeconds: 3600
correlationId: '12345678-1234-4567-89ab-123456789012'
'401':
$ref: '#/components/responses/Unauthorized'
'500':
$ref: '#/components/responses/InternalServerError'
components:
securitySchemes:
oauth2:
type: oauth2
description: Azure AD OAuth2 client credentials flow (Salesforce Named Credential → Node)
flows:
clientCredentials:
tokenUrl: https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token
scopes: {}
schemas:
DocgenRequest:
type: object
required:
- templateId
- outputFileName
- outputFormat
- locale
- timezone
- options
- data
properties:
templateId:
type: string
description: |
Salesforce ContentVersionId (18 chars) of the DOCX or PPTX template.
Template is cached immutably by this ID.
example: '068xx000000abcdXXX'
outputFileName:
type: string
description: |
Desired output file name. May contain template placeholders (e.g., `{{Opportunity.Name}}`).
These are resolved during merge.
example: 'Opportunity_{{Opportunity.Name}}.pdf'
outputFormat:
type: string
enum:
- PDF
- DOCX
- PPTX
description: |
Output format. PDF requires LibreOffice DOCX conversion. DOCX and PPTX return the merged template as-is.
locale:
type: string
description: |
Locale for formatting (used by Apex to preformat values). Examples: `en-GB`, `en-US`, `de-DE`.
example: en-GB
timezone:
type: string
description: |
Timezone for date/time formatting (used by Apex). Examples: `Europe/London`, `America/New_York`.
example: Europe/London
options:
type: object
required:
- storeMergedDocx
- returnDocxToBrowser
properties:
storeMergedDocx:
type: boolean
description: |
Whether to store the merged DOCX alongside the PDF in Salesforce Files.
Useful for debugging or archiving the intermediate step.
returnDocxToBrowser:
type: boolean
description: |
(Interactive mode only) If true, return the DOCX download URL instead of PDF.
Ignored in batch mode.
data:
type: object
additionalProperties: true
description: |
Template data object with Salesforce field paths. Structure is flexible but should match
template placeholders. Use `__formatted` suffix for display values (precomputed by Apex).
**Examples:**
- `Account.Name` → raw field
- `Account.AnnualRevenue__formatted` → currency formatted by Apex
- `Opportunity.LineItems` → array for loops
**Field Path Convention:** Salesforce API naming (no underscores except for `__formatted`).
example:
Account:
Name: Acme Ltd
BillingCity: London
AnnualRevenue__formatted: '£1,200,000'
parents:
type: object
additionalProperties:
oneOf:
- type: 'null'
- type: string
pattern: '^([a-zA-Z0-9]{15}|[a-zA-Z0-9]{18})$'
description: |
Parent record IDs for linking the generated file. Dynamic map supporting any Salesforce object type
configured in Custom Metadata (`Supported_Object__mdt`).
**Key format:** `"{ObjectType}Id"` (e.g., `AccountId`, `ContactId`, `LeadId`, `CustomObject__cId`)
**Value:** Salesforce record ID (15 or 18 characters) or `null`
All non-null IDs will receive a `ContentDocumentLink` with `ShareType=V`, `Visibility=AllUsers`.
**Pre-configured object types:** Account, Opportunity, Case, Contact, Lead
**Examples:**
- Single parent: `{ "ContactId": "003xxxxxxxxxxxx" }`
- Multi-parent: `{ "OpportunityId": "006xxx", "AccountId": "001xxx" }`
- Custom object: `{ "CustomObject__cId": "a0Axxx" }`
requestHash:
type: string
description: |
**Idempotency key** computed by Apex:
`sha256(templateId | outputFormat | sha256(canonical_json(data)))`
If provided, Node checks for an existing `Generated_Document__c` record with this hash.
If found and status=SUCCEEDED, returns the prior ContentVersionId without reprocessing.
example: 'sha256:a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6'
generatedDocumentId:
type: string
description: |
**T-12: Generated_Document__c record ID** (18 chars).
Passed by Apex so Node can update the record's status (SUCCEEDED/FAILED) and OutputFileId__c
after upload. Optional for backward compatibility, but required for status tracking.
example: 'a00xx000000abcdXXX'
DocgenResponse:
type: object
required:
- downloadUrl
- contentVersionId
- correlationId
properties:
downloadUrl:
type: string
format: uri
description: |
Salesforce ContentVersion download URL. Opens the generated PDF/DOCX/PPTX in the browser.
Format: `https://<SF_DOMAIN>/sfc/servlet.shepherd/version/download/<ContentVersionId>`
example: 'https://example.my.salesforce.com/sfc/servlet.shepherd/version/download/068xx000000abcdXXX'
contentVersionId:
type: string
description: |
Salesforce ContentVersionId (18 chars) of the uploaded file. Can be used for subsequent operations.
example: '068xx000000abcdXXX'
docxContentVersionId:
type: string
description: |
Optional Salesforce ContentVersionId of the stored merged DOCX file when `storeMergedDocx` is true.
example: '068xx000000docxYYY'
correlationId:
type: string
format: uuid
description: |
Correlation ID for tracking this request across logs, traces, and metrics.
Extracted from `x-correlation-id` header or generated as UUIDv4.
example: '12345678-1234-4567-89ab-123456789012'
Error:
type: object
required:
- statusCode
- error
- message
properties:
statusCode:
type: integer
description: HTTP status code
example: 400
error:
type: string
description: Error name/type
example: Bad Request
message:
type: string
description: Human-readable error message
example: "body must have required property 'templateId'"
responses:
Unauthorized:
description: Missing or invalid AAD JWT
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 401
error: Unauthorized
message: 'Missing or invalid Bearer token'
correlationId: '12345678-1234-4567-89ab-123456789012'
InternalServerError:
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
statusCode: 500
error: Internal Server Error
message: 'Unexpected server error'
correlationId: '12345678-1234-4567-89ab-123456789012'