Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/dms-mailing/docs/1.introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ A test send uses the draft by default and adds `[TEST]` to the subject. It appea

The module stores templates and sends per workspace (tenant), in its own tables. E-mails render through the DMS html-render chain, so they share the DMS e-mail branding. If that renderer fails, the module falls back to its own HTML renderer. E-mails go out through the module that implements `@antelopejs/interface-email`, for example `@antelopejs/nodemailer`.

Other modules call the module through `@antelopejs/interface-dms-mailing`. They send with `SendTemplate` and report provider events with `RecordEmailEvent`. When a workspace is provisioned, they can also ship templates, categories, the sender and the webhook secret as code (`DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender`, `DeclareWebhookSecret`) and import past sends (`ImportSends`).
Other modules call the module through `@antelopejs/interface-dms-mailing`. They send with `SendTemplate`, attached files included, and report provider events with `RecordEmailEvent`. When a workspace is provisioned, they can also ship templates, categories, the sender and the webhook secret as code (`DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender`, `DeclareWebhookSecret`) and import past sends (`ImportSends`).

## Where it lives in the dashboard

Expand Down
19 changes: 19 additions & 0 deletions packages/dms-mailing/docs/5.extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,25 @@ Read `result.results` before you retry a recipient. For several recipients, the

`content` sends an alternate body for an existing template without saving or publishing it. `isTest: true` marks a test send. Its subject starts with `[TEST] `, it uses the template's draft when there is one, and production figures leave it out.

### Attach files

`attachments` sends files with the e-mail, such as the PDF of an invoice. Pass the bytes you already hold:

```typescript fragment
const pdf = await readInvoicePdf(invoiceId); // a Buffer

await SendTemplate("invoice-sent", {
tenantId,
to: "sofie@example.com",
variables: { invoice: { number: "2026-001" } },
attachments: [{ filename: "invoice-2026-001.pdf", contentType: "application/pdf", content: pdf }],
});
```

- Every recipient of the call gets the same files. A file name keeps its last path segment, without line breaks.
- A send carries at most 10 files, adding up to at most 10 MiB. Over that, the call rejects with `code` `attachments_too_large` before anything is sent or logged.
- **Mailing › Sends** lists each file's name and size, and keeps its SHA-256, never its bytes. A send with files cannot be sent again from the dashboard: send it again from your code.

### Amounts and dates

Pass an amount or a date as a value, and the e-mail writes it in the locale of the send.
Expand Down
18 changes: 18 additions & 0 deletions packages/dms-mailing/frontend-vue/app/components/SendDrawer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
type SendActionId,
} from '../utils/send-actions'
import { renderingTitleKey } from '../utils/rendering-title'
import { formatFileSize, sentAttachments } from '../utils/attachments'
import { formatLatency, isSlowLatency } from '../utils/send-stats'
import {
isSuppressedStatus,
Expand Down Expand Up @@ -211,6 +212,10 @@ const stats = computed<StatTrioItem[]>(() => {
]
})

const attachments = computed(() =>
sentAttachments(send.value?.json_attachments),
)

const originTitle = computed(() => {
const template = detail.value?.template
const name = template?.name ?? send.value?.templateSlug ?? ''
Expand Down Expand Up @@ -600,6 +605,19 @@ onMounted(() => {
/>
</template>
</DmsListRow>
<DmsListRow
v-for="(file, index) in attachments"
:key="index"
icon="i-ph-paperclip"
icon-size="2xs"
size="sm"
:meta="[formatFileSize(file.size, locale)]"
data-send-attachment
>
<span class="min-w-0 text-[12.5px] [overflow-wrap:anywhere]">
{{ file.filename }}
</span>
</DmsListRow>
<!-- The "source" label goes under the value: beside it, a dotted
name like `automation.overdue-reminders` broke at its hyphen
against the label in a narrow drawer. -->
Expand Down
2 changes: 2 additions & 0 deletions packages/dms-mailing/frontend-vue/app/types/mailing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,8 @@ export interface SendRow {
error?: string
source?: string
json_variables: string
/** The files it carried (`SentAttachment[]` as JSON); absent for most sends. */
json_attachments?: string
opens: number
clicks: number
createdAt: string
Expand Down
35 changes: 35 additions & 0 deletions packages/dms-mailing/frontend-vue/app/utils/attachments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/** A file a send carried, as the send log keeps it: never its bytes. */
export interface SentAttachment {
filename: string
size: number
}

const KILOBYTE = 1024

const isSentAttachment = (value: unknown): value is SentAttachment =>
typeof value === 'object' &&
value !== null &&
'filename' in value &&
typeof value.filename === 'string' &&
'size' in value &&
typeof value.size === 'number'

/** The files of a send's `json_attachments`; none when absent or unreadable. */
export function sentAttachments(json: string | undefined): SentAttachment[] {
if (!json) return []
try {
const parsed: unknown = JSON.parse(json)
return Array.isArray(parsed) ? parsed.filter(isSentAttachment) : []
} catch {
return []
}
}

/** `size` in kilobytes, at least one: "120 kB", "2,048 kB". */
export const formatFileSize = (size: number, locale: string): string =>
new Intl.NumberFormat(locale, {
style: 'unit',
unit: 'kilobyte',
unitDisplay: 'short',
maximumFractionDigits: 0,
}).format(Math.max(1, Math.round(size / KILOBYTE)))
6 changes: 4 additions & 2 deletions packages/dms-mailing/frontend-vue/app/utils/send-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export interface DrawerSend extends SendRow {
/** What decides a drawer's footer. */
export interface FooterSend extends Pick<
DrawerSend,
'status' | 'isSoftBounce' | 'replayedBy'
'status' | 'isSoftBounce' | 'replayedBy' | 'json_attachments'
> {
/**
* Whether the recipient is on the suppression list today; unknown until
Expand Down Expand Up @@ -99,12 +99,14 @@ const ACTIONS_BY_STATUS: Partial<Record<SendStatus, SendAction[]>> = {
}

/**
* Footers that win over the status: a send someone already sent again offers
* Footers that win over the status: a send that carried attachments cannot be
* repeated since the log keeps no file, a send someone already sent again offers
* no second one, a temporary bounce (a full mailbox) may go to the same
* address later, and so may a suppressed send once its address is
* reactivated.
*/
const FOOTER_RULES: FooterRule[] = [
{ matches: (send) => !!send.json_attachments, actions: LOOK_ONLY },
{ matches: (send) => !!send.replayedBy, actions: LOOK_ONLY },
{
matches: (send) => send.status === 'bounced' && !!send.isSoftBounce,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@
"no_replay_after_spam": "The recipient reported this e-mail as spam: it is not sent again.",
"nothing_to_publish": "This template has no content to publish yet.",
"replay_needs_new_address": "This address bounced. Send to a corrected address instead.",
"no_replay_with_attachments": "This e-mail carried attachments, which the send log does not keep. Send it again from the application that sent it.",
"starter_not_found": "This starter template does not exist.",
"template_in_use": "Only an archived template that was never sent can be deleted. Archive it instead.",
"invalid_template": "The template name or slug is invalid.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@
"no_replay_after_spam": "Le destinataire a signalé cet e-mail comme spam : il n’est pas renvoyé.",
"nothing_to_publish": "Ce modèle n’a pas encore de contenu à publier.",
"replay_needs_new_address": "Cette adresse a rebondi. Envoyez plutôt à une adresse corrigée.",
"no_replay_with_attachments": "Cet e-mail portait des pièces jointes, que le journal des envois ne garde pas. Renvoyez-le depuis l’application qui l’a envoyé.",
"starter_not_found": "Ce modèle de départ n’existe pas.",
"template_in_use": "Seul un modèle archivé et jamais envoyé peut être supprimé. Archivez-le plutôt.",
"invalid_template": "Le nom ou le slug du modèle est invalide.",
Expand Down
24 changes: 24 additions & 0 deletions packages/dms-mailing/frontend-vue/tests/attachments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest'
import { formatFileSize, sentAttachments } from '../app/utils/attachments'

const FILE = { filename: 'invoice.pdf', size: 120 }

describe('sentAttachments', () => {
it('reads the files the send log kept', () => {
expect(sentAttachments(JSON.stringify([FILE]))).toEqual([FILE])
})

it('reads nothing from an absent, broken or foreign value', () => {
expect(sentAttachments(undefined)).toEqual([])
expect(sentAttachments('{not json')).toEqual([])
expect(sentAttachments('{"filename":"a"}')).toEqual([])
expect(sentAttachments('[{"filename":"a"}]')).toEqual([])
})
})

describe('formatFileSize', () => {
it('writes kilobytes, never zero', () => {
expect(formatFileSize(120, 'en')).toBe('1 kB')
expect(formatFileSize(2048, 'en')).toBe('2 kB')
})
})
12 changes: 12 additions & 0 deletions packages/dms-mailing/frontend-vue/tests/send-actions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ describe('sendFooterActions', () => {
expect(actions.map((action) => action.id)).not.toContain('fix_address')
})

it('offers no send again of a send whose files the log does not keep', () => {
const json =
'[{"filename":"a.pdf","contentType":"application/pdf","size":3,"sha256":"ab"}]'
for (const status of ['failed', 'bounced', 'sent'] as const) {
const actions = sendFooterActions({ status, json_attachments: json })
expect(actions.map((action) => action.id)).toEqual([
'rendering',
'copy_address',
])
}
})

it('always offers the rendering', () => {
for (const status of SEND_STATUSES)
expect(ids(status)).toContain('rendering')
Expand Down
30 changes: 28 additions & 2 deletions packages/dms-mailing/frontend-vue/tests/send-drawer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ const STUBS = Object.fromEntries(
STUB_NAMES.map((name) => [name, slotStub(name)]),
)

async function render(): Promise<HTMLElement> {
const { host } = mount(SendDrawer, { rowData: SEND }, STUBS)
async function render(row: SendRow = SEND): Promise<HTMLElement> {
const { host } = mount(SendDrawer, { rowData: row }, STUBS)
await flush()
return host
}
Expand Down Expand Up @@ -116,4 +116,30 @@ describe('send drawer layout', () => {
expect(row?.getAttribute('meta')).toContain('source')
expect(row?.textContent).toContain(SEND.source)
})

it('lists the files a send carried', async () => {
const row: SendRow = {
...SEND,
json_attachments: JSON.stringify([
{
filename: 'invoice-001.pdf',
contentType: 'application/pdf',
size: 2048,
sha256: 'a'.repeat(64),
},
]),
}
stubApiData().respond(
mailingReads({ send: () => ({ send: row, events: [] }) }),
)
const host = await render(row)
const listed = host.querySelector('[data-send-attachment]')
expect(listed?.textContent).toContain('invoice-001.pdf')
expect(listed?.getAttribute('meta')).toContain('2 kB')
})

it('shows no attachment section for a send without files', async () => {
const host = await render()
expect(host.querySelector('[data-send-attachment]')).toBeNull()
})
})
3 changes: 3 additions & 0 deletions packages/dms-mailing/skills/dms-mailing/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ const result = await SendTemplate("order-confirmed", {
the template; pass every required one.
- Don't pre-format amounts and dates per locale: pass `{ value: 987420, currency: "EUR" }` (minor units) or a
`Date`, or an ISO string at a `date` path; the send locale formats them. Plain strings print as given.
- Files: `attachments: [{ filename, contentType?, content: Buffer }]`, the same for every recipient; at most 10 files
and 10 MiB, else `error.code` = `attachments_too_large` before anything is sent. The log keeps name, type, size and
SHA-256, never the bytes, so the dashboard cannot send it again (409 `no_replay_with_attachments`): resend from code.
- In-process events: `RecordEmailEvent(tenantId, { provider, messageId, type, details })`.
HTTP: `POST <clientBaseUrl>/api/mailing/events/<provider>/<tenantId>` with header `x-mailing-webhook-secret`.
- Automation (if `interface-dms-automation` is loaded): action `mailing.send-template`, trigger `mailing.email-event`.
Expand Down
4 changes: 4 additions & 0 deletions packages/dms-mailing/src/db/tables/sends.table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ export class MailingSend extends Table {
@Field("string")
declare json_variables: string;

/** JSON list of the name, type, size and SHA-256 of each file the e-mail carried; absent for most sends. */
@Field("string")
declare json_attachments?: string;

@Field("number")
declare opens: number;

Expand Down
6 changes: 5 additions & 1 deletion packages/dms-mailing/src/routes/sends.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ import {
type CheckedSendParams,
sendUnlessSuppressed,
} from "../services/checked-send";
import { MANUAL_SEND_SOURCE, SendError, subjectFor } from "../services/send";
import { MANUAL_SEND_SOURCE, subjectFor } from "../services/send";
import { SendError } from "../services/send-error";
import {
buildSendStats,
isTransportFailure,
Expand Down Expand Up @@ -87,6 +88,8 @@ const REPLAY_SKIPPED = "$dms_mailing.sends.banner.replay_skipped";
const RECIPIENT_FIELD = "to";
const NEEDS_NEW_ADDRESS = "$dms_mailing.errors.replay_needs_new_address";
const NO_REPLAY_AFTER_SPAM = "$dms_mailing.errors.no_replay_after_spam";
const NO_REPLAY_WITH_ATTACHMENTS =
"$dms_mailing.errors.no_replay_with_attachments";
const TEST_SEND_SOURCE = "dms-mailing:test-send";
const REPLAY_SOURCE = "dms-mailing:replay";
const FIX_ADDRESS_SOURCE = "dms-mailing:fix-address";
Expand Down Expand Up @@ -522,6 +525,7 @@ export class SendsController extends Controller(API_BASE_PATH) {
to: string | undefined,
source: string,
): Promise<SendTemplateResult> {
assert(!send.json_attachments, HTTP_CONFLICT, NO_REPLAY_WITH_ATTACHMENTS);
const template = await requireTemplate(this.templates, send.templateId);
const version = send.templateVersion;
const content =
Expand Down
53 changes: 53 additions & 0 deletions packages/dms-mailing/src/services/attachments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { createHash } from "node:crypto";
import type { BufferAttachment } from "@antelopejs/interface-email";
import type { SendAttachment } from "@antelopejs/interface-dms-mailing";
import { SendError } from "./send-error";

/** Most files one send carries. */
export const MAX_ATTACHMENTS = 10;
/** Most bytes the files of one send add up to: base64 grows them by a third, under the 20 MB most mail servers accept. */
export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;

const PATH_SEPARATORS = /[\\/]/;
const LINE_BREAKS = /[\r\n]/g;

/**
* The files as the email interface takes them, each name cut to its last path
* segment without line breaks; absent for a send without any. Over
* {@link MAX_ATTACHMENTS} or {@link MAX_ATTACHMENT_BYTES}, it throws
* `attachments_too_large`.
*/
export function checkAttachments(
input: readonly SendAttachment[] | undefined,
): BufferAttachment[] | undefined {
if (!input?.length) return undefined;
const total = input.reduce((sum, file) => sum + file.content.byteLength, 0);
if (input.length > MAX_ATTACHMENTS || total > MAX_ATTACHMENT_BYTES)
throw new SendError(
"attachments_too_large",
`${input.length} files of ${total} bytes, at most ${MAX_ATTACHMENTS} files of ${MAX_ATTACHMENT_BYTES} bytes`,
);
return input.map(({ filename, contentType, content }) => ({
filename: (filename.split(PATH_SEPARATORS).pop() ?? "").replace(
LINE_BREAKS,
"",
),
contentType,
content: Buffer.from(content),
}));
}

/** What the send log keeps of the files: name, type, size and SHA-256, never the bytes. */
export function attachmentsLog(
files: readonly BufferAttachment[] | undefined,
): string | undefined {
if (!files) return undefined;
return JSON.stringify(
files.map(({ filename, contentType, content }) => ({
filename,
contentType,
size: content.byteLength,
sha256: createHash("sha256").update(content).digest("hex"),
})),
);
}
9 changes: 9 additions & 0 deletions packages/dms-mailing/src/services/send-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/** Why a send was refused before anything left: `code` names the rule. */
export class SendError extends Error {
constructor(
public readonly code: string,
message: string,
) {
super(message);
}
}
Loading
Loading