Skip to content

Enhance campaign management and template handling with error handling - #328

Merged
jeroenrinzema merged 13 commits into
mainfrom
fix/campaing-editor-coupling-and-loading-bugs
Nov 30, 2026
Merged

jeroenrinzema merged 13 commits into
mainfrom
fix/campaing-editor-coupling-and-loading-bugs

Conversation

@IamKirbki

@IamKirbki IamKirbki commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Why

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:

  1. Create an email campaign and set a reply-to. Click Next, reload, and the reply-to should still be there.
  2. Edit the content, go back to the details page, and the change should show without a reload.
  3. 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.

@IamKirbki
IamKirbki marked this pull request as ready for review October 30, 2026 16:36
@jeroenrinzema

Copy link
Copy Markdown
Contributor

@IamKirbki could you please include screenshots in the PR of the component changes?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

4 open issues
1 file not reviewed
  • console/pnpm-lock.yaml: Generated file
What changed in this PR

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.
File Description
internal/​store/​management/​migrations/​1787000000007_rename_email_reply_to.up.sql Migrates email reply-to keys.
internal/​store/​management/​migrations/​1787000000007_rename_email_reply_to.down.sql Restores the legacy reply-to key.
internal/​http/​controllers/​v1/​management/​templates.go Shares compilation logic and makes template creation transactional.
internal/​http/​controllers/​v1/​management/​templates_test.go Tests compilation, rollback and response shape.
internal/​http/​controllers/​v1/​management/​oapi/​resources.yml Corrects response schemas and adds the default-template option.
internal/​http/​controllers/​v1/​management/​oapi/​resources_gen.go Updates generated Go API models.
internal/​http/​controllers/​v1/​management/​campaigns.go Supports skipping default-template creation.
internal/​http/​controllers/​v1/​management/​campaigns_test.go Tests template defaults and campaign response shape.
docker/​postgres/​init-databases.sh Changes initialization-script encoding.
console/​src/​views/​router.tsx Loads campaigns through the shared query cache.
console/​src/​views/​campaign/​template/​UnsupportedChannel.tsx Extracts unsupported-channel messaging.
console/​src/​views/​campaign/​template/​text/​useTextForm.ts Adds the SMS form hook and payload mapping.
console/​src/​views/​campaign/​template/​text/​useSendTestSMS.ts Uses explicit step-save results before test sends.
console/​src/​views/​campaign/​template/​text/​Setup.tsx Uses typed forms and shared locale queries.
console/​src/​views/​campaign/​template/​TemplateProvider.tsx Derives template context from the cached campaign.
console/​src/​views/​campaign/​template/​Template.tsx Simplifies the editor frame and resets state per template.
console/​src/​views/​campaign/​template/​StepLayout.tsx Coordinates saving, navigation and locale switching.
console/​src/​views/​campaign/​template/​Review.tsx Separates publishing from step saves.
console/​src/​views/​campaign/​template/​push/​useSendTestPush.ts Checks save results before test sends.
console/​src/​views/​campaign/​template/​push/​usePushForm.ts Adds the push form hook and payload mapping.
console/​src/​views/​campaign/​template/​push/​Setup.tsx Uses typed forms and shared locale queries.
console/​src/​views/​campaign/​template/​mail/​useEmailForm.ts Adds the email form hook with reply_to mapping.
console/​src/​views/​campaign/​template/​mail/​Setup.tsx Updates email fields and extracts content previews.
console/​src/​views/​campaign/​template/​mail/​editor/​hooks/​useTemplatePersistence.ts Removes ref-based template persistence.
console/​src/​views/​campaign/​template/​mail/​editor/​hooks/​useSendTestEmail.ts Accepts an explicit save callback.
console/​src/​views/​campaign/​template/​mail/​editor/​hooks/​useEmailTemplateSave.ts Saves editor content through shared mutations.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​PreviewToolbar.tsx Extracts preview and test-send controls.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​ModeControls.tsx Extracts editor-mode controls and confirmation.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​hooks/​useEditorMode.ts Types stored editor-mode data.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​enterpriseHosts.tsx Extracts enterprise editor integration.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​editorOptions.ts Extracts Monaco editor options.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​CodeEditor.tsx Integrates step saves and extracted components.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​BuilderCompileCheck.tsx Extracts builder compilation feedback.
console/​src/​views/​campaign/​template/​mail/​editor/​codeEditor/​BlockEditorPane.tsx Extracts the block-editor layout.
console/​src/​views/​campaign/​template/​mail/​ContentPreview.tsx Extracts email previews and displays compilation errors.
console/​src/​views/​campaign/​template/​inbox/​useInboxForm.ts Adds the inbox form hook and payload mapping.
console/​src/​views/​campaign/​template/​inbox/​Setup.tsx Uses typed forms and shared locale queries.
console/​src/​views/​campaign/​template/​contexts.ts Defines save outcomes and shared failure reporting.
console/​src/​views/​campaign/​template/​Content.tsx Gives each channel step its own save operation.
console/​src/​views/​campaign/​template/​channels.ts Types channel configuration and form dispatch.
console/​src/​views/​campaign/​SubscriptionSelect.tsx Extracts subscription selection with retry support.
console/​src/​views/​campaign/​queries.ts Centralizes campaign queries, mutations and cache updates.
console/​src/​views/​campaign/​queries.test.tsx Tests mutation cache updates and failures.
console/​src/​views/​campaign/​NewCampaign.tsx Handles partial creation failures and refreshes lists.
console/​src/​views/​campaign/​NewCampaign.test.tsx Tests creation recovery and subscription retries.
console/​src/​views/​campaign/​ChannelSummary.tsx Extracts channel descriptions and icons.
console/​src/​views/​campaign/​Campaigns.tsx Uses cached list queries and visible action failures.
console/​src/​views/​campaign/​Campaigns.test.tsx Tests list recovery and campaign actions.
console/​src/​views/​campaign/​CampaignRow.tsx Extracts campaign rows and action menus.
console/​src/​views/​campaign/​CampaignEditor.test.tsx Tests preview synchronization, saves and locale switching.
console/​src/​views/​campaign/​CampaignDetails.tsx Uses cached templates and adds empty-template recovery.
console/​src/​views/​campaign/​Campaign.tsx Provides campaign context from the query cache.
console/​src/​views/​campaign/​ApiTipCard.tsx Extracts the API documentation card.
console/​src/​validation/​campaign/​template/​text/​setup.ts Exports SMS form values.
console/​src/​validation/​campaign/​template/​push/​setup.ts Removes the unused custom field and exports form values.
console/​src/​validation/​campaign/​template/​mail/​setup.ts Aligns reply-to naming and sender validation.
console/​src/​validation/​campaign/​template/​inbox/​setup.ts Updates body validation and exports form values.
console/​src/​validation/​campaign/​template/​data.ts Defines channel data filtering, defaults and warnings.
console/​src/​validation/​campaign/​template/​data.test.ts Tests template defaults and key filtering.
console/​src/​utils.ts Extracts details from OpenAPI request errors.
console/​src/​types.ts Updates template data and partial-update types.
console/​src/​oapi/​unwrap.ts Converts returned API failures into thrown errors.
console/​src/​oapi/​unwrap.test.ts Tests response unwrapping and error details.
console/​src/​oapi/​management.generated.ts Updates generated TypeScript API types.
console/​src/​lib/​query.ts Configures shared caching and mutation-error reporting.
console/​src/​hooks/​use-project-locales.ts Shares project locale queries.
console/​src/​components/​locale/​select.tsx Updates selection after successful switches and refreshes locales.
console/​src/​App.tsx Installs the shared query provider.
console/​public/​locales/​en.json Adds failure and recovery messages.
console/​pnpm-lock.yaml Locks the added query dependency.
console/​package.json Adds TanStack Query.

Review effort: Balanced

Comment thread docker/postgres/init-databases.sh Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

1 open issue
3 previously missed issues

In code that hasn't changed since last review

Medium severity Locale creation POST rejections are unhandled

console/​src/​components/​locale/​select.tsx:120

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.

Medium severity 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.

Medium severity 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.

3 resolved since last review
1 file not reviewed
  • console/pnpm-lock.yaml: Generated file

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High severity 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.

1 resolved since last review
1 file not reviewed
  • console/pnpm-lock.yaml: Generated file

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

No open issues 🎉

1 file not reviewed
  • console/pnpm-lock.yaml: Generated file

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

No open issues 🎉

1 file not reviewed
  • console/pnpm-lock.yaml: Generated file

Review effort: Balanced

@jeroenrinzema
jeroenrinzema force-pushed the fix/campaing-editor-coupling-and-loading-bugs branch from b05252b to bfab632 Compare November 30, 2026 11:35
jeroenrinzema
jeroenrinzema previously approved these changes Nov 30, 2026

@jeroenrinzema jeroenrinzema left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot findings addressed; CI green after rebase on main.

IamKirbki and others added 10 commits November 30, 2026 12:45
…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
… results

An older campaign request finishing after a save overwrote the saved template
in the cache, so the details page showed stale content again.
A campaign update never changes templates, and its response could be older
than a template save made while it was in flight.
@jeroenrinzema
jeroenrinzema force-pushed the fix/campaing-editor-coupling-and-loading-bugs branch from bfab632 to 0bfa598 Compare November 30, 2026 11:47

@jeroenrinzema jeroenrinzema left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebased on main (incl. #329); CI green.

@jeroenrinzema
jeroenrinzema merged commit 2366085 into main Nov 30, 2026
7 checks passed
@jeroenrinzema
jeroenrinzema deleted the fix/campaing-editor-coupling-and-loading-bugs branch November 30, 2026 12:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants