Skip to content
Open
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
76 changes: 76 additions & 0 deletions VueApp/src/CMS/__tests__/cms-home.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,79 @@ describe("cmsHome.vue - permission-gated sections", () => {
expect(wrapper.findAllComponents({ name: "QBtn" })).toHaveLength(0)
})
})

/**
* Delegated editors (no ManageContentBlocks) get a "Blocks you can edit" card listing GET /editable
* results, linking each to its editor. It shows only for non-managers with a non-empty list, and it
* suppresses the no-access banner. Managers use the normal Content Blocks card, so they never fetch
* or render this card. These specs run last because they replace the shared get() implementation.
*/
describe("cmsHome.vue - delegated editable blocks card", () => {
const EDITABLE = [
{
contentBlockId: 11,
title: "Alpha",
friendlyName: "alpha",
viperSectionPath: "/a",
page: null,
modifiedOn: "2024-01-01T00:00:00",
modifiedBy: "u",
},
{
contentBlockId: 12,
title: null,
friendlyName: "beta",
viperSectionPath: "/b",
page: null,
modifiedOn: "2024-01-02T00:00:00",
modifiedBy: "u",
},
]

function routeEditable(items: unknown[]) {
getMock.mockImplementation((...args: unknown[]) => {
const url = args[0] as unknown as string
if (url.includes("editable")) {
return Promise.resolve({ success: true, result: items })
}
return Promise.resolve({ success: true, result: [] })
})
}

function editLinks(wrapper: Awaited<ReturnType<typeof mountHome>>) {
return wrapper
.findAllComponents({ name: "QBtn" })
.filter((b) => (b.props("to") as { name?: string } | undefined)?.name === "CmsContentBlockEdit")
}

it("lists editable blocks with edit links and suppresses the no-access banner for a non-manager", async () => {
routeEditable(EDITABLE)
const wrapper = await mountHome(["SVMSecure.CMS"])
await flushPromises()
await flushPromises()

expect(wrapper.text()).toContain("Blocks you can edit")
expect(wrapper.text()).not.toContain("does not have access to any CMS tools")

// Falls back to the friendly name when a block has no title (block 12 -> "beta").
expect(editLinks(wrapper).map((b) => b.props("label"))).toStrictEqual(["Alpha", "beta"])
expect(editLinks(wrapper)[0]!.props("to")).toStrictEqual({
name: "CmsContentBlockEdit",
params: { id: 11 },
})
})

it("does not fetch or show the editable card for a manager", async () => {
// The shared get() mock accumulates calls across tests; clear it so this assertion only
// sees this manager mount's requests.
getMock.mockClear()
routeEditable(EDITABLE)
const wrapper = await mountHome() // full admin
await flushPromises()

expect(wrapper.text()).not.toContain("Blocks you can edit")
// Managers still get the normal tool card, and never hit the editable endpoint.
expect(wrapper.text()).toContain("Content Blocks")
expect(getMock.mock.calls.map((c) => c[0] as unknown as string).some((u) => u.includes("editable"))).toBe(false)
})
})
206 changes: 206 additions & 0 deletions VueApp/src/CMS/__tests__/content-block-edit-delegated.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import ContentBlockEdit from "@/CMS/pages/ContentBlockEdit.vue"
import { useUserStore } from "@/store/UserStore"
import { mountCms, flushPromises, createTestRouter } from "./test-utils"

/**
* Delegated editing: a user WITHOUT ManageContentBlocks/CreateContentBlock who reaches an existing
* block edits only its content and files. The settings sidebar collapses to a read-only summary
* (no inputs, no permission selectors, no public-access toggle), the content editor and attached
* files stay functional, and Save issues the content-only PATCH (with the same lastModifiedOn
* concurrency stamp + 409 conflict dialog as the full save). Mock ViperFetch; the inline uploader
* is stubbed with a controllable commit().
*/

const mockGet = vi.fn<(...args: unknown[]) => unknown>()
const mockPost = vi.fn<(...args: unknown[]) => unknown>()
const mockPut = vi.fn<(...args: unknown[]) => unknown>()
const mockPatch = vi.fn<(...args: unknown[]) => unknown>()
const mockDel = vi.fn<(...args: unknown[]) => unknown>()
vi.mock("@/composables/ViperFetch", () => ({
useFetch: () => ({
get: (...args: unknown[]) => mockGet(...args),
post: (...args: unknown[]) => mockPost(...args),
put: (...args: unknown[]) => mockPut(...args),
patch: (...args: unknown[]) => mockPatch(...args),
del: (...args: unknown[]) => mockDel(...args),
createUrlSearchParams: (obj: Record<string, string | number | null | undefined>) => {
const params = new URLSearchParams()
for (const [k, v] of Object.entries(obj)) {
if (v !== null && v !== undefined) {
params.append(k, v.toString())
}
}
return params
},
}),
}))

const BLOCK = {
contentBlockId: 7,
content: "<p>hello</p>",
title: "Welcome",
system: "Viper",
application: null,
page: "home",
viperSectionPath: "/apps",
blockOrder: 2,
friendlyName: "welcome",
allowPublicAccess: false,
modifiedOn: "2024-03-01T12:00:00",
modifiedBy: "editor",
deletedOn: null,
permissions: ["SVMSecure.CMS"],
editPermissions: ["SVMSecure.CMS.Delegate"],
files: [{ fileGuid: "f1", friendlyName: "a.pdf", url: "/files/a.pdf" }],
}

function routeGet() {
mockGet.mockImplementation((...args: unknown[]) => {
const url = args[0] as string
if (url.includes("/history")) {
return Promise.resolve({ success: true, result: [] })
}
return Promise.resolve({ success: true, result: structuredClone(BLOCK) })
})
}

// QEditor relies on document.execCommand and rich-text DOM that happy-dom lacks; stub it with a
// minimal v-model textarea so block.content still binds without exercising the real editor.
const qEditorStub = {
name: "QEditor",
props: ["modelValue"],
emits: ["update:modelValue"],
methods: {
getContentEl() {
return null
},
},
template: `<textarea :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />`,
}

const mockCommit = vi.fn<() => Promise<{ attached: unknown[]; createdGuids: string[] }>>()
const inlineUploadStub = {
name: "InlineFileUpload",
props: ["folder", "permissions", "allowPublicAccess", "contentBlockId"],
emits: ["staged-count"],
template: "<div class='inline-upload-stub' />",
methods: {
commit() {
return mockCommit()
},
},
}

// mountCms seeds a full CMS admin; drop to a delegated editor (holds a block edit permission but
// none of the CMS management permissions) so the page switches into content-only mode. canManage is
// a reactive computed, so the template re-renders after the permission change.
async function mountDelegated(permissions = ["SVMSecure", "SVMSecure.CMS", "SVMSecure.CMS.Delegate"]) {
const router = createTestRouter()
await router.push({ name: "CmsContentBlockEdit", params: { id: "7" } })
await router.isReady()
const wrapper = mountCms(
ContentBlockEdit,
{ global: { stubs: { QEditor: qEditorStub, InlineFileUpload: inlineUploadStub } } },
router,
)
useUserStore().setPermissions(permissions)
await flushPromises()
await flushPromises()
return { wrapper, router }
}

async function submitForm(wrapper: Awaited<ReturnType<typeof mountDelegated>>["wrapper"]): Promise<void> {
await wrapper.findComponent({ name: "QForm" }).find("form").trigger("submit")
await flushPromises()
await flushPromises()
}

beforeEach(() => {
mockGet.mockReset()
mockPost.mockReset()
mockPut.mockReset()
mockPatch.mockReset()
mockDel.mockReset()
mockCommit.mockReset()
mockCommit.mockResolvedValue({ attached: [], createdGuids: [] })
routeGet()
})

describe("ContentBlockEdit.vue - delegated (content-only) mode", () => {
it("renders a read-only settings summary and hides the manager-only controls", async () => {
const { wrapper } = await mountDelegated()

// No editable Title/Page inputs, no System select, no permission selectors, no public toggle.
const inputLabels = wrapper.findAllComponents({ name: "QInput" }).map((i) => i.props("label"))
expect(inputLabels).not.toContain("Title")
expect(inputLabels).not.toContain("Page")
const selectLabels = wrapper.findAllComponents({ name: "QSelect" }).map((s) => s.props("label"))
expect(selectLabels).not.toContain("System")
expect(selectLabels).not.toContain("Permissions")
expect(selectLabels).not.toContain("Edit access")
expect(wrapper.findComponent({ name: "QToggle" }).exists()).toBeFalsy()

// The identifying fields appear as plain text, and the content editor is still available.
const summary = wrapper.find(".settings-summary")
expect(summary.exists()).toBeTruthy()
expect(summary.text()).toContain("/apps")
expect(summary.text()).toContain("home")
expect(wrapper.text()).toContain("Welcome")
expect(wrapper.find("textarea").exists()).toBeTruthy()
})

it("treats a CreateContentBlock holder as delegated on an EXISTING block", async () => {
// CreateContentBlock owns only the create flow; the update endpoint is manager-only,
// so showing this user the manager editor would end in a 403 on save.
const { wrapper } = await mountDelegated([
"SVMSecure",
"SVMSecure.CMS",
"SVMSecure.CMS.CreateContentBlock",
"SVMSecure.CMS.Delegate",
])
expect(wrapper.find(".settings-summary").exists()).toBeTruthy()
const selectLabels = wrapper.findAllComponents({ name: "QSelect" }).map((s) => s.props("label"))
expect(selectLabels).not.toContain("Permissions")
expect(selectLabels).not.toContain("Edit access")
})

it("keeps the attached-files controls functional for a delegated editor", async () => {
const { wrapper } = await mountDelegated()

// The existing attachment, the attach-by-search select, and the inline uploader all render.
expect(wrapper.text()).toContain("a.pdf")
const attach = wrapper.findAllComponents({ name: "QSelect" }).find((s) => s.props("label") === "Attach a file")
expect(attach).toBeTruthy()
expect(wrapper.findComponent({ name: "InlineFileUpload" }).exists()).toBeTruthy()
})

it("saves via the content PATCH endpoint with content, lastModifiedOn, and the attachment set", async () => {
mockPatch.mockResolvedValue({ success: true, result: { ...BLOCK } })
const { wrapper } = await mountDelegated()

await submitForm(wrapper)

expect(mockPatch).toHaveBeenCalledOnce()
const [url, payload] = mockPatch.mock.calls[0]!
expect(url).toContain("CMS/content/7/content")
expect(payload).toEqual({
content: "<p>hello</p>",
lastModifiedOn: "2024-03-01T12:00:00",
fileGuids: ["f1"],
})
// The full-save verbs are never used in delegated mode.
expect(mockPut).not.toHaveBeenCalled()
expect(mockPost).not.toHaveBeenCalled()
expect(document.body.textContent).toContain("Content block saved")
})

it("opens the edit-conflict dialog when the content PATCH returns a 409", async () => {
mockPatch.mockResolvedValue({ success: false, status: 409, errors: ["Someone else saved this block."] })
const { wrapper } = await mountDelegated()

await submitForm(wrapper)

expect(document.body.textContent).toContain("Edit Conflict")
expect(document.body.textContent).toContain("Someone else saved this block.")
})
})
33 changes: 22 additions & 11 deletions VueApp/src/CMS/__tests__/content-block-edit-save.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ const BLOCK = {
modifiedBy: "editor",
deletedOn: null,
permissions: ["SVMSecure.CMS"],
editPermissions: ["SVMSecure.CMS.Delegate"],
files: [{ fileGuid: "f1", friendlyName: "a.pdf", url: "/files/a.pdf" }],
}

// The payload buildSavePayload derives from BLOCK (files flattened to fileGuids, modifiedOn
// becoming the lastModifiedOn concurrency stamp).
// becoming the lastModifiedOn concurrency stamp, editPermissions carried through).
const EXPECTED_PUT_PAYLOAD = {
contentBlockId: 7,
content: "<p>hello</p>",
Expand All @@ -63,6 +64,7 @@ const EXPECTED_PUT_PAYLOAD = {
friendlyName: "welcome",
allowPublicAccess: false,
permissions: ["SVMSecure.CMS"],
editPermissions: ["SVMSecure.CMS.Delegate"],
fileGuids: ["f1"],
lastModifiedOn: "2024-03-01T12:00:00",
}
Expand Down Expand Up @@ -173,6 +175,14 @@ describe("ContentBlockEdit.vue - save payload", () => {
expect(document.body.textContent).toContain("Content block saved")
})

it("renders the Edit access permission selector for a manager", async () => {
const { wrapper } = await mountEdit()
const editAccess = wrapper
.findAllComponents({ name: "QSelect" })
.find((s) => s.props("label") === "Edit access")
expect(editAccess).toBeTruthy()
})

it("create-mode save POSTs with a null lastModifiedOn and empty friendlyName collapsed to null", async () => {
mockPost.mockResolvedValue({ success: true, result: { ...BLOCK, contentBlockId: 42, files: [] } })
const { wrapper, router } = await mountEdit({ params: {} })
Expand Down Expand Up @@ -245,7 +255,7 @@ describe("ContentBlockEdit.vue - staged upload commit", () => {

// The new upload is soft-deleted and detached again; the pre-existing file stays.
expect(mockDel).toHaveBeenCalledOnce()
expect(mockDel.mock.calls[0]![0]).toContain("cms/files/f2")
expect(mockDel.mock.calls[0]![0]).toContain("CMS/content/7/files/f2")
expect(wrapper.text()).toContain("Friendly name already in use")
expect(wrapper.text()).toContain("a.pdf")
expect(wrapper.text()).not.toContain("b.pdf")
Expand All @@ -262,7 +272,7 @@ describe("ContentBlockEdit.vue - 409 conflict handling", () => {

await submitForm(wrapper)

expect(mockDel.mock.calls[0]![0]).toContain("cms/files/f2")
expect(mockDel.mock.calls[0]![0]).toContain("CMS/content/7/files/f2")
expect(document.body.textContent).toContain("Edit Conflict")
expect(document.body.textContent).toContain("Someone else saved this block.")

Expand All @@ -285,17 +295,17 @@ describe("ContentBlockEdit.vue - 409 conflict handling", () => {
})
})

// Like routeGet, but the file-search endpoint returns a catalog including one already-attached
// file (f1) and one new candidate (f9).
// Like routeGet, but the attachable-files endpoint returns candidates including one already-attached
// file (f1) and one new candidate (f9). The endpoint's slim shape omits the URL.
function routeGetWithFileSearch() {
mockGet.mockImplementation((...args: unknown[]) => {
const url = args[0] as string
if (url.includes("cms/files/")) {
if (url.includes("attachable-files")) {
return Promise.resolve({
success: true,
result: [
{ fileGuid: "f1", friendlyName: "a.pdf", friendlyUrl: "/files/a.pdf" },
{ fileGuid: "f9", friendlyName: "new.pdf", friendlyUrl: "/files/new.pdf" },
{ fileGuid: "f1", friendlyName: "a.pdf" },
{ fileGuid: "f9", friendlyName: "new.pdf" },
],
})
}
Expand All @@ -307,7 +317,7 @@ function routeGetWithFileSearch() {
}

describe("ContentBlockEdit.vue - attached files", () => {
it("searches active files (excluding already-attached ones) and attaches the selection", async () => {
it("searches attachable files (excluding already-attached ones) and attaches the selection", async () => {
routeGetWithFileSearch()
const { wrapper } = await mountEdit()

Expand All @@ -318,9 +328,10 @@ describe("ContentBlockEdit.vue - attached files", () => {
await flushPromises()
await flushPromises()

const fileSearch = mockGet.mock.calls.map((c) => c[0] as string).find((u) => u.includes("cms/files/?"))
// The block-scoped attachable-files endpoint (not the global file catalog) backs the search.
const fileSearch = mockGet.mock.calls.map((c) => c[0] as string).find((u) => u.includes("attachable-files"))
expect(fileSearch).toContain("search=pdf")
expect(fileSearch).toContain("status=active")
expect(fileSearch).toContain("contentBlockId=7")
// The already-attached f1 is excluded from the options.
const options = attachSelect.props("options") as { fileGuid: string }[]
expect(options.map((o) => o.fileGuid)).toEqual(["f9"])
Expand Down
Loading