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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions console/public/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,15 @@
"create": {
"action": "Create Campaign",
"title": "New Campaign",
"description": "Select a campaign type you would like to create."
"description": "Select a campaign type you would like to create.",
"setup_failed": "The campaign was created, but its setup didn't finish"
},
"details": {
"title": "Campaign",
"description": "Configure your campaign settings and preview how it will appear to users."
"description": "Configure your campaign settings and preview how it will appear to users.",
"no_templates": "This campaign has no template yet.",
"create_template": "Create template",
"save_failed": "Couldn't save the campaign"
},
"provider": {
"title": "Select Provider",
Expand Down Expand Up @@ -184,12 +188,20 @@
"upload_hint": "Click to browse and select an image"
}
}
}
},
"save_failed": "Couldn't save the template",
"publish_failed": "Couldn't publish the campaign",
"create_failed": "Couldn't create the template"
},
"review": {
"title": "Review",
"description": "Review your campaign before sending."
}
},
"channel_unsupported": "This channel type is not yet supported.",
"duplicate_failed": "Couldn't duplicate the campaign",
"archive_failed": "Couldn't archive the campaign",
"unarchive_failed": "Couldn't unarchive the campaign",
"subscriptions_load_failed": "Couldn't load subscriptions."
},
"channel_list": "Channels",
"channels": {
Expand Down Expand Up @@ -237,7 +249,9 @@
"cancel": "Cancel",
"create": "Create Locale"
}
}
},
"load_failed": "Couldn't load locales.",
"create_failed": "Couldn't add the language"
},
"provider": {
"select": {
Expand Down Expand Up @@ -1180,5 +1194,6 @@
"user_journeys_load_failed": "Couldn't load journeys.",
"user_organizations_load_failed": "Couldn't load organizations.",
"user_subscriptions_load_failed": "Couldn't load subscriptions.",
"users_load_failed": "Couldn't load users."
"users_load_failed": "Couldn't load users.",
"campaigns_load_failed": "Couldn't load campaigns."
}
33 changes: 33 additions & 0 deletions console/src/api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { afterEach, describe, expect, it, vi } from "vitest"
import api, { client } from "./api"

describe("api.campaigns.templates.update", () => {
afterEach(() => vi.restoreAllMocks())

function patchBody() {
return vi.mocked(client.patch).mock.calls[0][1]
}

// The server ignores a null sender; clearing only works with the nil UUID.
it("sends a cleared sender as the nil UUID", async () => {
vi.spyOn(client, "patch").mockResolvedValue({ data: {} })

await api.campaigns.templates.update("p1", "c1", "t1", {
data: { body: "Hi" },
sender_identity_id: null,
})

expect(patchBody()).toEqual({
data: { body: "Hi" },
sender_identity_id: "00000000-0000-0000-0000-000000000000",
})
})

it("leaves the sender out when it isn't changed", async () => {
vi.spyOn(client, "patch").mockResolvedValue({ data: {} })

await api.campaigns.templates.update("p1", "c1", "t1", { data: { body: "Hi" } })

expect(patchBody()).toEqual({ data: { body: "Hi" } })
})
})
9 changes: 7 additions & 2 deletions console/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ import type {
} from "./types"
import type { UUID } from "@/types/common"

// The server reads a null sender_identity_id as "leave it"; the nil UUID clears it.
const NIL_UUID = "00000000-0000-0000-0000-000000000000"

declare module "axios" {
export interface AxiosRequestConfig {
skipAuthRedirect?: boolean
Expand Down Expand Up @@ -470,12 +473,14 @@ const api = {
projectId: UUID,
campaignId: UUID,
templateId: UUID,
params: TemplateUpdateParams,
{ sender_identity_id, ...params }: TemplateUpdateParams,
) =>
await client
.patch<Template>(
`${projectUrl(projectId)}/campaigns/${campaignId}/templates/${templateId}`,
params,
sender_identity_id === undefined
? params
: { ...params, sender_identity_id: sender_identity_id ?? NIL_UUID },
)
.then((r) => r.data),
delete: async (projectId: UUID, campaignId: UUID, templateId: UUID) =>
Expand Down
60 changes: 44 additions & 16 deletions console/src/components/locale/select.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { useContext, useState, useEffect, useMemo } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { LocaleContext, ProjectContext } from "@/contexts"
import { projectLocalesQuery } from "@/hooks/use-project-locales"
import { oapiClient } from "@/oapi/client"
import { ApiError } from "@/oapi/unwrap"
import type { Locale } from "@/types"
import { problemDetail } from "@/utils"

import { Plus, Check, ChevronsUpDown } from "lucide-react"
import { Button } from "@/components/ui/button"
Expand Down Expand Up @@ -32,12 +37,17 @@ import { LocalePicker } from "./picker"
import { resolveLocaleName } from "./locales"

interface LocaleSelectProps {
onChange?: (localeKey: string) => void | Promise<void>
/**
* Switches to the locale. Return false when it didn't switch (e.g. the
* current work couldn't be saved), so the picker keeps showing the current one.
*/
onChange?: (localeKey: string) => boolean | void | Promise<boolean | void>
}

export function LocaleSelect({ onChange }: LocaleSelectProps) {
const { t } = useTranslation()
const [project] = useContext(ProjectContext)
const queryClient = useQueryClient()
const [localeSelection, setLocaleSelection] = useContext(LocaleContext)
const [open, setOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
Expand Down Expand Up @@ -79,12 +89,13 @@ export function LocaleSelect({ onChange }: LocaleSelectProps) {
const selectedLocale = locales.find((locale) => locale.key === value)

if (selectedLocale) {
if (onChange) await onChange(selectedLocale.key)

setLocaleSelection((prev) => ({
...prev,
currentLocale: selectedLocale,
}))
const switched = onChange ? await onChange(selectedLocale.key) : true
if (switched !== false) {
setLocaleSelection((prev) => ({
...prev,
currentLocale: selectedLocale,
}))
}
}

setOpen(false)
Expand All @@ -100,24 +111,41 @@ export function LocaleSelect({ onChange }: LocaleSelectProps) {
setIsCreating(true)
try {
const label = resolveLocaleName(newLocaleKey)
const { data: newLocale } = await oapiClient.POST(
"/api/admin/projects/{projectID}/locales",
{
const response = await oapiClient
.POST("/api/admin/projects/{projectID}/locales", {
params: { path: { projectID: project.id } },
body: { key: newLocaleKey, label },
},
)
if (!newLocale) return
})
.catch((err: unknown) => {
toast.error(
problemDetail(err) ??
t("locale.create_failed", "Couldn't add the language"),
)
})
if (!response) return
const { data: newLocale, error } = response
if (error || !newLocale) {
toast.error(
problemDetail(new ApiError(error)) ??
t("locale.create_failed", "Couldn't add the language"),
)
return
}

setLocaleSelection((prev) => ({
...prev,
currentLocale: newLocale,
allLocales: [...prev.allLocales, newLocale],
}))

setLocales((prev) => [newLocale, ...prev])
// Other locale lists (such as the previews' pickers) include it now too.
void queryClient.invalidateQueries({
queryKey: projectLocalesQuery(project.id).queryKey,
})

if (onChange) await onChange(newLocale.key)
const switched = onChange ? await onChange(newLocale.key) : true
if (switched !== false) {
setLocaleSelection((prev) => ({ ...prev, currentLocale: newLocale }))
}

setNewLocaleKey(undefined)
setIsDialogOpen(false)
Expand Down
13 changes: 7 additions & 6 deletions console/src/oapi/management.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3345,6 +3345,11 @@ export interface components {
subscription_id?: string;
/** @example false */
transactional?: boolean;
/**
* @description Whether to create an empty template in the project's locale along with the campaign. Defaults to true. Set to false when creating the campaign's templates yourself, so the campaign has no blank template next to them.
* @example false
*/
create_default_template?: boolean;
};
UpdateCampaign: {
/** @example epic hopper */
Expand Down Expand Up @@ -6132,9 +6137,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": {
data: components["schemas"]["Campaign"];
};
"application/json": components["schemas"]["Campaign"];
};
};
default: components["responses"]["Error"];
Expand Down Expand Up @@ -6270,9 +6273,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": {
data: components["schemas"]["Template"];
};
"application/json": components["schemas"]["Template"];
};
};
default: components["responses"]["Error"];
Expand Down
13 changes: 8 additions & 5 deletions console/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -817,15 +817,15 @@ export interface EmailTemplateData {
reply_to?: string
subject: string
preheader?: string
editor: "code" | "visual"
type?: "react-email"
editorMode?: "code" | "builder" | "blocks"
code?: {
source: string
bundle?: string
bundle_hash?: string
}
blocks?: Record<string, unknown>
plaintext?: {
generated?: string
custom?: string
}
}
Expand All @@ -837,8 +837,8 @@ export interface TextTemplateData {
export interface PushTemplateData {
title: string
body: string
url: string
custom: Record<string, unknown>
/** Sent to the device alongside the notification. */
data?: Record<string, unknown>
}

export interface InboxTemplateData {
Expand Down Expand Up @@ -886,7 +886,10 @@ export type Template<
)

export type TemplateCreateParams = Pick<Template, "data" | "locale">
export type TemplateUpdateParams = Pick<Template, "data" | "sender_identity_id">
// Leaving sender_identity_id out keeps the template's sender; null clears it
// (api.campaigns.templates.update sends it as the nil UUID, the server's clear marker).
export type TemplateUpdateParams = Pick<Template, "data"> &
Partial<Pick<Template, "sender_identity_id">>
export type VariantUpdateParams = { id?: UUID }

export interface TemplatePreviewParams {
Expand Down
71 changes: 71 additions & 0 deletions console/src/validation/campaign/template/data.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { afterEach, describe, expect, it, vi } from "vitest"
import type { Template } from "@/types"
import {
defaultTemplateData,
knownTemplateData,
unknownTemplateDataKeys,
warnUnknownTemplateData,
} from "./data"

describe("template data", () => {
afterEach(() => {
vi.restoreAllMocks()
})

it("lists keys an older console wrote that the schema no longer knows", () => {
const data = { subject: "Hi", replyTo: "a@b.c", editor: "visual", editorMode: "code" }
expect(unknownTemplateDataKeys("email", data)).toEqual(["replyTo", "editor"])
})

it("keeps only known keys when building a save payload", () => {
const data = { title: "Hi", body: "There", custom: { a: 1 }, url: "https://x" }
expect(knownTemplateData("push", data)).toEqual({ title: "Hi", body: "There" })
})

it("keeps the values of known keys untouched", () => {
const code = { source: "<Html />", bundle: "compiled" }
const data = { subject: "Hi", code, plaintext: { custom: "Hi there" } }
expect(knownTemplateData("email", data)).toEqual(data)
})

it("keeps the body of an email template without React source", () => {
const data = { subject: "Hi", html: "<p>Hello</p>", text: "Hello" }
expect(knownTemplateData("email", data)).toEqual(data)
})

it("starts new templates with only keys the backend reads", () => {
expect(defaultTemplateData("push")).toEqual({ title: "", body: "" })
expect(Object.keys(defaultTemplateData("email"))).toEqual(["from", "subject"])
})

it("warns about a loaded template with unknown keys", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
const template = {
id: "t1",
type: "sms",
data: { body: "Hi", message: "old" },
} as unknown as Template

warnUnknownTemplateData(template)

expect(warn).toHaveBeenCalledWith(expect.stringContaining("message"))
})

it("handles a template whose channel the console doesn't know", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
const template = { id: "t1", type: "fax", data: { page: 1 } } as unknown as Template

expect(() => warnUnknownTemplateData(template)).not.toThrow()
expect(warn).toHaveBeenCalledWith(expect.stringContaining("fax"))
expect(knownTemplateData(template.type, template.data)).toEqual({ page: 1 })
})

it("stays quiet for a template with only known keys", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
const template = { id: "t1", type: "sms", data: { body: "Hi" } } as unknown as Template

warnUnknownTemplateData(template)

expect(warn).not.toHaveBeenCalled()
})
})
Loading
Loading