diff --git a/.claude/skills/add-endpoint/SKILL.md b/.claude/skills/add-endpoint/SKILL.md index 256817d..34f6c41 100644 --- a/.claude/skills/add-endpoint/SKILL.md +++ b/.claude/skills/add-endpoint/SKILL.md @@ -11,10 +11,11 @@ Follow the layers in order. Look at `src/modules/elements/` as the reference mod 2. **Service** — `.service.ts`: the business rule. Read and write through `TemplateStore` (`store.read()` / `store.update()`). Throw `NotFoundError`, `ConflictError` or `AppError(status, "CODE", message)`; never touch `req`/`res`. 3. **Controller** — `.controller.ts`: arrow-function methods that read the validated `req`, call the service and set the status (`201` + body for create, `204` for update/delete). 4. **Router** — `.router.ts`: `validate({ body, params })` before the controller method. -5. **Wire it** — new module: construct it in `src/routes.ts`. -6. **Contract** — add the operation to `buildOpenApiDocument()` in `src/openapi.ts` (register new named schemas in `components`), then `npm run openapi` to regenerate `openapi.json`. + - Template-scoped route (under `/templates/:templateId`): `Router({ mergeParams: true })`, validate `templateParamsSchema` (or a schema that extends it) on every route, and in the service get the template with `findTemplate(data, templateId)` and call `touch(template)` after changing it. +5. **Wire it** — new module: construct it in `src/routes.ts` (template-scoped routers mount at `/templates/:templateId/`). +6. **Contract** — add the operation to `buildOpenApiDocument()` in `src/openapi.ts` (register new named schemas in `components`; path params via `templateIdParam`, `keyParam()` or `idParam()`), then `npm run openapi` to regenerate `openapi.json`. A new path placeholder also needs a substitute value in `test/openapi.test.ts`. 7. **Tests** - - HTTP: `test/app.test.ts` with Supertest — success status and body, 400 for invalid input, 404/409 where they apply, and that `db.json` changed as expected. + - HTTP: `test/app.test.ts` with Supertest — success status and body, 400 for invalid input, 404/409 where they apply (template-scoped routes: add them to the "unknown template" table), and that `db.json` changed as expected. The seed is one template `t1` (`T1 = "/templates/t1"`). - Pure logic (helpers): `*.test.ts` next to the code. - `test/openapi.test.ts` fails until `openapi.json` is regenerated, catches documented routes that do not exist, and catches routes missing from `buildOpenApiDocument()`. 8. **Docs** — the endpoint table in `README.md`. diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index e80d133..e1662b1 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -8,7 +8,7 @@ body: label: Request description: Method, path and body (a curl command is ideal). placeholder: | - curl -X PATCH localhost:9000/tree/nodes/abc -H 'content-type: application/json' -d '{"title":"x"}' + curl -X PATCH localhost:9000/templates//tree/nodes/abc -H 'content-type: application/json' -d '{"title":"x"}' validations: required: true - type: textarea diff --git a/AGENTS.md b/AGENTS.md index 742498f..f03946b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ > **Audience:** AI coding agents (Claude Code, Cursor, Copilot, Codex) and people working on this repository. > **Purpose:** enough context to make safe, consistent changes without rediscovering the layout. -REST API for the [email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs). It stores a tree of template parts and a library of reusable elements, and renders the tree into one HTML email. Read [`README.md`](README.md) for configuration, the endpoint table and Docker. +REST API for the [email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs). It stores email templates (each with its own tree of template parts and its own library of reusable elements), renders a template into one HTML email and keeps a log of sent emails (logged only; nothing is delivered yet). Read [`README.md`](README.md) for configuration, the endpoint table and Docker. **Stack:** Node 24 (`.nvmrc`), TypeScript 6 (strict, ESM, `NodeNext`), Express 5, zod 4, pino, Vitest + Supertest, ESLint 10 + typescript-eslint, Prettier. @@ -34,6 +34,14 @@ request → helmet → cors → request-id → pino-http → json → static - `src/openapi.ts` builds the OpenAPI 3.1 document from the same zod schemas the routers use. - `src/config/env.ts` validates environment variables with zod; invalid config stops the server at startup. +## Data and modules + +- `db.json` is `{ templates: Template[], sentEmails: SentEmail[] }` (types in `src/storage/db.types.ts`). A `Template` is `{ id, name, tree, elements, createdAt, updatedAt }`. `normalize()` in `src/storage/json-file-store.ts` migrates the v2 `recipeTemplate: { tree, options }` into one "Default template" on load. +- Modules: `templates` (CRUD), `tree`, `elements`, `generate` and `sent-emails`. +- Template-scoped routers (`tree`, `elements`, `generate`, the `send` router of `sent-emails`) are mounted under `/templates/:templateId/...` in `src/routes.ts`. They use `Router({ mergeParams: true })` and validate `templateId` with `templateParamsSchema` (extend it for routes with more params, e.g. `nodeParamsSchema`). +- Services look the template up with `findTemplate(data, templateId)` from `src/modules/templates/templates.helpers.ts` (404 NOT_FOUND if unknown) and call `touch(template)` after every change to its name, tree or elements. Node and element keys are unique within a template. +- `generate` writes `/generated/.html`; deleting a template deletes it. Sent-email entries keep a snapshot of the HTML and the template name and survive template deletion. + ## API contract - **Source of truth:** [`openapi.json`](openapi.json), generated from the zod schemas and served at `GET /openapi.json`. `test/openapi.test.ts` fails if the committed file is stale, documents a route the app does not have, or misses a route the app has. diff --git a/README.md b/README.md index 0c01bce..0b34f26 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # email-template-editor-nodejs REST API for the [LLazyEmail email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs). -It stores a tree of template parts and reusable elements, and renders the tree into a single HTML email. +It stores email templates (each one a tree of template parts plus its own library of reusable elements), renders a template into a single HTML email and keeps a log of sent emails. Stack: Node 24, TypeScript (strict), Express 5, zod, pino, Vitest + Supertest. @@ -46,9 +46,11 @@ src/ common/ errors, logger, middleware (request-id, validate, not-found, error-handler) storage/ TemplateStore interface + JsonFileStore modules/ - tree/ template tree CRUD - elements/ reusable elements CRUD + templates/ templates CRUD + findTemplate() used by the template-scoped modules + tree/ a template's tree CRUD + elements/ a template's reusable elements CRUD generate/ tree → HTML rendering + sent-emails/ "send" (log only, no delivery yet) and the sent-emails log test/ HTTP integration tests + fixtures ``` @@ -72,23 +74,41 @@ Invalid values stop the server at startup with a clear message. The machine-readable contract is [`openapi.json`](openapi.json) (OpenAPI 3.1, generated from the zod schemas, also served at `GET /openapi.json`). Agents and contributors: see [`AGENTS.md`](AGENTS.md). -| Method | Path | Body | Success | Errors | -| ------ | ------------------ | -------------------------- | --------------------------- | ------------- | -| GET | `/health` | – | 200 `{ "status": "ok" }` | | -| GET | `/tree` | – | 200 `TreeNode[]` | | -| PUT | `/tree` | `{ treeData: TreeNode[] }` | 204 | 400, 409 | -| POST | `/tree/nodes` | `{ parentKey, item }` | 201 `TreeNode` | 400, 404, 409 | -| PATCH | `/tree/nodes/:key` | `{ title?, value? }` | 204 | 400, 404 | -| DELETE | `/tree/nodes/:key` | – | 204 | 404 | -| GET | `/elements` | – | 200 `Element[]` | | -| POST | `/elements` | `{ key, title, value }` | 201 `Element` | 400, 409 | -| PATCH | `/elements/:key` | `{ title?, value? }` | 204 | 400, 404 | -| DELETE | `/elements/:key` | – | 204 | 404 | -| POST | `/generate` | – | 200 `{ "url": "http://…" }` | 422 | - -`TreeNode` is `{ key, title, value, children?: TreeNode[] }` and `Element` is `{ key, title, value }`. All fields are strings. Keys in paths must be URL-encoded. - -`POST /generate` renders the tree (each child's `title` placeholder inside its parent's `value` is replaced with the child's rendered value), writes it to `/generated/nmtgTemplate.html` and returns its URL. +Everything except `/health`, `/openapi.json` and `/sent-emails` belongs to one template, so paths start with `/templates/:templateId`. + +| Method | Path | Body | Success | Errors | +| ------ | ---------------------------------------- | --------------------------- | --------------------------- | ------------- | +| GET | `/health` | – | 200 `{ "status": "ok" }` | | +| GET | `/templates` | – | 200 `TemplateSummary[]` | | +| POST | `/templates` | `{ name }` | 201 `TemplateSummary` | 400 | +| GET | `/templates/:templateId` | – | 200 `TemplateSummary` | 400, 404 | +| PATCH | `/templates/:templateId` | `{ name }` | 204 | 400, 404 | +| DELETE | `/templates/:templateId` | – | 204 | 400, 404 | +| GET | `/templates/:templateId/tree` | – | 200 `TreeNode[]` | 400, 404 | +| PUT | `/templates/:templateId/tree` | `{ treeData: TreeNode[] }` | 204 | 400, 404, 409 | +| POST | `/templates/:templateId/tree/nodes` | `{ parentKey, item }` | 201 `TreeNode` | 400, 404, 409 | +| PATCH | `/templates/:templateId/tree/nodes/:key` | `{ title?, value? }` | 204 | 400, 404 | +| DELETE | `/templates/:templateId/tree/nodes/:key` | – | 204 | 400, 404 | +| GET | `/templates/:templateId/elements` | – | 200 `Element[]` | 400, 404 | +| POST | `/templates/:templateId/elements` | `{ key, title, value }` | 201 `Element` | 400, 404, 409 | +| PATCH | `/templates/:templateId/elements/:key` | `{ title?, value? }` | 204 | 400, 404 | +| DELETE | `/templates/:templateId/elements/:key` | – | 204 | 400, 404 | +| POST | `/templates/:templateId/generate` | – | 200 `{ "url": "http://…" }` | 400, 404, 422 | +| POST | `/templates/:templateId/send` | `{ to: string[], subject }` | 201 `SentEmailSummary` | 400, 404, 422 | +| GET | `/sent-emails` | – | 200 `SentEmailSummary[]` | | +| GET | `/sent-emails/:id` | – | 200 `SentEmail` | 400, 404 | + +All values are strings (or arrays of strings); timestamps are ISO 8601. + +- `TemplateSummary` is `{ id, name, createdAt, updatedAt }`. `GET /templates` returns the most recently changed first; any change to a template's name, tree or elements updates `updatedAt`. Template names are 1–200 characters. +- `TreeNode` is `{ key, title, value, children?: TreeNode[] }` and `Element` is `{ key, title, value }`. Node and element keys are unique within a template; two templates can use the same keys. +- `SentEmailSummary` is `{ id, templateId, templateName, to, subject, status: "logged", createdAt }`; `SentEmail` adds `html`. + +Template ids are generated by the server (`[A-Za-z0-9_-]`, up to 128 characters; anything else is a 400). Element and node keys in paths must be URL-encoded. + +`POST /templates/:templateId/generate` renders the tree (each child's `title` placeholder inside its parent's `value` is replaced with the child's rendered value), writes it to `/generated/.html` and returns its URL. Deleting the template deletes that file. + +`POST /templates/:templateId/send` takes 1–50 email addresses in `to` and a 1–300 character `subject`. **It does not deliver anything yet:** it renders the template and stores a log entry with a snapshot of the HTML and `status: "logged"`. `GET /sent-emails` lists entries newest first without the HTML; `GET /sent-emails/:id` includes it. Log entries stay after their template is deleted. ### Errors @@ -111,14 +131,33 @@ Every error uses the same shape. `requestId` matches the `X-Request-Id` response } ``` -| Status | `code` | -| ------ | ------------------------------------------ | -| 400 | `VALIDATION_ERROR`, `INVALID_JSON` | -| 404 | `NOT_FOUND` (resource or route) | -| 409 | `CONFLICT` (duplicate key) | -| 413 | `PAYLOAD_TOO_LARGE` | -| 422 | `TREE_EMPTY` | -| 500 | `INTERNAL_ERROR` (details are only logged) | +| Status | `code` | +| ------ | ---------------------------------------------------------- | +| 400 | `VALIDATION_ERROR`, `INVALID_JSON` | +| 404 | `NOT_FOUND` (template, node, element, sent email or route) | +| 409 | `CONFLICT` (duplicate key within the template) | +| 413 | `PAYLOAD_TOO_LARGE` | +| 422 | `TREE_EMPTY` (generate or send with an empty tree) | +| 500 | `INTERNAL_ERROR` (details are only logged) | + +### Migrating from v2 to v3 + +v3 keeps any number of templates. On first start the server converts an existing `db.json` from the v2 shape `{ recipeTemplate: { tree, options } }` to `{ templates, sentEmails }`: the old tree and elements become one template named "Default template". Get its id from `GET /templates`. Each template has its own elements. + +| v2 | v3 | +| ------------------------- | ----------------------------------------------------------------- | +| `GET /tree` | `GET /templates/:templateId/tree` | +| `PUT /tree` | `PUT /templates/:templateId/tree` | +| `POST /tree/nodes` | `POST /templates/:templateId/tree/nodes` | +| `PATCH /tree/nodes/:key` | `PATCH /templates/:templateId/tree/nodes/:key` | +| `DELETE /tree/nodes/:key` | `DELETE /templates/:templateId/tree/nodes/:key` | +| `GET /elements` | `GET /templates/:templateId/elements` | +| `POST /elements` | `POST /templates/:templateId/elements` | +| `PATCH /elements/:key` | `PATCH /templates/:templateId/elements/:key` | +| `DELETE /elements/:key` | `DELETE /templates/:templateId/elements/:key` | +| `POST /generate` | `POST /templates/:templateId/generate` (file `.html`) | + +New in v3: `/templates` CRUD, `POST /templates/:templateId/send`, `GET /sent-emails`, `GET /sent-emails/:id`. ### Migrating from v1 routes @@ -148,12 +187,12 @@ Data lives in `/app/data/db.json`. Mount a volume there so it survives container ### Sample data -The repository's `db.json` holds a complete example: a No More To-Go "Weekly Menu" issue. +The repository's `db.json` holds one template, "Default template": a complete No More To-Go "Weekly Menu" issue. The sent-emails log is empty. - **Tree:** the root HTML has three slots (`{{items}}`, `{{items2}}`, `{{items3}}`). Each slot holds a two-column row with two recipe cards, six recipes in total. Each card's `{{link}}`, `{{image}}`, `{{title}}` and `{{subtitle}}` are filled. - **Elements:** `{{twoBlocks}}` (two-column row), `{{recipeCard}}` (photo, title and subtitle) and `{{textBlock}}` (a paragraph). -Every child's title appears in its parent's HTML, and keys are unique. `POST /generate` renders the issue with no placeholders left over. +Every child's title appears in its parent's HTML, and keys are unique. `POST /templates/:templateId/generate` renders the issue with no placeholders left over. Development with hot reload: diff --git a/db.json b/db.json index 2f83779..dee9220 100644 --- a/db.json +++ b/db.json @@ -1,237 +1,244 @@ { - "recipeTemplate": { - "tree": [ - { - "key": "1", - "title": "root", - "value": "\n\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n Korean Barbecue Beef | Pork Schnitzel | Bahn Mi Meatball Skewers\n \n \n\n\n\n \n \n
\n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n \n
\n View in browser\n
\n
\n\n \n \n \n \n
\n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \"\"\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n Weekly Menu\n
\n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
April 22nd, 2021
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

We have a very diverse line-up of meals for this week. Kicking off the week we have a delicious flaky salmon with creamy chipotle sauce. Followed by Korean Barbecue Beef, a quick and outstanding dinner! And oh my- the Saucy Shrimp Salad is amazing! Don’t miss the Pork Schnitzel with German Spaetzle. Overall, my family was blown away by this week and I hope yours is too. Enjoy!!\n

\n

\n


Happy Cooking, 
Stacey, Sloane, and the No More To-Go Team

\n

\n

\n

\n

\n
\n
\n \n \n \n \n
\n
\n
\n \n \n\n {{items}}\n{{items2}}\n{{items3}}\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n Get This Week's Menu\n \n
\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

\n

\n

Ingredients

\n

Saffron: Gives traditional Tandoori its famous yellow coloring. This week we are using it in the marinade for the Yogurt Spiced Chicken. It can be pretty expensive, so turmeric is a good alternative, providing the same color and very comparable taste.

\n

Weekend Prep

\n

Free up your evening and get a little chopping and prep work done this weekend.

\n

Slice and Dice: Cut the vegetables and store in zippered bags or divided containers.

\n

Make Ahead and Refrigerate: Make the sauce; Cook the noodles; Make the dressing; Make the spaetzle; Cook the rice.




\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

No More To-Go Facebook Users:

\n

Connect with other home cooks on our closed group for No More To-Go Members Only Facebook Group Page.

\n

\n

\n

\n

Have Questions?
Please contact us via the \"How Can We Help\" link at the bottom of each page on the site. Or, email us at contact@nomoretogo.com. 

\n

\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \"\"\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
No More To-Go
\n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n
\n

Dallas, Texas United States

\n
\n \n \n \n \n \n \n
\n \n\"facebook\"\n\n \n \n\"twitter\"\n\n \n \n\"instagram\"\n\n
\n
\n \n \n \n \n \n \n \n \n \n \n
\n

You received this email because you signed up on our website or made a purchase from us.

\n
\n \nUnsubscribe\n\n
\n
\n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n
\n \n \n \n
\n \n
\n\n\n
\n\n\n\n\n", - "children": [ - { - "key": "27346831-29bb-4688-b7df-31356420cad3", - "title": "{{items}}", - "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
", - "children": [ - { - "key": "0681ef3c-85a3-42f7-9813-ec2f7bc7f684", - "title": "{{item1}}", - "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", - "children": [ - { - "key": "767c5e66-5f15-4371-8dc2-758b87d8aff0", - "title": "{{link}}", - "value": "https://www.nomoretogo.com/weekly-menu/", - "children": [] - }, - { - "key": "ed2ddf34-2b37-4ac5-9655-98e45c5d8772", - "title": "{{image}}", - "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe5.jpeg", - "children": [] - }, - { - "key": "c3039653-b00a-424d-9b39-431e4a9979e8", - "title": "{{title}}", - "value": "Chipotle Cream Salmon", - "children": [] - }, - { - "key": "342036c5-c245-40fc-b4b0-cb8f1a5629d2", - "title": "{{subtitle}}", - "value": "with Roasted Potatoes and Broccolini", - "children": [] - } - ] - }, - { - "key": "823f2eda-5627-4141-9689-4cc160ead7af", - "title": "{{item2}}", - "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", - "children": [ - { - "key": "88e38454-c68d-4098-8d11-65fdad8bd415", - "title": "{{link}}", - "value": "https://www.nomoretogo.com/weekly-menu/", - "children": [] - }, - { - "key": "fab05bdc-5a59-45c2-a6a1-a1c88d3379b3", - "title": "{{image}}", - "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe4.jpeg", - "children": [] - }, - { - "key": "862e8d32-6426-4e72-940e-ea6bd0118ac2", - "title": "{{title}}", - "value": "Korean Barbecue Beef", - "children": [] - }, - { - "key": "b5ffa8bd-60d7-41f1-9942-3dda42d3998c", - "title": "{{subtitle}}", - "value": "with Rice Noodles and Crunchy Veggies", - "children": [] - } - ] - } - ] - }, - { - "key": "2f713fed-0884-43d0-83d4-8a512ed6f058", - "title": "{{items2}}", - "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
", - "children": [ - { - "key": "7e0b1b83-a541-4287-9715-fad070b7bc24", - "title": "{{item1}}", - "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", - "children": [ - { - "key": "bbfa98bf-65a2-4057-a569-724e847e8f49", - "title": "{{link}}", - "value": "https://www.nomoretogo.com/weekly-menu/", - "children": [] - }, - { - "key": "f064402f-5d79-4490-b1ee-ed7b6fd33425", - "title": "{{image}}", - "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe6.jpeg", - "children": [] - }, - { - "key": "59efc040-1114-4b78-bbf9-c5139a6aad6e", - "title": "{{title}}", - "value": "Saucy Shrimp Salad", - "children": [] - }, - { - "key": "64bc07db-07a0-4302-a22b-4c8cc02e33cf", - "title": "{{subtitle}}", - "value": "with Sweet Corn and Radishes", - "children": [] - } - ] - }, - { - "key": "3749ec79-f3a0-4205-9990-cb8d0004d343", - "title": "{{item2}}", - "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", - "children": [ - { - "key": "9b9b0a9b-2442-48c8-9b39-2ad6ff91f1c0", - "title": "{{link}}", - "value": "https://www.nomoretogo.com/weekly-menu/", - "children": [] - }, - { - "key": "2934e01b-1a08-4270-832e-dc4e085d3621", - "title": "{{image}}", - "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe2.jpeg", - "children": [] - }, - { - "key": "ff98f803-2784-4c7b-959b-3d1f41d18873", - "title": "{{title}}", - "value": "Pork Schnitzel", - "children": [] - }, - { - "key": "bdc122f9-bb6f-47ca-91ab-6a754eda1d4b", - "title": "{{subtitle}}", - "value": "with German Spaetzle and Green Beans", - "children": [] - } - ] - } - ] - }, - { - "key": "044b0796-9474-4950-acb6-f71f71bf551c", - "title": "{{items3}}", - "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
", - "children": [ - { - "key": "4bce996e-9a4c-44bf-8d4e-d73339235503", - "title": "{{item1}}", - "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", - "children": [ - { - "key": "cf933c3f-e3d2-455a-a6ca-abc2e69aff08", - "title": "{{link}}", - "value": "https://www.nomoretogo.com/weekly-menu/", - "children": [] - }, - { - "key": "21f1dd77-ed0d-428f-b952-9d6ebe275576", - "title": "{{image}}", - "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe3.jpeg", - "children": [] - }, - { - "key": "a34f33a4-b804-45f4-a933-380651cb9157", - "title": "{{title}}", - "value": "Banh Mi Meatball Skewers", - "children": [] - }, - { - "key": "f220f5c8-bd02-4c16-b25b-eed6c2ca4ec7", - "title": "{{subtitle}}", - "value": "with Sriracha Mayo", - "children": [] - } - ] - }, - { - "key": "5049410c-1463-4f78-874a-5c8661885c5f", - "title": "{{item2}}", - "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", - "children": [ - { - "key": "51dce9b8-8d2c-4abd-aa92-d72c8c5c8e54", - "title": "{{link}}", - "value": "https://www.nomoretogo.com/weekly-menu/", - "children": [] - }, - { - "key": "9981a6f4-7c18-4f37-a6dc-a1d5fe53811a", - "title": "{{image}}", - "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe1.jpeg", - "children": [] - }, - { - "key": "efbd1af5-2ea7-43aa-82ec-1de8b4b22365", - "title": "{{title}}", - "value": "Yogurt Spiced Chicken", - "children": [] - }, - { - "key": "64d10763-906d-473e-8bc9-862bf3b2912e", - "title": "{{subtitle}}", - "value": "over Rice and Snap Peas", - "children": [] - } - ] - } - ] - } - ] - } - ], - "options": [ - { - "key": "882a632a-b240-4032-8539-75d801b72720", - "title": "{{twoBlocks}}", - "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
" - }, - { - "key": "b1c1aa5d-dd09-47c5-af36-3c940b7ca626", - "title": "{{recipeCard}}", - "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
" - }, - { - "key": "2ae6679c-458a-44de-aae8-5a6469d61ae1", - "title": "{{textBlock}}", - "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

{{text}}

\n
\n
\n \n \n \n \n
\n
\n
" - } - ] - } + "templates": [ + { + "id": "e2546e73-362d-434f-9290-058c85ffa7d6", + "name": "Default template", + "tree": [ + { + "key": "1", + "title": "root", + "value": "\n\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n Korean Barbecue Beef | Pork Schnitzel | Bahn Mi Meatball Skewers\n \n \n\n\n\n \n \n
\n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n \n
\n View in browser\n
\n
\n\n \n \n \n \n
\n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \"\"\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n Weekly Menu\n
\n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
April 22nd, 2021
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

\n

We have a very diverse line-up of meals for this week. Kicking off the week we have a delicious flaky salmon with creamy chipotle sauce. Followed by Korean Barbecue Beef, a quick and outstanding dinner! And oh my- the Saucy Shrimp Salad is amazing! Don’t miss the Pork Schnitzel with German Spaetzle. Overall, my family was blown away by this week and I hope yours is too. Enjoy!!\n

\n

\n


Happy Cooking, 
Stacey, Sloane, and the No More To-Go Team

\n

\n

\n

\n

\n
\n
\n \n \n \n \n
\n
\n
\n \n \n\n {{items}}\n{{items2}}\n{{items3}}\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n Get This Week's Menu\n \n
\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

\n

\n

Ingredients

\n

Saffron: Gives traditional Tandoori its famous yellow coloring. This week we are using it in the marinade for the Yogurt Spiced Chicken. It can be pretty expensive, so turmeric is a good alternative, providing the same color and very comparable taste.

\n

Weekend Prep

\n

Free up your evening and get a little chopping and prep work done this weekend.

\n

Slice and Dice: Cut the vegetables and store in zippered bags or divided containers.

\n

Make Ahead and Refrigerate: Make the sauce; Cook the noodles; Make the dressing; Make the spaetzle; Cook the rice.




\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

No More To-Go Facebook Users:

\n

Connect with other home cooks on our closed group for No More To-Go Members Only Facebook Group Page.

\n

\n

\n

\n

Have Questions?
Please contact us via the \"How Can We Help\" link at the bottom of each page on the site. Or, email us at contact@nomoretogo.com. 

\n

\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \"\"\n
\n
\n \n \n \n \n
\n
\n
\n \n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
No More To-Go
\n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n
\n

Dallas, Texas United States

\n
\n \n \n \n \n \n \n
\n \n\"facebook\"\n\n \n \n\"twitter\"\n\n \n \n\"instagram\"\n\n
\n
\n \n \n \n \n \n \n \n \n \n \n
\n

You received this email because you signed up on our website or made a purchase from us.

\n
\n \nUnsubscribe\n\n
\n
\n
\n \n \n \n \n
\n
\n
\n
\n \n \n \n \n
\n \n \n \n
\n \n
\n\n\n
\n\n\n\n\n", + "children": [ + { + "key": "27346831-29bb-4688-b7df-31356420cad3", + "title": "{{items}}", + "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
", + "children": [ + { + "key": "0681ef3c-85a3-42f7-9813-ec2f7bc7f684", + "title": "{{item1}}", + "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", + "children": [ + { + "key": "767c5e66-5f15-4371-8dc2-758b87d8aff0", + "title": "{{link}}", + "value": "https://www.nomoretogo.com/weekly-menu/", + "children": [] + }, + { + "key": "ed2ddf34-2b37-4ac5-9655-98e45c5d8772", + "title": "{{image}}", + "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe5.jpeg", + "children": [] + }, + { + "key": "c3039653-b00a-424d-9b39-431e4a9979e8", + "title": "{{title}}", + "value": "Chipotle Cream Salmon", + "children": [] + }, + { + "key": "342036c5-c245-40fc-b4b0-cb8f1a5629d2", + "title": "{{subtitle}}", + "value": "with Roasted Potatoes and Broccolini", + "children": [] + } + ] + }, + { + "key": "823f2eda-5627-4141-9689-4cc160ead7af", + "title": "{{item2}}", + "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", + "children": [ + { + "key": "88e38454-c68d-4098-8d11-65fdad8bd415", + "title": "{{link}}", + "value": "https://www.nomoretogo.com/weekly-menu/", + "children": [] + }, + { + "key": "fab05bdc-5a59-45c2-a6a1-a1c88d3379b3", + "title": "{{image}}", + "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe4.jpeg", + "children": [] + }, + { + "key": "862e8d32-6426-4e72-940e-ea6bd0118ac2", + "title": "{{title}}", + "value": "Korean Barbecue Beef", + "children": [] + }, + { + "key": "b5ffa8bd-60d7-41f1-9942-3dda42d3998c", + "title": "{{subtitle}}", + "value": "with Rice Noodles and Crunchy Veggies", + "children": [] + } + ] + } + ] + }, + { + "key": "2f713fed-0884-43d0-83d4-8a512ed6f058", + "title": "{{items2}}", + "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
", + "children": [ + { + "key": "7e0b1b83-a541-4287-9715-fad070b7bc24", + "title": "{{item1}}", + "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", + "children": [ + { + "key": "bbfa98bf-65a2-4057-a569-724e847e8f49", + "title": "{{link}}", + "value": "https://www.nomoretogo.com/weekly-menu/", + "children": [] + }, + { + "key": "f064402f-5d79-4490-b1ee-ed7b6fd33425", + "title": "{{image}}", + "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe6.jpeg", + "children": [] + }, + { + "key": "59efc040-1114-4b78-bbf9-c5139a6aad6e", + "title": "{{title}}", + "value": "Saucy Shrimp Salad", + "children": [] + }, + { + "key": "64bc07db-07a0-4302-a22b-4c8cc02e33cf", + "title": "{{subtitle}}", + "value": "with Sweet Corn and Radishes", + "children": [] + } + ] + }, + { + "key": "3749ec79-f3a0-4205-9990-cb8d0004d343", + "title": "{{item2}}", + "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", + "children": [ + { + "key": "9b9b0a9b-2442-48c8-9b39-2ad6ff91f1c0", + "title": "{{link}}", + "value": "https://www.nomoretogo.com/weekly-menu/", + "children": [] + }, + { + "key": "2934e01b-1a08-4270-832e-dc4e085d3621", + "title": "{{image}}", + "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe2.jpeg", + "children": [] + }, + { + "key": "ff98f803-2784-4c7b-959b-3d1f41d18873", + "title": "{{title}}", + "value": "Pork Schnitzel", + "children": [] + }, + { + "key": "bdc122f9-bb6f-47ca-91ab-6a754eda1d4b", + "title": "{{subtitle}}", + "value": "with German Spaetzle and Green Beans", + "children": [] + } + ] + } + ] + }, + { + "key": "044b0796-9474-4950-acb6-f71f71bf551c", + "title": "{{items3}}", + "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
", + "children": [ + { + "key": "4bce996e-9a4c-44bf-8d4e-d73339235503", + "title": "{{item1}}", + "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", + "children": [ + { + "key": "cf933c3f-e3d2-455a-a6ca-abc2e69aff08", + "title": "{{link}}", + "value": "https://www.nomoretogo.com/weekly-menu/", + "children": [] + }, + { + "key": "21f1dd77-ed0d-428f-b952-9d6ebe275576", + "title": "{{image}}", + "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe3.jpeg", + "children": [] + }, + { + "key": "a34f33a4-b804-45f4-a933-380651cb9157", + "title": "{{title}}", + "value": "Banh Mi Meatball Skewers", + "children": [] + }, + { + "key": "f220f5c8-bd02-4c16-b25b-eed6c2ca4ec7", + "title": "{{subtitle}}", + "value": "with Sriracha Mayo", + "children": [] + } + ] + }, + { + "key": "5049410c-1463-4f78-874a-5c8661885c5f", + "title": "{{item2}}", + "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
", + "children": [ + { + "key": "51dce9b8-8d2c-4abd-aa92-d72c8c5c8e54", + "title": "{{link}}", + "value": "https://www.nomoretogo.com/weekly-menu/", + "children": [] + }, + { + "key": "9981a6f4-7c18-4f37-a6dc-a1d5fe53811a", + "title": "{{image}}", + "value": "https://raw.githubusercontent.com/LLazyEmail/nomoretogo_email_template/main/data/images/recipe1.jpeg", + "children": [] + }, + { + "key": "efbd1af5-2ea7-43aa-82ec-1de8b4b22365", + "title": "{{title}}", + "value": "Yogurt Spiced Chicken", + "children": [] + }, + { + "key": "64d10763-906d-473e-8bc9-862bf3b2912e", + "title": "{{subtitle}}", + "value": "over Rice and Snap Peas", + "children": [] + } + ] + } + ] + } + ] + } + ], + "elements": [ + { + "key": "882a632a-b240-4032-8539-75d801b72720", + "title": "{{twoBlocks}}", + "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n {{item1}}\n \n {{item2}}\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n
\n
" + }, + { + "key": "b1c1aa5d-dd09-47c5-af36-3c940b7ca626", + "title": "{{recipeCard}}", + "value": "\n \n \n \n \n \n \n
\n \n\n\"\"\n\n\n
\n \n \n \n \n \n \n \n
\n

{{title}}
{{subtitle}}

\n
\n
" + }, + { + "key": "2ae6679c-458a-44de-aae8-5a6469d61ae1", + "title": "{{textBlock}}", + "value": "\n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n \n \n \n \n
\n

{{text}}

\n
\n
\n \n \n \n \n
\n
\n
" + } + ], + "createdAt": "2026-12-01T10:17:51.068Z", + "updatedAt": "2026-12-01T10:17:51.068Z" + } + ], + "sentEmails": [] } \ No newline at end of file diff --git a/openapi.json b/openapi.json index 0874792..2c9ae60 100644 --- a/openapi.json +++ b/openapi.json @@ -2,8 +2,8 @@ "openapi": "3.1.0", "info": { "title": "Email template editor API", - "version": "2.0.0", - "description": "Stores the template tree and the library of reusable elements, and renders the tree into one HTML email. Errors always have the ErrorResponse shape." + "version": "3.0.0", + "description": "Stores email templates (each with its own tree and library of reusable elements), renders a tree into one HTML email and keeps a log of sent emails. Errors always have the ErrorResponse shape." }, "servers": [ { @@ -39,9 +39,201 @@ } } }, - "/tree": { + "/templates": { "get": { - "summary": "Get the whole template tree", + "summary": "List templates, most recently changed first", + "responses": { + "200": { + "description": "Template summaries", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TemplateSummary" + } + } + } + } + } + } + }, + "post": { + "summary": "Create an empty template", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateTemplateBody" + } + } + } + }, + "responses": { + "201": { + "description": "The new template", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TemplateSummary" + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/templates/{templateId}": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], + "get": { + "summary": "Get a template's name and timestamps", + "responses": { + "200": { + "description": "Template summary", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TemplateSummary" + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + }, + "patch": { + "summary": "Rename a template", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateTemplateBody" + } + } + } + }, + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + }, + "delete": { + "summary": "Delete a template and its generated file (sent-email log entries are kept)", + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/templates/{templateId}/tree": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], + "get": { + "summary": "Get the template's whole tree", "responses": { "200": { "description": "Root nodes", @@ -55,11 +247,31 @@ } } } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } } } }, "put": { - "summary": "Replace the whole template tree", + "summary": "Replace the template's whole tree", "requestBody": { "required": true, "content": { @@ -84,8 +296,239 @@ } } }, - "409": { - "description": "Key already exists (CONFLICT)", + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "409": { + "description": "Key already exists (CONFLICT)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/templates/{templateId}/tree/nodes": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], + "post": { + "summary": "Add a node under a parent", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddNodeBody" + } + } + } + }, + "responses": { + "201": { + "description": "The added node", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TreeNode" + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "409": { + "description": "Key already exists (CONFLICT)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/templates/{templateId}/tree/nodes/{key}": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + }, + { + "name": "key", + "in": "path", + "required": true, + "description": "Tree node key, URL-encoded", + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "patch": { + "summary": "Change a node's title and/or value", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateNodeBody" + } + } + } + }, + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + }, + "delete": { + "summary": "Delete a node and its children", + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/templates/{templateId}/elements": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], + "get": { + "summary": "List the template's library elements", + "responses": { + "200": { + "description": "All elements", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Element" + } + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", "content": { "application/json": { "schema": { @@ -94,8 +537,8 @@ } } }, - "413": { - "description": "Body too large (PAYLOAD_TOO_LARGE)", + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -105,28 +548,26 @@ } } } - } - }, - "/tree/nodes": { + }, "post": { - "summary": "Add a node under a parent", + "summary": "Add a library element", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddNodeBody" + "$ref": "#/components/schemas/CreateElementBody" } } } }, "responses": { "201": { - "description": "The added node", + "description": "The added element", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TreeNode" + "$ref": "#/components/schemas/Element" } } } @@ -142,7 +583,7 @@ } }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -174,13 +615,23 @@ } } }, - "/tree/nodes/{key}": { + "/templates/{templateId}/elements/{key}": { "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + }, { "name": "key", "in": "path", "required": true, - "description": "Tree node key, URL-encoded", + "description": "Element key, URL-encoded", "schema": { "type": "string", "minLength": 1 @@ -188,13 +639,13 @@ } ], "patch": { - "summary": "Change a node's title and/or value", + "summary": "Change an element's title and/or value", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateNodeBody" + "$ref": "#/components/schemas/UpdateElementBody" } } } @@ -214,7 +665,7 @@ } }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -226,13 +677,13 @@ } }, "delete": { - "summary": "Delete a node and its children", + "summary": "Delete an element", "responses": { "204": { "description": "Done" }, - "404": { - "description": "Not found (NOT_FOUND)", + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", "content": { "application/json": { "schema": { @@ -240,48 +691,42 @@ } } } - } - } - } - }, - "/elements": { - "get": { - "summary": "List library elements", - "responses": { - "200": { - "description": "All elements", + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Element" - } + "$ref": "#/components/schemas/ErrorResponse" } } } } } - }, - "post": { - "summary": "Add a library element", - "requestBody": { + } + }, + "/templates/{templateId}/generate": { + "parameters": [ + { + "name": "templateId", + "in": "path", "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateElementBody" - } - } + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" } - }, + } + ], + "post": { + "summary": "Render the tree into .html and return its URL", "responses": { - "201": { - "description": "The added element", + "200": { + "description": "Link to the generated file", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Element" + "$ref": "#/components/schemas/GenerateResponse" } } } @@ -296,8 +741,8 @@ } } }, - "409": { - "description": "Key already exists (CONFLICT)", + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -306,8 +751,8 @@ } } }, - "413": { - "description": "Body too large (PAYLOAD_TOO_LARGE)", + "422": { + "description": "Template tree is empty (TREE_EMPTY)", "content": { "application/json": { "schema": { @@ -319,34 +764,41 @@ } } }, - "/elements/{key}": { + "/templates/{templateId}/send": { "parameters": [ { - "name": "key", + "name": "templateId", "in": "path", "required": true, - "description": "Element key, URL-encoded", + "description": "Template id", "schema": { "type": "string", - "minLength": 1 + "pattern": "^[\\w-]{1,128}$" } } ], - "patch": { - "summary": "Change an element's title and/or value", + "post": { + "summary": "Render the template and log it as sent (no email is delivered yet)", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateElementBody" + "$ref": "#/components/schemas/SendEmailBody" } } } }, "responses": { - "204": { - "description": "Done" + "201": { + "description": "The log entry", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SentEmailSummary" + } + } + } }, "400": { "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", @@ -359,7 +811,27 @@ } }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "422": { + "description": "Template tree is empty (TREE_EMPTY)", "content": { "application/json": { "schema": { @@ -369,19 +841,21 @@ } } } - }, - "delete": { - "summary": "Delete an element", + } + }, + "/sent-emails": { + "get": { + "summary": "List logged sends, newest first", "responses": { - "204": { - "description": "Done" - }, - "404": { - "description": "Not found (NOT_FOUND)", + "200": { + "description": "Log entries without HTML", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ErrorResponse" + "type": "array", + "items": { + "$ref": "#/components/schemas/SentEmailSummary" + } } } } @@ -389,22 +863,44 @@ } } }, - "/generate": { - "post": { - "summary": "Render the tree into an HTML file and return its URL", + "/sent-emails/{id}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Sent email id", + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "get": { + "summary": "Get a logged send with its HTML snapshot", "responses": { "200": { - "description": "Link to the generated file", + "description": "The log entry", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GenerateResponse" + "$ref": "#/components/schemas/SentEmail" } } } }, - "422": { - "description": "Template tree is empty (TREE_EMPTY)", + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -419,6 +915,59 @@ }, "components": { "schemas": { + "TemplateSummary": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp" + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp" + } + }, + "required": [ + "id", + "name", + "createdAt", + "updatedAt" + ] + }, + "CreateTemplateBody": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "name" + ] + }, + "UpdateTemplateBody": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "name" + ] + }, "TreeNode": { "type": "object", "properties": { @@ -548,6 +1097,121 @@ "url" ] }, + "SendEmailBody": { + "type": "object", + "properties": { + "to": { + "minItems": 1, + "maxItems": 50, + "type": "array", + "items": { + "type": "string", + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + } + }, + "subject": { + "type": "string", + "minLength": 1, + "maxLength": 300 + } + }, + "required": [ + "to", + "subject" + ] + }, + "SentEmailSummary": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "templateId": { + "type": "string" + }, + "templateName": { + "type": "string", + "description": "Template name at the time of sending" + }, + "to": { + "type": "array", + "items": { + "type": "string" + } + }, + "subject": { + "type": "string" + }, + "status": { + "type": "string", + "const": "logged", + "description": "Delivery is not configured yet; sends are only logged" + }, + "createdAt": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp" + } + }, + "required": [ + "id", + "templateId", + "templateName", + "to", + "subject", + "status", + "createdAt" + ] + }, + "SentEmail": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "templateId": { + "type": "string" + }, + "templateName": { + "type": "string", + "description": "Template name at the time of sending" + }, + "to": { + "type": "array", + "items": { + "type": "string" + } + }, + "subject": { + "type": "string" + }, + "status": { + "type": "string", + "const": "logged", + "description": "Delivery is not configured yet; sends are only logged" + }, + "createdAt": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp" + }, + "html": { + "type": "string", + "description": "Snapshot of the rendered template" + } + }, + "required": [ + "id", + "templateId", + "templateName", + "to", + "subject", + "status", + "createdAt", + "html" + ] + }, "ErrorResponse": { "type": "object", "properties": { diff --git a/package-lock.json b/package-lock.json index 5c505c1..eac9513 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "email-template-editor-nodejs", - "version": "2.0.0", + "version": "3.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "email-template-editor-nodejs", - "version": "2.0.0", + "version": "3.0.0", "license": "ISC", "dependencies": { "cors": "^2.8.6", diff --git a/package.json b/package.json index 658b5a2..1d6744f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "email-template-editor-nodejs", - "version": "2.0.0", + "version": "3.0.0", "description": "REST API for the LLazyEmail email template editor", "private": true, "type": "module", diff --git a/src/modules/elements/elements.controller.ts b/src/modules/elements/elements.controller.ts index 1a605ba..fbe6e78 100644 --- a/src/modules/elements/elements.controller.ts +++ b/src/modules/elements/elements.controller.ts @@ -1,25 +1,29 @@ import type { Request, Response } from "express"; -import type { CreateElementBody, UpdateElementBody } from "./elements.schemas.js"; +import type { TemplateParams } from "../templates/templates.schemas.js"; +import type { CreateElementBody, ElementParams, UpdateElementBody } from "./elements.schemas.js"; import type { ElementsService } from "./elements.service.js"; export class ElementsController { constructor(private readonly service: ElementsService) {} - list = async (_req: Request, res: Response): Promise => { - res.json(await this.service.list()); + list = async (req: Request, res: Response): Promise => { + res.json(await this.service.list(req.params.templateId)); }; - create = async (req: Request, res: Response): Promise => { - res.status(201).json(await this.service.create(req.body as CreateElementBody)); + create = async (req: Request, res: Response): Promise => { + const element = req.body as CreateElementBody; + res.status(201).json(await this.service.create(req.params.templateId, element)); }; - update = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.update(req.params.key, req.body as UpdateElementBody); + update = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.update(templateId, key, req.body as UpdateElementBody); res.status(204).end(); }; - remove = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.remove(req.params.key); + remove = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.remove(templateId, key); res.status(204).end(); }; } diff --git a/src/modules/elements/elements.router.ts b/src/modules/elements/elements.router.ts index 1f31346..6975d37 100644 --- a/src/modules/elements/elements.router.ts +++ b/src/modules/elements/elements.router.ts @@ -1,5 +1,6 @@ import { Router } from "express"; import { validate } from "../../common/middleware/validate.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; import type { ElementsController } from "./elements.controller.js"; import { createElementBodySchema, @@ -7,11 +8,13 @@ import { updateElementBodySchema, } from "./elements.schemas.js"; +/** Mounted at /templates/:templateId/elements. */ export function createElementsRouter(controller: ElementsController): Router { - const router = Router(); + const router = Router({ mergeParams: true }); + const params = templateParamsSchema; - router.get("/", controller.list); - router.post("/", validate({ body: createElementBodySchema }), controller.create); + router.get("/", validate({ params }), controller.list); + router.post("/", validate({ params, body: createElementBodySchema }), controller.create); router.patch( "/:key", validate({ params: elementParamsSchema, body: updateElementBodySchema }), diff --git a/src/modules/elements/elements.schemas.ts b/src/modules/elements/elements.schemas.ts index b7c6206..c4b8830 100644 --- a/src/modules/elements/elements.schemas.ts +++ b/src/modules/elements/elements.schemas.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; export const elementKeySchema = z.string().trim().min(1, "key must not be empty"); @@ -17,7 +18,8 @@ export const updateElementBodySchema = z message: "At least one of title or value is required", }); -export const elementParamsSchema = z.object({ key: elementKeySchema }); +export const elementParamsSchema = templateParamsSchema.extend({ key: elementKeySchema }); export type CreateElementBody = z.infer; export type UpdateElementBody = z.infer; +export type ElementParams = z.infer; diff --git a/src/modules/elements/elements.service.ts b/src/modules/elements/elements.service.ts index fb06dbe..7c492da 100644 --- a/src/modules/elements/elements.service.ts +++ b/src/modules/elements/elements.service.ts @@ -1,42 +1,47 @@ import { ConflictError, NotFoundError } from "../../common/errors.js"; import type { Element } from "../../storage/db.types.js"; import type { TemplateStore } from "../../storage/template-store.js"; +import { findTemplate, touch } from "../templates/templates.helpers.js"; import type { UpdateElementBody } from "./elements.schemas.js"; +/** The library of reusable elements of one template. Keys are unique within a template. */ export class ElementsService { constructor(private readonly store: TemplateStore) {} - async list(): Promise { - const data = await this.store.read(); - return data.recipeTemplate.options; + async list(templateId: string): Promise { + return findTemplate(await this.store.read(), templateId).elements; } - async create(element: Element): Promise { + async create(templateId: string, element: Element): Promise { await this.store.update((data) => { - const { options } = data.recipeTemplate; - if (options.some((item) => item.key === element.key)) { + const template = findTemplate(data, templateId); + if (template.elements.some((item) => item.key === element.key)) { throw new ConflictError(`Element with key "${element.key}" already exists`); } - options.push(element); + template.elements.push(element); + touch(template); }); return element; } - async update(key: string, patch: UpdateElementBody): Promise { + async update(templateId: string, key: string, patch: UpdateElementBody): Promise { await this.store.update((data) => { - const element = data.recipeTemplate.options.find((item) => item.key === key); + const template = findTemplate(data, templateId); + const element = template.elements.find((item) => item.key === key); if (!element) throw new NotFoundError(`Element with key "${key}" not found`); if (patch.title !== undefined) element.title = patch.title; if (patch.value !== undefined) element.value = patch.value; + touch(template); }); } - async remove(key: string): Promise { + async remove(templateId: string, key: string): Promise { await this.store.update((data) => { - const { options } = data.recipeTemplate; - const index = options.findIndex((item) => item.key === key); + const template = findTemplate(data, templateId); + const index = template.elements.findIndex((item) => item.key === key); if (index === -1) throw new NotFoundError(`Element with key "${key}" not found`); - options.splice(index, 1); + template.elements.splice(index, 1); + touch(template); }); } } diff --git a/src/modules/generate/generate.controller.ts b/src/modules/generate/generate.controller.ts index d9d11e5..eeb01f5 100644 --- a/src/modules/generate/generate.controller.ts +++ b/src/modules/generate/generate.controller.ts @@ -1,11 +1,12 @@ import type { Request, Response } from "express"; +import type { TemplateParams } from "../templates/templates.schemas.js"; import type { GenerateService } from "./generate.service.js"; export class GenerateController { constructor(private readonly service: GenerateService) {} - generate = async (req: Request, res: Response): Promise => { - const { publicPath } = await this.service.generate(); + generate = async (req: Request, res: Response): Promise => { + const { publicPath } = await this.service.generate(req.params.templateId); res.json({ url: `${req.protocol}://${req.get("host")}${publicPath}` }); }; } diff --git a/src/modules/generate/generate.router.ts b/src/modules/generate/generate.router.ts index b24f662..28beada 100644 --- a/src/modules/generate/generate.router.ts +++ b/src/modules/generate/generate.router.ts @@ -1,8 +1,11 @@ import { Router } from "express"; +import { validate } from "../../common/middleware/validate.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; import type { GenerateController } from "./generate.controller.js"; +/** Mounted at /templates/:templateId/generate. */ export function createGenerateRouter(controller: GenerateController): Router { - const router = Router(); - router.post("/", controller.generate); + const router = Router({ mergeParams: true }); + router.post("/", validate({ params: templateParamsSchema }), controller.generate); return router; } diff --git a/src/modules/generate/generate.service.ts b/src/modules/generate/generate.service.ts index 9046210..d79b7aa 100644 --- a/src/modules/generate/generate.service.ts +++ b/src/modules/generate/generate.service.ts @@ -2,10 +2,30 @@ import { randomUUID } from "node:crypto"; import { mkdir, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { AppError } from "../../common/errors.js"; +import type { TreeNode } from "../../storage/db.types.js"; import type { TemplateStore } from "../../storage/template-store.js"; +import { findTemplate } from "../templates/templates.helpers.js"; import { generateHtml } from "./generate-html.js"; -export const GENERATED_FILE_NAME = "nmtgTemplate.html"; +const GENERATED_DIR = "generated"; + +/** URL path of a template's generated HTML file (served from the public directory). */ +export function generatedPublicPath(templateId: string): string { + return `/${GENERATED_DIR}/${encodeURIComponent(templateId)}.html`; +} + +/** File system path of a template's generated HTML file. `templateId` is validated by the router. */ +export function generatedFilePath(publicDir: string, templateId: string): string { + return path.join(publicDir, GENERATED_DIR, `${path.basename(templateId)}.html`); +} + +/** Renders a template tree, or fails with 422 TREE_EMPTY when there is nothing to render. */ +export function renderTree(tree: TreeNode[]): string { + if (tree.length === 0) { + throw new AppError(422, "TREE_EMPTY", "Template tree is empty, add a root element first"); + } + return generateHtml(tree); +} export class GenerateService { constructor( @@ -13,22 +33,16 @@ export class GenerateService { private readonly publicDir: string, ) {} - /** Renders the current tree to `/generated/` and returns its public path. */ - async generate(): Promise<{ publicPath: string }> { - const { tree } = (await this.store.read()).recipeTemplate; - if (tree.length === 0) { - throw new AppError(422, "TREE_EMPTY", "Template tree is empty, add a root element first"); - } - - const html = generateHtml(tree); - const dir = path.join(this.publicDir, "generated"); - const target = path.join(dir, GENERATED_FILE_NAME); + /** Renders the template's tree to `/generated/.html`; returns its public path. */ + async generate(templateId: string): Promise<{ publicPath: string }> { + const html = renderTree(findTemplate(await this.store.read(), templateId).tree); + const target = generatedFilePath(this.publicDir, templateId); const tmp = `${target}.${randomUUID()}.tmp`; - await mkdir(dir, { recursive: true }); + await mkdir(path.dirname(target), { recursive: true }); await writeFile(tmp, html); await rename(tmp, target); - return { publicPath: `/generated/${GENERATED_FILE_NAME}` }; + return { publicPath: generatedPublicPath(templateId) }; } } diff --git a/src/modules/sent-emails/sent-emails.controller.ts b/src/modules/sent-emails/sent-emails.controller.ts new file mode 100644 index 0000000..b976ed0 --- /dev/null +++ b/src/modules/sent-emails/sent-emails.controller.ts @@ -0,0 +1,21 @@ +import type { Request, Response } from "express"; +import type { TemplateParams } from "../templates/templates.schemas.js"; +import type { SendEmailBody, SentEmailParams } from "./sent-emails.schemas.js"; +import type { SentEmailsService } from "./sent-emails.service.js"; + +export class SentEmailsController { + constructor(private readonly service: SentEmailsService) {} + + send = async (req: Request, res: Response): Promise => { + const body = req.body as SendEmailBody; + res.status(201).json(await this.service.send(req.params.templateId, body)); + }; + + list = async (_req: Request, res: Response): Promise => { + res.json(await this.service.list()); + }; + + get = async (req: Request, res: Response): Promise => { + res.json(await this.service.get(req.params.id)); + }; +} diff --git a/src/modules/sent-emails/sent-emails.router.ts b/src/modules/sent-emails/sent-emails.router.ts new file mode 100644 index 0000000..d7224cc --- /dev/null +++ b/src/modules/sent-emails/sent-emails.router.ts @@ -0,0 +1,24 @@ +import { Router } from "express"; +import { validate } from "../../common/middleware/validate.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; +import type { SentEmailsController } from "./sent-emails.controller.js"; +import { sendEmailBodySchema, sentEmailParamsSchema } from "./sent-emails.schemas.js"; + +/** Mounted at /sent-emails: the log of sent emails. */ +export function createSentEmailsRouter(controller: SentEmailsController): Router { + const router = Router(); + router.get("/", controller.list); + router.get("/:id", validate({ params: sentEmailParamsSchema }), controller.get); + return router; +} + +/** Mounted at /templates/:templateId/send. */ +export function createSendRouter(controller: SentEmailsController): Router { + const router = Router({ mergeParams: true }); + router.post( + "/", + validate({ params: templateParamsSchema, body: sendEmailBodySchema }), + controller.send, + ); + return router; +} diff --git a/src/modules/sent-emails/sent-emails.schemas.ts b/src/modules/sent-emails/sent-emails.schemas.ts new file mode 100644 index 0000000..741e2a6 --- /dev/null +++ b/src/modules/sent-emails/sent-emails.schemas.ts @@ -0,0 +1,32 @@ +import { z } from "zod"; +import { timestampSchema } from "../templates/templates.schemas.js"; + +export const sendEmailBodySchema = z.object({ + to: z + .array(z.email("Invalid email address")) + .min(1, "At least one recipient is required") + .max(50, "At most 50 recipients"), + subject: z.string().trim().min(1, "subject must not be empty").max(300), +}); + +export const sentEmailParamsSchema = z.object({ + id: z.string().trim().min(1, "id must not be empty"), +}); + +export const sentEmailSummarySchema = z.object({ + id: z.string(), + templateId: z.string(), + templateName: z.string().describe("Template name at the time of sending"), + to: z.array(z.string()), + subject: z.string(), + status: z.literal("logged").describe("Delivery is not configured yet; sends are only logged"), + createdAt: timestampSchema, +}); + +export const sentEmailSchema = sentEmailSummarySchema.extend({ + html: z.string().describe("Snapshot of the rendered template"), +}); + +export type SendEmailBody = z.infer; +export type SentEmailParams = z.infer; +export type SentEmailSummary = z.infer; diff --git a/src/modules/sent-emails/sent-emails.service.ts b/src/modules/sent-emails/sent-emails.service.ts new file mode 100644 index 0000000..a5de401 --- /dev/null +++ b/src/modules/sent-emails/sent-emails.service.ts @@ -0,0 +1,52 @@ +import { randomUUID } from "node:crypto"; +import { NotFoundError } from "../../common/errors.js"; +import type { SentEmail } from "../../storage/db.types.js"; +import type { TemplateStore } from "../../storage/template-store.js"; +import { renderTree } from "../generate/generate.service.js"; +import { findTemplate } from "../templates/templates.helpers.js"; +import type { SendEmailBody, SentEmailSummary } from "./sent-emails.schemas.js"; + +const toSummary = ({ html: _html, ...summary }: SentEmail): SentEmailSummary => summary; + +/** + * "Sending" renders the template and records it in the sent-emails log. No email is delivered: + * there is no transport yet, so every entry has status "logged". + */ +export class SentEmailsService { + constructor(private readonly store: TemplateStore) {} + + async send(templateId: string, { to, subject }: SendEmailBody): Promise { + const entry = await this.store.update((data) => { + const template = findTemplate(data, templateId); + const sent: SentEmail = { + id: randomUUID(), + templateId, + templateName: template.name, + to, + subject, + html: renderTree(template.tree), + status: "logged", + createdAt: new Date().toISOString(), + }; + data.sentEmails.push(sent); + return sent; + }); + return toSummary(entry); + } + + /** Summaries (without html), newest first. */ + async list(): Promise { + const { sentEmails } = await this.store.read(); + // Reverse first so that, with equal timestamps, the later entry comes first. + return [...sentEmails] + .reverse() + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) + .map(toSummary); + } + + async get(id: string): Promise { + const sent = (await this.store.read()).sentEmails.find((item) => item.id === id); + if (!sent) throw new NotFoundError(`Sent email "${id}" not found`); + return sent; + } +} diff --git a/src/modules/templates/templates.controller.ts b/src/modules/templates/templates.controller.ts new file mode 100644 index 0000000..41ae876 --- /dev/null +++ b/src/modules/templates/templates.controller.ts @@ -0,0 +1,35 @@ +import type { Request, Response } from "express"; +import type { + CreateTemplateBody, + TemplateParams, + UpdateTemplateBody, +} from "./templates.schemas.js"; +import type { TemplatesService } from "./templates.service.js"; + +export class TemplatesController { + constructor(private readonly service: TemplatesService) {} + + list = async (_req: Request, res: Response): Promise => { + res.json(await this.service.list()); + }; + + create = async (req: Request, res: Response): Promise => { + const { name } = req.body as CreateTemplateBody; + res.status(201).json(await this.service.create(name)); + }; + + get = async (req: Request, res: Response): Promise => { + res.json(await this.service.get(req.params.templateId)); + }; + + rename = async (req: Request, res: Response): Promise => { + const { name } = req.body as UpdateTemplateBody; + await this.service.rename(req.params.templateId, name); + res.status(204).end(); + }; + + remove = async (req: Request, res: Response): Promise => { + await this.service.delete(req.params.templateId); + res.status(204).end(); + }; +} diff --git a/src/modules/templates/templates.helpers.ts b/src/modules/templates/templates.helpers.ts new file mode 100644 index 0000000..a3cc8c1 --- /dev/null +++ b/src/modules/templates/templates.helpers.ts @@ -0,0 +1,19 @@ +import { NotFoundError } from "../../common/errors.js"; +import type { DbData, Template } from "../../storage/db.types.js"; +import type { TemplateSummary } from "./templates.schemas.js"; + +/** Returns the template with `id`, or throws NOT_FOUND. Shared by every template-scoped module. */ +export function findTemplate(data: DbData, id: string): Template { + const template = data.templates.find((item) => item.id === id); + if (!template) throw new NotFoundError(`Template "${id}" not found`); + return template; +} + +/** Marks the template as changed; call from every mutation of its name, tree or elements. */ +export function touch(template: Template): void { + template.updatedAt = new Date().toISOString(); +} + +export function toSummary({ id, name, createdAt, updatedAt }: Template): TemplateSummary { + return { id, name, createdAt, updatedAt }; +} diff --git a/src/modules/templates/templates.router.ts b/src/modules/templates/templates.router.ts new file mode 100644 index 0000000..dd1517f --- /dev/null +++ b/src/modules/templates/templates.router.ts @@ -0,0 +1,24 @@ +import { Router } from "express"; +import { validate } from "../../common/middleware/validate.js"; +import type { TemplatesController } from "./templates.controller.js"; +import { + createTemplateBodySchema, + templateParamsSchema, + updateTemplateBodySchema, +} from "./templates.schemas.js"; + +export function createTemplatesRouter(controller: TemplatesController): Router { + const router = Router(); + + router.get("/", controller.list); + router.post("/", validate({ body: createTemplateBodySchema }), controller.create); + router.get("/:templateId", validate({ params: templateParamsSchema }), controller.get); + router.patch( + "/:templateId", + validate({ params: templateParamsSchema, body: updateTemplateBodySchema }), + controller.rename, + ); + router.delete("/:templateId", validate({ params: templateParamsSchema }), controller.remove); + + return router; +} diff --git a/src/modules/templates/templates.schemas.ts b/src/modules/templates/templates.schemas.ts new file mode 100644 index 0000000..560e1bc --- /dev/null +++ b/src/modules/templates/templates.schemas.ts @@ -0,0 +1,36 @@ +import { z } from "zod"; + +/** + * Template ids are generated by the server (UUIDs). The id also names the generated HTML file, + * so only URL- and file-safe characters are accepted. + */ +export const TEMPLATE_ID_PATTERN = /^[\w-]{1,128}$/; + +export const templateIdSchema = z + .string() + .regex(TEMPLATE_ID_PATTERN, "templateId must be 1-128 letters, digits, '_' or '-'"); + +export const templateParamsSchema = z.object({ templateId: templateIdSchema }); + +const templateNameSchema = z.string().trim().min(1, "name must not be empty").max(200); + +export const createTemplateBodySchema = z.object({ name: templateNameSchema }); + +export const updateTemplateBodySchema = z.object({ name: templateNameSchema }); + +/** Response field: an ISO 8601 timestamp written by the server. */ +export const timestampSchema = z + .string() + .meta({ format: "date-time", description: "ISO 8601 timestamp" }); + +export const templateSummarySchema = z.object({ + id: z.string(), + name: z.string(), + createdAt: timestampSchema, + updatedAt: timestampSchema, +}); + +export type TemplateParams = z.infer; +export type CreateTemplateBody = z.infer; +export type UpdateTemplateBody = z.infer; +export type TemplateSummary = z.infer; diff --git a/src/modules/templates/templates.service.ts b/src/modules/templates/templates.service.ts new file mode 100644 index 0000000..13132d6 --- /dev/null +++ b/src/modules/templates/templates.service.ts @@ -0,0 +1,61 @@ +import { randomUUID } from "node:crypto"; +import { rm } from "node:fs/promises"; +import type { Template } from "../../storage/db.types.js"; +import type { TemplateStore } from "../../storage/template-store.js"; +import { generatedFilePath } from "../generate/generate.service.js"; +import { findTemplate, toSummary, touch } from "./templates.helpers.js"; +import type { TemplateSummary } from "./templates.schemas.js"; + +export class TemplatesService { + constructor( + private readonly store: TemplateStore, + private readonly publicDir: string, + ) {} + + /** Summaries (no tree or elements), most recently changed first. */ + async list(): Promise { + const { templates } = await this.store.read(); + // Reverse first so that, with equal timestamps, the later-created template comes first. + return [...templates] + .reverse() + .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) + .map(toSummary); + } + + async create(name: string): Promise { + const now = new Date().toISOString(); + const template: Template = { + id: randomUUID(), + name, + tree: [], + elements: [], + createdAt: now, + updatedAt: now, + }; + await this.store.update((data) => { + data.templates.push(template); + }); + return toSummary(template); + } + + async get(id: string): Promise { + return toSummary(findTemplate(await this.store.read(), id)); + } + + async rename(id: string, name: string): Promise { + await this.store.update((data) => { + const template = findTemplate(data, id); + template.name = name; + touch(template); + }); + } + + /** Deletes the template and its generated HTML file. Sent-email log entries are kept. */ + async delete(id: string): Promise { + await this.store.update((data) => { + const template = findTemplate(data, id); + data.templates.splice(data.templates.indexOf(template), 1); + }); + await rm(generatedFilePath(this.publicDir, id), { force: true }); + } +} diff --git a/src/modules/tree/tree.controller.ts b/src/modules/tree/tree.controller.ts index d60889c..e529581 100644 --- a/src/modules/tree/tree.controller.ts +++ b/src/modules/tree/tree.controller.ts @@ -1,33 +1,36 @@ import type { Request, Response } from "express"; -import type { AddNodeBody, SaveTreeBody, UpdateNodeBody } from "./tree.schemas.js"; +import type { TemplateParams } from "../templates/templates.schemas.js"; +import type { AddNodeBody, NodeParams, SaveTreeBody, UpdateNodeBody } from "./tree.schemas.js"; import type { TreeService } from "./tree.service.js"; /** HTTP adapter: maps requests to TreeService calls. Input is already validated by the router. */ export class TreeController { constructor(private readonly service: TreeService) {} - getTree = async (_req: Request, res: Response): Promise => { - res.json(await this.service.getTree()); + getTree = async (req: Request, res: Response): Promise => { + res.json(await this.service.getTree(req.params.templateId)); }; - replaceTree = async (req: Request, res: Response): Promise => { + replaceTree = async (req: Request, res: Response): Promise => { const { treeData } = req.body as SaveTreeBody; - await this.service.replaceTree(treeData); + await this.service.replaceTree(req.params.templateId, treeData); res.status(204).end(); }; - addNode = async (req: Request, res: Response): Promise => { + addNode = async (req: Request, res: Response): Promise => { const { parentKey, item } = req.body as AddNodeBody; - res.status(201).json(await this.service.addNode(parentKey, item)); + res.status(201).json(await this.service.addNode(req.params.templateId, parentKey, item)); }; - updateNode = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.updateNode(req.params.key, req.body as UpdateNodeBody); + updateNode = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.updateNode(templateId, key, req.body as UpdateNodeBody); res.status(204).end(); }; - deleteNode = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.deleteNode(req.params.key); + deleteNode = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.deleteNode(templateId, key); res.status(204).end(); }; } diff --git a/src/modules/tree/tree.router.ts b/src/modules/tree/tree.router.ts index ee6447d..4f8afbf 100644 --- a/src/modules/tree/tree.router.ts +++ b/src/modules/tree/tree.router.ts @@ -1,5 +1,6 @@ import { Router } from "express"; import { validate } from "../../common/middleware/validate.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; import type { TreeController } from "./tree.controller.js"; import { addNodeBodySchema, @@ -8,12 +9,14 @@ import { updateNodeBodySchema, } from "./tree.schemas.js"; +/** Mounted at /templates/:templateId/tree. */ export function createTreeRouter(controller: TreeController): Router { - const router = Router(); + const router = Router({ mergeParams: true }); + const params = templateParamsSchema; - router.get("/", controller.getTree); - router.put("/", validate({ body: saveTreeBodySchema }), controller.replaceTree); - router.post("/nodes", validate({ body: addNodeBodySchema }), controller.addNode); + router.get("/", validate({ params }), controller.getTree); + router.put("/", validate({ params, body: saveTreeBodySchema }), controller.replaceTree); + router.post("/nodes", validate({ params, body: addNodeBodySchema }), controller.addNode); router.patch( "/nodes/:key", validate({ params: nodeParamsSchema, body: updateNodeBodySchema }), diff --git a/src/modules/tree/tree.schemas.ts b/src/modules/tree/tree.schemas.ts index 6245ab0..1d1d459 100644 --- a/src/modules/tree/tree.schemas.ts +++ b/src/modules/tree/tree.schemas.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import type { TreeNode } from "../../storage/db.types.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; export const nodeKeySchema = z.string().trim().min(1, "key must not be empty"); @@ -31,8 +32,9 @@ export const updateNodeBodySchema = z message: "At least one of title or value is required", }); -export const nodeParamsSchema = z.object({ key: nodeKeySchema }); +export const nodeParamsSchema = templateParamsSchema.extend({ key: nodeKeySchema }); export type SaveTreeBody = z.infer; export type AddNodeBody = z.infer; export type UpdateNodeBody = z.infer; +export type NodeParams = z.infer; diff --git a/src/modules/tree/tree.service.ts b/src/modules/tree/tree.service.ts index cf6b826..f048dff 100644 --- a/src/modules/tree/tree.service.ts +++ b/src/modules/tree/tree.service.ts @@ -1,53 +1,61 @@ import { ConflictError, NotFoundError } from "../../common/errors.js"; import type { TreeNode } from "../../storage/db.types.js"; import type { TemplateStore } from "../../storage/template-store.js"; +import { findTemplate, touch } from "../templates/templates.helpers.js"; import { addNode, collectKeys, deleteNode, updateNode } from "./tree.helpers.js"; import type { UpdateNodeBody } from "./tree.schemas.js"; +/** The tree of one template. Node keys are unique within a template. */ export class TreeService { constructor(private readonly store: TemplateStore) {} - async getTree(): Promise { - const data = await this.store.read(); - return data.recipeTemplate.tree; + async getTree(templateId: string): Promise { + return findTemplate(await this.store.read(), templateId).tree; } - async replaceTree(tree: TreeNode[]): Promise { - assertUniqueKeys(tree); + async replaceTree(templateId: string, tree: TreeNode[]): Promise { await this.store.update((data) => { - data.recipeTemplate.tree = tree; + const template = findTemplate(data, templateId); + assertUniqueKeys(tree); + template.tree = tree; + touch(template); }); } - async addNode(parentKey: string, item: TreeNode): Promise { + async addNode(templateId: string, parentKey: string, item: TreeNode): Promise { await this.store.update((data) => { - const { tree } = data.recipeTemplate; - const existing = new Set(collectKeys(tree)); + const template = findTemplate(data, templateId); + const existing = new Set(collectKeys(template.tree)); const clash = collectKeys([item]).find((key) => existing.has(key)); if (clash !== undefined) { throw new ConflictError(`Tree node with key "${clash}" already exists`); } assertUniqueKeys([item]); - if (!addNode(tree, parentKey, item)) { + if (!addNode(template.tree, parentKey, item)) { throw new NotFoundError(`Parent tree node "${parentKey}" not found`); } + touch(template); }); return item; } - async updateNode(key: string, patch: UpdateNodeBody): Promise { + async updateNode(templateId: string, key: string, patch: UpdateNodeBody): Promise { await this.store.update((data) => { - if (!updateNode(data.recipeTemplate.tree, key, patch)) { + const template = findTemplate(data, templateId); + if (!updateNode(template.tree, key, patch)) { throw new NotFoundError(`Tree node "${key}" not found`); } + touch(template); }); } - async deleteNode(key: string): Promise { + async deleteNode(templateId: string, key: string): Promise { await this.store.update((data) => { - if (!deleteNode(data.recipeTemplate.tree, key)) { + const template = findTemplate(data, templateId); + if (!deleteNode(template.tree, key)) { throw new NotFoundError(`Tree node "${key}" not found`); } + touch(template); }); } } diff --git a/src/openapi.ts b/src/openapi.ts index 7332f0f..fe5c7b6 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -3,6 +3,17 @@ import { createElementBodySchema, updateElementBodySchema, } from "./modules/elements/elements.schemas.js"; +import { + sendEmailBodySchema, + sentEmailSchema, + sentEmailSummarySchema, +} from "./modules/sent-emails/sent-emails.schemas.js"; +import { + TEMPLATE_ID_PATTERN, + createTemplateBodySchema, + templateSummarySchema, + updateTemplateBodySchema, +} from "./modules/templates/templates.schemas.js"; import { addNodeBodySchema, saveTreeBodySchema, @@ -35,6 +46,9 @@ const healthSchema = z.object({ status: z.literal("ok") }); /** Named schemas; each becomes #/components/schemas/. */ const components = { + TemplateSummary: templateSummarySchema, + CreateTemplateBody: createTemplateBodySchema, + UpdateTemplateBody: updateTemplateBodySchema, TreeNode: treeNodeSchema, Element: elementSchema, SaveTreeBody: saveTreeBodySchema, @@ -43,6 +57,9 @@ const components = { CreateElementBody: createElementBodySchema, UpdateElementBody: updateElementBodySchema, GenerateResponse: generateResponseSchema, + SendEmailBody: sendEmailBodySchema, + SentEmailSummary: sentEmailSummarySchema, + SentEmail: sentEmailSchema, ErrorResponse: errorResponseSchema, Health: healthSchema, } satisfies Record; @@ -54,7 +71,7 @@ const json = (schema: object) => ({ content: { "application/json": { schema } } const ERROR_TEXT = { 400: "Invalid request (VALIDATION_ERROR, INVALID_JSON)", - 404: "Not found (NOT_FOUND)", + 404: "Not found (NOT_FOUND): the template, or the key or id in the path", 409: "Key already exists (CONFLICT)", 413: "Body too large (PAYLOAD_TOO_LARGE)", 422: "Template tree is empty (TREE_EMPTY)", @@ -71,13 +88,20 @@ const errors = (...statuses: (keyof typeof ERROR_TEXT)[]) => const body = (name: SchemaName) => ({ required: true, ...json(ref(name)) }); const noContent = { "204": { description: "Done" } }; -const keyParam = (what: string) => ({ - name: "key", +const pathParam = (name: string, description: string, schema: object) => ({ + name, in: "path", required: true, - description: `${what} key, URL-encoded`, - schema: { type: "string", minLength: 1 }, + description, + schema: { type: "string", ...schema }, +}); + +const keyParam = (what: string) => pathParam("key", `${what} key, URL-encoded`, { minLength: 1 }); +const idParam = (what: string) => pathParam("id", `${what} id`, { minLength: 1 }); +const templateIdParam = pathParam("templateId", "Template id", { + pattern: TEMPLATE_ID_PATTERN.source, }); +const arrayOf = (name: SchemaName) => ({ type: "array", items: ref(name) }); function componentSchemas(): Record { const registry = z.registry<{ id: string }>(); @@ -105,9 +129,9 @@ export function buildOpenApiDocument() { openapi: "3.1.0", info: { title: "Email template editor API", - version: "2.0.0", + version: "3.0.0", description: - "Stores the template tree and the library of reusable elements, and renders the tree into one HTML email. Errors always have the ErrorResponse shape.", + "Stores email templates (each with its own tree and library of reusable elements), renders a tree into one HTML email and keeps a log of sent emails. Errors always have the ErrorResponse shape.", }, servers: [{ url: "http://localhost:9000", description: "Local development" }], paths: { @@ -123,23 +147,58 @@ export function buildOpenApiDocument() { responses: { "200": { description: "OpenAPI 3.1 document" } }, }, }, - "/tree": { + "/templates": { get: { - summary: "Get the whole template tree", + summary: "List templates, most recently changed first", responses: { - "200": { - description: "Root nodes", - ...json({ type: "array", items: ref("TreeNode") }), - }, + "200": { description: "Template summaries", ...json(arrayOf("TemplateSummary")) }, + }, + }, + post: { + summary: "Create an empty template", + requestBody: body("CreateTemplateBody"), + responses: { + "201": { description: "The new template", ...json(ref("TemplateSummary")) }, + ...errors(400, 413), + }, + }, + }, + "/templates/{templateId}": { + parameters: [templateIdParam], + get: { + summary: "Get a template's name and timestamps", + responses: { + "200": { description: "Template summary", ...json(ref("TemplateSummary")) }, + ...errors(400, 404), + }, + }, + patch: { + summary: "Rename a template", + requestBody: body("UpdateTemplateBody"), + responses: { ...noContent, ...errors(400, 404) }, + }, + delete: { + summary: "Delete a template and its generated file (sent-email log entries are kept)", + responses: { ...noContent, ...errors(400, 404) }, + }, + }, + "/templates/{templateId}/tree": { + parameters: [templateIdParam], + get: { + summary: "Get the template's whole tree", + responses: { + "200": { description: "Root nodes", ...json(arrayOf("TreeNode")) }, + ...errors(400, 404), }, }, put: { - summary: "Replace the whole template tree", + summary: "Replace the template's whole tree", requestBody: body("SaveTreeBody"), - responses: { ...noContent, ...errors(400, 409, 413) }, + responses: { ...noContent, ...errors(400, 404, 409, 413) }, }, }, - "/tree/nodes": { + "/templates/{templateId}/tree/nodes": { + parameters: [templateIdParam], post: { summary: "Add a node under a parent", requestBody: body("AddNodeBody"), @@ -149,8 +208,8 @@ export function buildOpenApiDocument() { }, }, }, - "/tree/nodes/{key}": { - parameters: [keyParam("Tree node")], + "/templates/{templateId}/tree/nodes/{key}": { + parameters: [templateIdParam, keyParam("Tree node")], patch: { summary: "Change a node's title and/or value", requestBody: body("UpdateNodeBody"), @@ -158,17 +217,16 @@ export function buildOpenApiDocument() { }, delete: { summary: "Delete a node and its children", - responses: { ...noContent, ...errors(404) }, + responses: { ...noContent, ...errors(400, 404) }, }, }, - "/elements": { + "/templates/{templateId}/elements": { + parameters: [templateIdParam], get: { - summary: "List library elements", + summary: "List the template's library elements", responses: { - "200": { - description: "All elements", - ...json({ type: "array", items: ref("Element") }), - }, + "200": { description: "All elements", ...json(arrayOf("Element")) }, + ...errors(400, 404), }, }, post: { @@ -176,12 +234,12 @@ export function buildOpenApiDocument() { requestBody: body("CreateElementBody"), responses: { "201": { description: "The added element", ...json(ref("Element")) }, - ...errors(400, 409, 413), + ...errors(400, 404, 409, 413), }, }, }, - "/elements/{key}": { - parameters: [keyParam("Element")], + "/templates/{templateId}/elements/{key}": { + parameters: [templateIdParam, keyParam("Element")], patch: { summary: "Change an element's title and/or value", requestBody: body("UpdateElementBody"), @@ -189,15 +247,48 @@ export function buildOpenApiDocument() { }, delete: { summary: "Delete an element", - responses: { ...noContent, ...errors(404) }, + responses: { ...noContent, ...errors(400, 404) }, }, }, - "/generate": { + "/templates/{templateId}/generate": { + parameters: [templateIdParam], post: { - summary: "Render the tree into an HTML file and return its URL", + summary: "Render the tree into .html and return its URL", responses: { "200": { description: "Link to the generated file", ...json(ref("GenerateResponse")) }, - ...errors(422), + ...errors(400, 404, 422), + }, + }, + }, + "/templates/{templateId}/send": { + parameters: [templateIdParam], + post: { + summary: "Render the template and log it as sent (no email is delivered yet)", + requestBody: body("SendEmailBody"), + responses: { + "201": { description: "The log entry", ...json(ref("SentEmailSummary")) }, + ...errors(400, 404, 413, 422), + }, + }, + }, + "/sent-emails": { + get: { + summary: "List logged sends, newest first", + responses: { + "200": { + description: "Log entries without HTML", + ...json(arrayOf("SentEmailSummary")), + }, + }, + }, + }, + "/sent-emails/{id}": { + parameters: [idParam("Sent email")], + get: { + summary: "Get a logged send with its HTML snapshot", + responses: { + "200": { description: "The log entry", ...json(ref("SentEmail")) }, + ...errors(400, 404), }, }, }, diff --git a/src/routes.ts b/src/routes.ts index a187ab5..71f6a60 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -5,6 +5,15 @@ import { ElementsService } from "./modules/elements/elements.service.js"; import { GenerateController } from "./modules/generate/generate.controller.js"; import { createGenerateRouter } from "./modules/generate/generate.router.js"; import { GenerateService } from "./modules/generate/generate.service.js"; +import { SentEmailsController } from "./modules/sent-emails/sent-emails.controller.js"; +import { + createSendRouter, + createSentEmailsRouter, +} from "./modules/sent-emails/sent-emails.router.js"; +import { SentEmailsService } from "./modules/sent-emails/sent-emails.service.js"; +import { TemplatesController } from "./modules/templates/templates.controller.js"; +import { createTemplatesRouter } from "./modules/templates/templates.router.js"; +import { TemplatesService } from "./modules/templates/templates.service.js"; import { TreeController } from "./modules/tree/tree.controller.js"; import { createTreeRouter } from "./modules/tree/tree.router.js"; import { TreeService } from "./modules/tree/tree.service.js"; @@ -29,12 +38,27 @@ export function createRoutes({ store, publicDir }: RouteDeps): Router { res.json(openApiDocument); }); - router.use("/tree", createTreeRouter(new TreeController(new TreeService(store)))); - router.use("/elements", createElementsRouter(new ElementsController(new ElementsService(store)))); + const sentEmails = new SentEmailsController(new SentEmailsService(store)); + + router.use( + "/templates", + createTemplatesRouter(new TemplatesController(new TemplatesService(store, publicDir))), + ); + // Template-scoped routers use mergeParams and validate :templateId themselves. + router.use( + "/templates/:templateId/tree", + createTreeRouter(new TreeController(new TreeService(store))), + ); + router.use( + "/templates/:templateId/elements", + createElementsRouter(new ElementsController(new ElementsService(store))), + ); router.use( - "/generate", + "/templates/:templateId/generate", createGenerateRouter(new GenerateController(new GenerateService(store, publicDir))), ); + router.use("/templates/:templateId/send", createSendRouter(sentEmails)); + router.use("/sent-emails", createSentEmailsRouter(sentEmails)); return router; } diff --git a/src/storage/db.types.ts b/src/storage/db.types.ts index 40c51a8..0b4ec81 100644 --- a/src/storage/db.types.ts +++ b/src/storage/db.types.ts @@ -11,14 +11,37 @@ export interface Element { value: string; } -/** On-disk shape of db.json (kept compatible with the previous lowdb format). */ +/** One email template: its own tree and its own library of reusable elements. */ +export interface Template { + id: string; + name: string; + tree: TreeNode[]; + elements: Element[]; + /** ISO 8601 timestamps. */ + createdAt: string; + updatedAt: string; +} + +/** A logged "send": who it was for, the subject and a snapshot of the rendered HTML. */ +export interface SentEmail { + id: string; + templateId: string; + /** Template name at the time of sending; kept after the template is deleted. */ + templateName: string; + to: string[]; + subject: string; + html: string; + /** Delivery is not configured yet, so every send is only logged. */ + status: "logged"; + createdAt: string; +} + +/** On-disk shape of db.json. */ export interface DbData { - recipeTemplate: { - tree: TreeNode[]; - options: Element[]; - }; + templates: Template[]; + sentEmails: SentEmail[]; } export function createEmptyDb(): DbData { - return { recipeTemplate: { tree: [], options: [] } }; + return { templates: [], sentEmails: [] }; } diff --git a/src/storage/json-file-store.test.ts b/src/storage/json-file-store.test.ts index 18e7275..12256c6 100644 --- a/src/storage/json-file-store.test.ts +++ b/src/storage/json-file-store.test.ts @@ -2,7 +2,21 @@ import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { JsonFileStore, StorageError } from "./json-file-store.js"; +import type { DbData, Template } from "./db.types.js"; +import { JsonFileStore, MIGRATED_TEMPLATE_NAME, StorageError } from "./json-file-store.js"; + +const template = (id: string): Template => ({ + id, + name: `Template ${id}`, + tree: [], + elements: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", +}); + +const addTemplate = (id: string) => (data: DbData) => { + data.templates.push(template(id)); +}; describe("JsonFileStore", () => { let dir: string; @@ -17,27 +31,81 @@ describe("JsonFileStore", () => { await rm(dir, { recursive: true, force: true }); }); + const readFileJson = async () => JSON.parse(await readFile(file, "utf8")) as DbData; + it("init creates the file with an empty structure", async () => { await new JsonFileStore(file).init(); - expect(JSON.parse(await readFile(file, "utf8"))).toEqual({ - recipeTemplate: { tree: [], options: [] }, - }); + expect(await readFileJson()).toEqual({ templates: [], sentEmails: [] }); + }); + + it("treats an empty file as an empty database", async () => { + await writeFile(file, " \n"); + expect(await new JsonFileStore(file).read()).toEqual({ templates: [], sentEmails: [] }); }); it("fills in missing collections of an existing file", async () => { - await writeFile(file, JSON.stringify({ recipeTemplate: { tree: [] } })); + await writeFile(file, JSON.stringify({ templates: [{ id: "t1", name: "One" }] })); const data = await new JsonFileStore(file).read(); - expect(data.recipeTemplate.options).toEqual([]); + expect(data.sentEmails).toEqual([]); + expect(data.templates[0]).toMatchObject({ id: "t1", name: "One", tree: [], elements: [] }); + }); + + it("keeps unknown top-level keys", async () => { + await writeFile(file, JSON.stringify({ templates: [], sentEmails: [], extra: { a: 1 } })); + expect(await new JsonFileStore(file).read()).toMatchObject({ extra: { a: 1 } }); + }); + + describe("migration from the single-template format (recipeTemplate)", () => { + const tree = [{ key: "1", title: "root", value: "

{{a}}

", children: [] }]; + const options = [{ key: "el-1", title: "{{a}}", value: "A" }]; + + it("turns recipeTemplate into one template and drops the old key", async () => { + await writeFile(file, JSON.stringify({ recipeTemplate: { tree, options } })); + await new JsonFileStore(file).init(); + + const data = await readFileJson(); + expect(Object.keys(data).sort()).toEqual(["sentEmails", "templates"]); + expect(data.sentEmails).toEqual([]); + expect(data.templates).toHaveLength(1); + const [migrated] = data.templates; + expect(migrated).toMatchObject({ name: MIGRATED_TEMPLATE_NAME, tree, elements: options }); + expect(migrated!.id).toMatch(/^[\w-]{36}$/); + expect(migrated!.createdAt).toBe(migrated!.updatedAt); + expect(Number.isNaN(Date.parse(migrated!.createdAt))).toBe(false); + }); + + it("keeps the migrated id stable once written", async () => { + await writeFile(file, JSON.stringify({ recipeTemplate: { tree, options } })); + const store = new JsonFileStore(file); + await store.init(); + const { id } = (await store.read()).templates[0]!; + expect((await store.read()).templates[0]!.id).toBe(id); + }); + + it("fills in a partial recipeTemplate", async () => { + await writeFile(file, JSON.stringify({ recipeTemplate: { tree } })); + const data = await new JsonFileStore(file).read(); + expect(data.templates[0]).toMatchObject({ tree, elements: [] }); + }); + + it("does not migrate when templates already exist", async () => { + await writeFile( + file, + JSON.stringify({ templates: [template("t1")], recipeTemplate: { tree, options } }), + ); + const data = await new JsonFileStore(file).read(); + expect(data.templates.map((t) => t.id)).toEqual(["t1"]); + }); }); it("persists updates and returns the mutator's result", async () => { const store = new JsonFileStore(file); const result = await store.update((data) => { - data.recipeTemplate.options.push({ key: "k", title: "t", value: "v" }); + addTemplate("t1")(data); return "done"; }); expect(result).toBe("done"); - expect((await new JsonFileStore(file).read()).recipeTemplate.options).toHaveLength(1); + expect((await new JsonFileStore(file).read()).templates).toHaveLength(1); }); it("does not write anything when the mutator throws", async () => { @@ -45,33 +113,25 @@ describe("JsonFileStore", () => { await store.init(); await expect( store.update((data) => { - data.recipeTemplate.options.push({ key: "k", title: "t", value: "v" }); + addTemplate("t1")(data); throw new Error("boom"); }), ).rejects.toThrow("boom"); - expect((await store.read()).recipeTemplate.options).toEqual([]); + expect((await store.read()).templates).toEqual([]); }); it("serializes concurrent updates without losing writes", async () => { const store = new JsonFileStore(file); - await Promise.all( - Array.from({ length: 25 }, (_, i) => - store.update((data) => { - data.recipeTemplate.options.push({ key: String(i), title: "t", value: "v" }); - }), - ), - ); - expect((await store.read()).recipeTemplate.options).toHaveLength(25); + await Promise.all(Array.from({ length: 25 }, (_, i) => store.update(addTemplate(String(i))))); + expect((await store.read()).templates).toHaveLength(25); expect((await readdir(dir)).filter((name) => name.endsWith(".tmp"))).toEqual([]); }); it("keeps working after a failed update", async () => { const store = new JsonFileStore(file); await expect(store.update(() => Promise.reject(new Error("fail")))).rejects.toThrow("fail"); - await store.update((data) => { - data.recipeTemplate.options.push({ key: "k", title: "t", value: "v" }); - }); - expect((await store.read()).recipeTemplate.options).toHaveLength(1); + await store.update(addTemplate("t1")); + expect((await store.read()).templates).toHaveLength(1); }); it("raises StorageError for a corrupted file", async () => { diff --git a/src/storage/json-file-store.ts b/src/storage/json-file-store.ts index c5e3a56..1f945b1 100644 --- a/src/storage/json-file-store.ts +++ b/src/storage/json-file-store.ts @@ -1,14 +1,21 @@ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; -import { createEmptyDb, type DbData } from "./db.types.js"; +import { + createEmptyDb, + type DbData, + type Element, + type SentEmail, + type Template, + type TreeNode, +} from "./db.types.js"; import type { TemplateStore } from "./template-store.js"; export class StorageError extends Error { override name = "StorageError"; } -/** Stores everything in a single JSON file (same format as the previous lowdb db.json). */ +/** Stores everything in a single JSON file; older formats are migrated on load (see normalize). */ export class JsonFileStore implements TemplateStore { private queue: Promise = Promise.resolve(); @@ -69,21 +76,56 @@ export class JsonFileStore implements TemplateStore { } } -/** Fills in missing collections so older/partial files still load. */ +/** Name of the template that the single pre-v3 template (`recipeTemplate`) becomes. */ +export const MIGRATED_TEMPLATE_NAME = "Default template"; + +type Json = Record; + +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +const arrayOr = (value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : []); + +/** + * Brings older or partial files to the current shape: + * - the pre-v3 `recipeTemplate: { tree, options }` becomes one template named "Default template" + * (its `options` become the template's `elements`) and the old key is dropped; + * - missing collections are filled in; unknown top-level keys are kept. + */ function normalize(parsed: unknown): DbData { - const empty = createEmptyDb(); - if (typeof parsed !== "object" || parsed === null) return empty; + if (!isObject(parsed)) return createEmptyDb(); + + const { recipeTemplate, ...rest } = parsed; + let templates: unknown = rest.templates; + let legacy: Json = {}; - const rt = (parsed as { recipeTemplate?: unknown }).recipeTemplate; - if (typeof rt !== "object" || rt === null || Array.isArray(rt)) return { ...parsed, ...empty }; + if (!Array.isArray(templates) && isObject(recipeTemplate)) { + const now = new Date().toISOString(); + templates = [ + { + id: randomUUID(), + name: MIGRATED_TEMPLATE_NAME, + tree: recipeTemplate.tree, + elements: recipeTemplate.options, + createdAt: now, + updatedAt: now, + }, + ]; + } else if (recipeTemplate !== undefined) { + // Not migrated (templates already exist): keep it rather than lose data silently. + legacy = { recipeTemplate }; + } - const { tree, options } = rt as Partial; return { - ...(parsed as object), - recipeTemplate: { - ...rt, - tree: Array.isArray(tree) ? tree : [], - options: Array.isArray(options) ? options : [], - }, + ...rest, + ...legacy, + templates: arrayOr(templates) + .filter(isObject) + .map((template) => ({ + ...(template as unknown as Template), + tree: arrayOr(template.tree), + elements: arrayOr(template.elements), + })), + sentEmails: arrayOr(rest.sentEmails), }; } diff --git a/test/app.test.ts b/test/app.test.ts index afb4843..2d0e240 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Express } from "express"; @@ -7,11 +7,13 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { createApp } from "../src/app.js"; import { createLogger } from "../src/common/logger.js"; import { loadConfig } from "../src/config/env.js"; -import type { DbData, TreeNode } from "../src/storage/db.types.js"; +import type { DbData, Template, TreeNode } from "../src/storage/db.types.js"; import { JsonFileStore } from "../src/storage/json-file-store.js"; import type { TemplateStore } from "../src/storage/template-store.js"; const fixturesDir = path.join(import.meta.dirname, "fixtures"); +const SEED_TIME = "2026-01-01T00:00:00.000Z"; +const T1 = "/templates/t1"; let dir: string; let dbFile: string; @@ -37,16 +39,43 @@ async function readDb(): Promise { return JSON.parse(await readFile(dbFile, "utf8")) as DbData; } +type Summary = { id: string; name: string; createdAt: string; updatedAt: string }; + +async function createTemplate(name: string): Promise { + const res = await request(app).post("/templates").send({ name }).expect(201); + return res.body as Summary; +} + +/** Puts t1's updatedAt back to the seed value, to see whether the next call bumps it. */ +async function resetUpdatedAt(): Promise { + const db = await readDb(); + db.templates[0]!.updatedAt = SEED_TIME; + await writeFile(dbFile, JSON.stringify(db)); +} + +async function readTemplate(id = "t1"): Promise