( apiBase: string, headers: Record<string, string>, params: Record<string, unknown>, signal?: AbortSignal )
| 343 | } |
| 344 | |
| 345 | async function handleCreateFromTemplate( |
| 346 | apiBase: string, |
| 347 | headers: Record<string, string>, |
| 348 | params: Record<string, unknown>, |
| 349 | signal?: AbortSignal |
| 350 | ) { |
| 351 | const { templateId, emailSubject, emailBody, templateRoles, status } = params |
| 352 | |
| 353 | if (!templateId) { |
| 354 | return NextResponse.json({ success: false, error: 'templateId is required' }, { status: 400 }) |
| 355 | } |
| 356 | |
| 357 | let parsedRoles: unknown[] = [] |
| 358 | if (templateRoles) { |
| 359 | if (typeof templateRoles === 'string') { |
| 360 | try { |
| 361 | parsedRoles = JSON.parse(templateRoles) |
| 362 | } catch { |
| 363 | return NextResponse.json( |
| 364 | { success: false, error: 'Invalid JSON for templateRoles' }, |
| 365 | { status: 400 } |
| 366 | ) |
| 367 | } |
| 368 | } else if (Array.isArray(templateRoles)) { |
| 369 | parsedRoles = templateRoles |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | const envelopeBody: Record<string, unknown> = { |
| 374 | templateId, |
| 375 | status: (status as string) || 'sent', |
| 376 | templateRoles: parsedRoles, |
| 377 | } |
| 378 | |
| 379 | if (emailSubject) envelopeBody.emailSubject = emailSubject |
| 380 | if (emailBody) envelopeBody.emailBlurb = emailBody |
| 381 | |
| 382 | const response = await fetchDocusign( |
| 383 | `${apiBase}/envelopes`, |
| 384 | { |
| 385 | method: 'POST', |
| 386 | headers, |
| 387 | body: JSON.stringify(envelopeBody), |
| 388 | }, |
| 389 | signal |
| 390 | ) |
| 391 | |
| 392 | const data = await readDocusignJson(response, 'DocuSign create from template response') |
| 393 | if (!response.ok) { |
| 394 | logger.error('DocuSign create from template failed', { data, status: response.status }) |
| 395 | return NextResponse.json( |
| 396 | { |
| 397 | success: false, |
| 398 | error: docusignError(data, 'Failed to create envelope from template'), |
| 399 | }, |
| 400 | { status: response.status } |
| 401 | ) |
| 402 | } |
no test coverage detected