You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Enhance campaign management and template handling with error handling - #328
The campaign editor kept the same template in four places that weren't kept in sync:
the campaign context
the template route context
a local copy on the details page
each form's own state
On top of that, its saves went through a callback held in a ref. In practice:
The details page showed old content after editing a template, until you reloaded.
Switching locale on the details page changed the body but kept the old subject and sender.
Pages went blank or spun forever when a request failed. Next or Publish sometimes did nothing, with no message.
The reply-to address was never sent. The form saved it as replyTo; the sender reads reply_to.
Every campaign created in the console probably got two templates in the project's locale, one of them blank: CreateCampaign always added one, and the console then created its own.
API clients such as luno-studio also had to work around some of this when pushing campaigns.
Changes
Campaign editor (console)
One copy of the template.
The campaign, with its templates, is loaded once into the TanStack Query cache (views/campaign/queries.ts). Every page reads from that, and every save writes the server's response back into it.
The separate template request and the local copies are gone.
Each step saves itself.
The ref-based save slot is replaced by StepLayout: each step passes its own save(), which returns { ok: true } or { ok: false, reason: "invalid" | "failed" }.
Next, Publish, the locale switch and Send test all use it.
Send test on the Review step no longer runs the publish request.
Forms are real hooks (useEmailForm and so on), reset per template with key={template.id}. Switching locale updates subject, sender and body together.
Typed template data.
One schema per channel, matching what the backend reads.
Saves only send known keys, so stale keys (replyTo, editor) are dropped.
Unknown keys are logged when a template loads.
channels is fully typed through withChannel() instead of any.
Visible failures:
Failed loads show an error with Retry.
Failed saves show the server's reason and keep you on the step.
A campaign without a template shows "Create template" instead of a blank page.
New campaign:
A failure after the campaign exists opens it instead of offering to create it again, which used to make duplicates.
A failed subscriptions load shows Retry instead of "Loading…" forever.
Campaign list:
Duplicate, archive and unarchive report failures.
A failed list load shows an error with Retry.
Creating or renaming a campaign refreshes the list.
Locale picker: it only switches its label when the switch actually happened. Adding a language reports failures and refreshes the shared locale list.
Size: every file under views/campaign/ is now under 400 lines. CodeEditor.tsx went from 831 to 344, split into components next to it.
API (Go)
Spec matches the server:getCampaign and getTemplate are declared as returning the object directly, which is what the server always sent. The Go and TypeScript code is regenerated with oapi-codegen v2.7.0, the Makefile's version.
Optional default template:CreateCampaign accepts an optional create_default_template: false to skip the blank template. Leaving it out keeps today's behaviour.
Create compiles like update:CreateTemplate compiles template code the same way UpdateTemplate does, through one shared helper, and stores the template with its data in a single transaction. Code that fails to compile creates nothing.
Data
Migration 1787000000007_rename_email_reply_to moves data.replyTo into data.reply_to on email templates and drops the old key. The down migration copies it back.
Saves no longer write plaintext.generated. The backend never read it: it renders plain text at send time.
Push template data uses data (what the sender and the API spec use) instead of custom/url, which were never sent. The UI never exposed them.
Testing
Console:CampaignEditor.test.tsx, Campaigns.test.tsx, NewCampaign.test.tsx, queries.test.tsx, validation/campaign/template/data.test.ts and oapi/unwrap.test.ts. Each bug test fails against the old code. They cover:
a save showing on the details page without a reload
switching locale on the details page
a failed save on Next
a blocked locale switch
failed list actions and loads
creating a campaign without duplicates
Go:TestCreateCampaignDefaultTemplate, TestCreateTemplateCompilesCode, TestGetCampaignMatchesSpec and TestGetTemplateMatchesSpec, plus the full management test package against PostgreSQL.
Manual check:
Create an email campaign and set a reply-to. Click Next, reload, and the reply-to should still be there.
Edit the content, go back to the details page, and the change should show without a reload.
In a campaign with two locales, switch locale on the details page. Subject and body should change together.
Before merging
docker/postgres/init-databases.sh gained a UTF-8 byte-order mark before #!/bin/bash (commit 47ee8e74). That can stop the Postgres container from running the script. Revert that one line.
locale.create_failed clashes with the settings PR, which uses the same key with different text. Rename this branch's key, in components/locale/select.tsx and en.json, to locale.select.create_failed.
Notes
Publish doesn't publish. The Review step sends state: "running", which the backend ignores; campaigns have no state anymore. Behaviour is unchanged, and so is the type error it causes; what Publish should do is a product decision.
For luno-studio: it can drop DecodeCampaign/DecodeTemplate, claimDefaultTemplates, and its create-bare-then-update step.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unresolved defects can delete template bodies, halt fresh PostgreSQL initialization, and panic when sending campaigns without templates, while duplicate-template creation remains unfixed.
Refactors campaign management around shared template data and explicit step saves, improving consistency between editing and previews while making request failures visible.
Changes:
Centralizes campaign, template and locale queries with shared caching and error handling.
Introduces typed channel forms and splits the email editor into smaller components.
Adds optional default-template creation, transactional template compilation, API response corrections and reply-to migration coverage.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Unresolved issues leave sender-clearing documentation inconsistent with API behavior, campaign-load failures without a Retry action, and rejected locale-creation requests without user-visible error feedback.
If the locale-creation POST rejects, such as when the browser is offline, the rejection escapes the click handler without showing a failure message. Catch the rejection, report it through problemDetail and the creation-failure fallback, and stop before processing the response.
JSON null does not clear the sender
console/src/types.ts:889
The new comment promises that null clears the sender, but the update endpoint decodes sender_identity_id into *UUID and only processes non-nil pointers (templates.go:315–328). JSON null therefore leaves the sender unchanged; only the zero UUID reaches the clearing branch. Please either implement the documented null-clearing contract end to end or document the actual zero-UUID contract so callers do not silently retain the previous sender.
Campaign load errors lack a retry action
console/src/views/router.tsx:404
Initial campaign-load failures still have no Retry action: if ensureQueryData rejects, this route renders ErrorPage, whose generic branch only displays the error (console/src/views/ErrorPage.tsx:77–80). This leaves campaign details and the editor without the load recovery promised in the PR. Add a retry action that revalidates the loader, while preserving the existing authorization and not-found handling.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
An in-flight campaign fetch can overwrite mutation results with stale template data, which a later whole-document save may persist.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Cancel in-flight campaign query before updating cached template
console/src/views/campaign/queries.ts:174
If a background campaign GET returns old data after a template mutation updates this cache, it overwrites the saved template and the details page shows stale content again. A later whole-document save can persist those stale fields. Cancel the exact campaign-detail query before installing mutation results in both setTemplate and setCampaign (line 160); see TanStack's default-branch cancellation guidance.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because a delayed campaign-settings response can overwrite newer cached templates, allowing stale content to be saved back to the server.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because a same-template background refetch can refresh the preview body while leaving the subject, sender name, and reply-to stale.
…components
fix(validation): rename replyTo field to reply_to for consistency
chore(migrations): rename email template replyTo key to reply_to for backend compatibility
refactor(mail): optimize locale fetching in email forms and remove redundant API calls
refactor(push): streamline locale handling in push notification setup
refactor(text): enhance locale management in text template setup
- Add `unwrap` function to process API responses, throwing `ApiError` for errors.
- Create `ApiError` class to encapsulate error details from API responses.
- Introduce tests for `unwrap` to ensure correct behavior for success and error cases.
feat: enhance campaign management with React Query
- Refactor campaign-related components to use React Query for data fetching and mutation.
- Implement `useUpdateCampaign`, `useCreateTemplate`, and `useUpdateTemplate` hooks for managing campaign templates.
- Update `CampaignDetails` and `CampaignReview` components to utilize new hooks for state management.
fix: improve error handling in campaign template operations
- Update error handling in template creation and update processes to display user-friendly messages.
- Ensure that the campaign cache is updated correctly after mutations.
refactor: streamline template context management
- Introduce `TemplateProvider` to manage template state and context.
- Simplify template selection logic in the `Template` component.
test: add unit tests for campaign queries
- Create tests for campaign mutation hooks to verify correct cache updates and error handling.
- Mock API responses to simulate various scenarios during testing.
chore: clean up unused imports and improve code organization
- Remove unnecessary imports and consolidate related functionalities for better readability.
- Replaced zod type inference with explicit form value types in Inbox, Email, Push, and Text templates.
- Refactored useInboxForm, useEmailForm, usePushForm, and useTextForm hooks to return specific form types.
- Updated Setup components to use new form value types for better type safety.
- Removed unused imports and cleaned up code for clarity.
- Introduced useEmailTemplateSave hook for managing email template saves.
- Enhanced error handling in send test hooks for better user feedback.
- Removed deprecated template persistence logic.
…, compile checks, and mode controls
- Removed EmailContentPreview component and its related logic from Setup.tsx.
- Introduced BlockEditorPane for managing block editing UI.
- Added BuilderCompileCheck for handling compile checks in the editor.
- Created separate ModeControls and PreviewToolbar components for better organization.
- Consolidated editor options into a dedicated file.
- Updated CodeEditor to utilize new components and streamline functionality.
- Enhanced enterprise support with lazy loading for block editor.
- Keep html/text in the email template schema so saves don't drop the body
- Remove the UTF-8 BOM from the Postgres init script
- Fail sends of a campaign without templates permanently instead of panicking
- Opt out of the server's default template when the console creates a campaign
- Report a rejected locale-creation request instead of leaving it unhandled
- Send a cleared template sender as the nil UUID, which the server clears on
- Offer Retry on the generic route error page, rerunning the route's loaders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
The campaign editor kept the same template in four places that weren't kept in sync:
On top of that, its saves went through a callback held in a ref. In practice:
replyTo; the sender readsreply_to.CreateCampaignalways added one, and the console then created its own.API clients such as luno-studio also had to work around some of this when pushing campaigns.
Changes
Campaign editor (console)
views/campaign/queries.ts). Every page reads from that, and every save writes the server's response back into it.StepLayout: each step passes its ownsave(), which returns{ ok: true }or{ ok: false, reason: "invalid" | "failed" }.useEmailFormand so on), reset per template withkey={template.id}. Switching locale updates subject, sender and body together.replyTo,editor) are dropped.channelsis fully typed throughwithChannel()instead ofany.views/campaign/is now under 400 lines.CodeEditor.tsxwent from 831 to 344, split into components next to it.API (Go)
getCampaignandgetTemplateare declared as returning the object directly, which is what the server always sent. The Go and TypeScript code is regenerated with oapi-codegen v2.7.0, the Makefile's version.CreateCampaignaccepts an optionalcreate_default_template: falseto skip the blank template. Leaving it out keeps today's behaviour.CreateTemplatecompiles template code the same wayUpdateTemplatedoes, through one shared helper, and stores the template with its data in a single transaction. Code that fails to compile creates nothing.Data
1787000000007_rename_email_reply_tomovesdata.replyTointodata.reply_toon email templates and drops the old key. The down migration copies it back.plaintext.generated. The backend never read it: it renders plain text at send time.data(what the sender and the API spec use) instead ofcustom/url, which were never sent. The UI never exposed them.Testing
Console:
CampaignEditor.test.tsx,Campaigns.test.tsx,NewCampaign.test.tsx,queries.test.tsx,validation/campaign/template/data.test.tsandoapi/unwrap.test.ts. Each bug test fails against the old code. They cover:Go:
TestCreateCampaignDefaultTemplate,TestCreateTemplateCompilesCode,TestGetCampaignMatchesSpecandTestGetTemplateMatchesSpec, plus the full management test package against PostgreSQL.Manual check:
Before merging
docker/postgres/init-databases.shgained a UTF-8 byte-order mark before#!/bin/bash(commit47ee8e74). That can stop the Postgres container from running the script. Revert that one line.locale.create_failedclashes with the settings PR, which uses the same key with different text. Rename this branch's key, incomponents/locale/select.tsxanden.json, tolocale.select.create_failed.Notes
state: "running", which the backend ignores; campaigns have no state anymore. Behaviour is unchanged, and so is the type error it causes; what Publish should do is a product decision.DecodeCampaign/DecodeTemplate,claimDefaultTemplates, and its create-bare-then-update step.