The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
---
title: 2. Generating documents
description: One logic function, exposed as an AI tool and a workflow action.
---
import { PageBanner } from "/snippets/page-banner.mdx"
import { CardTitle } from "/snippets/card-title.mdx"
## Overview
Now the core: a [logic function](/developers/extend/apps/logic/logic-functions)
that loads a template and a record, fills the placeholders, and saves a new
document.
We'll write the business logic once as a **handler**, then expose it through
several triggers. This chapter wires up two of them — an **AI tool** and a
**workflow action**.
## The rendering helper
Keep pure logic in its own file so it's easy to unit-test. This flattens a record
into `{{dot.path}}` tokens and substitutes them.
```ts filename="src/logic-functions/utils/render-template.ts"
const PLACEHOLDER_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g;
export const renderTemplate = (body: string, values: Record<string, string>) => {
const missingTokens = new Set<string>();
const content = body.replace(PLACEHOLDER_PATTERN, (_m, token: string) => {
const value = values[token];
if (value === undefined || value === '') { missingTokens.add(token); return ''; }
return value;
});
return { content, missingTokens: [...missingTokens] };
};
```
<Tip>
Because this file has no side effects, you can cover it with fast unit tests
(`yarn test:unit`). See [Testing](/developers/extend/apps/operations/testing).
</Tip>
## The handler
The handler uses the generated [`CoreApiClient`](/developers/extend/apps/logic/logic-functions)
to read and write CRM data. It loads the template, loads the target record, fills
the body, and creates a `document`.
```ts filename="src/logic-functions/handlers/generate-document-handler.ts"
import { CoreApiClient } from 'twenty-client-sdk/core';
import { loadRecordValues } from 'src/logic-functions/utils/load-record-values';
import { renderTemplate } from 'src/logic-functions/utils/render-template';
export const generateDocumentHandler = async (
input: { templateId: string; recordId: string },
) => {
const client = new CoreApiClient();
// Use a filtered list query, not the singular lookup: the singular query
// throws when nothing matches, which would become a 500 instead of a 404.
const { documentTemplates } = await client.query({
documentTemplates: {
__args: { filter: { id: { eq: input.templateId } }, first: 1 },
edges: { node: { id: true, name: true, body: true, target: true } },
},
});
const documentTemplate = documentTemplates?.edges?.[0]?.node;
if (!documentTemplate?.id) return { success: false, status: 404, message: 'Template not found.' };
const record = await loadRecordValues(client, documentTemplate.target, input.recordId);
if (!record.found) return { success: false, status: 404, message: 'Record not found.' };
const { content, missingTokens } = renderTemplate(documentTemplate.body ?? '', record.values);
const { createDocument } = await client.mutation({
createDocument: {
__args: { data: {
name: `${documentTemplate.name} — ${record.displayName}`,
content, status: 'GENERATED', templateId: documentTemplate.id,
} },
id: true, name: true,
},
});
return { success: true, documentId: createDocument.id, content, missingTokens };
};
```
`loadRecordValues` runs a different query for a Person vs. a Company and flattens
the result — see
[`load-record-values.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/examples/document-generator/src/logic-functions/utils/load-record-values.ts).
## Expose it as a tool and a workflow action
A single `defineLogicFunction` can carry several triggers. Here, `toolTriggerSettings`
makes it callable by AI agents, and `workflowActionTriggerSettings` turns it into a
step in the visual workflow builder. Both describe their input with a JSON schema.
```ts filename="src/logic-functions/generate-document.ts"
import { defineLogicFunction } from 'twenty-sdk/define';
import { jsonSchemaToInputSchema } from 'twenty-sdk/logic-function';
import { GENERATE_DOCUMENT_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { generateDocumentHandler } from 'src/logic-functions/handlers/generate-document-handler';
import { generateDocumentInputSchema } from 'src/logic-functions/schemas/generate-document-input.schema';
export default defineLogicFunction({
universalIdentifier: GENERATE_DOCUMENT_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'generate-document',
description: 'Generate a document from a template and a CRM record.',
timeoutSeconds: 30,
toolTriggerSettings: {
inputSchema: generateDocumentInputSchema,
},
workflowActionTriggerSettings: {
label: 'Generate Document',
icon: 'IconFileText',
inputSchema: jsonSchemaToInputSchema(generateDocumentInputSchema),
outputSchema: [{ type: 'object', properties: {
success: { type: 'boolean' }, documentId: { type: 'string' },
} }],
},
handler: generateDocumentHandler,
});
```
The input schema is a plain JSON schema describing `templateId` and `recordId` —
see [`generate-document-input.schema.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/examples/document-generator/src/logic-functions/schemas/generate-document-input.schema.ts).
## Grant it access
Logic functions run as the app's role. It needs to read templates and records
and create documents, so allow that in `src/roles/default-role.ts`:
```ts
export default defineApplicationRole({
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
label: 'Document Generator default role',
canReadAllObjectRecords: true,
canUpdateAllObjectRecords: true,
canAccessAllTools: true,
canBeAssignedToAgents: true,
permissionFlagUniversalIdentifiers: [SystemPermissionFlag.UPLOAD_FILE],
});
```
`UPLOAD_FILE` lets the function upload the generated PDF in the next section.
See [Roles](/developers/extend/apps/config/roles) for finer-grained permissions.
## Attach a real PDF file
A rendered text field is useful, but users want a real document. Let's generate a
**PDF** and store it on the record as a downloadable file.
First, give the `document` object a `FILES` field to hold the PDF. Apps upload
into their **own** files fields, so this field is what routes the upload:
```ts filename="src/objects/document.object.ts"
{
universalIdentifier: DOCUMENT_FILE_FIELD_UNIVERSAL_IDENTIFIER,
type: FieldType.FILES,
name: 'file',
label: 'File',
icon: 'IconFileTypePdf',
universalSettings: { maxNumberOfValues: 1 },
}
```
Now render that PDF. An app is a real Node project, so you can add any npm
package you need and import it like anywhere else. We use **[pdf-lib](https://pdf-lib.js.org/)**
to draw the PDF and **[marked](https://marked.js.org/)** to parse the Markdown
body — the CLI installs them into the function's runtime for you:
```bash filename="Terminal"
yarn add pdf-lib marked
```
The full helper is
[`generate-document-pdf.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/examples/document-generator/src/logic-functions/utils/generate-document-pdf.ts).
It parses the Markdown into tokens with `marked.lexer`, then lays them out with
pdf-lib: real headings, **bold**/*italic* runs, bullet and numbered lists,
blockquotes and rules — a polished, multi-page A4 rendering of the template
itself, rather than a wall of text.
<Frame caption="The generated PDF: real typography and Markdown formatting, rendering the template body.">
<img src="/images/docs/developers/extends/apps/document-generator/07b-generated-pdf.png" alt="A polished, marketable generated PDF" />
</Frame>
<Note>
pdf-lib's built-in fonts use WinAnsi encoding, so Western-European accents render
out of the box; the helper maps smart quotes and dashes and drops characters it
can't encode. Rendering non-Latin scripts (Chinese, Arabic, Cyrillic) would mean
embedding a Unicode font.
</Note>
Then upload it and store the reference on the record. `uploadFile` sends the
bytes straight to file storage and attaches them to your app-owned files field;
the returned `id` is what you save:
```ts filename="src/logic-functions/handlers/generate-document-handler.ts"
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
import { generateDocumentPdf } from 'src/logic-functions/utils/generate-document-pdf';
const documentName = `${documentTemplate.name} — ${record.displayName}`;
const bytes = await generateDocumentPdf(documentName, content);
const fileName = 'proposal.pdf';
const uploaded = await new MetadataApiClient().uploadFile({
fileBuffer: Buffer.from(bytes),
filename: fileName,
fieldMetadataUniversalIdentifier: DOCUMENT_FILE_FIELD_UNIVERSAL_IDENTIFIER,
});
await client.mutation({
updateDocument: {
__args: {
id: documentId,
data: { file: [{ fileId: uploaded.id, label: fileName }] },
},
id: true,
},
});
```
The generated document now carries a downloadable PDF:
<Frame caption="The generated PDF, stored on the document's File field.">
<img src="/images/docs/developers/extends/apps/document-generator/08-document-with-pdf.png" alt="A document record with a generated PDF file" />
</Frame>
<Note>
`uploadFile` only targets **app-owned** files fields (so uploads always require an
app that owns the field, plus the `UPLOAD_FILE` role flag). That's why the PDF
lands on the record's own `file` field — the same pattern the
[call-recorder app](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/public/call-recorder)
uses for recordings.
</Note>
**After this step:** each generated document has a real, downloadable PDF. But
nothing can *call* the generator from the UI yet — for that we need an HTTP route.
<CardGroup cols={2} className="documentation-card-group">
<Card href="/developers/extend/apps/tutorials/document-generator/http-routes" img="/images/user-guide/halftone/card-page-tutorial-http.svg">
<CardTitle>Next: HTTP routes →</CardTitle>
Serve the function over HTTP and render documents as web pages.
</Card>
</CardGroup>
<PageBanner illustration="card-page-tutorial-documents" />