Skip to content

Commit 4c18c43

Browse files
fix(print): a print with no filename names the PDF from the record's display name (#36801)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBEaJzgBWzjWCNjBjkVoeRto)_ Fixes #35049 repo:objectstack#3 · os-support-ai · session_01WGufzi4PechTRCTBrfxV8W Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户在记录上点"打印"生成的 PDF 附件,现在以记录的标题命名(比如报价单号),不再是"页面名-记录编号"这种看不懂的名字;应用自己指定了文件名的照旧。 - 为兄弟应用 HotCRM 解决:打印报价单得到的附件名看不出是哪张报价单。 - 记录没有标题时仍沿用旧名字;同一条记录打印两次会得到两个同名附件,互不覆盖;改动可直接撤回。 - 无。 ## What changes `printRecordToFile` (and so `POST /api/v1/print/records`) archived every PDF without an explicit `filename` as `PAGE-RECORDID.pdf`. Seat route (the card's second option): the default is now the record's display name (ADR-0079) plus `.pdf`. No template key, no spec change, no new authorable key. - **Where the name comes from.** Step 4 already read the record AS THE CALLER and threw the row away; it now returns that row (`readAsCaller`, was `refuseUnlessReadable`), and the name is built from it, so there is no second read and the name never shows a value the caller may not read. The title field is `resolveDisplayField` (`@objectstack/spec/data`, the field `resolveRecordDisplayName` reads) over `engine.registry.getObject(object)`, the same registry the files opt-in reads. - **Fallback.** No title field, an empty value, a value the caller's field-level security leaves out of the row, a value that is not text or a finite number, or one empty once made safe keeps the old `PAGE-RECORDID.pdf`. The `Record #ID` floor of `resolveRecordDisplayName` is deliberately not used, so no file is named `Record #…`. - **Hygiene** (`safeFileBase`). Control characters become a space; path and reserved characters (slash, backslash, colon, asterisk, question mark, double quote, less-than, greater-than, pipe) become `_`; whitespace runs collapse; leading dots and spaces go (no hidden file, no `..`); a trailing `.pdf` is not doubled; the name is cut to 100 characters (code points, never inside a surrogate pair) with trailing dots and spaces dropped after the cut. The attachment service has no sanitiser to reuse: `attachFileAs` stores the name as given, keys the bytes by the file id (`buildKey`), and the download header encodes it (`contentDispositionValue`). The cap matters because `sys_attachment.file_name` is `maxLength: 255`, and a longer name would be refused only after the render. - **Explicit `filename`** is used exactly as given, unchanged. **Visible change:** a print with no explicit filename now attaches `DISPLAY-NAME.pdf` instead of `PAGE-RECORDID.pdf` (stated in the changeset too). ## Tests - `print-service.test.ts`, new top-level `describe` "the default file name": display name used, read once, with the caller's own context; derived title field (no `nameField`); explicit filename wins unchanged; five fallback cases (no title field, blank, field absent from the caller's row, non-text value, nothing left after sanitising) keep `invoice_print-inv_1.pdf`; a number display value; reserved and control characters; leading dots and a trailing `.pdf`; the 100-character cut never splits a character. - Dogfood (real showcase boot, real storage): `print-service-archive` now pins `INV-PRINT-OWN.pdf`, and a new case prints one invoice twice. Both carry the same name, have different `sys_file` and `sys_attachment` ids, both attachments are listed under that name and both files are `committed`. That is the collision measurement: the store neither refuses nor overwrites. `print-service-named-page` now pins the project's display name. - `vitest.config.ts`: an anchored alias for `@objectstack/spec/data` so the tests run the source, not `dist/` (`check:test-source-alias` flagged the new import). <details><summary>Local runs (head 4d45f05)</summary> - `pnpm --filter @objectstack/service-print test` then `typecheck`, under the verify lock on 4d45f05: VERDICT command-exit 0, Test Files 8 passed (8), Tests 131 passed (131). The typecheck program compiles all 8 test files (`tsc --listFiles`). - Ablation (one, on the tested behaviour), via `scripts/ablation-replace.mjs`: the default return was replaced by the old id-based name. The anchor went x1 to x0 and the blob 33627bb to eaeb6879. Result: 6 failed, 56 passed in `print-service.test.ts`: every display-name case went red, and the fallback and explicit-name cases stayed green, as they should. Restored: blob == HEAD, `git diff HEAD` empty. - Dogfood, the two touched files only, after building the dogfood closure (`pnpm --filter '@objectstack/dogfood^...' build`, service-print resolved through its rebuilt `dist/`), on c8ec539: VERDICT command-exit 0, Test Files 2 passed (2), Tests 16 passed (16). The full battery was not run locally: the title carries no `!` and there is no narrowing arm. It is the merge queue's. - Derived gate families (`dispatch-gates --commands`): 98 derived. 96 were run with exit 0 (94 on c8ec539; on 4d45f05 the re-run `check:test-source-alias` and the two `check-console-intercept-disarm` rows the alias commit added). `check:skill-examples` first answered exit 3 and was re-run green after building the client SDK. `--ran`: "98 derived famil(ies) accounted for — 96 run, 2 NOT-MEASURED". The NOT MEASURED pair are `check-plugin-teardown-shape --self-test` (the fixture needs an unshallowed clone, checker health only) and `check:dual-build-cjs-loads` (needs a full build). Both are left to CI. </details> ## Acceptance notes - **Metadata-protocol `none`, measured.** No `packages/spec` file is in the diff. The `filename` request field lives on `PrintRecordRequest` in this service, not in any spec schema (`git grep` for a print `filename` under `packages/spec/src`: 0 hits). What an author can write is unchanged; the output of an existing print changes. Clause-② `no`: no exported type or option changes shape. Only the TSDoc of `PrintRecordRequest.filename` is reworded. - **Docs.** `content/docs/ui/print-pages.mdx` showed `invoice_document-inv_1.pdf` as the result. It now shows the display-name result and states the default, the fallback, the hygiene and the two-prints behaviour. - **Files outside the claimed surface:** the two dogfood files (their pins asserted the old default and would red the merge queue's dogfood shards; the collision measurement rides in one of them) and `service-print/vitest.config.ts` (the test-source-alias gate). ## Verification Read first (by risk): `print-service.ts` `defaultPrintFilename` and `safeFileBase`; `print-service.ts` `readAsCaller` (the row returned is the caller's own read); `print-service-archive.dogfood.test.ts` "a second print of the same invoice". Two-minute check: `pnpm --filter @objectstack/service-print exec vitest run --maxWorkers=2 src/print-service.test.ts`. Expect 62 passed, including the 12 under "the default file name". --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzi4PechTRCTBrfxV8W)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzi4PechTRCTBrfxV8W --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a98f8c6 commit 4c18c43

7 files changed

Lines changed: 197 additions & 9 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/service-print': patch
3+
---
4+
5+
fix(print): a print with no `filename` names the PDF from the record's display name
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`printRecordToFile` (and `POST /api/v1/print/records`) used to archive every PDF without an explicit `filename` as `<page>-<recordId>.pdf`, which tells the reader nothing about which record it is. It now names the file from the record's display name (ADR-0079: the object's `nameField`, or the title field derived from its fields), read from the row the caller's own read answered, plus `.pdf` — printing quote `Q-2026-0042` attaches `Q-2026-0042.pdf`.
11+
12+
- The name is made a safe file name: `/ \ : * ? " < > |` become `_`, control characters and whitespace runs become one space, leading dots are dropped, a trailing `.pdf` is not doubled, and it is cut to 100 characters.
13+
- A record with no display value (no title field, an empty value, or one the caller's field-level security leaves out) keeps `<page>-<recordId>.pdf`, never the `Record #<id>` floor.
14+
- An explicit `filename` is used exactly as given, as before.
15+
- Printing a record twice attaches two files of the same name; neither replaces the other.
16+
17+
Visible change: a print with no explicit filename now attaches `<display name>.pdf` instead of `<page>-<recordId>.pdf`. Nothing to migrate; pass `filename` to keep a fixed name.

‎content/docs/ui/print-pages.mdx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,19 @@ const file = await print.printRecordToFile(
145145
{ app: 'sales', object: 'invoice', recordId: 'inv_1', page: 'invoice_document' },
146146
context, // the requesting user's execution context
147147
);
148-
// { fileId, attachmentId, size, filename: 'invoice_document-inv_1.pdf' }
148+
// { fileId, attachmentId, size, filename: 'INV-0001.pdf' }
149149
```
150150

151+
With no `filename`, the PDF is named after the record: its display name — the
152+
value of the object's title field (`nameField`, or the field derived from its
153+
fields) — plus `.pdf`, read from the record as the requesting user reads it.
154+
The name is made safe for a file: `/ \ : * ? " < > |` become `_`, control
155+
characters and runs of whitespace become one space, leading dots are dropped,
156+
and it is cut to 100 characters. A record with no display value keeps
157+
`<page>-<recordId>.pdf` (`invoice_document-inv_1.pdf`). A `filename` in the
158+
request is used exactly as given. Printing a record twice attaches two files
159+
of the same name; neither replaces the other.
160+
151161
The page is rendered as the requesting user — never as the system — through a
152162
short-lived session minted for that user and revoked as soon as the print ends,
153163
whether it succeeded or not. The PDF is archived as theirs: the attachment is

‎packages/qa/dogfood/test/print-service-archive.dogfood.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,8 @@ describe('print service on a real showcase boot', () => {
267267
expect.objectContaining({ url: `http://127.0.0.1:1/_console/apps/showcase/showcase_invoice/record/${ownInvoice}` }),
268268
);
269269
expect(revoke).toHaveBeenCalledTimes(1);
270-
expect(out).toMatchObject({ size: PDF.byteLength, filename: `${PAGE}-${ownInvoice}.pdf` });
270+
// No filename in the request: the PDF is named from the invoice's display name (ADR-0079), its number.
271+
expect(out).toMatchObject({ size: PDF.byteLength, filename: 'INV-PRINT-OWN.pdf' });
271272

272273
const file = await ql.findOne('sys_file', { where: { id: out.fileId } }, { context: SYS });
273274
expect(file).toMatchObject({ status: 'committed', mime_type: 'application/pdf', size: PDF.byteLength, scope: 'attachments' });
@@ -278,6 +279,25 @@ describe('print service on a real showcase boot', () => {
278279
expect(attachment!.uploaded_by).toBe(ctx.userId);
279280
});
280281

282+
it('a second print of the same invoice carries the same name and is a second attachment: neither replaces the other', async () => {
283+
const ctx = await stack.contextFor(adminToken);
284+
const first = await service.printRecordToFile(request(ownInvoice), ctx);
285+
const second = await service.printRecordToFile(request(ownInvoice), ctx);
286+
expect(second.filename).toBe(first.filename);
287+
expect(second.fileId).not.toBe(first.fileId);
288+
expect(second.attachmentId).not.toBe(first.attachmentId);
289+
const named = await ql.find(
290+
'sys_attachment',
291+
{ where: { parent_object: 'showcase_invoice', parent_id: ownInvoice, file_name: first.filename } },
292+
{ context: SYS },
293+
);
294+
const ids = named.map((row) => String(row.id));
295+
expect(ids).toEqual(expect.arrayContaining([first.attachmentId, second.attachmentId]));
296+
for (const fileId of [first.fileId, second.fileId]) {
297+
expect(await ql.findOne('sys_file', { where: { id: fileId } }, { context: SYS })).toMatchObject({ status: 'committed' });
298+
}
299+
});
300+
281301
it('a member who may attach files archives their own invoice: the attachment is their write, and sys_file stays unreadable to them', async () => {
282302
const ctx = await stack.contextFor(attacherToken);
283303
// Preconditions: the member reads their invoice, and is refused a read of `sys_file`.

‎packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ describe('a record printed on a print page that is not its object’s default re
5757
let ql: IDataEngine;
5858
let service: PrintService;
5959
let project: string;
60+
let projectName: string;
6061
const saved: Record<string, string | undefined> = {};
6162
const revoke = vi.fn(async () => undefined);
6263
const mint = vi.fn(async () => ({
@@ -85,6 +86,7 @@ describe('a record printed on a print page that is not its object’s default re
8586
await protocol.saveMetaItem({ type: 'page', name: PROJECT_BRIEF_PAGE.name, item: PROJECT_BRIEF_PAGE });
8687
const [seeded] = await ql.find('showcase_project', { limit: 1 }, { context: SYS });
8788
project = String(seeded!.id);
89+
projectName = String(seeded!.name);
8890

8991
service = new PrintService({
9092
placement: { state: 'configured', resolved: { placement: 'local', target: '/stand-in/chromium', consoleUrl: CONSOLE } },
@@ -130,7 +132,8 @@ describe('a record printed on a print page that is not its object’s default re
130132
expect.objectContaining({ url: `${CONSOLE}/apps/showcase/showcase_project/record/${project}/page/${PROJECT_BRIEF_PAGE.name}` }),
131133
);
132134
expect(revoke).toHaveBeenCalledTimes(1);
133-
expect(out).toMatchObject({ size: PDF.byteLength, filename: `${PROJECT_BRIEF_PAGE.name}-${project}.pdf` });
135+
// No filename in the request: the PDF is named from the project's display name (ADR-0079).
136+
expect(out).toMatchObject({ size: PDF.byteLength, filename: `${projectName}.pdf` });
134137
const attachment = await ql.findOne('sys_attachment', { where: { id: out.attachmentId } }, { context: SYS });
135138
expect(attachment).toMatchObject({ parent_object: 'showcase_project', parent_id: project, file_id: out.fileId, uploaded_by: ctx.userId });
136139
});

‎packages/services/service-print/src/print-service.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,76 @@ describe('PrintService — mint, render, archive, revoke', () => {
499499
});
500500
});
501501

502+
describe('PrintService — the default file name (the record’s display name, ADR-0079)', () => {
503+
const INVOICE = {
504+
name: 'invoice',
505+
enable: { files: true },
506+
nameField: 'number',
507+
fields: { number: { type: 'text' }, total: { type: 'currency' } },
508+
};
509+
510+
/** The name a print with no `filename` archives `record` under, on an object `object`. */
511+
async function defaultName(record: Record<string, unknown>, object: unknown = INVOICE): Promise<string> {
512+
const h = await harness({ object, record: { id: 'inv_1', ...record } });
513+
const out = await h.service.printRecordToFile(REQUEST, USER);
514+
expect(h.attachFile.mock.calls[0]![0].filename).toBe(out.filename);
515+
return out.filename;
516+
}
517+
518+
it('names the PDF from the record’s display name, read once, from the row the caller’s own read answered', async () => {
519+
const h = await harness({ object: INVOICE, record: { id: 'inv_1', number: 'INV-0001' } });
520+
const out = await h.service.printRecordToFile(REQUEST, USER);
521+
expect(out.filename).toBe('INV-0001.pdf');
522+
expect(h.attachFile).toHaveBeenCalledWith(expect.objectContaining({ filename: 'INV-0001.pdf' }), USER);
523+
expect(h.findOne).toHaveBeenCalledTimes(1);
524+
expect(h.findOne.mock.calls[0]![2].context).toBe(USER);
525+
});
526+
527+
it('a derived title field names it too (no nameField: the name-ish field)', async () => {
528+
const object = { name: 'invoice', enable: { files: true }, fields: { total: { type: 'number' }, title: { type: 'text' } } };
529+
expect(await defaultName({ title: 'March retainer' }, object)).toBe('March retainer.pdf');
530+
});
531+
532+
it('an explicit filename wins unchanged, display name or not', async () => {
533+
const h = await harness({ object: INVOICE, record: { id: 'inv_1', number: 'INV-0001' } });
534+
const out = await h.service.printRecordToFile({ ...REQUEST, filename: 'a/b: raw.PDF' }, USER);
535+
expect(out.filename).toBe('a/b: raw.PDF');
536+
});
537+
538+
for (const [label, record, object] of [
539+
['the object has no title field', { id: 'inv_1' }, { name: 'invoice', enable: { files: true } }],
540+
['the display value is empty', { number: ' ' }, INVOICE],
541+
['the caller’s row carries no display value (field-level security left it out)', {}, INVOICE],
542+
['the display value is not text or a number', { number: { first: 'x' } }, INVOICE],
543+
['nothing is left once the name is made safe', { number: ' .. . ' }, INVOICE],
544+
] as const) {
545+
it(`${label}: keeps <page>-<recordId>.pdf, never the Record # floor`, async () => {
546+
expect(await defaultName(record, object)).toBe('invoice_print-inv_1.pdf');
547+
});
548+
}
549+
550+
it('a number display value is used as written', async () => {
551+
expect(await defaultName({ number: 1042 })).toBe('1042.pdf');
552+
});
553+
554+
it('path and reserved characters become _, control characters and whitespace runs one space', async () => {
555+
expect(await defaultName({ number: 'Q/1\\2: "big" <deal>?*|\u0007end\n' })).toBe('Q_1_2_ _big_ _deal____ end.pdf');
556+
});
557+
558+
it('leading dots go (no hidden file, no ..), and a trailing .pdf is not doubled', async () => {
559+
expect(await defaultName({ number: '../..secret' })).toBe('_..secret.pdf');
560+
expect(await defaultName({ number: '...hidden' })).toBe('hidden.pdf');
561+
expect(await defaultName({ number: 'Quote 7.PDF' })).toBe('Quote 7.pdf');
562+
});
563+
564+
it('a long name is cut to 100 characters before .pdf, never inside a character', async () => {
565+
const name = await defaultName({ number: `${'a'.repeat(99)}\u{1F600}tail` });
566+
expect(name).toBe(`${'a'.repeat(99)}\u{1F600}.pdf`);
567+
expect(await defaultName({ number: `${'b'.repeat(99)}. more` })).toBe(`${'b'.repeat(99)}.pdf`);
568+
expect((await defaultName({ number: 'x'.repeat(400) })).length).toBe(104);
569+
});
570+
});
571+
502572
describe('principalSessionMinterOf — the one read of the auth service’s mint', () => {
503573
it('absent auth, or an auth service without the member, has no mint', () => {
504574
expect(principalSessionMinterOf(undefined)).toBeUndefined();

‎packages/services/service-print/src/print-service.ts‎

Lines changed: 73 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import { createHash } from 'node:crypto';
44
import { recordNotFoundError } from '@objectstack/core';
55
import type { RegisteredErrorCode, StandardErrorCode } from '@objectstack/spec/api';
6+
import { resolveDisplayField, type DisplayNameObjectMeta } from '@objectstack/spec/data';
67
import type { EngineSchemaRegistryView, IDataEngine, IFileAttachmentService } from '@objectstack/spec/contracts';
78
import type { ExecutionContext } from '@objectstack/spec/kernel';
89
import { defaultRecordPageObject } from '@objectstack/spec/ui';
@@ -41,7 +42,9 @@ import type { PrincipalSessionMinter, PrintSession } from './principal-session.j
4142
* 4. **The record, read AS THE CALLER.** A record the caller cannot read and
4243
* a record that does not exist answer the same `RECORD_NOT_FOUND` / `404`,
4344
* so the answer says nothing about a record the caller may not see. A user
44-
* never archives what they could not read.
45+
* never archives what they could not read. The row this read answers is
46+
* the one the default file name is built from ({@link defaultPrintFilename}),
47+
* so the name never shows a value the caller may not read.
4548
* 5. **The files opt-in, and the attach rule.** The record's object must
4649
* declare `enable: { files: true }`, the opt-in every attachment of it
4750
* needs (`FILES_DISABLED` / `403`), and the caller must be allowed to
@@ -75,7 +78,11 @@ export interface PrintRecordRequest {
7578
recordId: string;
7679
/** The print page the caller expects the record to print on. */
7780
page: string;
78-
/** The archived file's name. Defaults to `<page>-<recordId>.pdf`. */
81+
/**
82+
* The archived file's name, used as given. Defaults to the record's display
83+
* name (ADR-0079) as a safe file name plus `.pdf`, or to
84+
* `<page>-<recordId>.pdf` when the record has no display value.
85+
*/
7986
filename?: string;
8087
}
8188

@@ -209,6 +216,63 @@ function printPageUrl(consoleUrl: string, req: ValidRequest, page: Record<string
209216
return defaultRecordPageObject(page) === req.object ? record : `${record}/page/${encodeURIComponent(req.page)}`;
210217
}
211218

219+
/** The most characters a default file name keeps before its `.pdf`. */
220+
const DEFAULT_FILENAME_MAX_CHARS = 100;
221+
222+
/**
223+
* A display name made a safe attachment name, without its extension: control
224+
* characters become spaces, the path and reserved characters
225+
* (`/ \ : * ? " < > |`) become `_`, whitespace runs collapse to one space,
226+
* leading dots and spaces are dropped (no hidden file, no `..`), a trailing
227+
* `.pdf` is dropped so it is not doubled, and the name is cut to
228+
* {@link DEFAULT_FILENAME_MAX_CHARS} characters, never inside a character,
229+
* with trailing dots and spaces dropped after the cut. `''` when nothing is
230+
* left.
231+
*
232+
* The archive stores the bytes under a key built from the file's id, never its
233+
* name, and the download header encodes the name, so this keeps the name
234+
* readable and storable on the user's own disk: `sys_attachment.file_name`
235+
* holds at most 255 characters, and a longer name would be refused only after
236+
* the render.
237+
*/
238+
function safeFileBase(name: string): string {
239+
const cleaned = name
240+
.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
241+
.replace(/[\\/:*?"<>|]/g, '_')
242+
.replace(/\s+/g, ' ')
243+
.trim()
244+
.replace(/\.pdf$/i, '')
245+
.replace(/^[.\s]+/, '');
246+
return Array.from(cleaned).slice(0, DEFAULT_FILENAME_MAX_CHARS).join('').replace(/[.\s]+$/, '');
247+
}
248+
249+
/**
250+
* The name a print is archived under when the request names none: the
251+
* record's display name (ADR-0079), made safe by {@link safeFileBase}, plus
252+
* `.pdf` — `Q-2026-0042.pdf` rather than `quote_print-<recordId>.pdf`.
253+
*
254+
* The display value is read as `resolveRecordDisplayName` reads it (the
255+
* object's primary title field, `resolveDisplayField`), from the row the
256+
* caller's own read answered. A record with no display value — no title
257+
* field, an empty value, a value the caller's field-level security left out
258+
* of that row, a value that is not text or a number, or one that is empty once
259+
* made safe — keeps `<page>-<recordId>.pdf`, never the `Record #<id>` floor.
260+
*
261+
* Two prints of one record carry the same name and are two attachments: the
262+
* archive keys each file by its own id and holds no unique name per record.
263+
*/
264+
function defaultPrintFilename(
265+
objectDef: DisplayNameObjectMeta | undefined,
266+
row: Record<string, unknown>,
267+
req: ValidRequest,
268+
): string {
269+
const field = resolveDisplayField(objectDef);
270+
const value = field ? row[field] : undefined;
271+
const text = typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)) ? String(value) : '';
272+
const base = safeFileBase(text);
273+
return base ? `${base}.pdf` : `${req.page}-${req.recordId}.pdf`;
274+
}
275+
212276
/** What the engine's last probe answered. */
213277
type ProbeResult = { ok: true; version: string } | { ok: false; reason: string };
214278

@@ -304,7 +368,7 @@ export class PrintService implements IPrintService {
304368
const page = this.refuseUnlessPrintPage(engine, req);
305369

306370
// ④ The record, read as the caller.
307-
await this.refuseUnlessReadable(engine, req, context);
371+
const row = await this.readAsCaller(engine, req, context);
308372

309373
// ⑤ The files opt-in, and the attach rule for the caller.
310374
this.refuseUnlessFilesEnabled(engine, req.object);
@@ -320,7 +384,8 @@ export class PrintService implements IPrintService {
320384
}
321385

322386
// Mint, render, archive — and revoke, whatever happened.
323-
const filename = req.filename ?? `${req.page}-${req.recordId}.pdf`;
387+
const filename =
388+
req.filename ?? defaultPrintFilename(engine.registry.getObject(req.object) as DisplayNameObjectMeta | undefined, row, req);
324389
const url = printPageUrl(placement.resolved.consoleUrl, req, page);
325390
const session: PrintSession = await minter.mint(context, PRINT_SESSION_TTL_SECONDS);
326391
try {
@@ -400,11 +465,12 @@ export class PrintService implements IPrintService {
400465
return page;
401466
}
402467

403-
private async refuseUnlessReadable(
468+
/** The record as the caller reads it, or the one `RECORD_NOT_FOUND` / `404` for absent and unreadable alike. */
469+
private async readAsCaller(
404470
engine: PrintEngine,
405471
req: ValidRequest,
406472
context: ExecutionContext,
407-
): Promise<void> {
473+
): Promise<Record<string, unknown>> {
408474
let row: Record<string, unknown> | null;
409475
try {
410476
row = await engine.findOne(req.object, { where: { id: req.recordId } }, { context });
@@ -415,6 +481,7 @@ export class PrintService implements IPrintService {
415481
throw err;
416482
}
417483
if (!row) throw recordNotFoundError(req.object, req.recordId, context);
484+
return row;
418485
}
419486

420487
private refuseUnlessFilesEnabled(engine: PrintEngine, object: string): void {

‎packages/services/service-print/vitest.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export default defineConfig({
2323
{ find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') },
2424
{ find: /^@objectstack\/spec$/, replacement: path.resolve(__dirname, '../../spec/src/index.ts') },
2525
{ find: /^@objectstack\/spec\/api$/, replacement: path.resolve(__dirname, '../../spec/src/api/index.ts') },
26+
{ find: /^@objectstack\/spec\/data$/, replacement: path.resolve(__dirname, '../../spec/src/data/index.ts') },
2627
{ find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(__dirname, '../../spec/src/contracts/index.ts') },
2728
{ find: /^@objectstack\/spec\/kernel$/, replacement: path.resolve(__dirname, '../../spec/src/kernel/index.ts') },
2829
{ find: /^@objectstack\/spec\/ui$/, replacement: path.resolve(__dirname, '../../spec/src/ui/index.ts') },

0 commit comments

Comments
 (0)