diff --git a/VueApp/.fallowrc.json b/VueApp/.fallowrc.json index f7d8695b9..efa89f023 100644 --- a/VueApp/.fallowrc.json +++ b/VueApp/.fallowrc.json @@ -7,6 +7,7 @@ "src/ClinicalScheduler/clinicalscheduler.ts", "src/Computing/computing.ts", "src/Effort/effort.ts", + "src/Reports/reports.ts", "src/Students/students.ts", "src/CAHFS/index.html", "src/CMS/index.html", @@ -15,6 +16,7 @@ "src/Computing/index.html", "src/Effort/index.html", "src/Personnel/index.html", + "src/Reports/index.html", "src/Students/index.html" ], "ignorePatterns": [ diff --git a/VueApp/src/Personnel/__tests__/personnel-home.test.ts b/VueApp/src/Personnel/__tests__/personnel-home.test.ts new file mode 100644 index 000000000..478c5acc6 --- /dev/null +++ b/VueApp/src/Personnel/__tests__/personnel-home.test.ts @@ -0,0 +1,14 @@ +import { mount } from "@vue/test-utils" +import Home from "../pages/Home.vue" + +/** The Personnel home page shows its CMS content; Personnel reports are in the Report Builder. */ + +describe("personnel home page", () => { + it("shows the CMS content", () => { + expect.hasAssertions() + + const wrapper = mount(Home, { global: { stubs: { CmsContent: true } } }) + + expect(wrapper.findComponent({ name: "CmsContent" }).props("contentName")).toBe("personnel-home") + }) +}) diff --git a/VueApp/src/Personnel/__tests__/router-permissions.test.ts b/VueApp/src/Personnel/__tests__/router-permissions.test.ts index 648533a1b..33c7c5819 100644 --- a/VueApp/src/Personnel/__tests__/router-permissions.test.ts +++ b/VueApp/src/Personnel/__tests__/router-permissions.test.ts @@ -17,6 +17,10 @@ const { mockRequireLogin } = vi.hoisted(() => ({ vi.mock("@/composables/RequireLogin", () => ({ useRequireLogin: () => ({ requireLogin: (...args: unknown[]) => mockRequireLogin(...args) }), getLoginUrl: () => ({ value: "" }), + createAuthenticator: (permission: string) => async () => { + const loginResult = await mockRequireLogin(true, permission) + return loginResult === null || loginResult + }, })) /** diff --git a/VueApp/src/Personnel/router/index.ts b/VueApp/src/Personnel/router/index.ts index 705e604e8..e431755c1 100644 --- a/VueApp/src/Personnel/router/index.ts +++ b/VueApp/src/Personnel/router/index.ts @@ -1,23 +1,15 @@ import { createSpaRouter } from "@/shared/create-spa-router" import type { NavigationGuard, RouteLocationNormalized } from "vue-router" import { routes } from "./routes" -import { useRequireLogin } from "@/composables/RequireLogin" +import { createAuthenticator } from "@/composables/RequireLogin" import { useUserStore } from "@/store/UserStore" import { checkHasOnePermission } from "@/composables/CheckPagePermission" const router = createSpaRouter(routes) -/** - * Signs the visitor in and loads the SVMSecure.PhoneLists permissions in the same request. - * Those roles are the only permissions anything in this SPA reads, so asking requireLogin for - * them directly leaves no second permission set to fetch or keep in sync. - * A null result means requireLogin reached no verdict, which is not a refusal. - */ -async function authenticate(to: RouteLocationNormalized): Promise { - const { requireLogin } = useRequireLogin(to) - const loginResult = await requireLogin(true, "SVMSecure.PhoneLists") - return loginResult === null || loginResult -} +// Those are the only permissions anything in this SPA reads, so asking requireLogin for them +// directly leaves no second permission set to fetch or keep in sync. +const authenticate = createAuthenticator("SVMSecure.PhoneLists") /** * An in-app navigation (tab switch, list to list) is already signed in and already holds its diff --git a/VueApp/src/Reports/App.vue b/VueApp/src/Reports/App.vue new file mode 100644 index 000000000..2c061bfad --- /dev/null +++ b/VueApp/src/Reports/App.vue @@ -0,0 +1,13 @@ + + + diff --git a/VueApp/src/Reports/__tests__/deferred.ts b/VueApp/src/Reports/__tests__/deferred.ts new file mode 100644 index 000000000..d31e80cf0 --- /dev/null +++ b/VueApp/src/Reports/__tests__/deferred.ts @@ -0,0 +1,11 @@ +/** A promise the test settles by hand, to hold a request in flight. */ +function deferred() { + let settle: ((value: T) => void) | null = null + // eslint-disable-next-line avoid-new -- a promise the test settles by hand + const promise = new Promise((resolve) => { + settle = resolve + }) + return { promise, resolve: (value: T) => settle?.(value) } +} + +export { deferred } diff --git a/VueApp/src/Reports/__tests__/report-admin-edit-form.test.ts b/VueApp/src/Reports/__tests__/report-admin-edit-form.test.ts new file mode 100644 index 000000000..cd7739207 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-edit-form.test.ts @@ -0,0 +1,171 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportAdminEditForm from "../components/ReportAdminEditForm.vue" +import { toForm } from "../admin/report-admin-form" +import { rosterReport, saved } from "./report-admin-fixtures" + +/** + * ReportAdminEditForm only wires its children's v-models and events to its own props, so each + * child is stubbed and its events are emitted directly: the children's own behavior is covered by + * their own tests. + */ +const global = { + plugins: [[Quasar, {}]] as [typeof Quasar, object][], + stubs: { + ReportAdminStatus: true, + ReportAdminBasics: true, + ReportAdminColumns: true, + ReportAdminParameters: true, + ReportAdminDisplay: true, + ReportAdminPermissions: true, + ReportAdminPreview: true, + ReportAdminHistory: true, + }, +} + +function mountForm(overrides: Record = {}) { + return mount(ReportAdminEditForm, { + props: { + modelValue: toForm(rosterReport), + definition: saved, + sources: [], + sourcesFailed: false, + columnsError: null, + sourceColumns: [], + canAddMissing: false, + targets: [], + isView: true, + views: [], + errors: [], + conflict: false, + saving: false, + isDirty: false, + request: rosterReport, + changeSource: vi.fn<() => Promise>(), + addMissingColumns: vi.fn<() => void>(), + save: vi.fn<() => Promise>(), + setDeleted: vi.fn<() => Promise>(), + reload: vi.fn<() => Promise>(), + applyVersion: vi.fn<() => Promise>(), + ...overrides, + }, + global, + }) +} + +function saveButton(wrapper: ReturnType) { + return wrapper.findAllComponents({ name: "QBtn" }).find((button) => button.props("type") === "submit") +} + +describe("report admin edit form", () => { + it("deletes and restores through the status bar", () => { + expect.hasAssertions() + const setDeleted = vi.fn<() => Promise>() + const wrapper = mountForm({ setDeleted }) + + wrapper.findComponent({ name: "ReportAdminStatus" }).vm.$emit("delete") + wrapper.findComponent({ name: "ReportAdminStatus" }).vm.$emit("restore") + + expect(setDeleted.mock.calls).toStrictEqual([[true], [false]]) + }) + + it("replaces the whole form from basics and display", () => { + expect.hasAssertions() + const wrapper = mountForm() + const form = toForm(rosterReport) + + wrapper.findComponent({ name: "ReportAdminBasics" }).vm.$emit("update:modelValue", { ...form, title: "New" }) + wrapper.findComponent({ name: "ReportAdminDisplay" }).vm.$emit("update:modelValue", { ...form, area: "Effort" }) + + const updates = wrapper.emitted("update:modelValue")! + expect(updates.map((update) => update[0])).toStrictEqual([ + { ...form, title: "New" }, + { ...form, area: "Effort" }, + ]) + }) + + // Columns/parameters/permissions each v-model one field of the form rather than the whole + // thing, so a child's update mutates that field on the shared form object in place - it + // doesn't itself emit update:modelValue (ReportAdminEditForm only forwards whole-form + // replacements upward). The mutation still reaches whoever holds the same form reference, + // including the test's own modelValue prop. + it("updates the form's columns, parameters and permissions in place", () => { + expect.hasAssertions() + const wrapper = mountForm() + + wrapper.findComponent({ name: "ReportAdminColumns" }).vm.$emit("update:modelValue", []) + wrapper.findComponent({ name: "ReportAdminParameters" }).vm.$emit("update:modelValue", []) + wrapper.findComponent({ name: "ReportAdminPermissions" }).vm.$emit("update:modelValue", ["SVMSecure.Effort"]) + + const form = wrapper.props("modelValue") as ReturnType + expect([form.columns, form.parameters, form.permissions]).toStrictEqual([[], [], ["SVMSecure.Effort"]]) + expect(wrapper.emitted("update:modelValue")).toBeUndefined() + }) + + it("asks for a new source", () => { + expect.hasAssertions() + const changeSource = vi.fn<() => Promise>() + const wrapper = mountForm({ changeSource }) + + wrapper.findComponent({ name: "ReportAdminBasics" }).vm.$emit("source", "usp_Leave") + + expect(changeSource).toHaveBeenCalledWith("usp_Leave") + }) + + it("adds the source's missing columns", () => { + expect.hasAssertions() + const addMissingColumns = vi.fn<() => void>() + const wrapper = mountForm({ addMissingColumns }) + + wrapper.findComponent({ name: "ReportAdminColumns" }).vm.$emit("add-missing") + + expect(addMissingColumns).toHaveBeenCalledOnce() + }) + + it("applies an earlier version from history", () => { + expect.hasAssertions() + const applyVersion = vi.fn<() => Promise>() + const wrapper = mountForm({ applyVersion }) + + wrapper.findComponent({ name: "ReportAdminHistory" }).vm.$emit("load", rosterReport) + + expect(applyVersion).toHaveBeenCalledWith(rosterReport) + }) + + it("submits the form to save", async () => { + expect.hasAssertions() + const save = vi.fn<() => Promise>() + const wrapper = mountForm({ save }) + + await wrapper.get("form").trigger("submit") + + expect(save).toHaveBeenCalledOnce() + }) + + it("shows the errors, a reload action when they conflict, and unsaved-changes note", async () => { + expect.hasAssertions() + const reload = vi.fn<() => Promise>() + const wrapper = mountForm({ errors: ["Someone else saved it."], conflict: true, isDirty: true, reload }) + + expect(wrapper.text()).toContain("Someone else saved it.") + expect(wrapper.text()).toContain("Unsaved changes") + + await wrapper + .findAll("button") + .find((button) => button.text() === "Reload the saved report") + ?.trigger("click") + + expect(reload).toHaveBeenCalledOnce() + }) + + it("labels and disables the save button for a new, saved or deleted report", () => { + expect.hasAssertions() + const creating = mountForm({ definition: null }) + const deleted = mountForm({ definition: { ...saved, deletedOn: "2026-11-16T10:00:00" } }) + + expect(saveButton(creating)?.props("label")).toBe("Create report") + expect(saveButton(mountForm())?.props("label")).toBe("Save") + expect(saveButton(deleted)?.props("disable")).toBeTruthy() + expect(mountForm({ saving: true }).text()).toContain("Saving") + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-admin-edit.test.ts b/VueApp/src/Reports/__tests__/report-admin-edit.test.ts new file mode 100644 index 000000000..b3b0a70e9 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-edit.test.ts @@ -0,0 +1,162 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import { ref } from "vue" +import ReportAdminEdit from "../pages/ReportAdminEdit.vue" +import { emptyForm, toForm } from "../admin/report-admin-form" +import type { ReportAdminDefinition } from "../admin/report-admin-types" +import { rosterReport, saved } from "./report-admin-fixtures" + +/** + * The edit page only arranges what useReportAdminEdit provides, so the composable is replaced by + * plain refs the tests set directly. + */ + +const { state, calls, route } = vi.hoisted(() => ({ + state: {} as Record, + calls: { id: null as { value: number | null } | null }, + route: { params: {} as Record }, +})) +vi.mock("../admin/use-report-admin-edit", () => ({ + useReportAdminEdit: (id: { value: number | null }) => { + calls.id = id + return state + }, +})) +vi.mock("vue-router", () => ({ useRoute: () => route, onBeforeRouteLeave: vi.fn<() => void>() })) + +function setState(overrides: Record = {}) { + const values = { + form: ref(toForm(rosterReport)), + definition: ref(saved), + sources: ref([]), + source: ref(null), + loading: ref(false), + notFound: ref(false), + sourcesFailed: ref(false), + saving: ref(false), + errors: ref([]), + conflict: ref(false), + isDirty: ref(false), + isView: ref(true), + views: ref([]), + targets: ref([]), + sourceColumns: ref([]), + canAddMissing: ref(false), + changeSource: vi.fn<() => Promise>(), + addMissingColumns: vi.fn<() => void>(), + save: vi.fn<() => Promise>(), + setDeleted: vi.fn<() => Promise>(), + applyVersion: vi.fn<() => Promise>(), + reload: vi.fn<() => Promise>(), + } + Object.assign(state, values, overrides) + return values +} + +function mountPage(id?: string) { + route.params = id === undefined ? {} : { id } + return mount(ReportAdminEdit, { + global: { + plugins: [[Quasar, {}]], + stubs: { + RouterLink: { template: "" }, + ReportAdminPreview: true, + ReportAdminHistory: { name: "ReportAdminHistory", props: ["reportId"], template: "
" }, + ReportAdminPermissions: true, + ReportAdminParameters: true, + ReportAdminColumns: true, + }, + }, + }) +} + +describe("report admin edit page", () => { + it("edits the report named in the address", () => { + expect.hasAssertions() + setState() + + const wrapper = mountPage("4") + + expect(calls.id?.value).toBe(4) + expect(wrapper.get("h1").text()).toContain("Faculty roster") + expect(wrapper.findComponent({ name: "ReportAdminHistory" }).props("reportId")).toBe(4) + }) + + it("starts a new report without an id", () => { + expect.hasAssertions() + setState({ definition: ref(null), form: ref(emptyForm()) }) + + const wrapper = mountPage() + + expect(calls.id?.value).toBeNull() + expect(wrapper.get("h1").text()).toContain("New report") + expect(wrapper.text()).toContain("Create report") + }) + + it("announces that the report is loading, and explains a missing one", () => { + expect.hasAssertions() + setState({ loading: ref(true) }) + const loading = mountPage("4") + setState({ notFound: ref(true) }) + const missing = mountPage("9") + + expect(loading.get("[role='status']").text()).toBe("Loading report") + expect(missing.text()).toContain("There's no report with that number.") + }) + + it("lists the server's messages and offers a reload after a conflicting save", async () => { + expect.hasAssertions() + const { reload } = setState({ errors: ref(["Someone else saved it."]), conflict: ref(true) }) + const wrapper = mountPage("4") + + await wrapper + .findAll("button") + .find((button) => button.text() === "Reload the saved report") + ?.trigger("click") + + expect(wrapper.text()).toContain("Someone else saved it.") + expect(reload).toHaveBeenCalledOnce() + }) + + it("notes unsaved changes", () => { + expect.hasAssertions() + setState({ isDirty: ref(true) }) + + expect(mountPage("4").text()).toContain("Unsaved changes") + }) + + it("can't save a deleted report", () => { + expect.hasAssertions() + setState({ definition: ref({ ...saved, deletedOn: "2026-11-16T10:00:00" }) }) + + const save = mountPage("4") + .findAllComponents({ name: "QBtn" }) + .find((button) => button.props("label") === "Save") + + expect(save?.props("disable")).toBeTruthy() + }) + + it("passes deleting and picking a source on", () => { + expect.hasAssertions() + const { setDeleted, changeSource } = setState() + const wrapper = mountPage("4") + + wrapper.findComponent({ name: "ReportAdminStatus" }).vm.$emit("restore") + wrapper.findComponent({ name: "ReportAdminBasics" }).vm.$emit("source", "usp_Leave") + + expect(setDeleted).toHaveBeenCalledWith(false) + expect(changeSource).toHaveBeenCalledWith("usp_Leave") + }) + + it("updates the form from the basics section", () => { + expect.hasAssertions() + const { form } = setState() + const wrapper = mountPage("4") + + wrapper + .findComponent({ name: "ReportAdminBasics" }) + .vm.$emit("update:modelValue", { ...form.value, title: "Renamed" }) + + expect(form.value.title).toBe("Renamed") + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-admin-fixtures.ts b/VueApp/src/Reports/__tests__/report-admin-fixtures.ts new file mode 100644 index 000000000..35cb887f7 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-fixtures.ts @@ -0,0 +1,63 @@ +import type { ReportAdminDefinition, ReportEditRequest, ReportSourceDetail } from "../admin/report-admin-types" + +/** Shared admin test data: a saved roster report over a view. */ + +const rosterView: ReportSourceDetail = { + name: "FacultyRoster", + kind: "View", + description: "Current faculty", + columns: [ + { name: "Name", sqlType: "varchar", kind: "Text", isSupported: true }, + { name: "Hired", sqlType: "date", kind: "Date", isSupported: true }, + { name: "Photo", sqlType: "varbinary", kind: "Binary", isSupported: false }, + ], + parameters: [], + columnsError: null, + pagesInSql: true, +} + +const rosterReport: ReportEditRequest = { + title: "Faculty roster", + description: null, + area: "Personnel", + source: "FacultyRoster", + paginate: true, + pageSize: null, + allowExcel: true, + allowPdf: false, + pdfLandscape: false, + sensitiveNotice: null, + orderBy: "Name", + orderByDescending: false, + permissions: ["SVMSecure.Personnel"], + columns: [{ sourceColumn: "Name", label: null, format: "Text", sortable: true, visible: true }], + parameters: [ + { + name: "Dept", + label: "Department", + type: "Choice", + operator: "Equals", + required: false, + defaultValue: null, + choicesSource: null, + choicesList: [{ value: "VME", label: "Medicine" }], + binding: "UserInput", + }, + ], + lastModifiedOn: "2026-11-16T09:30:00", +} + +const saved: ReportAdminDefinition = { + id: 4, + slug: "8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e", + createdOn: "2026-11-01T08:00:00", + createdBy: "jdoe", + modifiedOn: "2026-11-16T09:30:00", + modifiedBy: "jdoe", + deletedOn: null, + deletedBy: null, + report: rosterReport, + missingPermissions: [], +} + +export { rosterReport, rosterView, saved } diff --git a/VueApp/src/Reports/__tests__/report-admin-form.test.ts b/VueApp/src/Reports/__tests__/report-admin-form.test.ts new file mode 100644 index 000000000..7a8382180 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-form.test.ts @@ -0,0 +1,154 @@ +import { + emptyForm, + formatChoices, + missingColumns, + newColumn, + newParameter, + operatorsFor, + parameterTargets, + parseChoices, + toForm, + toRequest, + withType, +} from "../admin/report-admin-form" +import { rosterReport, rosterView } from "./report-admin-fixtures" + +describe("choice text", () => { + it("reads one choice per line, with an optional label", () => { + expect.hasAssertions() + + expect(parseChoices("VME | Medicine\n\n PMI \r\nA|B|C")).toStrictEqual([ + { value: "VME", label: "Medicine" }, + { value: "PMI", label: "PMI" }, + { value: "A", label: "B|C" }, + ]) + }) + + it("writes a choice's label only when it differs from its value", () => { + expect.hasAssertions() + + expect( + formatChoices([ + { value: "VME", label: "Medicine" }, + { value: "PMI", label: "PMI" }, + ]), + ).toBe("VME | Medicine\nPMI") + expect(formatChoices(null)).toBe("") + }) +}) + +describe("form and request", () => { + it("round-trips a saved report", () => { + expect.hasAssertions() + + expect(toRequest(toForm(rosterReport))).toStrictEqual(rosterReport) + }) + + it("edits a fixed choice list as text", () => { + expect.hasAssertions() + + const [dept] = toForm(rosterReport).parameters + + expect([dept?.choicesFrom, dept?.choicesText]).toStrictEqual(["list", "VME | Medicine"]) + }) + + it("sends choices only for choice parameters, from the list or the view picked", () => { + expect.hasAssertions() + const form = toForm(rosterReport) + const [dept] = form.parameters + + const fromView = toRequest({ + ...form, + parameters: [{ ...dept!, choicesFrom: "view", choicesSource: "DeptChoices" }], + }) + const asText = toRequest({ ...form, parameters: [{ ...dept!, type: "Text", choicesSource: "DeptChoices" }] }) + + expect([fromView.parameters[0]?.choicesList, fromView.parameters[0]?.choicesSource]).toStrictEqual([ + null, + "DeptChoices", + ]) + expect([asText.parameters[0]?.choicesList, asText.parameters[0]?.choicesSource]).toStrictEqual([null, null]) + }) + + it("picks a choice view for a parameter saved with one", () => { + expect.hasAssertions() + const [dept] = rosterReport.parameters + + const form = toForm({ + ...rosterReport, + parameters: [{ ...dept!, choicesList: null, choicesSource: "DeptChoices" }], + }) + + expect(form.parameters[0]?.choicesFrom).toBe("view") + }) + + it("starts a new report paged, with Excel and no PDF", () => { + expect.hasAssertions() + + expect(emptyForm()).toMatchObject({ + title: "", + source: "", + paginate: true, + allowExcel: true, + allowPdf: false, + columns: [], + }) + }) +}) + +describe("columns", () => { + it("adds the source's showable columns the report lacks, with formats from their types", () => { + expect.hasAssertions() + + const added = missingColumns(rosterView, [newColumn("name")]) + + expect(added.map((column) => [column.sourceColumn, column.format])).toStrictEqual([["Hired", "Date"]]) + }) + + it("gives each new column its own key", () => { + expect.hasAssertions() + + expect(newColumn().key).not.toBe(newColumn().key) + }) +}) + +describe("parameters", () => { + it("starts a view's parameter as an equals filter and a procedure's without one", () => { + expect.hasAssertions() + + expect([newParameter(true).operator, newParameter(false).operator]).toStrictEqual(["Equals", null]) + }) + + it("keeps an operator that suits the new type, or picks the first that does", () => { + expect.hasAssertions() + const from = { ...newParameter(true), type: "Number" as const, operator: "From" as const } + + expect(withType(from, "Date", true).operator).toBe("From") + expect(withType(from, "MultiChoice", true).operator).toBe("In") + expect(withType(from, "Text", false).operator).toBeNull() + }) + + it("offers the operators that suit each type", () => { + expect.hasAssertions() + + expect([operatorsFor("Text"), operatorsFor("MultiChoice")]).toStrictEqual([["Equals", "Contains"], ["In"]]) + }) + + it("binds to a view's showable columns or a procedure's parameters", () => { + expect.hasAssertions() + const procedure = { + ...rosterView, + kind: "Procedure" as const, + parameters: [ + { name: "LoginId", sqlType: "varchar", isSupported: true }, + { name: "Out", sqlType: "int", isSupported: false }, + ], + } + + expect([parameterTargets(rosterView), parameterTargets(procedure), parameterTargets(null)]).toStrictEqual([ + ["Name", "Hired"], + ["LoginId"], + [], + ]) + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-admin-list.test.ts b/VueApp/src/Reports/__tests__/report-admin-list.test.ts new file mode 100644 index 000000000..b6b6401e9 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-list.test.ts @@ -0,0 +1,94 @@ +import { flushPromises, mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportAdminList from "../pages/ReportAdminList.vue" +import { reportAdminService } from "../admin/report-admin-service" +import type { ReportAdminListItem } from "../admin/report-admin-types" +import { deferred } from "./deferred" + +vi.mock("../admin/report-admin-service", () => ({ + reportAdminService: { list: vi.fn<(...args: unknown[]) => unknown>() }, +})) + +const RouterLinkStub = { props: ["to"], template: "" } + +const roster: ReportAdminListItem = { + id: 4, + slug: "8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e", + title: "Faculty roster", + area: "Personnel", + source: "FacultyRoster", + modifiedOn: "2026-11-16T09:30:00", + modifiedBy: "jdoe", + deletedOn: null, + permissions: ["SVMSecure.Personnel", "SVMSecure.Gone"], + missingPermissions: ["SVMSecure.Gone"], +} + +async function mountList(reports: ReportAdminListItem[] | null = [roster]) { + vi.mocked(reportAdminService.list).mockResolvedValue(reports) + const wrapper = mount(ReportAdminList, { + global: { plugins: [[Quasar, {}]], stubs: { RouterLink: RouterLinkStub } }, + }) + await flushPromises() + return wrapper +} + +describe("report admin list", () => { + it("lists the reports with who can view them, flagging permissions RAPS lacks", async () => { + expect.hasAssertions() + + const wrapper = await mountList() + + expect(wrapper.text()).toContain("Faculty roster") + expect(wrapper.text()).toContain("SVMSecure.Gone (not in RAPS)") + expect(wrapper.text()).toContain("11/16/2026 9:30 AM by jdoe") + }) + + it("marks deleted reports and says when a report is for admins only", async () => { + expect.hasAssertions() + + const wrapper = await mountList([ + { ...roster, deletedOn: "2026-11-16T10:00:00", permissions: [], missingPermissions: [] }, + ]) + + expect(wrapper.text()).toContain("Deleted") + expect(wrapper.text()).toContain("Admins only") + }) + + it("shows deleted reports when asked", async () => { + expect.hasAssertions() + const wrapper = await mountList() + + await wrapper.findComponent({ name: "QToggle" }).vm.$emit("update:modelValue", true) + await flushPromises() + + expect(reportAdminService.list).toHaveBeenLastCalledWith(true) + }) + + it("says when the list couldn't be loaded", async () => { + expect.hasAssertions() + + const wrapper = await mountList(null) + + expect(wrapper.text()).toContain("The reports couldn't be loaded.") + }) + + it("ignores a list response that finishes after a newer toggle started", async () => { + expect.hasAssertions() + const slow = deferred() + vi.mocked(reportAdminService.list).mockReturnValueOnce(slow.promise) + const wrapper = mount(ReportAdminList, { + global: { plugins: [[Quasar, {}]], stubs: { RouterLink: RouterLinkStub } }, + }) + await flushPromises() + vi.mocked(reportAdminService.list).mockResolvedValue([roster]) + + await wrapper.findComponent({ name: "QToggle" }).vm.$emit("update:modelValue", true) + await flushPromises() + slow.resolve([{ ...roster, title: "Stale" }]) + await flushPromises() + + expect(wrapper.text()).toContain("Faculty roster") + expect(wrapper.text()).not.toContain("Stale") + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-admin-panels.test.ts b/VueApp/src/Reports/__tests__/report-admin-panels.test.ts new file mode 100644 index 000000000..963ea183e --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-panels.test.ts @@ -0,0 +1,270 @@ +import { flushPromises, mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportAdminPermissions from "../components/ReportAdminPermissions.vue" +import ReportAdminPreview from "../components/ReportAdminPreview.vue" +import ReportAdminHistory from "../components/ReportAdminHistory.vue" +import ReportAdminStatus from "../components/ReportAdminStatus.vue" +import ReportBuilderTable from "@/shared/report-builder/ReportBuilderTable.vue" +import { reportAdminService } from "../admin/report-admin-service" +import { rosterReport, saved } from "./report-admin-fixtures" +import { deferred } from "./deferred" +import type { ReportHistoryVersion } from "../admin/report-admin-types" + +vi.mock("../admin/report-admin-service", () => ({ + reportAdminService: { + searchPermissions: vi.fn<(...args: unknown[]) => unknown>(), + preview: vi.fn<(...args: unknown[]) => unknown>(), + getHistory: vi.fn<(...args: unknown[]) => unknown>(), + getVersion: vi.fn<(...args: unknown[]) => unknown>(), + }, +})) +const { mockConfirm } = vi.hoisted(() => ({ mockConfirm: vi.fn<(...args: unknown[]) => Promise>() })) +vi.mock("@/composables/use-confirm-dialog", () => ({ useConfirmDialog: () => ({ confirmAction: mockConfirm }) })) + +const service = vi.mocked(reportAdminService) +const global = { + plugins: [[Quasar, {}]] as [typeof Quasar, object][], + stubs: { RouterLink: { template: "" } }, +} + +function button(wrapper: ReturnType, text: string) { + return wrapper.findAll("button").find((candidate) => candidate.text().includes(text)) +} + +describe("report permissions section", () => { + it("searches RAPS as the admin types", async () => { + expect.hasAssertions() + service.searchPermissions.mockResolvedValue([{ permission: "SVMSecure.Effort", description: "Effort" }]) + const wrapper = mount(ReportAdminPermissions, { props: { modelValue: [] }, global }) + const select = wrapper.findComponent({ name: "QSelect" }) + + select.vm.$emit("filter", "eff", (update: () => void) => update(), vi.fn<() => void>()) + await flushPromises() + + expect(service.searchPermissions).toHaveBeenCalledWith("eff") + expect(select.props("options")).toStrictEqual([{ permission: "SVMSecure.Effort", description: "Effort" }]) + + select.vm.$emit("update:modelValue", ["SVMSecure.Effort"]) + + expect(wrapper.emitted("update:modelValue")).toStrictEqual([[["SVMSecure.Effort"]]]) + }) + + it("warns about chosen permissions RAPS no longer has", () => { + expect.hasAssertions() + + const one = mount(ReportAdminPermissions, { + props: { modelValue: ["SVMSecure.Gone"], missing: ["SVMSecure.Gone"] }, + global, + }) + const two = mount(ReportAdminPermissions, { props: { modelValue: ["A", "B"], missing: ["A", "B"] }, global }) + const removed = mount(ReportAdminPermissions, { + props: { modelValue: [], missing: ["SVMSecure.Gone"] }, + global, + }) + + expect(one.text()).toContain("RAPS no longer has SVMSecure.Gone, so nobody holds it. Remove it before") + expect(two.text()).toContain("A, B, so nobody holds them. Remove them") + expect(removed.text()).not.toContain("no longer has") + }) + + // QSelect virtualizes its option list, which jsdom's layout never populates, so a mount of the + // real component never renders the #option/#no-option slots. Stub QSelect to render them + // directly instead. + const QSelectStub = { + name: "QSelect", + props: ["options"], + template: ` +
+ + +
+ `, + } + const stubbedGlobal = { ...global, stubs: { ...global.stubs, QSelect: QSelectStub } } + + it("shows each matching permission, with its description when it has one", async () => { + expect.hasAssertions() + service.searchPermissions.mockResolvedValue([ + { permission: "SVMSecure.Effort", description: "Effort access" }, + { permission: "SVMSecure.CTS", description: null }, + ]) + const wrapper = mount(ReportAdminPermissions, { props: { modelValue: [] }, global: stubbedGlobal }) + + wrapper + .findComponent({ name: "QSelect" }) + .vm.$emit("filter", "s", (update: () => void) => update(), vi.fn<() => void>()) + await flushPromises() + + expect(wrapper.text()).toContain("SVMSecure.Effort") + expect(wrapper.text()).toContain("Effort access") + expect(wrapper.text()).toContain("SVMSecure.CTS") + }) + + it("says when nothing matches", () => { + expect.hasAssertions() + + const wrapper = mount(ReportAdminPermissions, { props: { modelValue: [] }, global: stubbedGlobal }) + + expect(wrapper.text()).toContain("No matching RAPS permissions") + }) +}) + +describe("report preview section", () => { + const page = { columns: [], rows: [{ Name: "Ada" }], page: 1, perPage: 50, totalRows: 75, truncated: false } + + it("previews the unsaved report from the first page", async () => { + expect.hasAssertions() + service.preview.mockResolvedValue({ result: page, errors: [] }) + const wrapper = mount(ReportAdminPreview, { props: { report: rosterReport }, global }) + + await button(wrapper, "Preview")?.trigger("click") + await flushPromises() + + expect(service.preview).toHaveBeenCalledWith(rosterReport, expect.objectContaining({ page: 1, perPage: null })) + expect(wrapper.findComponent(ReportBuilderTable).props("pagination")).toMatchObject({ page: 1, rowsNumber: 75 }) + }) + + it("pages and sorts the preview", async () => { + expect.hasAssertions() + service.preview.mockResolvedValue({ result: { ...page, totalRows: null }, errors: [] }) + const wrapper = mount(ReportAdminPreview, { props: { report: rosterReport }, global }) + await button(wrapper, "Preview")?.trigger("click") + await flushPromises() + + wrapper + .findComponent(ReportBuilderTable) + .vm.$emit("request", { page: 2, rowsPerPage: 50, sortBy: "Name", descending: true }) + await flushPromises() + + expect(service.preview).toHaveBeenLastCalledWith( + rosterReport, + expect.objectContaining({ page: 2, sortBy: "Name", sortDescending: true }), + ) + expect(wrapper.findComponent(ReportBuilderTable).props("pagination")).toMatchObject({ page: 2, rowsNumber: 51 }) + }) + + it("lists why the preview couldn't run", async () => { + expect.hasAssertions() + service.preview.mockResolvedValue({ result: null, errors: ["Show at least one column."] }) + const wrapper = mount(ReportAdminPreview, { props: { report: rosterReport }, global }) + + await button(wrapper, "Preview")?.trigger("click") + await flushPromises() + + expect(wrapper.text()).toContain("Show at least one column.") + expect(wrapper.findComponent(ReportBuilderTable).exists()).toBeFalsy() + }) +}) + +describe("report history section", () => { + it("lists the versions and loads one into the form", async () => { + expect.hasAssertions() + service.getHistory.mockResolvedValue([ + { id: 9, action: "Updated", changedOn: "2026-11-16T09:30:00", changedBy: "jdoe" }, + { id: 8, action: null, changedOn: null, changedBy: null }, + ]) + service.getVersion.mockResolvedValue({ + version: { id: 9, action: "Updated", changedOn: null, changedBy: null }, + report: rosterReport, + }) + const wrapper = mount(ReportAdminHistory, { props: { reportId: 4 }, global }) + + await button(wrapper, "Show earlier versions")?.trigger("click") + await flushPromises() + await button(wrapper, "Load into form")?.trigger("click") + await flushPromises() + + expect(wrapper.text()).toContain("11/16/2026 9:30 AM by jdoe") + expect(wrapper.text()).toContain("Saved") + expect(wrapper.emitted("load")).toStrictEqual([[rosterReport]]) + }) + + it("says when the history or a version can't be read", async () => { + expect.hasAssertions() + service.getHistory.mockResolvedValueOnce(null) + const failed = mount(ReportAdminHistory, { props: { reportId: 4 }, global }) + await button(failed, "Show earlier versions")?.trigger("click") + await flushPromises() + service.getHistory.mockResolvedValueOnce([{ id: 9, action: "Created", changedOn: null, changedBy: null }]) + service.getVersion.mockResolvedValue({ + version: { id: 9, action: "Created", changedOn: null, changedBy: null }, + report: null, + }) + const unreadable = mount(ReportAdminHistory, { props: { reportId: 4 }, global }) + await button(unreadable, "Show earlier versions")?.trigger("click") + await flushPromises() + await button(unreadable, "Load into form")?.trigger("click") + await flushPromises() + + expect(failed.text()).toContain("The history couldn't be loaded.") + expect(unreadable.text()).toContain("That version can't be read.") + expect(unreadable.emitted("load")).toBeUndefined() + }) + + it("ignores an older selection's response arriving after a newer one", async () => { + expect.hasAssertions() + service.getHistory.mockResolvedValue([ + { id: 9, action: "Updated", changedOn: null, changedBy: null }, + { id: 8, action: "Created", changedOn: null, changedBy: null }, + ]) + const slow = deferred() + service.getVersion.mockReturnValueOnce(slow.promise) + const wrapper = mount(ReportAdminHistory, { props: { reportId: 4 }, global }) + await button(wrapper, "Show earlier versions")?.trigger("click") + await flushPromises() + const loadButtons = wrapper.findAll("button").filter((candidate) => candidate.text().includes("Load into form")) + + await loadButtons[0]?.trigger("click") + service.getVersion.mockResolvedValue({ + version: { id: 8, action: "Created", changedOn: null, changedBy: null }, + report: { ...rosterReport, title: "Eight" }, + }) + await loadButtons[1]?.trigger("click") + await flushPromises() + slow.resolve({ + version: { id: 9, action: "Updated", changedOn: null, changedBy: null }, + report: { ...rosterReport, title: "Nine" }, + }) + await flushPromises() + + expect(wrapper.emitted("load")).toStrictEqual([[{ ...rosterReport, title: "Eight" }]]) + }) +}) + +describe("report status bar", () => { + it("shows who changed it last and deletes after confirming", async () => { + expect.hasAssertions() + mockConfirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true) + const wrapper = mount(ReportAdminStatus, { props: { definition: saved }, global }) + + await button(wrapper, "Delete")?.trigger("click") + await flushPromises() + await button(wrapper, "Delete")?.trigger("click") + await flushPromises() + + expect(wrapper.text()).toContain("Last changed 11/16/2026 9:30 AM by jdoe") + expect(wrapper.emitted("delete")).toHaveLength(1) + }) + + it("explains and restores a deleted report", async () => { + expect.hasAssertions() + const wrapper = mount(ReportAdminStatus, { + props: { definition: { ...saved, deletedOn: "2026-11-16T10:00:00", deletedBy: "admin", modifiedBy: null } }, + global, + }) + + await button(wrapper, "Restore")?.trigger("click") + + expect(wrapper.text()).toContain("This report was deleted by admin") + expect(wrapper.text()).toContain("Last changed 11/16/2026 9:30 AM") + expect(wrapper.emitted("restore")).toHaveLength(1) + }) + + it("shows nothing for a report that isn't saved yet", () => { + expect.hasAssertions() + + expect(mount(ReportAdminStatus, { props: { definition: null }, global }).text()).toBe("") + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts b/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts new file mode 100644 index 000000000..e8dd63b47 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts @@ -0,0 +1,213 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportAdminParameters from "../components/ReportAdminParameters.vue" +import ReportAdminParameterFields from "../components/ReportAdminParameterFields.vue" +import ReportAdminChoices from "../components/ReportAdminChoices.vue" +import { newParameter } from "../admin/report-admin-form" +import type { FormParameter } from "../admin/report-admin-form" + +const global = { plugins: [[Quasar, {}]] as [typeof Quasar, object][] } + +type Emitter = { emitted: (name: string) => unknown[][] | undefined } + +function lastEmitted(wrapper: Emitter): unknown { + return wrapper.emitted("update:modelValue")?.at(-1)?.[0] +} + +function lastParameter(wrapper: Emitter): FormParameter { + return lastEmitted(wrapper) as FormParameter +} + +function lastParameters(wrapper: Emitter): FormParameter[] { + return lastEmitted(wrapper) as FormParameter[] +} + +function parameter(change: Partial = {}): FormParameter { + return { ...newParameter(true), name: "Dept", ...change } +} + +function mountFields(model: FormParameter, isView = true) { + return mount(ReportAdminParameterFields, { + props: { modelValue: model, targets: ["Dept", "Hired"], isView, views: ["DeptChoices"] }, + global, + }) +} + +function select(wrapper: ReturnType, label: string) { + return wrapper + .findAllComponents({ name: "QSelect" }) + .find((field) => String(field.props("label")).startsWith(label)) +} + +function mountChoices(model: FormParameter) { + return mount(ReportAdminChoices, { props: { modelValue: model, views: ["DeptChoices"] }, global }) +} + +function mountParameters(parameters: FormParameter[], isView = true) { + return mount(ReportAdminParameters, { + props: { modelValue: parameters, targets: ["Dept"], isView, views: [] }, + global, + }) +} + +describe("report parameter fields", () => { + it("offers the operators that suit the type, for a view", () => { + expect.hasAssertions() + + const options = select(mountFields(parameter({ type: "Number", operator: "From" })), "Match")?.props( + "options", + ) as { + value: string + }[] + + expect(options.map((option) => option.value)).toStrictEqual(["Equals", "From", "To"]) + }) + + it("has no operator for a procedure, and names the field for it", () => { + expect.hasAssertions() + const wrapper = mountFields(parameter({ operator: null }), false) + + expect(select(wrapper, "Match")).toBeUndefined() + expect(select(wrapper, "Procedure parameter")).toBeDefined() + }) + + it("changes the type, fixing the operator to suit it", () => { + expect.hasAssertions() + const wrapper = mountFields(parameter()) + + select(wrapper, "Type")?.vm.$emit("update:modelValue", "MultiChoice") + + expect([lastParameter(wrapper).type, lastParameter(wrapper).operator]).toStrictEqual(["MultiChoice", "In"]) + }) + + it("updates the name, label, binding, operator, default and required flag", () => { + expect.hasAssertions() + const wrapper = mountFields(parameter()) + + select(wrapper, "Column to filter")?.vm.$emit("update:modelValue", null) + expect(lastParameter(wrapper).name).toBe("") + wrapper.findAllComponents({ name: "QInput" })[0]?.vm.$emit("update:modelValue", " ") + expect(lastParameter(wrapper).label).toBeNull() + select(wrapper, "Match")?.vm.$emit("update:modelValue", "Contains") + expect(lastParameter(wrapper).operator).toBe("Contains") + wrapper.findAllComponents({ name: "QInput" })[1]?.vm.$emit("update:modelValue", "VME") + expect(lastParameter(wrapper).defaultValue).toBe("VME") + wrapper.findComponent({ name: "QCheckbox" }).vm.$emit("update:modelValue", true) + expect(lastParameter(wrapper).required).toBeTruthy() + }) + + it("explains a parameter filled from the signed-in user, without type or choices", () => { + expect.hasAssertions() + const wrapper = mountFields(parameter({ binding: "CurrentUserLoginId" })) + + select(wrapper, "Value comes from")?.vm.$emit("update:modelValue", "UserInput") + + expect(wrapper.text()).toContain("Filled in from the signed-in user") + expect(select(wrapper, "Type")).toBeUndefined() + expect(lastParameter(wrapper).binding).toBe("UserInput") + }) + + it("shows the choices for choice parameters only", () => { + expect.hasAssertions() + + expect( + mountFields(parameter({ type: "Choice" })) + .findComponent(ReportAdminChoices) + .exists(), + ).toBeTruthy() + expect(mountFields(parameter()).findComponent(ReportAdminChoices).exists()).toBeFalsy() + }) + + it("passes a change to the choices on", () => { + expect.hasAssertions() + const wrapper = mountFields(parameter({ type: "Choice" })) + + wrapper + .findComponent(ReportAdminChoices) + .vm.$emit("update:modelValue", parameter({ type: "Choice", choicesText: "VME" })) + + expect(lastParameter(wrapper).choicesText).toBe("VME") + }) +}) + +describe("report choices", () => { + it("edits a fixed list as text", () => { + expect.hasAssertions() + const wrapper = mountChoices(parameter({ type: "Choice" })) + + wrapper.findComponent({ name: "QInput" }).vm.$emit("update:modelValue", null) + + expect(lastParameter(wrapper).choicesText).toBe("") + }) + + it("switches to a view and picks it", async () => { + expect.hasAssertions() + const wrapper = mountChoices(parameter({ type: "Choice" })) + + wrapper.findComponent({ name: "QOptionGroup" }).vm.$emit("update:modelValue", "view") + await wrapper.setProps({ modelValue: lastParameter(wrapper) }) + wrapper.findComponent({ name: "QSelect" }).vm.$emit("update:modelValue", "DeptChoices") + + expect([lastParameter(wrapper).choicesFrom, lastParameter(wrapper).choicesSource]).toStrictEqual([ + "view", + "DeptChoices", + ]) + }) +}) + +describe("report parameters section", () => { + it("explains what parameters do for a view and a procedure", () => { + expect.hasAssertions() + + expect(mountParameters([]).text()).toContain("Filters the user fills in") + expect(mountParameters([], false).text()).toContain("Values passed to the procedure.") + }) + + it("adds, changes and removes parameters", async () => { + expect.hasAssertions() + const first = parameter() + const second = parameter({ name: "Unit" }) + const adding = mountParameters([first]) + const changing = mountParameters([first, second]) + const removing = mountParameters([first]) + + await adding + .findAll("button") + .find((button) => button.text().includes("Add parameter")) + ?.trigger("click") + changing + .findAllComponents(ReportAdminParameterFields)[0] + ?.vm.$emit("update:modelValue", { ...first, label: "Department" }) + await removing.get(`[aria-label="Remove Dept"]`).trigger("click") + + expect(lastParameters(adding)).toHaveLength(2) + expect(lastParameters(changing)).toStrictEqual([{ ...first, label: "Department" }, second]) + expect(lastParameters(removing)).toStrictEqual([]) + }) + + it("reorders parameters", () => { + expect.hasAssertions() + const first = parameter() + const second = parameter({ name: "Unit" }) + const wrapper = mountParameters([first, second]) + + wrapper.findComponent({ name: "SortableList" }).vm.$emit("update:modelValue", [second, first]) + + expect(lastParameters(wrapper)).toStrictEqual([second, first]) + }) + + it("announces a moved parameter by name", () => { + expect.hasAssertions() + + const { announce } = mountParameters([parameter()]) + .findComponent({ name: "SortableList" }) + .props() as unknown as { + announce: (item: FormParameter, index: number, total: number) => string + } + + expect([announce(parameter(), 0, 2), announce(parameter({ name: "" }), 1, 2)]).toStrictEqual([ + "Dept moved to position 1 of 2", + "Parameter moved to position 2 of 2", + ]) + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-admin-sections.test.ts b/VueApp/src/Reports/__tests__/report-admin-sections.test.ts new file mode 100644 index 000000000..4039c2820 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-sections.test.ts @@ -0,0 +1,285 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportAdminBasics from "../components/ReportAdminBasics.vue" +import ReportAdminColumns from "../components/ReportAdminColumns.vue" +import ReportAdminDisplay from "../components/ReportAdminDisplay.vue" +import { newColumn, toForm } from "../admin/report-admin-form" +import type { FormColumn, ReportAdminForm } from "../admin/report-admin-form" +import { rosterReport } from "./report-admin-fixtures" + +const global = { plugins: [[Quasar, {}]] as [typeof Quasar, object][] } + +type Emitter = { emitted: (name: string) => unknown[][] | undefined } + +function lastEmitted(wrapper: Emitter): unknown { + return wrapper.emitted("update:modelValue")?.at(-1)?.[0] +} + +function lastForm(wrapper: Emitter): ReportAdminForm { + return lastEmitted(wrapper) as ReportAdminForm +} + +function lastColumns(wrapper: Emitter): FormColumn[] { + return lastEmitted(wrapper) as FormColumn[] +} + +function mountBasics(props: Record = {}) { + return mount(ReportAdminBasics, { + props: { + modelValue: toForm(rosterReport), + sources: [ + { name: "FacultyRoster", kind: "View", description: "Current faculty" }, + { name: "usp_Leave", kind: "Procedure", description: null }, + ], + ...props, + }, + global, + }) +} + +function mountColumns(columns: FormColumn[], sourceColumns = ["Name", "Hired"], canAddMissing = false) { + return mount(ReportAdminColumns, { props: { modelValue: columns, sourceColumns, canAddMissing }, global }) +} + +function mountDisplay(form: Partial = {}, sourceColumns = ["Name", "Hired"]) { + return mount(ReportAdminDisplay, { + props: { modelValue: { ...toForm(rosterReport), ...form }, sourceColumns }, + global, + }) +} + +describe("report basics section", () => { + it("offers each source with its kind and description", () => { + expect.hasAssertions() + + const select = mountBasics().findAllComponents({ name: "QSelect" }).at(-1) + + expect(select?.props("options")).toStrictEqual([ + { value: "FacultyRoster", label: "FacultyRoster", caption: "View: Current faculty" }, + { value: "usp_Leave", label: "usp_Leave", caption: "Procedure" }, + ]) + }) + + it("updates the title, area and description, keeping blanks as empty", async () => { + expect.hasAssertions() + const wrapper = mountBasics() + const [title, area, description] = wrapper.findAllComponents({ name: "QInput" }) + + title?.vm.$emit("update:modelValue", "Roster") + await wrapper.setProps({ modelValue: lastForm(wrapper) }) + area?.vm.$emit("update:modelValue", " ") + await wrapper.setProps({ modelValue: lastForm(wrapper) }) + description?.vm.$emit("update:modelValue", "A roster of faculty.") + + expect([lastForm(wrapper).title, lastForm(wrapper).area, lastForm(wrapper).description]).toStrictEqual([ + "Roster", + null, + "A roster of faculty.", + ]) + }) + + it("asks for a new source rather than changing it itself", () => { + expect.hasAssertions() + const wrapper = mountBasics() + + wrapper.findAllComponents({ name: "QSelect" }).at(-1)?.vm.$emit("update:modelValue", null) + + expect(wrapper.emitted("source")).toStrictEqual([[""]]) + }) + + it("explains a missing source list and a procedure SQL Server can't describe", () => { + expect.hasAssertions() + + const text = mountBasics({ sourcesFailed: true, columnsError: "Uses a temp table." }).text() + + expect(text).toContain("The list of data sources couldn't be loaded.") + expect(text).toContain("SQL Server can't describe this procedure's columns (Uses a temp table.)") + }) + + // QSelect virtualizes its option list, which jsdom's layout never populates, so a mount of + // the real component never renders the #option slot. Stub QSelect to render it directly. + it("shows each source's kind and description in the option list", () => { + expect.hasAssertions() + const QSelectStub = { + name: "QSelect", + props: ["options"], + template: ` + + `, + } + + const wrapper = mount(ReportAdminBasics, { + props: { + modelValue: toForm(rosterReport), + sources: [ + { name: "FacultyRoster", kind: "View", description: "Current faculty" }, + { name: "usp_Leave", kind: "Procedure", description: null }, + ], + }, + global: { ...global, stubs: { QSelect: QSelectStub } }, + }) + + expect(wrapper.text()).toContain("FacultyRoster") + expect(wrapper.text()).toContain("View: Current faculty") + expect(wrapper.text()).toContain("usp_Leave") + expect(wrapper.text()).toContain("Procedure") + }) +}) + +describe("report columns section", () => { + it("edits a column's heading, format and flags, leaving the others alone", async () => { + expect.hasAssertions() + const column = newColumn("Name") + const other = newColumn("Hired") + const wrapper = mountColumns([column, other]) + + wrapper.findComponent({ name: "QInput" }).vm.$emit("update:modelValue", "Full name") + await wrapper.setProps({ modelValue: lastColumns(wrapper) }) + wrapper.findComponent({ name: "QInput" }).vm.$emit("update:modelValue", " ") + await wrapper.setProps({ modelValue: lastColumns(wrapper) }) + wrapper.findAllComponents({ name: "QCheckbox" })[0]?.vm.$emit("update:modelValue", false) + await wrapper.setProps({ modelValue: lastColumns(wrapper) }) + wrapper.findAllComponents({ name: "QCheckbox" })[1]?.vm.$emit("update:modelValue", false) + + expect(lastColumns(wrapper)).toStrictEqual([{ ...column, label: null, visible: false, sortable: false }, other]) + }) + + it("changes the source column and format", () => { + expect.hasAssertions() + const column = newColumn("Name") + const wrapper = mountColumns([column]) + const [name, format] = wrapper.findAllComponents({ name: "QSelect" }) + + name?.vm.$emit("update:modelValue", null) + format?.vm.$emit("update:modelValue", "Date") + + expect(lastColumns(wrapper)[0]?.format).toBe("Date") + expect(wrapper.emitted("update:modelValue")?.[0]?.[0]).toStrictEqual([{ ...column, sourceColumn: "" }]) + }) + + it("lets the admin type column names a procedure can't describe", () => { + expect.hasAssertions() + + const select = mountColumns([newColumn()], []).findComponent({ name: "QSelect" }) + + expect([select.props("useInput"), select.props("newValueMode")]).toStrictEqual([true, "add-unique"]) + }) + + it("adds and removes columns", async () => { + expect.hasAssertions() + const column = newColumn("Name") + const adding = mountColumns([column]) + const removing = mountColumns([column]) + + await adding + .findAll("button") + .find((button) => button.text().includes("Add column")) + ?.trigger("click") + await removing.get(`[aria-label="Remove Name"]`).trigger("click") + + expect(lastColumns(adding)).toHaveLength(2) + expect(lastColumns(removing)).toStrictEqual([]) + }) + + it("reorders columns", () => { + expect.hasAssertions() + const first = newColumn("Name") + const second = newColumn("Hired") + const wrapper = mountColumns([first, second]) + + wrapper.findComponent({ name: "SortableList" }).vm.$emit("update:modelValue", [second, first]) + + expect(lastColumns(wrapper)).toStrictEqual([second, first]) + }) + + it("offers the source's other columns when there are some", async () => { + expect.hasAssertions() + const wrapper = mountColumns([], ["Name"], true) + + await wrapper + .findAll("button") + .find((button) => button.text().includes("other columns")) + ?.trigger("click") + + expect(wrapper.emitted("addMissing")).toHaveLength(1) + expect(wrapper.text()).toContain("No columns yet.") + }) + + it("announces a moved column by name", () => { + expect.hasAssertions() + + const { announce } = mountColumns([newColumn("Name")]) + .findComponent({ name: "SortableList" }) + .props() as unknown as { + announce: (column: FormColumn, index: number, total: number) => string + } + + expect([announce(newColumn("Name"), 1, 3), announce(newColumn(), 0, 1)]).toStrictEqual([ + "Name moved to position 2 of 3", + "Column moved to position 1 of 1", + ]) + }) +}) + +describe("report display section", () => { + it("sorts by the source's columns, or the report's when the source can't be described", () => { + expect.hasAssertions() + + const known = mountDisplay().findComponent({ name: "QSelect" }).props("options") + const unknown = mountDisplay({}, []).findComponent({ name: "QSelect" }).props("options") + + expect([known, unknown]).toStrictEqual([["Name", "Hired"], ["Name"]]) + }) + + it("keeps the page size as a number, or empty for the default", () => { + expect.hasAssertions() + const wrapper = mountDisplay() + const pageSize = wrapper.findComponent({ name: "QInput" }) + + pageSize.vm.$emit("update:modelValue", "50") + const fifty = lastForm(wrapper).pageSize + pageSize.vm.$emit("update:modelValue", "") + + expect([fifty, lastForm(wrapper).pageSize]).toStrictEqual([50, null]) + }) + + it("updates the sort, downloads and notice", () => { + expect.hasAssertions() + const wrapper = mountDisplay() + + wrapper.findComponent({ name: "QSelect" }).vm.$emit("update:modelValue", null) + const sort = lastForm(wrapper).orderBy + wrapper.findAllComponents({ name: "QCheckbox" })[0]?.vm.$emit("update:modelValue", false) + const excel = lastForm(wrapper).allowExcel + wrapper.findAllComponents({ name: "QCheckbox" })[1]?.vm.$emit("update:modelValue", true) + const pdf = lastForm(wrapper).allowPdf + wrapper.findAllComponents({ name: "QCheckbox" })[2]?.vm.$emit("update:modelValue", true) + const landscape = lastForm(wrapper).pdfLandscape + wrapper.findAllComponents({ name: "QInput" }).at(-1)?.vm.$emit("update:modelValue", " ") + const blanked = lastForm(wrapper).sensitiveNotice + wrapper.findAllComponents({ name: "QInput" }).at(-1)?.vm.$emit("update:modelValue", "Confidential data") + + expect([sort, excel, pdf, landscape, blanked, lastForm(wrapper).sensitiveNotice]).toStrictEqual([ + null, + false, + true, + true, + null, + "Confidential data", + ]) + }) + + it("turns paging and descending sort on and off", () => { + expect.hasAssertions() + const wrapper = mountDisplay() + const [paginate, descending] = wrapper.findAllComponents({ name: "QToggle" }) + + paginate?.vm.$emit("update:modelValue", false) + const paged = lastForm(wrapper).paginate + descending?.vm.$emit("update:modelValue", true) + + expect([paged, lastForm(wrapper).orderByDescending]).toStrictEqual([false, true]) + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-admin-service.test.ts b/VueApp/src/Reports/__tests__/report-admin-service.test.ts new file mode 100644 index 000000000..93b1bae9e --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-service.test.ts @@ -0,0 +1,190 @@ +import { reportAdminService } from "../admin/report-admin-service" +import { rosterReport, rosterView, saved } from "./report-admin-fixtures" + +const { mockGet, mockPost, mockPut, mockDel } = vi.hoisted(() => ({ + mockGet: vi.fn<(...args: unknown[]) => unknown>(), + mockPost: vi.fn<(...args: unknown[]) => unknown>(), + mockPut: vi.fn<(...args: unknown[]) => unknown>(), + 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), + del: (...args: unknown[]) => mockDel(...args), + }), +})) + +const run = { parameters: {}, page: 1, perPage: null, sortBy: null, sortDescending: false, search: null } + +describe("admin reads", () => { + it.each([ + { name: "sources", read: () => reportAdminService.getSources(), url: /admin\/sources$/u, result: [rosterView] }, + { + name: "one source", + read: () => reportAdminService.getSource("Faculty Roster"), + url: /admin\/sources\/Faculty%20Roster$/u, + result: rosterView, + }, + { + name: "the list", + read: () => reportAdminService.list(true), + url: /definitions\?includeDeleted=true$/u, + result: [], + }, + { name: "a report", read: () => reportAdminService.get(4), url: /definitions\/4$/u, result: saved }, + { + name: "the history", + read: () => reportAdminService.getHistory(4), + url: /definitions\/4\/history$/u, + result: [], + }, + { + name: "a version", + read: () => reportAdminService.getVersion(4, 9), + url: /definitions\/4\/history\/9$/u, + result: { version: { id: 9 } }, + }, + { + name: "the failed runs", + read: () => reportAdminService.getFailures(7), + url: /admin\/failures\?days=7$/u, + result: [], + }, + { + name: "the check", + read: () => reportAdminService.check(), + url: /admin\/check$/u, + result: { checked: 0, failing: [] }, + }, + ])("gets $name", async ({ read, url, result }) => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result }) + + await expect(read()).resolves.toStrictEqual(result) + expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(url)) + }) + + it.each([ + () => reportAdminService.getSources(), + () => reportAdminService.getSource("x"), + () => reportAdminService.list(false), + () => reportAdminService.get(4), + () => reportAdminService.getHistory(4), + () => reportAdminService.getVersion(4, 9), + () => reportAdminService.getFailures(30), + () => reportAdminService.check(), + ])("returns null when a read fails (%#)", async (read) => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: false, result: null }) + + await expect(read()).resolves.toBeNull() + }) + + it("searches RAPS permissions, finding none when the request fails", async () => { + expect.hasAssertions() + mockGet.mockResolvedValueOnce({ + success: true, + result: [{ permission: "SVMSecure.Effort", description: null }], + }) + mockGet.mockResolvedValueOnce({ success: false, result: null }) + + await expect(reportAdminService.searchPermissions("a&b")).resolves.toHaveLength(1) + await expect(reportAdminService.searchPermissions("x")).resolves.toStrictEqual([]) + expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/permissions\?search=a%26b$/u)) + }) +}) + +describe("admin saves", () => { + it("creates a new report and saves over an existing one", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: true, result: saved }) + mockPut.mockResolvedValue({ success: true, result: saved }) + + await expect(reportAdminService.save(null, rosterReport)).resolves.toStrictEqual({ + definition: saved, + errors: [], + conflict: false, + }) + await reportAdminService.save(4, rosterReport) + + expect(mockPost).toHaveBeenCalledWith(expect.stringMatching(/admin\/definitions$/u), rosterReport) + expect(mockPut).toHaveBeenCalledWith(expect.stringMatching(/definitions\/4$/u), rosterReport) + }) + + it("returns the server's messages and whether someone else saved first", async () => { + expect.hasAssertions() + mockPut.mockResolvedValue({ success: false, result: null, errors: ["Someone else saved it."], status: 409 }) + + await expect(reportAdminService.save(4, rosterReport)).resolves.toStrictEqual({ + definition: null, + errors: ["Someone else saved it."], + conflict: true, + }) + }) + + it("explains a failure that came without messages", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: false, result: null, errors: null, status: null }) + + const outcome = await reportAdminService.save(null, rosterReport) + + expect([outcome.errors, outcome.conflict]).toStrictEqual([ + ["The report couldn't be saved. Please try again later."], + false, + ]) + }) + + it("explains a successful request that came back with no report", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: true, result: null, errors: null, status: null }) + + const outcome = await reportAdminService.save(null, rosterReport) + + expect([outcome.definition, outcome.errors]).toStrictEqual([ + null, + ["The report couldn't be saved. Please try again later."], + ]) + }) + + it("deletes and restores", async () => { + expect.hasAssertions() + mockDel.mockResolvedValue({ success: true, result: saved }) + mockPost.mockResolvedValue({ success: false, result: null }) + + await expect(reportAdminService.remove(4)).resolves.toStrictEqual(saved) + await expect(reportAdminService.restore(4)).resolves.toBeNull() + expect(mockPost).toHaveBeenCalledWith(expect.stringMatching(/definitions\/4\/restore$/u)) + }) + + it("returns null when a delete or a restore fails", async () => { + expect.hasAssertions() + mockDel.mockResolvedValue({ success: false, result: null }) + mockPost.mockResolvedValue({ success: true, result: saved }) + + await expect(reportAdminService.remove(4)).resolves.toBeNull() + await expect(reportAdminService.restore(4)).resolves.toStrictEqual(saved) + }) +}) + +describe("admin preview", () => { + it("posts the unsaved report with the page to show", async () => { + expect.hasAssertions() + const result = { columns: [], rows: [], page: 1, perPage: 50, totalRows: 0, truncated: false } + mockPost.mockResolvedValue({ success: true, result }) + + await expect(reportAdminService.preview(rosterReport, run)).resolves.toStrictEqual({ result, errors: [] }) + expect(mockPost).toHaveBeenCalledWith(expect.stringMatching(/admin\/preview$/u), { report: rosterReport, run }) + }) + + it("returns the server's messages", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: false, result: null, errors: ["Show at least one column.", 3] }) + + await expect(reportAdminService.preview(rosterReport, run)).resolves.toStrictEqual({ + result: null, + errors: ["Show at least one column."], + }) + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-page.test.ts b/VueApp/src/Reports/__tests__/report-page.test.ts new file mode 100644 index 000000000..283e9173b --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-page.test.ts @@ -0,0 +1,54 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import { defineComponent } from "vue" +import ReportPage from "../pages/ReportPage.vue" +import BreadcrumbHeading from "@/components/BreadcrumbHeading.vue" + +vi.mock("vue-router", () => ({ useRoute: () => ({ params: { slug: "8a6f1d2e" } }) })) + +/** Stands in for ReportViewer, giving the heading slot the title a loaded report would. */ +function viewerStub(title: string | null) { + return defineComponent({ + name: "ReportViewer", + props: { slug: { type: String, required: true }, syncQuery: Boolean }, + setup: () => ({ title }), + template: `
`, + }) +} + +function mountPage(title: string | null) { + return mount(ReportPage, { + global: { + plugins: [[Quasar, {}]], + stubs: { ReportViewer: viewerStub(title), RouterLink: { template: "" } }, + }, + }) +} + +describe("report page", () => { + it("shows the report named in the URL, with its values in the URL", () => { + expect.hasAssertions() + + const viewer = mountPage("Faculty roster").findComponent({ name: "ReportViewer" }) + + expect([viewer.props("slug"), viewer.props("syncQuery")]).toStrictEqual(["8a6f1d2e", true]) + }) + + it("heads the page with the report's title, under Reports", () => { + expect.hasAssertions() + + const heading = mountPage("Faculty roster").findComponent(BreadcrumbHeading) + + expect(heading.props()).toStrictEqual({ + label: "Faculty roster", + parentLabel: "Reports", + parentTo: { name: "ReportsHome" }, + }) + }) + + it("says a report that isn't available isn't", () => { + expect.hasAssertions() + + expect(mountPage(null).findComponent(BreadcrumbHeading).props("label")).toBe("Report not available") + }) +}) diff --git a/VueApp/src/Reports/__tests__/report-problems.test.ts b/VueApp/src/Reports/__tests__/report-problems.test.ts new file mode 100644 index 000000000..ea56ea40c --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-problems.test.ts @@ -0,0 +1,189 @@ +import { flushPromises, mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportAdminProblems from "../pages/ReportAdminProblems.vue" +import ReportFailedRuns from "../components/ReportFailedRuns.vue" +import ReportProblemsCheck from "../components/ReportProblemsCheck.vue" +import { reportAdminService } from "../admin/report-admin-service" +import type { ReportCheckResult, ReportFailure } from "../admin/report-admin-types" +import { deferred } from "./deferred" + +vi.mock("../admin/report-admin-service", () => ({ + reportAdminService: { + getFailures: vi.fn<(...args: unknown[]) => unknown>(), + check: vi.fn<(...args: unknown[]) => unknown>(), + }, +})) + +const RouterLinkStub = { props: ["to"], template: "" } +const global = { plugins: [[Quasar, {}]] as never, stubs: { RouterLink: RouterLinkStub } } + +const denied: ReportFailure = { + id: 11, + reportId: 4, + reportTitle: "Faculty roster", + reportDeleted: false, + action: "ExportExcel", + loginId: "jdoe", + ranOn: "2026-11-17T09:30:00", + parameters: '{"Dept":"VME"}', + errorNumber: 229, + errorMessage: "The SELECT permission was denied on the object 'FacultyRoster'.", +} + +const sourceGone: ReportFailure = { + ...denied, + id: 10, + reportId: 7, + reportTitle: "Leave balances", + reportDeleted: true, + action: "Run", + parameters: null, + errorNumber: null, + errorMessage: "This report's data source is no longer available.", +} + +async function mountFailedRuns(failures: ReportFailure[] | null = [denied, sourceGone]) { + vi.mocked(reportAdminService.getFailures).mockResolvedValue(failures) + const wrapper = mount(ReportFailedRuns, { global }) + await flushPromises() + return wrapper +} + +async function runCheck(result: ReportCheckResult | null) { + vi.mocked(reportAdminService.check).mockResolvedValue(result) + const wrapper = mount(ReportProblemsCheck, { global }) + await wrapper.findComponent({ name: "QBtn" }).trigger("click") + await flushPromises() + return wrapper +} + +describe("report failed runs", () => { + it("lists the last 30 days of failures with SQL Server's reason", async () => { + expect.hasAssertions() + + const wrapper = await mountFailedRuns() + + expect(reportAdminService.getFailures).toHaveBeenLastCalledWith(30) + expect(wrapper.text()).toContain("2 failed runs across 2 reports.") + expect(wrapper.text()).toContain( + "SQL error 229: The SELECT permission was denied on the object 'FacultyRoster'.", + ) + expect(wrapper.text()).toContain("This report's data source is no longer available.") + }) + + it("shows how each failed report was run and whether it's since been deleted", async () => { + expect.hasAssertions() + + const wrapper = await mountFailedRuns() + + expect(wrapper.text()).toContain('Values: {"Dept":"VME"}') + expect(wrapper.text()).toContain("Excel") + expect(wrapper.text()).toContain("Deleted") + }) + + it("narrows the list to one report", async () => { + expect.hasAssertions() + const wrapper = await mountFailedRuns() + + await wrapper.findAllComponents({ name: "QSelect" })[1]?.vm.$emit("update:modelValue", 7) + + expect(wrapper.text()).toContain("Leave balances") + expect(wrapper.text()).not.toContain("SQL error 229") + }) + + it("reloads for another period and forgets a report that no longer failed in it", async () => { + expect.hasAssertions() + const wrapper = await mountFailedRuns() + await wrapper.findAllComponents({ name: "QSelect" })[1]?.vm.$emit("update:modelValue", 7) + vi.mocked(reportAdminService.getFailures).mockResolvedValue([denied]) + + await wrapper.findAllComponents({ name: "QSelect" })[0]?.vm.$emit("update:modelValue", 7) + await flushPromises() + + expect(reportAdminService.getFailures).toHaveBeenLastCalledWith(7) + expect(wrapper.text()).toContain("1 failed run across 1 report.") + expect(wrapper.text()).toContain("SQL error 229") + }) + + it("ignores a list for a period that was changed again before it arrived", async () => { + expect.hasAssertions() + const wrapper = await mountFailedRuns([]) + const slow = deferred() + vi.mocked(reportAdminService.getFailures).mockReturnValueOnce(slow.promise).mockResolvedValueOnce([sourceGone]) + const [periods] = wrapper.findAllComponents({ name: "QSelect" }) + + await periods?.vm.$emit("update:modelValue", 7) + await periods?.vm.$emit("update:modelValue", 90) + await flushPromises() + slow.resolve([denied]) + await flushPromises() + + expect(wrapper.text()).toContain("Leave balances") + expect(wrapper.text()).not.toContain("SQL error 229") + }) + + it("says when nothing failed, and when the list couldn't be loaded", async () => { + expect.hasAssertions() + + const empty = await mountFailedRuns([]) + const broken = await mountFailedRuns(null) + + expect(empty.text()).toContain("No failed runs in this period.") + expect(broken.text()).toContain("The failed runs couldn't be loaded.") + }) +}) + +describe("report problems check", () => { + it("lists each failing report with its problems", async () => { + expect.hasAssertions() + + const wrapper = await runCheck({ + checked: 12, + checkedOn: "2026-11-17T09:30:00", + failing: [ + { + id: 7, + title: "Leave balances", + area: "Personnel", + source: "Dropped", + problems: ["RAPS has no permission named 'SVMSecure.Retired'."], + }, + ], + }) + + expect(wrapper.text()).toContain("1 of 12 reports have problems (checked 11/17/2026 9:30 AM).") + expect(wrapper.text()).toContain("Personnel · Dropped") + expect(wrapper.text()).toContain("RAPS has no permission named 'SVMSecure.Retired'.") + }) + + it("says when every report passed", async () => { + expect.hasAssertions() + + const wrapper = await runCheck({ checked: 12, checkedOn: "2026-11-17T09:30:00", failing: [] }) + + expect(wrapper.text()).toContain("All 12 reports passed (checked 11/17/2026 9:30 AM).") + }) + + it("says when the check couldn't be run", async () => { + expect.hasAssertions() + + const wrapper = await runCheck(null) + + expect(wrapper.text()).toContain("The reports couldn't be checked.") + }) +}) + +describe("report problems page", () => { + it("shows the check and the failed runs, but doesn't check until asked", async () => { + expect.hasAssertions() + vi.mocked(reportAdminService.getFailures).mockResolvedValue([]) + vi.mocked(reportAdminService.check).mockClear() + + const wrapper = mount(ReportAdminProblems, { global }) + await flushPromises() + + expect(wrapper.text()).toContain("Check every report") + expect(wrapper.text()).toContain("Failed runs") + expect(reportAdminService.check).not.toHaveBeenCalled() + }) +}) diff --git a/VueApp/src/Reports/__tests__/reports-home.test.ts b/VueApp/src/Reports/__tests__/reports-home.test.ts new file mode 100644 index 000000000..c4300f1c6 --- /dev/null +++ b/VueApp/src/Reports/__tests__/reports-home.test.ts @@ -0,0 +1,79 @@ +import { flushPromises, mount } from "@vue/test-utils" +import { createPinia, setActivePinia } from "pinia" +import { Quasar } from "quasar" +import ReportsHome from "../pages/ReportsHome.vue" +import { reportBuilderService } from "@/shared/report-builder/report-builder-service" +import { useUserStore } from "@/store/UserStore" + +vi.mock("@/shared/report-builder/report-builder-service", () => ({ + reportBuilderService: { getCatalog: vi.fn<(...args: unknown[]) => unknown>() }, +})) + +async function mountHome() { + setActivePinia(createPinia()) + const wrapper = mount(ReportsHome, { global: { plugins: [[Quasar, {}]] } }) + await flushPromises() + return wrapper +} + +describe("reports home page", () => { + it("announces that the list is loading", () => { + expect.hasAssertions() + // eslint-disable-next-line avoid-new -- a request that never settles holds the page in its loading state + vi.mocked(reportBuilderService.getCatalog).mockReturnValue(new Promise(vi.fn<() => void>())) + setActivePinia(createPinia()) + + const wrapper = mount(ReportsHome, { global: { plugins: [[Quasar, {}]] } }) + + expect(wrapper.get("[role='status']").text()).toBe("Loading reports") + }) + + it("lists the reports by area, linking to each", async () => { + expect.hasAssertions() + vi.mocked(reportBuilderService.getCatalog).mockResolvedValue([ + { slug: "a", title: "Roster", description: "Current faculty.", area: "Personnel" }, + { slug: "b", title: "Courses", description: null, area: "Effort" }, + ]) + + const wrapper = await mountHome() + + expect(wrapper.findAll("h2").map((heading) => heading.text())).toStrictEqual(["Effort", "Personnel"]) + expect(wrapper.text()).toContain("Current faculty.") + expect(wrapper.findComponent({ name: "QItem" }).props("to")).toStrictEqual({ + name: "Report", + params: { slug: "b" }, + }) + }) + + it("says when the user has no reports", async () => { + expect.hasAssertions() + vi.mocked(reportBuilderService.getCatalog).mockResolvedValue([]) + + const wrapper = await mountHome() + + expect(wrapper.text()).toContain("There are no reports for you to view yet.") + }) + + it("says when the list couldn't be loaded", async () => { + expect.hasAssertions() + vi.mocked(reportBuilderService.getCatalog).mockResolvedValue(null) + + const wrapper = await mountHome() + + expect(wrapper.text()).toContain("The report list couldn't be loaded.") + }) + + it("links admins to managing reports", async () => { + expect.hasAssertions() + vi.mocked(reportBuilderService.getCatalog).mockResolvedValue([]) + const visitor = await mountHome() + setActivePinia(createPinia()) + useUserStore().setPermissions(["SVMSecure.Reports.Admin"]) + + const admin = mount(ReportsHome, { global: { plugins: [[Quasar, {}]] } }) + await flushPromises() + + expect(visitor.text()).not.toContain("Manage reports") + expect(admin.text()).toContain("Manage reports") + }) +}) diff --git a/VueApp/src/Reports/__tests__/router.test.ts b/VueApp/src/Reports/__tests__/router.test.ts new file mode 100644 index 000000000..b3e3655b4 --- /dev/null +++ b/VueApp/src/Reports/__tests__/router.test.ts @@ -0,0 +1,118 @@ +import { createPinia, setActivePinia } from "pinia" +import type { Router } from "vue-router" +import { useUserStore } from "@/store/UserStore" +import { createGuardedStubRouter } from "@/shared/__tests__/guarded-stub-router" +import { reportsGuard } from "../router" +import { routes } from "../router/routes" + +const { mockRequireLogin } = vi.hoisted(() => ({ + mockRequireLogin: vi.fn<(...args: unknown[]) => unknown>(), +})) +vi.mock("@/composables/RequireLogin", () => ({ + useRequireLogin: () => ({ requireLogin: (...args: unknown[]) => mockRequireLogin(...args) }), + getLoginUrl: () => ({ value: "" }), + createAuthenticator: (permission: string) => async () => { + const loginResult = await mockRequireLogin(true, permission) + return loginResult === null || loginResult + }, +})) + +function signIn() { + useUserStore().loadUser({ + firstName: "Test", + lastName: "Caller", + mailId: "caller", + loginId: "caller", + mothraId: "caller01", + userId: 1, + token: "", + emulating: false, + permissions: [], + }) +} + +function routerFor(loginResult: boolean | null): Router { + setActivePinia(createPinia()) + mockRequireLogin.mockResolvedValue(loginResult) + return createGuardedStubRouter(routes, reportsGuard) +} + +describe("reports routes", () => { + it("signs the visitor in with the Report Builder's permissions", async () => { + expect.hasAssertions() + const router = routerFor(true) + + await router.push("/Reports/8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e") + + expect(mockRequireLogin).toHaveBeenCalledExactlyOnceWith(true, "SVMSecure.Reports") + expect(router.currentRoute.value.name).toBe("Report") + }) + + it("opens the list of reports", async () => { + expect.hasAssertions() + const router = routerFor(null) + + await router.push("/Reports/") + + expect(router.currentRoute.value.name).toBe("ReportsHome") + }) + + it.each([ + "/Reports/Other", + "/Reports/Admin/x", + "/Reports/8a6f1d2e", + "/Reports/8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e-x", + ])("sends a path that isn't a report's slug to the 404 page (%s)", async (path) => { + expect.hasAssertions() + const router = routerFor(true) + + await router.push(path) + + expect(router.currentRoute.value.matched[0]?.path).toBe("/:catchAll(.*)*") + }) + + it.each([ + { path: "/Reports/Admin/4", name: "ReportAdminEdit" }, + { path: "/Reports/Admin/Problems", name: "ReportAdminProblems" }, + ])("lets admins into $path", async ({ path, name }) => { + expect.hasAssertions() + const router = routerFor(true) + useUserStore().setPermissions(["SVMSecure.Reports.Admin"]) + + await router.push(path) + + expect(router.currentRoute.value.name).toBe(name) + }) + + it.each(["/Reports/Admin", "/Reports/Admin/New", "/Reports/Admin/4", "/Reports/Admin/Problems"])( + "sends others from %s to the list of reports", + async (path) => { + expect.hasAssertions() + const router = routerFor(true) + + await router.push(path) + + expect(router.currentRoute.value.name).toBe("ReportsHome") + }, + ) + + it("stays put when sign-in is refused", async () => { + expect.hasAssertions() + const router = routerFor(false) + + await router.push("/Reports/") + + expect(router.currentRoute.value.matched).toHaveLength(0) + }) + + it("doesn't sign in again when moving within the app", async () => { + expect.hasAssertions() + const router = routerFor(true) + await router.push("/Reports/") + signIn() + + await router.push("/Reports/8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e") + + expect(mockRequireLogin).toHaveBeenCalledOnce() + }) +}) diff --git a/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts b/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts new file mode 100644 index 000000000..57e5d7bcb --- /dev/null +++ b/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts @@ -0,0 +1,307 @@ +import { flushPromises } from "@vue/test-utils" +import { ref } from "vue" +import { useReportAdminEdit } from "../admin/use-report-admin-edit" +import { reportAdminService } from "../admin/report-admin-service" +import type { ReportAdminDefinition } from "../admin/report-admin-types" +import { rosterReport, rosterView, saved } from "./report-admin-fixtures" +import { deferred } from "./deferred" + +const { mockReplace } = vi.hoisted(() => ({ mockReplace: vi.fn<(...args: unknown[]) => Promise>() })) +vi.mock("vue-router", () => ({ useRouter: () => ({ replace: mockReplace }) })) +vi.mock("quasar", () => ({ useQuasar: () => ({ dialog: vi.fn<() => void>() }) })) +vi.mock("../admin/report-admin-service", () => ({ + reportAdminService: { + getSources: vi.fn<(...args: unknown[]) => unknown>(), + getSource: vi.fn<(...args: unknown[]) => unknown>(), + get: vi.fn<(...args: unknown[]) => unknown>(), + save: vi.fn<(...args: unknown[]) => unknown>(), + remove: vi.fn<(...args: unknown[]) => unknown>(), + restore: vi.fn<(...args: unknown[]) => unknown>(), + }, +})) + +const service = vi.mocked(reportAdminService) +const sources = [ + { name: "FacultyRoster", kind: "View" as const, description: null }, + { name: "usp_Leave", kind: "Procedure" as const, description: null }, +] + +function reset(): void { + mockReplace.mockResolvedValue() + service.getSources.mockResolvedValue(sources) + service.getSource.mockResolvedValue(rosterView) + service.get.mockResolvedValue(saved) + service.save.mockResolvedValue({ definition: saved, errors: [], conflict: false }) +} + +async function edit(id: number | null = 4) { + reset() + const state = useReportAdminEdit(id) + await flushPromises() + return state +} + +describe("report edit state - loading", () => { + it("loads the report, the sources and its source's shape", async () => { + expect.hasAssertions() + + const state = await edit() + + expect([state.loading.value, state.form.value.title, state.definition.value?.id]).toStrictEqual([ + false, + "Faculty roster", + 4, + ]) + expect([state.views.value, state.targets.value, state.sourceColumns.value]).toStrictEqual([ + ["FacultyRoster"], + ["Name", "Hired"], + ["Name", "Hired"], + ]) + expect([state.isView.value, state.canAddMissing.value, state.isDirty.value]).toStrictEqual([true, true, false]) + }) + + it("starts a new report empty", async () => { + expect.hasAssertions() + + const state = await edit(null) + + expect([state.form.value.title, state.definition.value, state.source.value]).toStrictEqual(["", null, null]) + expect(state.sourceColumns.value).toStrictEqual([]) + expect(service.get).not.toHaveBeenCalled() + }) + + it("marks a report that doesn't exist", async () => { + expect.hasAssertions() + reset() + service.get.mockResolvedValue(null) + + const state = useReportAdminEdit(9) + await flushPromises() + + expect(state.notFound.value).toBeTruthy() + }) + + it("says when the sources couldn't be loaded", async () => { + expect.hasAssertions() + reset() + service.getSources.mockResolvedValue(null) + + const state = useReportAdminEdit(4) + await flushPromises() + + expect([state.sourcesFailed.value, state.sources.value]).toStrictEqual([true, []]) + }) + + it("ignores a load that finishes after a newer one started", async () => { + expect.hasAssertions() + reset() + const slow = deferred() + service.get.mockReturnValueOnce(slow.promise) + const id = ref(4) + + const state = useReportAdminEdit(id) + id.value = 5 + await flushPromises() + slow.resolve({ ...saved, report: { ...rosterReport, title: "Stale" } }) + await flushPromises() + + expect(state.form.value.title).toBe("Faculty roster") + }) + + it("ignores a source description that arrives after a newer load", async () => { + expect.hasAssertions() + reset() + const slow = deferred() + service.getSource.mockReturnValueOnce(slow.promise) + const id = ref(4) + + const state = useReportAdminEdit(id) + await flushPromises() + id.value = null + await flushPromises() + slow.resolve(rosterView) + await flushPromises() + + expect([state.form.value.title, state.source.value]).toStrictEqual(["", null]) + }) +}) + +describe("report edit state - editing", () => { + it("fills an empty report with the chosen source's columns", async () => { + expect.hasAssertions() + const state = await edit(null) + + await state.changeSource("FacultyRoster") + + expect(state.form.value.columns.map((column) => column.sourceColumn)).toStrictEqual(["Name", "Hired"]) + expect(state.isDirty.value).toBeTruthy() + }) + + it("keeps a report's columns when its source changes", async () => { + expect.hasAssertions() + const state = await edit() + + await state.changeSource("FacultyRoster") + + expect(state.form.value.columns).toHaveLength(1) + }) + + it("clears the source's shape when no source is picked", async () => { + expect.hasAssertions() + const state = await edit() + + await state.changeSource("") + + expect(state.source.value).toBeNull() + }) + + it("adds the source's other columns", async () => { + expect.hasAssertions() + const state = await edit() + + state.addMissingColumns() + + expect(state.form.value.columns.map((column) => column.sourceColumn)).toStrictEqual(["Name", "Hired"]) + }) + + it("adds nothing without a source", async () => { + expect.hasAssertions() + const state = await edit(null) + + state.addMissingColumns() + + expect(state.form.value.columns).toStrictEqual([]) + }) + + it("puts an earlier version in the form, keeping the version being edited", async () => { + expect.hasAssertions() + const state = await edit() + + await state.applyVersion({ ...rosterReport, title: "Old title", lastModifiedOn: "2026-01-01T00:00:00" }) + + expect([state.form.value.title, state.form.value.lastModifiedOn]).toStrictEqual([ + "Old title", + rosterReport.lastModifiedOn, + ]) + }) +}) + +describe("report edit state - saving", () => { + it("saves over the report and marks the form clean", async () => { + expect.hasAssertions() + const state = await edit() + state.form.value = { ...state.form.value, title: "Renamed" } + + await state.save() + + expect(service.save).toHaveBeenCalledWith(4, expect.objectContaining({ title: "Renamed" })) + expect([state.isDirty.value, state.saving.value]).toStrictEqual([false, false]) + expect(mockReplace).not.toHaveBeenCalled() + }) + + it("moves a new report to its own address once saved", async () => { + expect.hasAssertions() + const state = await edit(null) + + await state.save() + + expect(service.save).toHaveBeenCalledWith(null, expect.anything()) + expect(mockReplace).toHaveBeenCalledWith({ name: "ReportAdminEdit", params: { id: "4" } }) + }) + + it("shows the server's messages and whether someone else saved first", async () => { + expect.hasAssertions() + const state = await edit() + service.save.mockResolvedValue({ definition: null, errors: ["Someone else saved it."], conflict: true }) + + await state.save() + + expect([state.errors.value, state.conflict.value]).toStrictEqual([["Someone else saved it."], true]) + }) + + it("reloads the saved report", async () => { + expect.hasAssertions() + const state = await edit() + state.form.value = { ...state.form.value, title: "Mine" } + + await state.reload() + + expect([state.form.value.title, service.get.mock.calls.length]).toStrictEqual(["Faculty roster", 2]) + }) + + it("reloads a never-saved report as empty again", async () => { + expect.hasAssertions() + const state = await edit(null) + state.form.value = { ...state.form.value, title: "Mine" } + + await state.reload() + + expect(state.form.value.title).toBe("") + expect(service.get).not.toHaveBeenCalled() + }) +}) + +describe("report edit state - deleting", () => { + const deleted = { + ...saved, + deletedOn: "2026-11-16T10:00:00", + report: { ...rosterReport, lastModifiedOn: "2026-11-16T10:00:00" }, + } + + it("deletes and takes the new version's time, staying clean", async () => { + expect.hasAssertions() + const state = await edit() + service.remove.mockResolvedValue(deleted) + + await state.setDeleted(true) + + expect([state.definition.value?.deletedOn, state.form.value.lastModifiedOn]).toStrictEqual([ + deleted.deletedOn, + deleted.deletedOn, + ]) + expect(state.isDirty.value).toBeFalsy() + }) + + it("keeps unsaved edits when restoring, and the form's own version with them", async () => { + expect.hasAssertions() + const state = await edit() + const originalVersion = state.form.value.lastModifiedOn + service.restore.mockResolvedValue({ + ...saved, + modifiedOn: "2026-11-16T11:00:00", + report: { ...rosterReport, lastModifiedOn: "2026-11-16T11:00:00" }, + }) + state.form.value = { ...state.form.value, title: "Mine" } + + await state.setDeleted(false) + + // The version stays the one the form was last loaded with, not restore's newer one, so a + // save of "Mine" is caught as a conflict instead of silently overwriting what changed since. + expect([state.form.value.title, state.form.value.lastModifiedOn, state.isDirty.value]).toStrictEqual([ + "Mine", + originalVersion, + true, + ]) + }) + + it("does nothing when the request fails or the report isn't saved yet", async () => { + expect.hasAssertions() + const state = await edit() + service.remove.mockResolvedValue(null) + await state.setDeleted(true) + const fresh = await edit(null) + await fresh.setDeleted(true) + + expect([state.definition.value?.deletedOn, service.remove.mock.calls.length]).toStrictEqual([null, 1]) + }) + + it("does nothing when a restore fails", async () => { + expect.hasAssertions() + const state = await edit() + service.restore.mockResolvedValue(null) + + await state.setDeleted(false) + + expect(state.definition.value).toStrictEqual(saved) + }) +}) diff --git a/VueApp/src/Reports/admin/report-admin-form.ts b/VueApp/src/Reports/admin/report-admin-form.ts new file mode 100644 index 000000000..dc07ac3da --- /dev/null +++ b/VueApp/src/Reports/admin/report-admin-form.ts @@ -0,0 +1,215 @@ +import type { + ReportChoice, + ReportColumnFormat, + ReportParameterType, +} from "@/shared/report-builder/report-builder-types" +import type { + ReportColumnEdit, + ReportEditRequest, + ReportFilterOperator, + ReportParameterEdit, + ReportSourceDetail, + ReportValueKind, +} from "./report-admin-types" + +/** + * The admin form's state and the conversions to and from the API's shape. Columns and + * parameters carry a key for the sortable lists, and a choice parameter's fixed list is edited as + * text, one "value | label" per line. + */ + +type ChoicesFrom = "list" | "view" + +interface FormColumn extends ReportColumnEdit { + key: number +} + +interface FormParameter extends Omit { + key: number + choicesFrom: ChoicesFrom + choicesText: string +} + +interface ReportAdminForm extends Omit { + columns: FormColumn[] + parameters: FormParameter[] +} + +const CHOICE_SEPARATOR = "|" + +/** Which operators suit each parameter type, the first being the default. */ +const OPERATORS: Record = { + Text: ["Equals", "Contains"], + Number: ["Equals", "From", "To"], + Date: ["Equals", "From", "To"], + Boolean: ["Equals"], + Choice: ["Equals"], + MultiChoice: ["In"], +} + +const FORMATS_BY_KIND: Partial> = { + WholeNumber: "Number", + FractionalNumber: "Number", + Date: "Date", + DateTime: "DateTime", + Boolean: "YesNo", +} + +let lastKey = 0 + +function nextKey(): number { + lastKey += 1 + return lastKey +} + +function emptyForm(): ReportAdminForm { + return { + title: "", + description: null, + area: null, + source: "", + paginate: true, + pageSize: null, + allowExcel: true, + allowPdf: false, + pdfLandscape: false, + sensitiveNotice: null, + orderBy: null, + orderByDescending: false, + permissions: [], + columns: [], + parameters: [], + lastModifiedOn: null, + } +} + +/** "VME | Medicine" per line; a line without a label uses the value. Blank lines are skipped. */ +function parseChoices(text: string): ReportChoice[] { + return text + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter((line) => line !== "") + .map((line) => { + const at = line.indexOf(CHOICE_SEPARATOR) + const value = (at === -1 ? line : line.slice(0, at)).trim() + const label = at === -1 ? "" : line.slice(at + 1).trim() + return { value, label: label === "" ? value : label } + }) +} + +function formatChoices(choices: ReportChoice[] | null): string { + return (choices ?? []) + .map((choice) => + choice.label === choice.value ? choice.value : `${choice.value} ${CHOICE_SEPARATOR} ${choice.label}`, + ) + .join("\n") +} + +function toFormParameter(parameter: ReportParameterEdit): FormParameter { + const { choicesList, ...rest } = parameter + const hasList = (choicesList?.length ?? 0) > 0 + return { + ...rest, + key: nextKey(), + choicesFrom: hasList || parameter.choicesSource === null ? "list" : "view", + choicesText: formatChoices(choicesList), + } +} + +function toForm(report: ReportEditRequest): ReportAdminForm { + return { + ...report, + permissions: [...report.permissions], + columns: report.columns.map((column) => ({ ...column, key: nextKey() })), + parameters: report.parameters.map(toFormParameter), + } +} + +function toRequestParameter(parameter: FormParameter): ReportParameterEdit { + const { key: _key, choicesFrom, choicesText, ...rest } = parameter + const isChoice = parameter.type === "Choice" || parameter.type === "MultiChoice" + return { + ...rest, + choicesList: isChoice && choicesFrom === "list" ? parseChoices(choicesText) : null, + choicesSource: isChoice && choicesFrom === "view" ? parameter.choicesSource : null, + } +} + +function toRequest(form: ReportAdminForm): ReportEditRequest { + return { + ...form, + columns: form.columns.map(({ key: _key, ...column }) => column), + parameters: form.parameters.map(toRequestParameter), + } +} + +/** A format to start a column with, from the kind of value it holds. */ +function formatFor(kind: ReportValueKind): ReportColumnFormat { + return FORMATS_BY_KIND[kind] ?? "Text" +} + +function newColumn(name = "", kind: ReportValueKind = "Text"): FormColumn { + return { key: nextKey(), sourceColumn: name, label: null, format: formatFor(kind), sortable: true, visible: true } +} + +/** The source's showable columns the form doesn't have yet, as new columns. */ +function missingColumns(source: ReportSourceDetail, columns: FormColumn[]): FormColumn[] { + const have = new Set(columns.map((column) => column.sourceColumn.toLowerCase())) + return source.columns + .filter((column) => column.isSupported && !have.has(column.name.toLowerCase())) + .map((column) => newColumn(column.name, column.kind)) +} + +function newParameter(isView: boolean): FormParameter { + return { + key: nextKey(), + name: "", + label: null, + type: "Text", + operator: isView ? "Equals" : null, + required: false, + defaultValue: null, + choicesSource: null, + binding: "UserInput", + choicesFrom: "list", + choicesText: "", + } +} + +function operatorsFor(type: ReportParameterType): ReportFilterOperator[] { + return OPERATORS[type] +} + +/** The parameter with its type changed, keeping its operator if it still suits the type. */ +function withType(parameter: FormParameter, type: ReportParameterType, isView: boolean): FormParameter { + if (!isView) { + return { ...parameter, type, operator: null } + } + const allowed = OPERATORS[type] + const keep = parameter.operator !== null && allowed.includes(parameter.operator) + return { ...parameter, type, operator: keep ? parameter.operator : (allowed[0] ?? null) } +} + +/** What a parameter can be bound to: a view's showable columns, or a procedure's parameters. */ +function parameterTargets(source: ReportSourceDetail | null): string[] { + if (source === null) { + return [] + } + const list = source.kind === "View" ? source.columns : source.parameters + return list.filter((item) => item.isSupported).map((item) => item.name) +} + +export { + emptyForm, + formatChoices, + missingColumns, + newColumn, + newParameter, + operatorsFor, + parameterTargets, + parseChoices, + toForm, + toRequest, + withType, +} +export type { ChoicesFrom, FormColumn, FormParameter, ReportAdminForm } diff --git a/VueApp/src/Reports/admin/report-admin-permissions.ts b/VueApp/src/Reports/admin/report-admin-permissions.ts new file mode 100644 index 000000000..ee970d838 --- /dev/null +++ b/VueApp/src/Reports/admin/report-admin-permissions.ts @@ -0,0 +1,2 @@ +/** The RAPS permission for managing reports (ReportBuilderPermissions.Admin on the server). */ +export const REPORT_ADMIN_PERMISSION = "SVMSecure.Reports.Admin" diff --git a/VueApp/src/Reports/admin/report-admin-service.ts b/VueApp/src/Reports/admin/report-admin-service.ts new file mode 100644 index 000000000..75fbe2ec2 --- /dev/null +++ b/VueApp/src/Reports/admin/report-admin-service.ts @@ -0,0 +1,125 @@ +import { useFetch } from "@/composables/ViperFetch" +import type { ReportRunOutcome } from "@/shared/report-builder/report-builder-service" +import type { ReportRunRequest, ReportRunResult } from "@/shared/report-builder/report-builder-types" +import type { + ReportAdminDefinition, + ReportAdminListItem, + ReportCheckResult, + ReportEditRequest, + ReportFailure, + ReportHistoryItem, + ReportHistoryVersion, + ReportPermissionOption, + ReportSourceDetail, + ReportSourceSummary, +} from "./report-admin-types" + +const { get, post, put, del } = useFetch() + +const HTTP_CONFLICT = 409 +const SAVE_FAILED = "The report couldn't be saved. Please try again later." +const PREVIEW_FAILED = "The preview couldn't be run. Please try again later." + +/** + * A save's result: the saved report, or the server's messages. `conflict` is true when someone + * else saved the report after this editor loaded it. + */ +type ReportSaveOutcome = + | { definition: ReportAdminDefinition; errors: []; conflict: false } + | { definition: null; errors: string[]; conflict: boolean } + +function messages(errors: unknown, fallback: string): string[] { + const list = (Array.isArray(errors) ? errors : []).filter( + (message): message is string => typeof message === "string" && message !== "", + ) + return list.length > 0 ? list : [fallback] +} + +/** Client for the Report Builder admin API. Reads return null when the request fails. */ +class ReportAdminService { + private baseUrl = `${import.meta.env.VITE_API_URL}report-builder/admin` + + async getSources(): Promise { + const r = await get(`${this.baseUrl}/sources`) + return r.success && Array.isArray(r.result) ? (r.result as ReportSourceSummary[]) : null + } + + async getSource(name: string): Promise { + const r = await get(`${this.baseUrl}/sources/${encodeURIComponent(name)}`) + return r.success && r.result ? (r.result as ReportSourceDetail) : null + } + + /** RAPS permissions whose name contains the text; none when the request fails. */ + async searchPermissions(text: string): Promise { + const r = await get(`${this.baseUrl}/permissions?search=${encodeURIComponent(text)}`) + return r.success && Array.isArray(r.result) ? (r.result as ReportPermissionOption[]) : [] + } + + async list(includeDeleted: boolean): Promise { + const r = await get(`${this.baseUrl}/definitions?includeDeleted=${includeDeleted}`) + return r.success && Array.isArray(r.result) ? (r.result as ReportAdminListItem[]) : null + } + + async get(id: number): Promise { + const r = await get(this.definitionUrl(id)) + return r.success && r.result ? (r.result as ReportAdminDefinition) : null + } + + /** Creates the report when `id` is null, otherwise saves over it. */ + async save(id: number | null, report: ReportEditRequest): Promise { + const r = + id === null ? await post(`${this.baseUrl}/definitions`, report) : await put(this.definitionUrl(id), report) + if (r.success && r.result) { + return { definition: r.result as ReportAdminDefinition, errors: [], conflict: false } + } + return { definition: null, errors: messages(r.errors, SAVE_FAILED), conflict: r.status === HTTP_CONFLICT } + } + + async remove(id: number): Promise { + const r = await del(this.definitionUrl(id)) + return r.success && r.result ? (r.result as ReportAdminDefinition) : null + } + + async restore(id: number): Promise { + const r = await post(`${this.definitionUrl(id)}/restore`) + return r.success && r.result ? (r.result as ReportAdminDefinition) : null + } + + async getHistory(id: number): Promise { + const r = await get(`${this.definitionUrl(id)}/history`) + return r.success && Array.isArray(r.result) ? (r.result as ReportHistoryItem[]) : null + } + + async getVersion(id: number, historyId: number): Promise { + const r = await get(`${this.definitionUrl(id)}/history/${historyId}`) + return r.success && r.result ? (r.result as ReportHistoryVersion) : null + } + + /** A page of the report as the form now stands, without saving it. */ + async preview(report: ReportEditRequest, run: ReportRunRequest): Promise { + const r = await post(`${this.baseUrl}/preview`, { report, run }) + if (r.success && r.result) { + return { result: r.result as ReportRunResult, errors: [] } + } + return { result: null, errors: messages(r.errors, PREVIEW_FAILED) } + } + + /** Runs that failed in the last `days` days, newest first. */ + async getFailures(days: number): Promise { + const r = await get(`${this.baseUrl}/failures?days=${days}`) + return r.success && Array.isArray(r.result) ? (r.result as ReportFailure[]) : null + } + + /** Checks every live report as a save would. */ + async check(): Promise { + const r = await get(`${this.baseUrl}/check`) + return r.success && r.result ? (r.result as ReportCheckResult) : null + } + + private definitionUrl(id: number): string { + return `${this.baseUrl}/definitions/${id}` + } +} + +const reportAdminService = new ReportAdminService() +export { reportAdminService } diff --git a/VueApp/src/Reports/admin/report-admin-types.ts b/VueApp/src/Reports/admin/report-admin-types.ts new file mode 100644 index 000000000..4507f3972 --- /dev/null +++ b/VueApp/src/Reports/admin/report-admin-types.ts @@ -0,0 +1,197 @@ +import type { + ReportChoice, + ReportColumnFormat, + ReportParameterType, +} from "@/shared/report-builder/report-builder-types" + +/** + * Types mirroring the Report Builder admin API (ReportBuilderAdminController). Enum values + * arrive as their C# names; dates as ISO strings. + */ + +type ReportSourceKind = "View" | "Procedure" +type ReportFilterOperator = "Equals" | "Contains" | "From" | "To" | "In" +type ReportParameterBinding = "UserInput" | "CurrentUserLoginId" | "CurrentUserMothraId" +type ReportHistoryAction = "Created" | "Updated" | "Deleted" | "Restored" + +interface ReportSourceSummary { + name: string + kind: ReportSourceKind + description: string | null +} + +/** The kind of value a source column holds, from its SQL type. */ +type ReportValueKind = + | "Text" + | "WholeNumber" + | "FractionalNumber" + | "Date" + | "DateTime" + | "Time" + | "Boolean" + | "UniqueId" + | "Binary" + | "Other" + +interface ReportSourceColumn { + name: string + sqlType: string + kind: ReportValueKind + isSupported: boolean +} + +interface ReportSourceParameter { + name: string + sqlType: string + isSupported: boolean +} + +interface ReportSourceDetail extends ReportSourceSummary { + columns: ReportSourceColumn[] + parameters: ReportSourceParameter[] + /** Why SQL Server couldn't describe a procedure's columns; null when they're known. */ + columnsError: string | null + /** Whether the source pages itself (views, and procedures taking @Skip and @Take). */ + pagesInSql: boolean +} + +interface ReportColumnEdit { + sourceColumn: string + label: string | null + format: ReportColumnFormat + sortable: boolean + visible: boolean +} + +interface ReportParameterEdit { + name: string + label: string | null + type: ReportParameterType + operator: ReportFilterOperator | null + required: boolean + defaultValue: string | null + choicesSource: string | null + choicesList: ReportChoice[] | null + binding: ReportParameterBinding +} + +/** A report's editable fields: the body of a save, and what a read's `report` holds. */ +interface ReportEditRequest { + title: string + description: string | null + area: string | null + source: string + paginate: boolean + pageSize: number | null + allowExcel: boolean + allowPdf: boolean + pdfLandscape: boolean + sensitiveNotice: string | null + orderBy: string | null + orderByDescending: boolean + permissions: string[] + columns: ReportColumnEdit[] + parameters: ReportParameterEdit[] + /** The saved version this edit started from; a save from an older one is refused. */ + lastModifiedOn: string | null +} + +interface ReportAdminDefinition { + id: number + slug: string + createdOn: string | null + createdBy: string | null + modifiedOn: string | null + modifiedBy: string | null + deletedOn: string | null + deletedBy: string | null + report: ReportEditRequest + /** Permissions the report names that RAPS no longer has. */ + missingPermissions: string[] +} + +interface ReportAdminListItem { + id: number + slug: string + title: string + area: string | null + source: string + modifiedOn: string | null + modifiedBy: string | null + deletedOn: string | null + permissions: string[] + missingPermissions: string[] +} + +interface ReportHistoryItem { + id: number + action: ReportHistoryAction | null + changedOn: string | null + changedBy: string | null +} + +interface ReportHistoryVersion { + version: ReportHistoryItem + report: ReportEditRequest | null +} + +type ReportRunAction = "Run" | "ExportExcel" | "ExportPdf" + +/** A run or download that failed because of the report or its source. */ +interface ReportFailure { + id: number + reportId: number + reportTitle: string + reportDeleted: boolean + action: ReportRunAction | null + loginId: string | null + ranOn: string | null + /** The values the user chose, as JSON. */ + parameters: string | null + errorNumber: number | null + errorMessage: string +} + +interface ReportCheckProblem { + id: number + title: string + area: string | null + source: string + problems: string[] +} + +/** Every live report checked as a save would check it; only the failing ones are listed. */ +interface ReportCheckResult { + checked: number + checkedOn: string + failing: ReportCheckProblem[] +} + +interface ReportPermissionOption { + permission: string + description: string | null +} + +export type { + ReportAdminDefinition, + ReportAdminListItem, + ReportCheckProblem, + ReportCheckResult, + ReportColumnEdit, + ReportEditRequest, + ReportFailure, + ReportFilterOperator, + ReportHistoryAction, + ReportHistoryItem, + ReportHistoryVersion, + ReportParameterBinding, + ReportParameterEdit, + ReportPermissionOption, + ReportRunAction, + ReportSourceColumn, + ReportSourceDetail, + ReportSourceKind, + ReportSourceParameter, + ReportSourceSummary, + ReportValueKind, +} diff --git a/VueApp/src/Reports/admin/use-report-admin-edit.ts b/VueApp/src/Reports/admin/use-report-admin-edit.ts new file mode 100644 index 000000000..54ef39f66 --- /dev/null +++ b/VueApp/src/Reports/admin/use-report-admin-edit.ts @@ -0,0 +1,185 @@ +import { computed, ref, toValue, watch } from "vue" +import type { MaybeRefOrGetter } from "vue" +import { useRouter } from "vue-router" +import { useUnsavedChanges } from "@/composables/use-unsaved-changes" +import { emptyForm, missingColumns, parameterTargets, toForm, toRequest } from "./report-admin-form" +import type { ReportAdminForm } from "./report-admin-form" +import { reportAdminService } from "./report-admin-service" +import type { + ReportAdminDefinition, + ReportEditRequest, + ReportSourceDetail, + ReportSourceSummary, +} from "./report-admin-types" + +/** + * State for the report edit page: loads the report (or starts a new one) with the list of + * [report] sources, describes the chosen source, and saves, deletes and restores. A new report + * moves to its own edit address once saved. Only the latest load may update the page. + */ +// oxlint-disable-next-line max-lines-per-function -- one report's edit state and the actions on it belong together +export function useReportAdminEdit(reportId: MaybeRefOrGetter) { + const router = useRouter() + + const form = ref(emptyForm()) + const definition = ref(null) + const sources = ref([]) + const source = ref(null) + const loading = ref(true) + const notFound = ref(false) + const sourcesFailed = ref(false) + const saving = ref(false) + const errors = ref([]) + const conflict = ref(false) + const { isDirty, setInitialState } = useUnsavedChanges(form) + + let loadId = 0 + let sourceId = 0 + + const isView = computed(() => source.value?.kind !== "Procedure") + const views = computed(() => sources.value.filter((item) => item.kind === "View").map((item) => item.name)) + const targets = computed(() => parameterTargets(source.value)) + const sourceColumns = computed( + () => source.value?.columns.filter((column) => column.isSupported).map((column) => column.name) ?? [], + ) + const canAddMissing = computed( + () => source.value !== null && missingColumns(source.value, form.value.columns).length > 0, + ) + + /** Describes the source; false when a newer request has taken over and nothing was changed. */ + async function describeSource(name: string): Promise { + sourceId += 1 + const current = sourceId + const detail = name === "" ? null : await reportAdminService.getSource(name) + if (current !== sourceId) { + return false + } + source.value = detail + return true + } + + async function load(id: number | null): Promise { + loadId += 1 + const current = loadId + loading.value = true + errors.value = [] + conflict.value = false + const [list, report] = await Promise.all([ + reportAdminService.getSources(), + id === null ? Promise.resolve(null) : reportAdminService.get(id), + ]) + if (current !== loadId) { + return + } + sources.value = list ?? [] + sourcesFailed.value = list === null + notFound.value = id !== null && report === null + definition.value = report + form.value = report ? toForm(report.report) : emptyForm() + await describeSource(form.value.source) + if (current !== loadId) { + return + } + setInitialState() + loading.value = false + } + + /** Picks a source; a report without columns yet gets all the source's columns. */ + async function changeSource(name: string): Promise { + form.value = { ...form.value, source: name } + if ((await describeSource(name)) && source.value !== null && form.value.columns.length === 0) { + form.value = { ...form.value, columns: missingColumns(source.value, []) } + } + } + + function addMissingColumns(): void { + if (source.value !== null) { + form.value = { + ...form.value, + columns: [...form.value.columns, ...missingColumns(source.value, form.value.columns)], + } + } + } + + async function save(): Promise { + saving.value = true + errors.value = [] + conflict.value = false + const wasNew = definition.value === null + const outcome = await reportAdminService.save(definition.value?.id ?? null, toRequest(form.value)) + saving.value = false + if (outcome.definition === null) { + errors.value = outcome.errors + conflict.value = outcome.conflict + return + } + definition.value = outcome.definition + form.value = toForm(outcome.definition.report) + setInitialState() + if (wasNew) { + await router.replace({ name: "ReportAdminEdit", params: { id: String(outcome.definition.id) } }) + } + } + + /** + * Deletes or restores the report. Either one is a save on the server, which moves its + * version on without checking the form's fields, so the form only takes that new version + * when it has no unsaved edits to lose; with edits pending, it keeps its own version, so a + * save of those edits is caught as a conflict instead of silently overwriting what changed. + */ + async function setDeleted(deleted: boolean): Promise { + const current = definition.value + if (current === null) { + return + } + const updated = deleted + ? await reportAdminService.remove(current.id) + : await reportAdminService.restore(current.id) + if (updated === null) { + return + } + definition.value = updated + if (!isDirty.value) { + form.value = toForm(updated.report) + setInitialState() + } + } + + /** Puts an earlier version's fields in the form, to save over the current one. */ + async function applyVersion(report: ReportEditRequest): Promise { + form.value = toForm({ ...report, lastModifiedOn: form.value.lastModifiedOn }) + await describeSource(form.value.source) + } + + /** Starts again from the saved report, dropping the edits; used after a conflicting save. */ + async function reload(): Promise { + await load(definition.value?.id ?? null) + } + + watch(() => toValue(reportId), load, { immediate: true }) + + return { + form, + definition, + sources, + source, + loading, + notFound, + sourcesFailed, + saving, + errors, + conflict, + isDirty, + isView, + views, + targets, + sourceColumns, + canAddMissing, + changeSource, + addMissingColumns, + save, + setDeleted, + applyVersion, + reload, + } +} diff --git a/VueApp/src/Reports/components/ReportAdminBasics.vue b/VueApp/src/Reports/components/ReportAdminBasics.vue new file mode 100644 index 000000000..f78e5db64 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminBasics.vue @@ -0,0 +1,117 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminChoices.vue b/VueApp/src/Reports/components/ReportAdminChoices.vue new file mode 100644 index 000000000..4dad8a399 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminChoices.vue @@ -0,0 +1,51 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminColumns.vue b/VueApp/src/Reports/components/ReportAdminColumns.vue new file mode 100644 index 000000000..1b86b1a52 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminColumns.vue @@ -0,0 +1,143 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminDisplay.vue b/VueApp/src/Reports/components/ReportAdminDisplay.vue new file mode 100644 index 000000000..ea80cbbc3 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminDisplay.vue @@ -0,0 +1,116 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminEditForm.vue b/VueApp/src/Reports/components/ReportAdminEditForm.vue new file mode 100644 index 000000000..3a1c386ed --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminEditForm.vue @@ -0,0 +1,136 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminHistory.vue b/VueApp/src/Reports/components/ReportAdminHistory.vue new file mode 100644 index 000000000..598579731 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminHistory.vue @@ -0,0 +1,108 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminParameterFields.vue b/VueApp/src/Reports/components/ReportAdminParameterFields.vue new file mode 100644 index 000000000..824ae2596 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminParameterFields.vue @@ -0,0 +1,157 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminParameters.vue b/VueApp/src/Reports/components/ReportAdminParameters.vue new file mode 100644 index 000000000..f6d8ed2d3 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminParameters.vue @@ -0,0 +1,80 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminPermissions.vue b/VueApp/src/Reports/components/ReportAdminPermissions.vue new file mode 100644 index 000000000..939fedcd1 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminPermissions.vue @@ -0,0 +1,83 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminPreview.vue b/VueApp/src/Reports/components/ReportAdminPreview.vue new file mode 100644 index 000000000..f0c005a07 --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminPreview.vue @@ -0,0 +1,107 @@ + + + diff --git a/VueApp/src/Reports/components/ReportAdminStatus.vue b/VueApp/src/Reports/components/ReportAdminStatus.vue new file mode 100644 index 000000000..091f8a1fe --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminStatus.vue @@ -0,0 +1,81 @@ + + + diff --git a/VueApp/src/Reports/components/ReportFailedRuns.vue b/VueApp/src/Reports/components/ReportFailedRuns.vue new file mode 100644 index 000000000..eeb0bc0df --- /dev/null +++ b/VueApp/src/Reports/components/ReportFailedRuns.vue @@ -0,0 +1,180 @@ + + + diff --git a/VueApp/src/Reports/components/ReportProblemsCheck.vue b/VueApp/src/Reports/components/ReportProblemsCheck.vue new file mode 100644 index 000000000..a515fd067 --- /dev/null +++ b/VueApp/src/Reports/components/ReportProblemsCheck.vue @@ -0,0 +1,97 @@ + + + diff --git a/VueApp/src/Reports/index.html b/VueApp/src/Reports/index.html new file mode 100644 index 000000000..dce827ca3 --- /dev/null +++ b/VueApp/src/Reports/index.html @@ -0,0 +1,18 @@ + + + + + + VIPER - Reports + + +
+ + + diff --git a/VueApp/src/Reports/pages/ReportAdminEdit.vue b/VueApp/src/Reports/pages/ReportAdminEdit.vue new file mode 100644 index 000000000..32bc809b1 --- /dev/null +++ b/VueApp/src/Reports/pages/ReportAdminEdit.vue @@ -0,0 +1,94 @@ + + + diff --git a/VueApp/src/Reports/pages/ReportAdminList.vue b/VueApp/src/Reports/pages/ReportAdminList.vue new file mode 100644 index 000000000..aa8d99d60 --- /dev/null +++ b/VueApp/src/Reports/pages/ReportAdminList.vue @@ -0,0 +1,142 @@ + + + diff --git a/VueApp/src/Reports/pages/ReportAdminProblems.vue b/VueApp/src/Reports/pages/ReportAdminProblems.vue new file mode 100644 index 000000000..f672804f8 --- /dev/null +++ b/VueApp/src/Reports/pages/ReportAdminProblems.vue @@ -0,0 +1,15 @@ + + + diff --git a/VueApp/src/Reports/pages/ReportPage.vue b/VueApp/src/Reports/pages/ReportPage.vue new file mode 100644 index 000000000..9a2f1efed --- /dev/null +++ b/VueApp/src/Reports/pages/ReportPage.vue @@ -0,0 +1,26 @@ + + + diff --git a/VueApp/src/Reports/pages/ReportsHome.vue b/VueApp/src/Reports/pages/ReportsHome.vue new file mode 100644 index 000000000..28f3d0014 --- /dev/null +++ b/VueApp/src/Reports/pages/ReportsHome.vue @@ -0,0 +1,99 @@ + + + diff --git a/VueApp/src/Reports/reports.ts b/VueApp/src/Reports/reports.ts new file mode 100644 index 000000000..05a2d5366 --- /dev/null +++ b/VueApp/src/Reports/reports.ts @@ -0,0 +1,10 @@ +import { bootstrapSpa } from "@/shared/bootstrap-spa" +import { router } from "./router" +import App from "./App.vue" + +bootstrapSpa({ + areaPath: "/Reports", + appComponent: App, + router, + provides: { apiURL: import.meta.env.VITE_API_URL }, +}) diff --git a/VueApp/src/Reports/router/index.ts b/VueApp/src/Reports/router/index.ts new file mode 100644 index 000000000..a55213799 --- /dev/null +++ b/VueApp/src/Reports/router/index.ts @@ -0,0 +1,30 @@ +import { createSpaRouter } from "@/shared/create-spa-router" +import type { NavigationGuard } from "vue-router" +import { routes } from "./routes" +import { createAuthenticator } from "@/composables/RequireLogin" +import { useUserStore } from "@/store/UserStore" +import { checkHasOnePermission } from "@/composables/CheckPagePermission" + +const router = createSpaRouter(routes) + +// Which reports a visitor may see is decided by the API, report by report, so the only +// permissions loaded here are the Report Builder's own (SVMSecure.Reports.*). +const authenticate = createAuthenticator("SVMSecure.Reports") + +// Exported so tests can run the guard over a router whose page components are stubs. +const reportsGuard: NavigationGuard = async (to, from) => { + // An in-app navigation is already signed in, so the login round-trip would only cost a request. + const needsAuthentication = from.matched.length === 0 || !useUserStore().isLoggedIn + if (needsAuthentication && !(await authenticate(to))) { + return false + } + + const required = to.meta.permissions as string[] | undefined + if (required !== undefined && !checkHasOnePermission(required)) { + return { name: "ReportsHome" } + } +} + +router.beforeEach(reportsGuard) + +export { router, reportsGuard } diff --git a/VueApp/src/Reports/router/routes.ts b/VueApp/src/Reports/router/routes.ts new file mode 100644 index 000000000..f7a6053c4 --- /dev/null +++ b/VueApp/src/Reports/router/routes.ts @@ -0,0 +1,58 @@ +import ViperLayout from "@/layouts/ViperLayout.vue" +import { REPORT_ADMIN_PERMISSION } from "@/Reports/admin/report-admin-permissions" + +// A report's slug is a GUID. Matching only GUIDs leaves other paths under /Reports (such as +// /Reports/Admin) to their own routes or the 404 page, rather than looking them up as reports. +const SLUG = String.raw`[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}` + +// The admin pages need the admin permission; the API checks it again on every request. +const adminMeta = { layout: ViperLayout, allowUnAuth: false, permissions: [REPORT_ADMIN_PERMISSION] } + +const routes = [ + { + path: "/Reports/", + alias: "/Reports/Home", + meta: { layout: ViperLayout, allowUnAuth: false }, + component: () => import("@/Reports/pages/ReportsHome.vue"), + name: "ReportsHome", + }, + { + path: "/Reports/Admin", + meta: adminMeta, + component: () => import("@/Reports/pages/ReportAdminList.vue"), + name: "ReportAdmin", + }, + { + path: "/Reports/Admin/New", + meta: adminMeta, + component: () => import("@/Reports/pages/ReportAdminEdit.vue"), + name: "ReportAdminNew", + }, + { + path: "/Reports/Admin/Problems", + meta: adminMeta, + component: () => import("@/Reports/pages/ReportAdminProblems.vue"), + name: "ReportAdminProblems", + }, + { + path: String.raw`/Reports/Admin/:id(\d+)`, + meta: adminMeta, + component: () => import("@/Reports/pages/ReportAdminEdit.vue"), + name: "ReportAdminEdit", + }, + { + // Any admin-built report, by its slug. The API enforces each report's own permissions, + // so the route needs none; a report the user can't view shows as not available. + path: `/Reports/:slug(${SLUG})`, + meta: { layout: ViperLayout, allowUnAuth: false }, + component: () => import("@/Reports/pages/ReportPage.vue"), + name: "Report", + }, + { + path: "/:catchAll(.*)*", + meta: { layout: ViperLayout }, + component: () => import("@/pages/Error404.vue"), + }, +] + +export { routes } diff --git a/VueApp/src/composables/RequireLogin.ts b/VueApp/src/composables/RequireLogin.ts index 884105bf2..15a4b850b 100644 --- a/VueApp/src/composables/RequireLogin.ts +++ b/VueApp/src/composables/RequireLogin.ts @@ -131,6 +131,19 @@ function useRequireLogin(to: RouteLocationNormalized) { return { requireLogin } } +/** + * A router guard's `authenticate` step: signs the visitor in and loads the permissions under + * `permissionPrefix` in the same request, so there's no second permission set to fetch or keep in + * sync. A null result means requireLogin reached no verdict, which is not a refusal. + */ +function createAuthenticator(permissionPrefix: string) { + return async function authenticate(to: RouteLocationNormalized): Promise { + const { requireLogin } = useRequireLogin(to) + const loginResult = await requireLogin(true, permissionPrefix) + return loginResult === null || loginResult + } +} + // Everything before the separator, and everything after it. function splitFirst(value: string, separator: string): [string, string] { const at = value.indexOf(separator) @@ -166,4 +179,4 @@ function resolveSendBackTo(route: ReturnType): SendBackToLocati return { path: stripApplicationBase(rawPath), query, hash: fragment ? `#${fragment}` : "" } } -export { buildLoginUrl, getLoginUrl, isValidInternalPath, resolveSendBackTo, useRequireLogin } +export { buildLoginUrl, createAuthenticator, getLoginUrl, isValidInternalPath, resolveSendBackTo, useRequireLogin } diff --git a/VueApp/src/shared/report-builder/ReportBuilderForm.vue b/VueApp/src/shared/report-builder/ReportBuilderForm.vue new file mode 100644 index 000000000..11742bcc9 --- /dev/null +++ b/VueApp/src/shared/report-builder/ReportBuilderForm.vue @@ -0,0 +1,108 @@ + + + diff --git a/VueApp/src/shared/report-builder/ReportBuilderResults.vue b/VueApp/src/shared/report-builder/ReportBuilderResults.vue new file mode 100644 index 000000000..ea4064a12 --- /dev/null +++ b/VueApp/src/shared/report-builder/ReportBuilderResults.vue @@ -0,0 +1,78 @@ + + + diff --git a/VueApp/src/shared/report-builder/ReportBuilderTable.vue b/VueApp/src/shared/report-builder/ReportBuilderTable.vue new file mode 100644 index 000000000..916b50a39 --- /dev/null +++ b/VueApp/src/shared/report-builder/ReportBuilderTable.vue @@ -0,0 +1,105 @@ + + + diff --git a/VueApp/src/shared/report-builder/ReportChoiceField.vue b/VueApp/src/shared/report-builder/ReportChoiceField.vue new file mode 100644 index 000000000..bb9e90f6c --- /dev/null +++ b/VueApp/src/shared/report-builder/ReportChoiceField.vue @@ -0,0 +1,73 @@ + + + diff --git a/VueApp/src/shared/report-builder/ReportViewer.vue b/VueApp/src/shared/report-builder/ReportViewer.vue new file mode 100644 index 000000000..900634c15 --- /dev/null +++ b/VueApp/src/shared/report-builder/ReportViewer.vue @@ -0,0 +1,93 @@ + + + diff --git a/VueApp/src/shared/report-builder/ReportViewerLoaded.vue b/VueApp/src/shared/report-builder/ReportViewerLoaded.vue new file mode 100644 index 000000000..f41095d89 --- /dev/null +++ b/VueApp/src/shared/report-builder/ReportViewerLoaded.vue @@ -0,0 +1,105 @@ + + + diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-catalog.test.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-catalog.test.ts new file mode 100644 index 000000000..a26094051 --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-catalog.test.ts @@ -0,0 +1,37 @@ +import { OTHER_AREA, groupByArea } from "../report-builder-catalog" +import type { ReportCatalogItem } from "../report-builder-types" + +function report(title: string, area: string | null): ReportCatalogItem { + return { slug: title, title, description: null, area } +} + +describe("grouping by area", () => { + it("groups reports by area, in alphabetical order, keeping each group's order", () => { + expect.hasAssertions() + + const groups = groupByArea([ + report("Roster", "Personnel"), + report("Courses", "Effort"), + report("Leave", "Personnel"), + ]) + + expect(groups.map((group) => [group.area, group.reports.map((r) => r.title)])).toStrictEqual([ + ["Effort", ["Courses"]], + ["Personnel", ["Roster", "Leave"]], + ]) + }) + + it("lists reports without an area last", () => { + expect.hasAssertions() + + const groups = groupByArea([report("Misc", null), report("Blank", " "), report("Roster", "Personnel")]) + + expect(groups.map((group) => group.area)).toStrictEqual(["Personnel", OTHER_AREA]) + }) + + it("has no groups for no reports", () => { + expect.hasAssertions() + + expect(groupByArea([])).toStrictEqual([]) + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-fixtures.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-fixtures.ts new file mode 100644 index 000000000..de6fe12fb --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-fixtures.ts @@ -0,0 +1,66 @@ +import type { ReportRunResult, ReportViewerDefinition, ReportViewerParameter } from "../report-builder-types" + +/** Shared test data: a roster report with one of each kind of parameter. */ + +const textParameter: ReportViewerParameter = { + name: "Name", + label: "Name", + type: "Text", + required: false, + defaultValue: null, + choices: null, +} + +const deptParameter: ReportViewerParameter = { + name: "Dept", + label: "Department", + type: "MultiChoice", + required: false, + defaultValue: null, + choices: [ + { value: "VME", label: "Medicine" }, + { value: "PMI", label: "Pathology" }, + ], +} + +const hiredParameter: ReportViewerParameter = { + name: "Hired", + label: "Hired from", + type: "Date", + required: true, + defaultValue: "2026-01-01", + choices: null, +} + +const roster: ReportViewerDefinition = { + slug: "8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e", + title: "Faculty roster", + description: "Current faculty by department.", + area: "Personnel", + sensitiveNotice: null, + paginate: true, + pageSize: 25, + allowExcel: true, + allowPdf: false, + sortBy: "Name", + sortDescending: false, + columns: [ + { name: "Name", label: "Name", format: "Text", sortable: true }, + { name: "Salary", label: "Salary", format: "Currency", sortable: false }, + ], + parameters: [textParameter, deptParameter, hiredParameter], +} + +function resultOf(rows: ReportRunResult["rows"], overrides: Partial = {}): ReportRunResult { + return { + columns: roster.columns, + rows, + page: 1, + perPage: 25, + totalRows: rows.length, + truncated: false, + ...overrides, + } +} + +export { deptParameter, hiredParameter, resultOf, roster, textParameter } diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-form.test.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-form.test.ts new file mode 100644 index 000000000..7649b52a4 --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-form.test.ts @@ -0,0 +1,109 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportBuilderForm from "../ReportBuilderForm.vue" +import ReportChoiceField from "../ReportChoiceField.vue" +import type { ReportParameterValues, ReportViewerParameter } from "../report-builder-types" +import { deptParameter, hiredParameter, textParameter } from "./report-builder-fixtures" + +const paidParameter: ReportViewerParameter = { + name: "Paid", + label: "Paid", + type: "Boolean", + required: false, + defaultValue: null, + choices: null, +} +const countParameter: ReportViewerParameter = { ...textParameter, name: "Count", label: "Count", type: "Number" } + +function mountForm(parameters: ReportViewerParameter[], values: ReportParameterValues = {}) { + return mount(ReportBuilderForm, { + props: { + parameters, + modelValue: values, + "onUpdate:modelValue": vi.fn<(values: ReportParameterValues) => void>(), + }, + global: { plugins: [[Quasar, {}]] }, + }) +} + +describe("report form", () => { + it("shows a field per parameter, marking the required ones", () => { + expect.hasAssertions() + + const wrapper = mountForm([textParameter, hiredParameter]) + + expect(wrapper.findAll("input").map((input) => input.attributes("type"))).toStrictEqual(["text", "date"]) + expect(wrapper.text()).toContain("Hired from *") + }) + + it("offers choices for choice parameters, and Yes or No for a yes/no parameter", () => { + expect.hasAssertions() + + const fields = mountForm([deptParameter, paidParameter]).findAllComponents(ReportChoiceField) + + expect(fields.map((field) => field.props("choices").map((choice) => choice.label))).toStrictEqual([ + ["Medicine", "Pathology"], + ["Yes", "No"], + ]) + expect(fields.map((field) => field.props("multiple"))).toStrictEqual([true, false]) + }) + + it("treats a choice parameter without choices as having none", () => { + expect.hasAssertions() + + const field = mountForm([{ ...deptParameter, choices: null }]).findComponent(ReportChoiceField) + + expect(field.props("choices")).toStrictEqual([]) + }) + + it("keeps typed values as text, and a cleared field as empty", async () => { + expect.hasAssertions() + const wrapper = mountForm([countParameter, textParameter], { Count: null, Name: "Ada" }) + + await wrapper.findAll("input")[0]!.setValue("12") + await wrapper.setProps({ + modelValue: wrapper.emitted<[ReportParameterValues]>("update:modelValue")!.at(-1)![0], + }) + await wrapper.findAll("input")[1]!.setValue("") + + expect(wrapper.emitted<[ReportParameterValues]>("update:modelValue")!.at(-1)![0]).toStrictEqual({ + Count: "12", + Name: null, + }) + }) + + it("passes a choice on to the model", () => { + expect.hasAssertions() + const wrapper = mountForm([deptParameter], { Dept: [] }) + + wrapper.findComponent(ReportChoiceField).vm.$emit("update:modelValue", ["VME"]) + + expect(wrapper.emitted<[ReportParameterValues]>("update:modelValue")!.at(-1)![0]).toStrictEqual({ + Dept: ["VME"], + }) + }) + + it("has no Run button: the report runs when the values change", () => { + expect.hasAssertions() + + expect(mountForm([textParameter]).find("button[type=submit]").exists()).toBeFalsy() + }) + + it("submits when every required field is filled", async () => { + expect.hasAssertions() + const wrapper = mountForm([hiredParameter], { Hired: "2026-01-01" }) + + await wrapper.get("form").trigger("submit") + await vi.waitFor(() => expect(wrapper.emitted("submit")).toHaveLength(1)) + }) + + it("explains an empty required field instead of submitting", async () => { + expect.hasAssertions() + const wrapper = mountForm([hiredParameter], { Hired: null }) + + await wrapper.get("form").trigger("submit") + await vi.waitFor(() => expect(wrapper.text()).toContain("Hired from is required.")) + + expect(wrapper.emitted("submit")).toBeUndefined() + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-format.test.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-format.test.ts new file mode 100644 index 000000000..069b6da0d --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-format.test.ts @@ -0,0 +1,74 @@ +import { formatCell, isNumericFormat } from "../report-builder-format" + +describe("cell text", () => { + it.each([ + [1234.5, "Number", "1,234.5"], + [1234.5, "Currency", "$1,234.50"], + [0.255, "Percent", "25.5%"], + [7, "Text", "7"], + ] as const)("shows %j in a %s column as %s", (value, format, expected) => { + expect.hasAssertions() + + expect(formatCell(value, format)).toBe(expected) + }) + + it.each([ + ["2026-03-01T00:00:00", "Date", "03/01/2026"], + ["2026-03-01T14:05:00", "Date", "03/01/2026"], + ["2026-03-01T00:00:00", "DateTime", "03/01/2026 12:00 AM"], + ["2026-03-01T14:05:00", "DateTime", "03/01/2026 2:05 PM"], + ["2026-03-01T12:30:00", "Text", "03/01/2026 12:30 PM"], + ["2026-03-01T00:00:00", "Text", "03/01/2026"], + ["2026-03-01", "Date", "03/01/2026"], + ] as const)("shows the date %s in a %s column as %s", (value, format, expected) => { + expect.hasAssertions() + + expect(formatCell(value, format)).toBe(expected) + }) + + it("leaves text that only looks like a date alone in a text column", () => { + expect.hasAssertions() + + expect(formatCell("2026-03-01", "Text")).toBe("2026-03-01") + }) + + it("leaves text that isn't a date alone in a text column", () => { + expect.hasAssertions() + + expect(formatCell("N/A", "Text")).toBe("N/A") + }) + + it.each([ + [true, "Yes"], + [false, "No"], + [1, "Yes"], + [0, "No"], + [" y ", "Yes"], + ["FALSE", "No"], + ["Maybe", "Maybe"], + ] as const)("shows %j in a yes/no column as %s", (value, expected) => { + expect.hasAssertions() + + expect(formatCell(value, "YesNo")).toBe(expected) + }) + + it("shows true and false as Yes and No in any column, and nothing as blank", () => { + expect.hasAssertions() + + expect([formatCell(true, "Text"), formatCell(false, "Number"), formatCell(null, "Text")]).toStrictEqual([ + "Yes", + "No", + "", + ]) + }) +}) + +describe("numeric formats", () => { + it("is true for number, currency and percent columns only", () => { + expect.hasAssertions() + + expect( + ["Number", "Currency", "Percent", "Text", "Date"].map((format) => isNumericFormat(format as never)), + ).toStrictEqual([true, true, true, false, false]) + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-query.test.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-query.test.ts new file mode 100644 index 000000000..57554b031 --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-query.test.ts @@ -0,0 +1,72 @@ +import { hasRequiredValues, initialValues, isEmptyValue, toQuery, toRequestParameters } from "../report-builder-query" +import { deptParameter, hiredParameter, roster, textParameter } from "./report-builder-fixtures" + +describe("starting values", () => { + it("takes values from the query first", () => { + expect.hasAssertions() + + const values = initialValues(roster.parameters, { Name: "Ada", Dept: ["VME", "PMI"], Hired: "2026-03-01" }) + + expect(values).toStrictEqual({ Name: "Ada", Dept: ["VME", "PMI"], Hired: "2026-03-01" }) + }) + + it("then from the embedding page, then from the defaults", () => { + expect.hasAssertions() + + const values = initialValues(roster.parameters, {}, { Name: "Bo", Dept: "VME" }) + + expect(values).toStrictEqual({ Name: "Bo", Dept: ["VME"], Hired: "2026-01-01" }) + }) + + it("leaves a parameter without a value empty", () => { + expect.hasAssertions() + + expect(initialValues([textParameter, deptParameter], { Name: "" })).toStrictEqual({ Name: null, Dept: [] }) + }) + + it("ignores query values that aren't strings", () => { + expect.hasAssertions() + + expect(initialValues([textParameter], { Name: [null, "Ada"] })).toStrictEqual({ Name: "Ada" }) + }) +}) + +describe("required values", () => { + it("is true only when every required parameter has a value", () => { + expect.hasAssertions() + + expect(hasRequiredValues([textParameter, hiredParameter], { Name: null, Hired: "2026-01-01" })).toBeTruthy() + expect(hasRequiredValues([textParameter, hiredParameter], { Name: "Ada", Hired: null })).toBeFalsy() + }) +}) + +describe("request and query", () => { + const values = { Name: "Ada", Dept: ["VME", "PMI"], Hired: null, Unknown: "x" } + + it("sends every filled-in value as a list", () => { + expect.hasAssertions() + + expect(toRequestParameters(roster.parameters, values)).toStrictEqual({ Name: ["Ada"], Dept: ["VME", "PMI"] }) + }) + + it("writes single values plainly and repeats the key for lists", () => { + expect.hasAssertions() + + expect(toQuery(roster.parameters, values)).toStrictEqual({ Name: "Ada", Dept: ["VME", "PMI"] }) + }) +}) + +describe("empty values", () => { + it.each([null, undefined, "", []])("treats %j as empty", (value) => { + expect.hasAssertions() + + expect(isEmptyValue(value)).toBeTruthy() + }) + + it("treats text and lists with values as filled in", () => { + expect.hasAssertions() + + expect(isEmptyValue("x")).toBeFalsy() + expect(isEmptyValue(["x"])).toBeFalsy() + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-results.test.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-results.test.ts new file mode 100644 index 000000000..444857afc --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-results.test.ts @@ -0,0 +1,110 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportBuilderResults from "../ReportBuilderResults.vue" +import ReportBuilderTable from "../ReportBuilderTable.vue" +import ExportToolbar from "@/components/ExportToolbar.vue" +import type { ReportExportFormat, ReportRunResult } from "../report-builder-types" +import { resultOf } from "./report-builder-fixtures" + +const exportAs = vi.fn<(format: ReportExportFormat) => Promise>() + +function mountResults(result: ReportRunResult = resultOf([{ Name: "Ada" }]), overrides: Record = {}) { + return mount(ReportBuilderResults, { + props: { + result, + pagination: { page: 1, rowsPerPage: 25, sortBy: null, descending: false, rowsNumber: 1 }, + paginate: true, + title: "Faculty roster", + search: "", + allowExcel: true, + allowPdf: false, + canExport: true, + running: false, + exporting: null, + nothingToExport: false, + exportAs, + ...overrides, + }, + global: { plugins: [[Quasar, {}]] }, + }) +} + +function toolbar(wrapper: ReturnType) { + return wrapper.findComponent(ExportToolbar) +} + +describe("report results", () => { + it("offers only the downloads the report allows", async () => { + expect.hasAssertions() + const bar = toolbar(mountResults()) + + await bar.props("excelExport")?.() + + expect(bar.props("pdfExport")).toBeUndefined() + expect(exportAs).toHaveBeenCalledWith("xlsx") + }) + + it("offers a PDF when the report allows it", async () => { + expect.hasAssertions() + const bar = toolbar(mountResults(undefined, { allowExcel: false, allowPdf: true })) + + await bar.props("pdfExport")?.() + + expect([bar.props("excelExport"), exportAs.mock.lastCall]).toStrictEqual([undefined, ["pdf"]]) + }) + + it("offers no downloads when there's nothing to download", () => { + expect.hasAssertions() + + const bar = toolbar(mountResults(undefined, { canExport: false, allowPdf: true })) + + expect([bar.props("excelExport"), bar.props("pdfExport")]).toStrictEqual([undefined, undefined]) + }) + + it("passes the search on", () => { + expect.hasAssertions() + const wrapper = mountResults() + + toolbar(wrapper).vm.$emit("update:filter", "ada") + + expect(wrapper.emitted("search")).toStrictEqual([["ada"]]) + }) + + it("passes the table's page requests on", () => { + expect.hasAssertions() + const wrapper = mountResults() + const request = { page: 2, rowsPerPage: 25, sortBy: null, descending: false } + + wrapper.findComponent(ReportBuilderTable).vm.$emit("request", request) + + expect(wrapper.emitted("request")).toStrictEqual([[request]]) + }) + + it("says when the row cap cut the result short", () => { + expect.hasAssertions() + + expect(mountResults(resultOf([{ Name: "Ada" }], { truncated: true })).text()).toContain( + "Only the first 50,000 rows are shown.", + ) + }) + + it("says when there are no rows instead of showing an empty table", () => { + expect.hasAssertions() + const wrapper = mountResults(resultOf([])) + + expect(wrapper.text()).toContain("No rows match these filters.") + expect(wrapper.findComponent(ReportBuilderTable).exists()).toBeFalsy() + }) + + it("keeps the table while a new page loads", () => { + expect.hasAssertions() + + expect(mountResults(resultOf([]), { running: true }).findComponent(ReportBuilderTable).exists()).toBeTruthy() + }) + + it("says when a download had nothing in it", () => { + expect.hasAssertions() + + expect(mountResults(undefined, { nothingToExport: true }).text()).toContain("There's nothing to download") + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-service.test.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-service.test.ts new file mode 100644 index 000000000..b7c5821da --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-service.test.ts @@ -0,0 +1,136 @@ +import { reportBuilderService } from "../report-builder-service" +import type { ReportRunRequest } from "../report-builder-types" +import { resultOf, roster } from "./report-builder-fixtures" + +/** + * The service returns null or an outcome instead of throwing, so pages can tell a failure apart + * from an empty result and show the server's messages. + */ + +const { mockGet, mockPost, mockPostForBlob, mockDownloadBlob } = vi.hoisted(() => ({ + mockGet: vi.fn<(...args: unknown[]) => unknown>(), + mockPost: vi.fn<(...args: unknown[]) => unknown>(), + mockPostForBlob: vi.fn<(...args: unknown[]) => unknown>(), + mockDownloadBlob: vi.fn<(...args: unknown[]) => unknown>(), +})) +vi.mock("@/composables/ViperFetch", () => ({ + useFetch: () => ({ + get: (...args: unknown[]) => mockGet(...args), + post: (...args: unknown[]) => mockPost(...args), + }), + postForBlob: (...args: unknown[]) => mockPostForBlob(...args), + downloadBlob: (...args: unknown[]) => mockDownloadBlob(...args), +})) + +const request: ReportRunRequest = { + parameters: { Dept: ["VME"] }, + page: 1, + perPage: 25, + sortBy: null, + sortDescending: false, + search: null, +} + +describe("catalog", () => { + it("returns the user's reports", async () => { + expect.hasAssertions() + const catalog = [{ slug: roster.slug, title: roster.title, description: null, area: "Personnel" }] + mockGet.mockResolvedValue({ success: true, result: catalog }) + + await expect(reportBuilderService.getCatalog()).resolves.toStrictEqual(catalog) + expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/report-builder$/u)) + }) + + it.each([ + { success: false, result: null }, + { success: true, result: { slug: "x" } }, + ])("returns null when the request fails or isn't a list (%j)", async (response) => { + expect.hasAssertions() + mockGet.mockResolvedValue(response) + + await expect(reportBuilderService.getCatalog()).resolves.toBeNull() + }) +}) + +describe("definition", () => { + it("returns the report's definition", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result: roster }) + + await expect(reportBuilderService.getDefinition(roster.slug)).resolves.toStrictEqual(roster) + expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(new RegExp(`report-builder/${roster.slug}$`, "u"))) + }) + + it("returns null when the report isn't available", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: false, result: null }) + + await expect(reportBuilderService.getDefinition("x")).resolves.toBeNull() + }) +}) + +describe("run", () => { + it("posts the request and returns the rows", async () => { + expect.hasAssertions() + const result = resultOf([{ Name: "Ada", Salary: 1 }]) + mockPost.mockResolvedValue({ success: true, result }) + + await expect(reportBuilderService.run(roster.slug, request)).resolves.toStrictEqual({ result, errors: [] }) + expect(mockPost).toHaveBeenCalledWith(expect.stringMatching(/\/run$/u), request) + }) + + it("returns the server's messages", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: false, result: null, errors: ["Department is required.", ""] }) + + await expect(reportBuilderService.run(roster.slug, request)).resolves.toStrictEqual({ + result: null, + errors: ["Department is required."], + }) + }) + + it("explains a failure that came without messages", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: false, result: null, errors: null }) + + const outcome = await reportBuilderService.run(roster.slug, request) + + expect(outcome.errors).toStrictEqual(["The report couldn't be run. Please try again later."]) + }) +}) + +describe("download", () => { + it("saves the file under the server's name", async () => { + expect.hasAssertions() + const blob = new Blob(["xlsx"]) + mockPostForBlob.mockResolvedValue({ blob, filename: "Faculty roster.xlsx" }) + + await expect(reportBuilderService.exportReport(roster, "xlsx", request)).resolves.toBe("downloaded") + expect(mockPostForBlob).toHaveBeenCalledWith(expect.stringMatching(/\/export\/xlsx$/u), request) + expect(mockDownloadBlob).toHaveBeenCalledWith(blob, "Faculty roster.xlsx") + }) + + it("names the file after the report when the server doesn't", async () => { + expect.hasAssertions() + mockPostForBlob.mockResolvedValue({ blob: new Blob(["pdf"]), filename: null }) + + await reportBuilderService.exportReport(roster, "pdf", request) + + expect(mockDownloadBlob).toHaveBeenCalledWith(expect.any(Blob), "Faculty roster.pdf") + }) + + it("saves nothing when the report has no rows", async () => { + expect.hasAssertions() + mockPostForBlob.mockResolvedValue({ blob: new Blob([]), filename: null }) + + await expect(reportBuilderService.exportReport(roster, "pdf", request)).resolves.toBe("empty") + expect(mockDownloadBlob).not.toHaveBeenCalled() + }) + + it("reports a failed download", async () => { + expect.hasAssertions() + mockPostForBlob.mockRejectedValue(new Error("Forbidden")) + + await expect(reportBuilderService.exportReport(roster, "pdf", request)).resolves.toBe("failed") + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-builder-table.test.ts b/VueApp/src/shared/report-builder/__tests__/report-builder-table.test.ts new file mode 100644 index 000000000..4847fc5dd --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-table.test.ts @@ -0,0 +1,139 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportBuilderTable from "../ReportBuilderTable.vue" +import type { ReportPagination } from "../use-report-builder" +import { roster } from "./report-builder-fixtures" + +const pagination: ReportPagination = { page: 1, rowsPerPage: 25, sortBy: null, descending: false, rowsNumber: 2 } + +function mountTable(overrides: Partial = {}, paginate = true) { + return mount(ReportBuilderTable, { + props: { + columns: roster.columns, + rows: [ + { Name: "Ada", Salary: 1234.5 }, + { Name: "Bo", Salary: null }, + ], + pagination: { ...pagination, ...overrides }, + paginate, + title: "Faculty roster", + }, + global: { plugins: [[Quasar, {}]] }, + }) +} + +function table(wrapper: ReturnType) { + return wrapper.findComponent({ name: "QTable" }) +} + +describe("report table", () => { + it("shows each row's values formatted by column", () => { + expect.hasAssertions() + + const cells = mountTable() + .findAll("tbody tr") + .map((row) => row.findAll("td").map((cell) => cell.text())) + + expect(cells).toStrictEqual([ + ["Ada", "$1,234.50"], + ["Bo", ""], + ]) + }) + + it("lines numbers up on the right and sorts only sortable columns", () => { + expect.hasAssertions() + + const columns = table(mountTable()).props("columns") as { align: string; sortable: boolean }[] + + expect(columns.map((column) => [column.align, column.sortable])).toStrictEqual([ + ["left", true], + ["right", false], + ]) + }) + + it("asks the report for the page and sort the user picks", () => { + expect.hasAssertions() + const wrapper = mountTable() + + table(wrapper).vm.$emit("request", { + pagination: { page: 2, rowsPerPage: 50, sortBy: "Name", descending: true }, + }) + + expect(wrapper.emitted("request")).toStrictEqual([ + [{ page: 2, rowsPerPage: 50, sortBy: "Name", descending: true }], + ]) + }) + + it.each([ + { from: "unsorted", sortBy: null, descending: false, next: { sortBy: "Name", descending: false } }, + { from: "ascending", sortBy: "Name", descending: false, next: { sortBy: "Name", descending: true } }, + { from: "descending", sortBy: "Name", descending: true, next: { sortBy: "Name", descending: false } }, + ])("flips the sort when the $from column's heading is clicked", async ({ sortBy, descending, next }) => { + expect.hasAssertions() + const wrapper = mountTable({ sortBy, descending }) + + await wrapper.get("thead th").trigger("click") + + expect(wrapper.emitted("request")).toStrictEqual([[{ page: 1, rowsPerPage: 25, ...next }]]) + }) + + it("follows the report's sort after a request, so the next click flips it", async () => { + expect.hasAssertions() + const wrapper = mountTable() + await wrapper.get("thead th").trigger("click") + + await wrapper.setProps({ pagination: { ...pagination, sortBy: "Name", descending: false } }) + await wrapper.get("thead th").trigger("click") + + expect(wrapper.emitted<[ReportPagination]>("request")?.at(-1)?.[0]).toMatchObject({ + sortBy: "Name", + descending: true, + }) + }) + + it("shows the page the report is on", async () => { + expect.hasAssertions() + const wrapper = mountTable({ rowsNumber: 60 }) + + await wrapper.setProps({ pagination: { ...pagination, page: 2, rowsNumber: 60 } }) + + expect(wrapper.text()).toContain("26–50 of 60") + }) + + it("fills in what the table leaves out of a request", () => { + expect.hasAssertions() + const wrapper = mountTable() + + table(wrapper).vm.$emit("request", { pagination: {} }) + + expect(wrapper.emitted("request")).toStrictEqual([ + [{ page: 1, rowsPerPage: 25, sortBy: null, descending: false }], + ]) + }) + + it.each([ + [25, [10, 25, 50, 100, 250, 500]], + [30, [10, 25, 30, 50, 100, 250, 500]], + [0, [10, 25, 50, 100, 250, 500]], + ])("offers the usual page sizes plus the report's own (%i)", (rowsPerPage, expected) => { + expect.hasAssertions() + + expect(table(mountTable({ rowsPerPage })).props("rowsPerPageOptions")).toStrictEqual(expected) + }) + + it("hides the pager and scrolls instead for an unpaginated report", () => { + expect.hasAssertions() + + const props = table(mountTable({ rowsPerPage: 0 }, false)).props() + + expect([props.hidePagination, props.virtualScroll]).toStrictEqual([true, true]) + }) + + it("names its scrolling region after the report", () => { + expect.hasAssertions() + + const region = mountTable().find(".q-table__middle.scroll") + + expect([region.attributes("role"), region.attributes("aria-label")]).toStrictEqual(["region", "Faculty roster"]) + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts b/VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts new file mode 100644 index 000000000..392a915f1 --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts @@ -0,0 +1,75 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportChoiceField from "../ReportChoiceField.vue" +import { deptParameter } from "./report-builder-fixtures" + +const choices = deptParameter.choices! + +function mountField(multiple = false) { + return mount(ReportChoiceField, { + props: { modelValue: null, label: "Department", choices, multiple }, + global: { plugins: [[Quasar, {}]] }, + }) +} + +/** Types into the select the way QSelect reports it: a filter event with an update callback. */ +function filterTo(wrapper: ReturnType, text: string): void { + wrapper + .findComponent({ name: "QSelect" }) + .vm.$emit("filter", text, (update: () => void) => update(), vi.fn<() => void>()) +} + +describe("choice field", () => { + it("narrows the choices to the typed text, ignoring case", async () => { + expect.hasAssertions() + const wrapper = mountField() + + filterTo(wrapper, "PATH") + await wrapper.vm.$nextTick() + + expect(wrapper.findComponent({ name: "QSelect" }).props("options")).toStrictEqual([choices[1]]) + }) + + it("shows every choice when the text is cleared", async () => { + expect.hasAssertions() + const wrapper = mountField() + + filterTo(wrapper, "path") + filterTo(wrapper, " ") + await wrapper.vm.$nextTick() + + expect(wrapper.findComponent({ name: "QSelect" }).props("options")).toStrictEqual(choices) + }) + + it("follows a new list of choices", async () => { + expect.hasAssertions() + const wrapper = mountField(true) + + await wrapper.setProps({ choices: [choices[0]!] }) + + expect(wrapper.findComponent({ name: "QSelect" }).props("options")).toStrictEqual([choices[0]]) + }) + + it("passes the picked value on", () => { + expect.hasAssertions() + const wrapper = mountField() + + wrapper.findComponent({ name: "QSelect" }).vm.$emit("update:modelValue", "VME") + + expect(wrapper.emitted("update:modelValue")).toStrictEqual([["VME"]]) + }) + + // QSelect virtualizes its option list, which jsdom's layout never populates, so a mount of + // the real component never renders the #no-option slot. Stub QSelect to render it directly. + it("says when nothing matches", () => { + expect.hasAssertions() + const QSelectStub = { name: "QSelect", template: `
` } + + const wrapper = mount(ReportChoiceField, { + props: { modelValue: null, label: "Department", choices }, + global: { plugins: [[Quasar, {}]], stubs: { QSelect: QSelectStub } }, + }) + + expect(wrapper.text()).toContain("No matching choices") + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/report-viewer.test.ts b/VueApp/src/shared/report-builder/__tests__/report-viewer.test.ts new file mode 100644 index 000000000..4f81def3e --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-viewer.test.ts @@ -0,0 +1,182 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import { ref } from "vue" +import ReportViewer from "../ReportViewer.vue" +import ReportBuilderForm from "../ReportBuilderForm.vue" +import ReportBuilderResults from "../ReportBuilderResults.vue" +import type { ReportRunResult, ReportViewerDefinition } from "../report-builder-types" +import { resultOf, roster } from "./report-builder-fixtures" + +/** + * ReportViewer only arranges what useReportBuilder provides, so the composable is replaced by + * plain refs the tests set directly. + */ + +const { state, calls } = vi.hoisted(() => ({ + state: {} as Record, + calls: { slug: null as (() => string) | null, options: null as Record | null }, +})) +vi.mock("../use-report-builder", () => ({ + useReportBuilder: (slug: () => string, options: Record) => { + calls.slug = slug + calls.options = options + return state + }, +})) + +function setState(overrides: Record = {}) { + const values = { + definition: ref(roster), + values: ref({ Name: null }), + result: ref(null), + errors: ref([]), + loading: ref(false), + running: ref(false), + exporting: ref(null), + nothingToExport: ref(false), + search: ref(""), + pagination: ref({ page: 1, rowsPerPage: 25, sortBy: null, descending: false, rowsNumber: 0 }), + canExport: ref(false), + ready: ref(true), + run: vi.fn<() => Promise>(), + changePage: vi.fn<() => Promise>(), + changeSearch: vi.fn<() => Promise>(), + exportAs: vi.fn<() => Promise>(), + } + Object.assign(state, values, overrides) + return values +} + +function mountViewer(slots: Record = {}) { + return mount(ReportViewer, { + props: { slug: roster.slug, params: { Name: "Ada" }, syncQuery: true }, + slots, + global: { plugins: [[Quasar, {}]] }, + }) +} + +describe("report viewer - states", () => { + it("announces that the report is loading", () => { + expect.hasAssertions() + setState({ loading: ref(true) }) + + expect(mountViewer().get("[role='status']").text()).toBe("Loading report") + }) + + it("explains a report that isn't available", () => { + expect.hasAssertions() + setState({ definition: ref(null) }) + + expect(mountViewer().text()).toContain("This report isn't available.") + }) + + it("shows the title, description and form", () => { + expect.hasAssertions() + setState() + const wrapper = mountViewer() + + expect(wrapper.get("h2").text()).toBe("Faculty roster") + expect(wrapper.text()).toContain("Current faculty by department.") + expect(wrapper.findComponent(ReportBuilderForm).exists()).toBeTruthy() + }) + + it("lets the page supply its own heading", () => { + expect.hasAssertions() + setState() + + const wrapper = mountViewer({ heading: `` }) + + expect([wrapper.get("h1").text(), wrapper.find("h2").exists()]).toStrictEqual(["Faculty roster!", false]) + }) + + it("gives the page's heading no title for a report that isn't available", () => { + expect.hasAssertions() + setState({ definition: ref(null) }) + + const wrapper = mountViewer({ + heading: ``, + }) + + expect(wrapper.get("h1").text()).toBe("None") + }) + + it("shows the report's notice and leaves out an empty form", () => { + expect.hasAssertions() + setState({ definition: ref({ ...roster, sensitiveNotice: "Confidential", description: null, parameters: [] }) }) + const wrapper = mountViewer() + + expect(wrapper.text()).toContain("Confidential") + expect(wrapper.findComponent(ReportBuilderForm).exists()).toBeFalsy() + }) + + it("lists the server's messages", () => { + expect.hasAssertions() + setState({ errors: ref(["Department is required.", "That page doesn't exist."]) }) + + expect( + mountViewer() + .findAll("li") + .map((item) => item.text()), + ).toStrictEqual(["Department is required.", "That page doesn't exist."]) + }) +}) + +describe("report viewer - wiring", () => { + it("loads the report by slug with the page's values and URL setting", () => { + expect.hasAssertions() + setState() + mountViewer() + + expect(calls.slug?.()).toBe(roster.slug) + const params = calls.options?.params as (() => unknown) | undefined + expect([params?.(), calls.options?.syncQuery]).toStrictEqual([{ Name: "Ada" }, true]) + }) + + it("asks for the required fields until they're filled", () => { + expect.hasAssertions() + setState({ ready: ref(false) }) + + expect(mountViewer().text()).toContain("Fill in the required fields to see the report.") + }) + + it("announces a run that hasn't shown rows yet", () => { + expect.hasAssertions() + setState({ running: ref(true) }) + + expect(mountViewer().get("[role=status]").text()).toBe("Running report") + }) + + it("runs the report when the form is submitted", () => { + expect.hasAssertions() + const { run } = setState() + + mountViewer().findComponent(ReportBuilderForm).vm.$emit("submit") + + expect(run).toHaveBeenCalledOnce() + }) + + it("keeps the form's values in the report state", () => { + expect.hasAssertions() + const { values } = setState() + + mountViewer().findComponent(ReportBuilderForm).vm.$emit("update:modelValue", { Name: "Bo" }) + + expect(values.value).toStrictEqual({ Name: "Bo" }) + }) + + it("shows the rows with the report's settings and passes the table's requests on", () => { + expect.hasAssertions() + const { changePage, changeSearch } = setState({ result: ref(resultOf([{ Name: "Ada" }])) }) + const results = mountViewer().findComponent(ReportBuilderResults) + + results.vm.$emit("request", { page: 2 }) + results.vm.$emit("search", "ada") + + expect([results.props("allowExcel"), results.props("allowPdf"), results.props("paginate")]).toStrictEqual([ + true, + false, + true, + ]) + expect([changePage.mock.lastCall, changeSearch.mock.lastCall]).toStrictEqual([[{ page: 2 }], ["ada"]]) + }) +}) diff --git a/VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts b/VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts new file mode 100644 index 000000000..48a9f294d --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts @@ -0,0 +1,405 @@ +import { flushPromises } from "@vue/test-utils" +import { ref } from "vue" +import { useReportBuilder } from "../use-report-builder" +import { reportBuilderService } from "../report-builder-service" +import type { ReportViewerDefinition } from "../report-builder-types" +import { resultOf, roster, textParameter } from "./report-builder-fixtures" + +const { route, mockReplace } = vi.hoisted(() => ({ + route: { query: {} as Record }, + mockReplace: vi.fn<(...args: unknown[]) => Promise>(), +})) +vi.mock("vue-router", () => ({ + useRoute: () => route, + useRouter: () => ({ replace: mockReplace }), +})) +vi.mock("../report-builder-service", () => ({ + reportBuilderService: { + getDefinition: vi.fn<(...args: unknown[]) => unknown>(), + run: vi.fn<(...args: unknown[]) => unknown>(), + exportReport: vi.fn<(...args: unknown[]) => unknown>(), + }, +})) + +const rows = resultOf([{ Name: "Ada", Salary: 1 }]) +const optionalOnly: ReportViewerDefinition = { ...roster, parameters: [textParameter] } + +function reset(definition: ReportViewerDefinition | null, query: Record = {}): void { + route.query = query + mockReplace.mockResolvedValue() + vi.mocked(reportBuilderService.getDefinition).mockResolvedValue(definition) + vi.mocked(reportBuilderService.run).mockResolvedValue({ result: rows, errors: [] }) + vi.mocked(reportBuilderService.exportReport).mockResolvedValue("downloaded") +} + +/** A promise the test settles by hand, to hold a request in flight. */ +function deferred() { + let settle: ((value: T) => void) | null = null + // eslint-disable-next-line avoid-new -- a promise the test settles by hand + const promise = new Promise((resolve) => { + settle = resolve + }) + return { promise, resolve: (value: T) => settle?.(value) } +} + +function lastRequest() { + return vi.mocked(reportBuilderService.run).mock.lastCall?.[1] +} + +describe("report builder state - loading", () => { + it("loads the report and fills the form from the query and defaults", async () => { + expect.hasAssertions() + reset(roster, { Name: "Ada" }) + + const report = useReportBuilder(roster.slug) + await flushPromises() + + expect(report.loading.value).toBeFalsy() + expect(report.values.value).toStrictEqual({ Name: "Ada", Dept: [], Hired: "2026-01-01" }) + expect(report.pagination.value).toStrictEqual({ + page: 1, + rowsPerPage: 25, + sortBy: "Name", + descending: false, + rowsNumber: 1, + }) + }) + + it("runs straight away when every required field has a value", async () => { + expect.hasAssertions() + reset(roster) + + const report = useReportBuilder(roster.slug) + await flushPromises() + + expect(report.result.value).toStrictEqual(rows) + expect(lastRequest()).toStrictEqual({ + parameters: { Hired: ["2026-01-01"] }, + page: 1, + perPage: 25, + sortBy: "Name", + sortDescending: false, + search: null, + }) + }) + + it("waits for the user when a required field is empty", async () => { + expect.hasAssertions() + reset({ ...roster, parameters: [{ ...roster.parameters[2]!, defaultValue: null }] }) + + useReportBuilder(roster.slug) + await flushPromises() + + expect(reportBuilderService.run).not.toHaveBeenCalled() + }) + + it("marks a report that isn't available", async () => { + expect.hasAssertions() + reset(null) + + const report = useReportBuilder("missing") + await flushPromises() + + expect(report.notFound.value).toBeTruthy() + expect(report.values.value).toStrictEqual({}) + }) + + it("uses the embedding page's values and leaves the URL alone", async () => { + expect.hasAssertions() + reset(optionalOnly, { Name: "From the URL" }) + + const report = useReportBuilder(roster.slug, { params: { Name: "Given" }, syncQuery: false }) + await flushPromises() + await report.run() + + expect(report.values.value).toStrictEqual({ Name: "Given" }) + expect(mockReplace).not.toHaveBeenCalled() + }) + + it("shows all rows of an unpaginated report", async () => { + expect.hasAssertions() + reset({ ...optionalOnly, paginate: false }) + + const report = useReportBuilder(roster.slug) + await flushPromises() + + expect(report.pagination.value.rowsPerPage).toBe(0) + expect(lastRequest()?.perPage).toBeNull() + }) + + it("ignores a definition that arrives after the slug changed", async () => { + expect.hasAssertions() + reset(roster) + const first = deferred() + vi.mocked(reportBuilderService.getDefinition).mockReturnValueOnce(first.promise) + const slug = ref("first") + + const report = useReportBuilder(slug) + slug.value = "second" + await flushPromises() + first.resolve({ ...roster, title: "Stale" }) + await flushPromises() + + expect(report.definition.value?.title).toBe("Faculty roster") + }) +}) + +describe("report builder state - running", () => { + it("runs from the first page and records the values in the URL", async () => { + expect.hasAssertions() + reset(optionalOnly) + const report = useReportBuilder(roster.slug) + await flushPromises() + report.pagination.value = { ...report.pagination.value, page: 3 } + report.values.value = { Name: "Ada" } + + await report.run() + + expect(mockReplace).toHaveBeenCalledWith({ query: { Name: "Ada" } }) + expect(lastRequest()).toMatchObject({ parameters: { Name: ["Ada"] }, page: 1 }) + }) + + it("lists the server's messages instead of rows", async () => { + expect.hasAssertions() + reset(optionalOnly) + vi.mocked(reportBuilderService.run).mockResolvedValue({ result: null, errors: ["Department is required."] }) + + const report = useReportBuilder(roster.slug) + await flushPromises() + + expect(report.result.value).toBeNull() + expect(report.errors.value).toStrictEqual(["Department is required."]) + }) + + it("asks for the page and sort the table picked", async () => { + expect.hasAssertions() + reset(optionalOnly) + const report = useReportBuilder(roster.slug) + await flushPromises() + + await report.changePage({ page: 2, rowsPerPage: 50, sortBy: "Salary", descending: true }) + + expect(lastRequest()).toMatchObject({ page: 2, perPage: 50, sortBy: "Salary", sortDescending: true }) + }) + + it("searches from the first page", async () => { + expect.hasAssertions() + reset(optionalOnly) + const report = useReportBuilder(roster.slug) + await flushPromises() + await report.changePage({ page: 4, rowsPerPage: 25, sortBy: null, descending: false }) + + await report.changeSearch(" ada ") + + expect(lastRequest()).toMatchObject({ page: 1, search: "ada" }) + }) + + it("clears the search", async () => { + expect.hasAssertions() + reset(optionalOnly) + const report = useReportBuilder(roster.slug) + await flushPromises() + + await report.changeSearch(null) + + expect(lastRequest()?.search).toBeNull() + }) + + it("counts a further page when a source that can't count fills this one", async () => { + expect.hasAssertions() + reset(optionalOnly) + const full = resultOf( + Array.from({ length: 25 }, (_, index) => ({ Name: `P${index}` })), + { + totalRows: null, + page: 2, + }, + ) + vi.mocked(reportBuilderService.run).mockResolvedValue({ result: full, errors: [] }) + + const report = useReportBuilder(roster.slug) + await flushPromises() + + expect(report.pagination.value.rowsNumber).toBe(51) + }) + + it("doesn't assume a further page when a source that can't count fills less than a page", async () => { + expect.hasAssertions() + reset(optionalOnly) + const partial = resultOf( + Array.from({ length: 10 }, (_, index) => ({ Name: `P${index}` })), + { totalRows: null, page: 2 }, + ) + vi.mocked(reportBuilderService.run).mockResolvedValue({ result: partial, errors: [] }) + + const report = useReportBuilder(roster.slug) + await flushPromises() + + expect(report.pagination.value.rowsNumber).toBe(35) + }) + + it("keeps only the latest run's rows", async () => { + expect.hasAssertions() + reset(optionalOnly) + const report = useReportBuilder(roster.slug) + await flushPromises() + const slow = deferred<{ result: typeof rows; errors: [] }>() + vi.mocked(reportBuilderService.run).mockReturnValueOnce(slow.promise) + + const stale = report.changePage({ page: 2, rowsPerPage: 25, sortBy: null, descending: false }) + await report.changePage({ page: 3, rowsPerPage: 25, sortBy: null, descending: false }) + slow.resolve({ result: resultOf([{ Name: "Stale" }]), errors: [] }) + await stale + + expect(report.result.value).toStrictEqual(rows) + }) + + it("does nothing before the report has loaded", async () => { + expect.hasAssertions() + reset(null) + const report = useReportBuilder("missing") + await flushPromises() + + await report.run() + await report.changePage({ page: 2, rowsPerPage: 25, sortBy: null, descending: false }) + await report.exportAs("xlsx") + + expect(reportBuilderService.run).not.toHaveBeenCalled() + expect(reportBuilderService.exportReport).not.toHaveBeenCalled() + }) +}) + +/** Fakes only the timers the auto-run waits on; flushPromises keeps its own scheduler. */ +function fakeDebounce(): void { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) +} + +async function waitForAutoRun(): Promise { + await vi.runOnlyPendingTimersAsync() + await flushPromises() +} + +describe("report builder state - running when the form changes", () => { + it("runs again once the form settles, from the first page and with the last values", async () => { + expect.hasAssertions() + fakeDebounce() + reset(optionalOnly) + const report = useReportBuilder(roster.slug) + await flushPromises() + report.pagination.value = { ...report.pagination.value, page: 3 } + + report.values.value = { Name: "A" } + await flushPromises() + report.values.value = { Name: "Ada" } + await waitForAutoRun() + vi.useRealTimers() + + expect(reportBuilderService.run).toHaveBeenCalledTimes(2) + expect(lastRequest()).toMatchObject({ parameters: { Name: ["Ada"] }, page: 1 }) + expect(mockReplace).toHaveBeenLastCalledWith({ query: { Name: "Ada" } }) + }) + + it("doesn't run again for the values it loaded with or just ran", async () => { + expect.hasAssertions() + fakeDebounce() + reset(optionalOnly) + const report = useReportBuilder(roster.slug) + await waitForAutoRun() + report.values.value = { Name: "Ada" } + await report.run() + await waitForAutoRun() + vi.useRealTimers() + + expect(reportBuilderService.run).toHaveBeenCalledTimes(2) + }) + + it("clears the rows, and drops a run on its way, when a required field is emptied", async () => { + expect.hasAssertions() + fakeDebounce() + reset(roster) + const report = useReportBuilder(roster.slug) + await flushPromises() + const slow = deferred<{ result: typeof rows; errors: [] }>() + vi.mocked(reportBuilderService.run).mockReturnValueOnce(slow.promise) + const inFlight = report.changePage({ page: 2, rowsPerPage: 25, sortBy: "Name", descending: false }) + + report.values.value = { ...report.values.value, Hired: null } + await waitForAutoRun() + slow.resolve({ result: resultOf([{ Name: "Stale" }]), errors: [] }) + await inFlight + vi.useRealTimers() + + expect([report.ready.value, report.result.value, report.running.value]).toStrictEqual([false, null, false]) + expect(reportBuilderService.run).toHaveBeenCalledTimes(2) + }) + + it("clears the rows without touching the URL when the page doesn't sync the query", async () => { + expect.hasAssertions() + fakeDebounce() + reset(roster) + const report = useReportBuilder(roster.slug, { syncQuery: false }) + await flushPromises() + mockReplace.mockClear() + + report.values.value = { ...report.values.value, Hired: null } + await waitForAutoRun() + vi.useRealTimers() + + expect(report.result.value).toBeNull() + expect(mockReplace).not.toHaveBeenCalled() + }) +}) + +describe("report builder state - downloads", () => { + it("downloads the rows on screen, not the form's newer values", async () => { + expect.hasAssertions() + reset(optionalOnly, { Name: "Ada" }) + const report = useReportBuilder(roster.slug) + await flushPromises() + report.values.value = { Name: "Edited" } + + await report.exportAs("xlsx") + + expect(reportBuilderService.exportReport).toHaveBeenCalledWith( + expect.objectContaining({ slug: roster.slug }), + "xlsx", + expect.objectContaining({ parameters: { Name: ["Ada"] } }), + ) + expect(report.exporting.value).toBeNull() + }) + + it("says when there was nothing to download", async () => { + expect.hasAssertions() + reset(optionalOnly) + vi.mocked(reportBuilderService.exportReport).mockResolvedValue("empty") + const report = useReportBuilder(roster.slug) + await flushPromises() + + await report.exportAs("pdf") + + expect(report.nothingToExport.value).toBeTruthy() + }) + + it("can download only when there are rows", async () => { + expect.hasAssertions() + reset(optionalOnly) + vi.mocked(reportBuilderService.run).mockResolvedValue({ result: resultOf([]), errors: [] }) + + const report = useReportBuilder(roster.slug) + await flushPromises() + + expect(report.canExport.value).toBeFalsy() + }) + + it("has nothing to download after a failed run", async () => { + expect.hasAssertions() + reset(optionalOnly) + vi.mocked(reportBuilderService.run).mockResolvedValue({ result: null, errors: ["No."] }) + const report = useReportBuilder(roster.slug) + await flushPromises() + + await report.exportAs("pdf") + + expect(reportBuilderService.exportReport).not.toHaveBeenCalled() + }) +}) diff --git a/VueApp/src/shared/report-builder/report-builder-catalog.ts b/VueApp/src/shared/report-builder/report-builder-catalog.ts new file mode 100644 index 000000000..7cbf9daa2 --- /dev/null +++ b/VueApp/src/shared/report-builder/report-builder-catalog.ts @@ -0,0 +1,28 @@ +import type { ReportCatalogItem } from "./report-builder-types" + +/** Reports without an area are listed last, under this heading. */ +const OTHER_AREA = "Other reports" + +interface ReportArea { + area: string + reports: ReportCatalogItem[] +} + +/** + * The reports grouped by area, areas in alphabetical order with "Other reports" last. The server + * already sorts by area then title, so each group keeps that order. + */ +function groupByArea(reports: ReportCatalogItem[]): ReportArea[] { + const groups = new Map() + for (const report of reports) { + const area = report.area?.trim() || OTHER_AREA + groups.set(area, [...(groups.get(area) ?? []), report]) + } + const named = [...groups.keys()].filter((area) => area !== OTHER_AREA) + named.sort((a, b) => a.localeCompare(b)) + const order = groups.has(OTHER_AREA) ? [...named, OTHER_AREA] : named + return order.map((area) => ({ area, reports: groups.get(area) ?? [] })) +} + +export { OTHER_AREA, groupByArea } +export type { ReportArea } diff --git a/VueApp/src/shared/report-builder/report-builder-format.ts b/VueApp/src/shared/report-builder/report-builder-format.ts new file mode 100644 index 000000000..3bf8e0496 --- /dev/null +++ b/VueApp/src/shared/report-builder/report-builder-format.ts @@ -0,0 +1,102 @@ +import type { ReportCellValue, ReportColumnFormat } from "./report-builder-types" + +/** + * Formats values for the screen the way the server formats them for downloads + * (ReportCellFormatter), so the table and the files agree: US English separators, dates as + * MM/dd/yyyy, and percent columns holding fractions (0.25 shows as 25%). + */ + +const LOCALE = "en-US" +const MAX_DECIMALS = 2 +const CURRENCY_DECIMALS = 2 +const ISO_DATE_TIME = /^(?\d{4})-(?\d{2})-(?\d{2})(?:T(?\d{2}):(?\d{2}))?/u +const NUMERIC_FORMATS: ReadonlySet = new Set(["Number", "Currency", "Percent"]) +const YES_WORDS = new Set(["y", "yes", "true", "1"]) +const NO_WORDS = new Set(["n", "no", "false", "0"]) +const NOON = 12 + +const NUMBER_FORMATS: Record<"Number" | "Currency" | "Percent", Intl.NumberFormat> = { + Number: new Intl.NumberFormat(LOCALE, { maximumFractionDigits: MAX_DECIMALS }), + Currency: new Intl.NumberFormat(LOCALE, { + style: "currency", + currency: "USD", + minimumFractionDigits: CURRENCY_DECIMALS, + maximumFractionDigits: CURRENCY_DECIMALS, + }), + Percent: new Intl.NumberFormat(LOCALE, { style: "percent", maximumFractionDigits: MAX_DECIMALS }), +} + +/** Whether the format lines its values up on the right. */ +function isNumericFormat(format: ReportColumnFormat): boolean { + return NUMERIC_FORMATS.has(format) +} + +function formatNumber(value: number, format: ReportColumnFormat): string { + const style = format === "Currency" || format === "Percent" ? format : "Number" + return NUMBER_FORMATS[style].format(value) +} + +function formatTime(hour: number, minute: string): string { + const twelveHour = hour % NOON === 0 ? NOON : hour % NOON + return `${twelveHour}:${minute} ${hour < NOON ? "AM" : "PM"}` +} + +/** + * The value's ISO date parts, when the column should reformat it: a text column only reformats + * full date-times, which only real date values arrive as, never a date-only text that merely + * looks like one. + */ +function isoDateParts(value: string, format: ReportColumnFormat) { + const parts = ISO_DATE_TIME.exec(value)?.groups + const isDateFormat = format === "Date" || format === "DateTime" + return parts && (isDateFormat || parts.hour !== undefined) ? parts : undefined +} + +/** + * An ISO date or date-time as MM/dd/yyyy, with the time when the column shows times or, for a + * text column, when there is one. Null when the text isn't an ISO date the column should reformat. + */ +function formatIsoDate(value: string, format: ReportColumnFormat): string | null { + const parts = isoDateParts(value, format) + if (!parts) { + return null + } + const date = `${parts.month}/${parts.day}/${parts.year}` + const hour = Number(parts.hour ?? "0") + const minute = parts.minute ?? "00" + const hasTime = hour !== 0 || minute !== "00" + const showTime = format === "DateTime" || (format === "Text" && hasTime) + return showTime ? `${date} ${formatTime(hour, minute)}` : date +} + +function formatYesNo(value: string | number | boolean): string { + if (typeof value === "boolean") { + return value ? "Yes" : "No" + } + if (typeof value === "number") { + return value === 0 ? "No" : "Yes" + } + const word = value.trim().toLowerCase() + if (YES_WORDS.has(word)) { + return "Yes" + } + return NO_WORDS.has(word) ? "No" : value +} + +function formatCell(value: ReportCellValue | undefined, format: ReportColumnFormat): string { + if (value === null || value === undefined) { + return "" + } + if (format === "YesNo") { + return formatYesNo(value) + } + if (typeof value === "boolean") { + return value ? "Yes" : "No" + } + if (typeof value === "number") { + return formatNumber(value, format) + } + return formatIsoDate(value, format) ?? value +} + +export { formatCell, isNumericFormat } diff --git a/VueApp/src/shared/report-builder/report-builder-query.ts b/VueApp/src/shared/report-builder/report-builder-query.ts new file mode 100644 index 000000000..f59a9eb00 --- /dev/null +++ b/VueApp/src/shared/report-builder/report-builder-query.ts @@ -0,0 +1,77 @@ +import type { LocationQuery, LocationQueryRaw } from "vue-router" +import type { ReportParameterValue, ReportParameterValues, ReportViewerParameter } from "./report-builder-types" + +/** + * Moves parameter values between the form, the URL query and the run request, so a report page + * can be bookmarked or shared with its parameters filled in. + */ + +type QueryValue = LocationQuery[string] + +function queryStrings(value: QueryValue | undefined): string[] { + const list = Array.isArray(value) ? value : [value] + return list.filter((item): item is string => typeof item === "string" && item !== "") +} + +/** True for a value the user hasn't filled in; such values are left out of queries and requests. */ +function isEmptyValue(value: ReportParameterValue | undefined): boolean { + return value === null || value === undefined || value === "" || (Array.isArray(value) && value.length === 0) +} + +/** A list of strings as the parameter holds it: all of them for multi-choice, otherwise the first. */ +function toParameterValue(parameter: ReportViewerParameter, values: string[]): ReportParameterValue { + if (parameter.type === "MultiChoice") { + return values + } + return values[0] ?? null +} + +/** + * The form's starting values. Each comes from the first source that has it: the URL query, the + * values the embedding page passed, then the report's default. + */ +function initialValues( + parameters: ReportViewerParameter[], + query: LocationQuery, + given: Record = {}, +): ReportParameterValues { + return Object.fromEntries( + parameters.map((parameter) => { + const fromQuery = queryStrings(query[parameter.name]) + const fromGiven = queryStrings(given[parameter.name]) + const fromDefault = parameter.defaultValue === null ? [] : [parameter.defaultValue] + const first = [fromQuery, fromGiven, fromDefault].find((values) => values.length > 0) ?? [] + return [parameter.name, toParameterValue(parameter, first)] + }), + ) +} + +/** True when every required parameter has a value, so the report can run without the user. */ +function hasRequiredValues(parameters: ReportViewerParameter[], values: ReportParameterValues): boolean { + return parameters.every((parameter) => !parameter.required || !isEmptyValue(values[parameter.name])) +} + +/** The filled-in values, each as a list. Names the report doesn't have are never sent. */ +function toRequestParameters( + parameters: ReportViewerParameter[], + values: ReportParameterValues, +): Record { + return Object.fromEntries( + parameters + .map((parameter) => [parameter.name, values[parameter.name]] as const) + .filter(([, value]) => !isEmptyValue(value)) + .map(([name, value]) => [name, Array.isArray(value) ? value : [String(value)]]), + ) +} + +/** The filled-in values as query parameters; lists repeat the key. */ +function toQuery(parameters: ReportViewerParameter[], values: ReportParameterValues): LocationQueryRaw { + return Object.fromEntries( + Object.entries(toRequestParameters(parameters, values)).map(([name, list]) => [ + name, + list.length === 1 ? list[0] : list, + ]), + ) +} + +export { hasRequiredValues, initialValues, isEmptyValue, toQuery, toRequestParameters } diff --git a/VueApp/src/shared/report-builder/report-builder-service.ts b/VueApp/src/shared/report-builder/report-builder-service.ts new file mode 100644 index 000000000..773319026 --- /dev/null +++ b/VueApp/src/shared/report-builder/report-builder-service.ts @@ -0,0 +1,80 @@ +import { downloadBlob, postForBlob, useFetch } from "@/composables/ViperFetch" +import type { + ReportCatalogItem, + ReportExportFormat, + ReportRunRequest, + ReportRunResult, + ReportViewerDefinition, +} from "./report-builder-types" + +const { get, post } = useFetch() + +const RUN_FAILED = "The report couldn't be run. Please try again later." + +/** A finished run has a result and no errors; a refused or failed run has messages instead. */ +type ReportRunOutcome = { result: ReportRunResult; errors: [] } | { result: null; errors: string[] } + +/** + * What became of a download: saved, nothing to save (the report had no rows), or failed, in + * which case the shared error handler has already told the user why. + */ +type ReportExportOutcome = "downloaded" | "empty" | "failed" + +/** Client for the Report Builder viewer API. */ +class ReportBuilderService { + private baseUrl = `${import.meta.env.VITE_API_URL}report-builder` + + /** + * The reports the signed-in user may view; the server filters by permission. Null when the + * request fails, so the page can tell a failed load apart from having no reports. + */ + async getCatalog(): Promise { + const r = await get(this.baseUrl) + return r.success && Array.isArray(r.result) ? (r.result as ReportCatalogItem[]) : null + } + + /** + * A report's form fields and columns. Null when the report doesn't exist, was deleted, or the + * user may not view it; the page treats all three alike. + */ + async getDefinition(slug: string): Promise { + const r = await get(this.reportUrl(slug)) + return r.success && r.result ? (r.result as ReportViewerDefinition) : null + } + + async run(slug: string, request: ReportRunRequest): Promise { + const r = await post(`${this.reportUrl(slug)}/run`, request) + if (r.success && r.result) { + return { result: r.result as ReportRunResult, errors: [] } + } + const messages = ((r.errors ?? []) as string[]).filter((message) => message !== "") + return { result: null, errors: messages.length > 0 ? messages : [RUN_FAILED] } + } + + /** Runs the report on the server and saves it in the chosen format. */ + async exportReport( + report: Pick, + format: ReportExportFormat, + request: ReportRunRequest, + ): Promise { + try { + const { blob, filename } = await postForBlob(`${this.reportUrl(report.slug)}/export/${format}`, request) + // The server answers 204 No Content when there are no rows to download. + if (blob.size === 0) { + return "empty" + } + downloadBlob(blob, filename ?? `${report.title}.${format}`) + return "downloaded" + } catch { + return "failed" + } + } + + private reportUrl(slug: string): string { + return `${this.baseUrl}/${encodeURIComponent(slug)}` + } +} + +const reportBuilderService = new ReportBuilderService() +export { reportBuilderService } +export type { ReportRunOutcome } diff --git a/VueApp/src/shared/report-builder/report-builder-types.ts b/VueApp/src/shared/report-builder/report-builder-types.ts new file mode 100644 index 000000000..d592e0617 --- /dev/null +++ b/VueApp/src/shared/report-builder/report-builder-types.ts @@ -0,0 +1,101 @@ +/** + * Types mirroring the Report Builder API (web/Areas/ReportBuilder). Enum values arrive as their + * C# names. + */ + +type ReportColumnFormat = "Text" | "Number" | "Currency" | "Percent" | "Date" | "DateTime" | "YesNo" +type ReportParameterType = "Text" | "Number" | "Date" | "Boolean" | "Choice" | "MultiChoice" +type ReportExportFormat = "xlsx" | "pdf" + +/** A form value: a list for multi-choice parameters, otherwise one string (dates as "yyyy-MM-dd"). */ +type ReportParameterValue = string | string[] | null +type ReportParameterValues = Record + +/** A cell as the API sends it; dates and times are ISO strings. */ +type ReportCellValue = string | number | boolean | null +type ReportRow = Record + +/** A report the signed-in user may view. */ +interface ReportCatalogItem { + slug: string + title: string + description: string | null + area: string | null +} + +interface ReportChoice { + value: string + label: string +} + +interface ReportResultColumn { + /** The source column; also the key of the value in each row. */ + name: string + label: string + format: ReportColumnFormat + sortable: boolean +} + +interface ReportViewerParameter { + name: string + label: string + type: ReportParameterType + required: boolean + defaultValue: string | null + /** The choices, for choice parameters; null for the others. */ + choices: ReportChoice[] | null +} + +interface ReportViewerDefinition { + slug: string + title: string + description: string | null + area: string | null + sensitiveNotice: string | null + paginate: boolean + pageSize: number + allowExcel: boolean + allowPdf: boolean + sortBy: string | null + sortDescending: boolean + columns: ReportResultColumn[] + parameters: ReportViewerParameter[] +} + +/** What a run asks for. Every parameter value is a list, so multi-choice parameters fit. */ +interface ReportRunRequest { + parameters: Record + page: number + perPage: number | null + sortBy: string | null + sortDescending: boolean + search: string | null +} + +interface ReportRunResult { + columns: ReportResultColumn[] + rows: ReportRow[] + page: number + perPage: number + /** Rows across all pages; null when the source can't say. */ + totalRows: number | null + /** True when the row cap cut the result short. */ + truncated: boolean +} + +export type { + ReportCatalogItem, + ReportCellValue, + ReportChoice, + ReportColumnFormat, + ReportExportFormat, + ReportParameterType, + ReportParameterValue, + ReportParameterValues, + ReportResultColumn, + ReportRow, + ReportRunRequest, + ReportRunResult, + ReportViewerDefinition, + ReportViewerParameter, +} diff --git a/VueApp/src/shared/report-builder/use-report-builder.ts b/VueApp/src/shared/report-builder/use-report-builder.ts new file mode 100644 index 000000000..7f7223411 --- /dev/null +++ b/VueApp/src/shared/report-builder/use-report-builder.ts @@ -0,0 +1,256 @@ +import { computed, ref, toValue, watch } from "vue" +import type { MaybeRefOrGetter } from "vue" +import { watchDebounced } from "@vueuse/core" +import { useRoute, useRouter } from "vue-router" +import { hasRequiredValues, initialValues, toQuery, toRequestParameters } from "./report-builder-query" +import { reportBuilderService } from "./report-builder-service" +import type { + ReportExportFormat, + ReportParameterValues, + ReportRunRequest, + ReportRunResult, + ReportViewerDefinition, +} from "./report-builder-types" + +/** The table's paging and sorting, in Quasar's QTable pagination shape. */ +interface ReportPagination { + page: number + rowsPerPage: number + sortBy: string | null + descending: boolean + rowsNumber: number +} + +interface ReportBuilderOptions { + /** Values for the form when the URL doesn't give them, such as from an embedding page. */ + params?: MaybeRefOrGetter | undefined> + /** + * Whether the form's values are written to and read from the URL query, so the page can be + * bookmarked. Off for an embedded report, whose page owns its own URL. + */ + syncQuery?: boolean +} + +const ALL_ROWS = 0 + +// How long the form must be still before a change runs the report, so typing a name doesn't +// send a request per keystroke. +const AUTO_RUN_DELAY_MS = 500 + +function emptyPagination(): ReportPagination { + return { page: 1, rowsPerPage: ALL_ROWS, sortBy: null, descending: false, rowsNumber: 0 } +} + +/** + * A row count for the table's pager. A source that can't count its rows still gets a next page + * when this one came back full. + */ +function rowsNumber(result: ReportRunResult, pagination: ReportPagination): number { + if (result.totalRows !== null) { + return result.totalRows + } + const before = (result.page - 1) * result.perPage + const more = pagination.rowsPerPage > 0 && result.rows.length === pagination.rowsPerPage ? 1 : 0 + return before + result.rows.length + more +} + +/** + * State for one admin-built report: loads its definition whenever the slug changes, fills the + * form from the URL query, the embedding page or the report's defaults, and runs, pages, sorts, + * searches and downloads it. A report whose required fields are all filled runs straight away, + * and runs again shortly after the form changes; emptying a required field clears the rows. + * Only the latest load and the latest run may update the state, so a slow reply never overwrites + * a newer one. + */ +// oxlint-disable-next-line max-lines-per-function -- one report's state and the actions on it belong together +export function useReportBuilder(slug: MaybeRefOrGetter, options: ReportBuilderOptions = {}) { + const route = useRoute() + const router = useRouter() + const syncQuery = options.syncQuery ?? true + + const definition = ref(null) + const values = ref({}) + const result = ref(null) + const errors = ref([]) + const loading = ref(true) + const notFound = ref(false) + const running = ref(false) + const exporting = ref(null) + const nothingToExport = ref(false) + const search = ref("") + const pagination = ref(emptyPagination()) + + // The request behind the rows on screen, so a download matches what the user sees even + // after the form has been edited. + let shownRequest: ReportRunRequest | null = null + let loadId = 0 + let runId = 0 + // The form's values as last run (or as loaded), so a change back to them, or the load + // itself, doesn't run the report again. + let settledValues = "" + + const canExport = computed(() => result.value !== null && result.value.rows.length > 0) + + /** Whether every required field has a value, so the report can run. */ + const ready = computed( + () => definition.value !== null && hasRequiredValues(definition.value.parameters, values.value), + ) + + function valuesKey(report: ReportViewerDefinition): string { + return JSON.stringify(toRequestParameters(report.parameters, values.value)) + } + + function buildRequest(report: ReportViewerDefinition): ReportRunRequest { + const { page, rowsPerPage, sortBy, descending } = pagination.value + return { + parameters: toRequestParameters(report.parameters, values.value), + page, + perPage: report.paginate ? rowsPerPage : null, + sortBy, + sortDescending: descending, + search: search.value.trim() === "" ? null : search.value.trim(), + } + } + + async function fetchRows(): Promise { + const report = definition.value + if (report === null) { + return + } + runId += 1 + const id = runId + running.value = true + errors.value = [] + nothingToExport.value = false + const request = buildRequest(report) + const outcome = await reportBuilderService.run(report.slug, request) + if (id !== runId) { + return + } + result.value = outcome.result + errors.value = outcome.errors + shownRequest = outcome.result === null ? null : request + if (outcome.result !== null) { + pagination.value = { ...pagination.value, rowsNumber: rowsNumber(outcome.result, pagination.value) } + } + running.value = false + } + + /** Runs the report from the first page with the form's values, recording them in the URL. */ + async function run(): Promise { + const report = definition.value + if (report === null) { + return + } + settledValues = valuesKey(report) + pagination.value = { ...pagination.value, page: 1 } + if (syncQuery) { + await router.replace({ query: toQuery(report.parameters, values.value) }) + } + await fetchRows() + } + + /** Drops the rows on screen (and any run still on its way) when a required field is emptied. */ + async function clearRows(report: ReportViewerDefinition): Promise { + runId += 1 + settledValues = valuesKey(report) + running.value = false + result.value = null + errors.value = [] + shownRequest = null + if (syncQuery) { + await router.replace({ query: toQuery(report.parameters, values.value) }) + } + } + + /** Runs the report again once the form has settled on new values. */ + async function valuesChanged(): Promise { + const report = definition.value + if (report === null || loading.value || valuesKey(report) === settledValues) { + return + } + await (ready.value ? run() : clearRows(report)) + } + + /** A page or sort change from the table. */ + async function changePage(next: Omit): Promise { + pagination.value = { ...pagination.value, ...next } + await fetchRows() + } + + async function changeSearch(text: string | null): Promise { + search.value = text ?? "" + pagination.value = { ...pagination.value, page: 1 } + await fetchRows() + } + + /** Downloads the report on screen; does nothing until a run has produced rows. */ + async function exportAs(format: ReportExportFormat): Promise { + const report = definition.value + if (report === null || shownRequest === null) { + return + } + exporting.value = format + const outcome = await reportBuilderService.exportReport(report, format, shownRequest) + nothingToExport.value = outcome === "empty" + exporting.value = null + } + + async function load(reportSlug: string): Promise { + loadId += 1 + const id = loadId + runId += 1 + loading.value = true + result.value = null + errors.value = [] + shownRequest = null + search.value = "" + const report = await reportBuilderService.getDefinition(reportSlug) + if (id !== loadId) { + return + } + definition.value = report + notFound.value = report === null + values.value = report + ? initialValues(report.parameters, syncQuery ? route.query : {}, toValue(options.params)) + : {} + pagination.value = report + ? { + ...emptyPagination(), + rowsPerPage: report.paginate ? report.pageSize : ALL_ROWS, + sortBy: report.sortBy, + descending: report.sortDescending, + } + : emptyPagination() + settledValues = report ? valuesKey(report) : "" + loading.value = false + if (report && hasRequiredValues(report.parameters, values.value)) { + await fetchRows() + } + } + + watch(() => toValue(slug), load, { immediate: true }) + watchDebounced(values, valuesChanged, { debounce: AUTO_RUN_DELAY_MS, deep: true }) + + return { + definition, + values, + result, + errors, + loading, + notFound, + running, + exporting, + nothingToExport, + search, + pagination, + canExport, + ready, + run, + changePage, + changeSearch, + exportAs, + } +} + +export type { ReportPagination } diff --git a/VueApp/vite.config.ts b/VueApp/vite.config.ts index 9fe6405ac..2b3fe4f39 100644 --- a/VueApp/vite.config.ts +++ b/VueApp/vite.config.ts @@ -168,6 +168,7 @@ export default defineConfig(({ mode }) => { clinicalscheduler: path.resolve(import.meta.dirname, "src/ClinicalScheduler/index.html"), effort: path.resolve(import.meta.dirname, "src/Effort/index.html"), personnel: path.resolve(import.meta.dirname, "src/Personnel/index.html"), + reports: path.resolve(import.meta.dirname, "src/Reports/index.html"), }, output: { manualChunks(id) { diff --git a/test/ReportBuilder/ReportAccessTests.cs b/test/ReportBuilder/ReportAccessTests.cs new file mode 100644 index 000000000..7c4fd8d05 --- /dev/null +++ b/test/ReportBuilder/ReportAccessTests.cs @@ -0,0 +1,86 @@ +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// The defaults and rules every viewer endpoint shares. +public sealed class ReportAccessTests +{ + [Fact] + public void VisibleColumns_InOrderWithLabelsAndFormatsDefaulted() + { + var report = new ReportDefinition + { + Columns = + [ + new ReportColumn { Id = 3, SourceColumn = " Dept ", DisplayOrder = 2, Label = "Department", Format = ReportColumnFormat.Text, Sortable = false }, + new ReportColumn { Id = 2, SourceColumn = "Name", DisplayOrder = 1 }, + new ReportColumn { Id = 1, SourceColumn = "Salary", DisplayOrder = 1, Format = ReportColumnFormat.Currency }, + new ReportColumn { Id = 4, SourceColumn = "Hidden", DisplayOrder = 0, Visible = false }, + new ReportColumn { Id = 5, SourceColumn = " ", DisplayOrder = 0 }, + ], + }; + + Assert.Equal( + [ + new ReportResultColumn { Name = "Salary", Label = "Salary", Format = ReportColumnFormat.Currency, Sortable = true }, + new ReportResultColumn { Name = "Name", Label = "Name", Format = ReportColumnFormat.Text, Sortable = true }, + new ReportResultColumn { Name = "Dept", Label = "Department", Format = ReportColumnFormat.Text, Sortable = false }, + ], + ReportAccess.VisibleColumns(report)); + } + + [Fact] + public void UserParameters_LeaveOutCurrentUserAndUnnamedOnes() + { + var report = new ReportDefinition + { + Parameters = + [ + new ReportParameter { Name = "B", DisplayOrder = 2, Binding = ReportParameterBinding.UserInput }, + new ReportParameter { Name = "Login", DisplayOrder = 0, Binding = ReportParameterBinding.CurrentUserLoginId }, + new ReportParameter { Name = " ", DisplayOrder = 0 }, + new ReportParameter { Name = "A", DisplayOrder = 1 }, + ], + }; + + Assert.Equal(["A", "B"], ReportAccess.UserParameters(report).Select(p => p.Name)); + } + + [Theory] + [InlineData(null, true)] + [InlineData(true, true)] + [InlineData(false, false)] + public void Paginates_UnlessTurnedOff(bool? paginate, bool expected) + { + Assert.Equal(expected, ReportAccess.Paginates(new ReportDefinition { Paginate = paginate })); + } + + [Theory] + [InlineData(null, ReportLimits.DefaultPageSize)] + [InlineData(10, 10)] + [InlineData(0, 1)] + [InlineData(5000, ReportLimits.MaxPageSize)] + public void PageSize_DefaultsAndStaysInRange(int? pageSize, int expected) + { + Assert.Equal(expected, ReportAccess.PageSize(new ReportDefinition { PageSize = pageSize })); + } + + [Fact] + public void CanView_AdminOrAnyOfTheReportsPermissions() + { + var users = new FakeReportUserService(); + var report = new ReportDefinition { Permissions = [new ReportPermission { Permission = "SVMSecure.A" }] }; + + Assert.False(ReportAccess.CanView(users, report)); + + users.Permissions.Add("SVMSecure.A"); + Assert.True(ReportAccess.CanView(users, report)); + + users.Permissions.Clear(); + users.Permissions.Add(ReportBuilderPermissions.Admin); + Assert.True(ReportAccess.CanView(users, new ReportDefinition())); + } +} diff --git a/test/ReportBuilder/ReportAdminServiceRollbackTests.cs b/test/ReportBuilder/ReportAdminServiceRollbackTests.cs new file mode 100644 index 000000000..4a5d6815d --- /dev/null +++ b/test/ReportBuilder/ReportAdminServiceRollbackTests.cs @@ -0,0 +1,131 @@ +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// Runs the real ReportAdminService (with its production transaction handling) against SQLite, +/// which supports transactions, unlike the in-memory provider the other ReportBuilder tests use. +/// This proves a failed history write rolls the report mutation back too, not just that the +/// exception surfaces. +/// +public sealed class ReportAdminServiceRollbackTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly DbContextOptions _options; + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportPermissionLookup _permissions = new(); + private readonly FakeReportUserService _users = new(); + + public ReportAdminServiceRollbackTests() + { + _connection = new SqliteConnection("Filename=:memory:"); + _connection.Open(); + _options = new DbContextOptionsBuilder().UseSqlite(_connection).Options; + using (var create = new ReportBuilderDbContext(_options)) + { + create.Database.EnsureCreated(); + } + + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "FacultyRoster", + Kind = ReportSourceKind.View, + Columns = [FakeReportSourceCatalog.Column("Name")], + Parameters = [], + PagesInSql = true, + }); + } + + public void Dispose() + { + _connection.Dispose(); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class FixedClock : TimeProvider + { + public override DateTimeOffset GetUtcNow() => new(2026, 11, 16, 9, 30, 0, TimeSpan.Zero); + } + + /// Not exercised by create, update or delete; throws if the test is wrong about that. + private sealed class UnusedRunService : IReportRunService + { + public Task RunAsync(string slug, ReportRunRequest request, ReportRunMode mode, CancellationToken ct) + { + throw new NotSupportedException(); + } + + public Task PreviewAsync(ReportDefinition report, ReportRunRequest request, CancellationToken ct) + { + throw new NotSupportedException(); + } + } + + /// Saves the mutation itself, then fails the history write that follows it. + private sealed class FailingHistoryContext : ReportBuilderDbContext + { + private int _calls; + + public FailingHistoryContext(DbContextOptions options) : base(options) + { + } + + public override Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + _calls++; + return _calls == 1 ? base.SaveChangesAsync(cancellationToken) : throw new DbUpdateException("history table is locked"); + } + } + + private ReportAdminService CreateService(ReportBuilderDbContext context) + { + return new ReportAdminService( + context, new ReportDefinitionValidator(_catalog, _permissions), _permissions, _users, new UnusedRunService(), new FixedClock()); + } + + private static ReportEditRequest Roster() + { + return new ReportEditRequest + { + Title = "Faculty roster", + Source = "FacultyRoster", + Columns = [new ReportColumnEdit { SourceColumn = "Name", Format = ReportColumnFormat.Text, Sortable = true, Visible = true }], + }; + } + + [Fact] + public async Task Create_WhenHistoryFailsToSave_RollsBackTheReportToo() + { + await using var failing = new FailingHistoryContext(_options); + + await Assert.ThrowsAsync(() => CreateService(failing).CreateAsync(Roster(), Ct)); + + await using var check = new ReportBuilderDbContext(_options); + Assert.Empty(await check.Reports.ToListAsync(Ct)); + } + + [Fact] + public async Task Update_WhenHistoryFailsToSave_RollsBackTheEditToo() + { + int id; + await using (var seed = new ReportBuilderDbContext(_options)) + { + var created = CreateService(seed); + id = (await created.CreateAsync(Roster(), Ct)).Value!.Id; + } + + await using var failing = new FailingHistoryContext(_options); + ReportEditRequest edit = Roster() with { Title = "Renamed", LastModifiedOn = (await CreateService(failing).GetAsync(id, Ct))!.ModifiedOn }; + + await Assert.ThrowsAsync(() => CreateService(failing).UpdateAsync(id, edit, Ct)); + + await using var check = new ReportBuilderDbContext(_options); + Assert.Equal("Faculty roster", (await check.Reports.SingleAsync(r => r.Id == id, Ct)).Title); + } +} diff --git a/test/ReportBuilder/ReportAdminServiceTests.cs b/test/ReportBuilder/ReportAdminServiceTests.cs new file mode 100644 index 000000000..e032cd87e --- /dev/null +++ b/test/ReportBuilder/ReportAdminServiceTests.cs @@ -0,0 +1,472 @@ +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// Saving reports: checked first, stored as the catalog and RAPS spell things, guarded against +/// overwriting someone else's save, soft-deleted, and copied into the history on every change. +/// +public sealed class ReportAdminServiceTests : IDisposable +{ + private static readonly DateTimeOffset Now = new(2026, 11, 16, 9, 30, 0, TimeSpan.Zero); + + private readonly ReportBuilderDbContext _context; + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportPermissionLookup _permissions = new(); + private readonly FakeReportUserService _users = new(); + private readonly PreviewRecorder _runs = new(); + private readonly ReportAdminService _service; + + public ReportAdminServiceTests() + { + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); + _context = new ReportBuilderDbContext(options); + _service = new ReportAdminService( + _context, new ReportDefinitionValidator(_catalog, _permissions), _permissions, _users, _runs, new FixedClock()); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "FacultyRoster", + Kind = ReportSourceKind.View, + Columns = [FakeReportSourceCatalog.Column("Name"), FakeReportSourceCatalog.Column("Dept")], + Parameters = [], + PagesInSql = true, + }); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "usp_Leave", + Kind = ReportSourceKind.Procedure, + Columns = [FakeReportSourceCatalog.Column("Name")], + Parameters = [FakeReportSourceCatalog.Parameter("LoginId"), FakeReportSourceCatalog.Parameter("Kind")], + PagesInSql = false, + }); + } + + public void Dispose() + { + _context.Dispose(); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class FixedClock : TimeProvider + { + public override DateTimeOffset GetUtcNow() => Now; + + public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; + } + + /// Records the report a preview was asked to run. + private sealed class PreviewRecorder : IReportRunService + { + public ReportDefinition? Previewed { get; private set; } + + public Task RunAsync(string slug, ReportRunRequest request, ReportRunMode mode, CancellationToken ct) + { + throw new NotSupportedException("The admin service only previews."); + } + + public Task PreviewAsync(ReportDefinition report, ReportRunRequest request, CancellationToken ct) + { + Previewed = report; + return Task.FromResult(new ReportRunOutcome { Status = ReportRunStatus.Ok }); + } + } + + private static ReportEditRequest Roster() + { + return new ReportEditRequest + { + Title = " Faculty roster ", + Description = " ", + Area = "Personnel", + Source = "facultyroster", + Paginate = true, + PageSize = 50, + AllowExcel = true, + SensitiveNotice = " Confidential ", + OrderBy = "name", + Permissions = ["svmsecure.personnel"], + Columns = + [ + new ReportColumnEdit { SourceColumn = "name", Label = " ", Format = ReportColumnFormat.Text, Sortable = true, Visible = true }, + new ReportColumnEdit { SourceColumn = "Dept", Label = "Department", Format = ReportColumnFormat.Text, Sortable = false, Visible = true }, + ], + Parameters = + [ + new ReportParameterEdit + { + Name = "dept", + Label = "Department", + Type = ReportParameterType.MultiChoice, + Operator = ReportFilterOperator.In, + ChoicesList = [new ReportChoice { Value = " VME ", Label = " " }], + ChoicesSource = "Ignored", + Binding = ReportParameterBinding.UserInput, + }, + new ReportParameterEdit { Name = "Name", Type = ReportParameterType.Text, Binding = ReportParameterBinding.UserInput }, + ], + }; + } + + private async Task CreateAsync(ReportEditRequest? request = null) + { + ReportAdminOutcome outcome = await _service.CreateAsync(request ?? Roster(), Ct); + Assert.Equal(ReportAdminStatus.Ok, outcome.Status); + return Assert.IsType(outcome.Value); + } + + private ReportDefinition Stored(int id) + { + return _context.Reports.AsNoTracking() + .Include(r => r.Columns) + .Include(r => r.Parameters) + .Include(r => r.Permissions) + .Single(r => r.Id == id); + } + + // Creating + + [Fact] + public async Task Create_StoresTheReportTidiedAndSpelledAsTheCatalogDoes() + { + ReportAdminDefinition created = await CreateAsync(); + + ReportDefinition stored = Stored(created.Id); + Assert.Equal(("Faculty roster", null, "FacultyRoster", "Confidential", "Name"), (stored.Title, stored.Description, stored.Source, stored.SensitiveNotice, stored.OrderBy)); + Assert.NotEqual(Guid.Empty, stored.Slug); + Assert.Equal(["SVMSecure.Personnel"], stored.Permissions.Select(p => p.Permission)); + (string?, string?, int)[] columns = [("Name", null, 1), ("Dept", "Department", 2)]; + Assert.Equal(columns, stored.Columns.OrderBy(c => c.DisplayOrder).Select(c => (c.SourceColumn, c.Label, c.DisplayOrder))); + } + + [Fact] + public async Task Create_StoresParametersWithOnlyTheSettingsThatApply() + { + ReportAdminDefinition created = await CreateAsync(); + + ReportParameter dept = Stored(created.Id).Parameters.Single(p => p.DisplayOrder == 1); + Assert.Equal("Dept", dept.Name); + Assert.Null(dept.ChoicesSource); + Assert.Equal("""[{"value":"VME","label":"VME"}]""", dept.ChoicesList); + Assert.Equal(ReportFilterOperator.Equals, Stored(created.Id).Parameters.Single(p => p.DisplayOrder == 2).Operator); + } + + [Fact] + public async Task Create_RecordsWhoAndWhen() + { + ReportAdminDefinition created = await CreateAsync(); + + Assert.Equal((Now.DateTime, "jdoe"), (created.CreatedOn, created.CreatedBy)); + Assert.Equal((Now.DateTime, "jdoe"), (created.ModifiedOn, created.ModifiedBy)); + Assert.Equal(Now.DateTime, created.Report.LastModifiedOn); + ReportDefinitionHistory history = Assert.Single(_context.ReportHistory); + Assert.Equal((created.Id, ReportHistoryAction.Created, "jdoe"), (history.ReportId, history.Action, history.ChangedBy)); + } + + [Fact] + public async Task Create_Invalid_SavesNothing() + { + ReportAdminOutcome outcome = await _service.CreateAsync(Roster() with { Title = "" }, Ct); + + Assert.Equal(ReportAdminStatus.Invalid, outcome.Status); + Assert.Equal(["Enter a title."], outcome.Errors); + Assert.Empty(_context.Reports); + } + + [Fact] + public async Task Create_ProcedureParameters_HaveNoOperatorAndCurrentUserOnesAreText() + { + ReportAdminDefinition created = await CreateAsync(new ReportEditRequest + { + Title = "Leave", + Source = "usp_Leave", + Columns = [new ReportColumnEdit { SourceColumn = "Name", Format = ReportColumnFormat.Text, Sortable = true, Visible = true }], + Parameters = + [ + new ReportParameterEdit + { + Name = "loginid", + Type = ReportParameterType.Choice, + Required = true, + DefaultValue = "x", + Binding = ReportParameterBinding.CurrentUserLoginId, + }, + new ReportParameterEdit + { + Name = "Kind", + Type = ReportParameterType.Choice, + Operator = ReportFilterOperator.Equals, + ChoicesSource = " FacultyRoster ", + Binding = ReportParameterBinding.UserInput, + }, + ], + }); + + List parameters = [.. Stored(created.Id).Parameters.OrderBy(p => p.DisplayOrder)]; + Assert.Equal<(string?, ReportParameterType?, bool?, string?, ReportFilterOperator?)>(("LoginId", ReportParameterType.Text, false, null, null), (parameters[0].Name, parameters[0].Type, parameters[0].Required, parameters[0].DefaultValue, parameters[0].Operator)); + Assert.Equal(("FacultyRoster", null), (parameters[1].ChoicesSource, parameters[1].Operator)); + } + + // Reading + + [Fact] + public async Task Get_ReturnsTheFormsFieldsInOrder() + { + ReportAdminDefinition created = await CreateAsync(); + + ReportAdminDefinition? read = await _service.GetAsync(created.Id, Ct); + + Assert.NotNull(read); + Assert.Equal(["Name", "Dept"], read.Report.Columns.Select(c => c.SourceColumn)); + Assert.Equal(["Dept", "Name"], read.Report.Parameters.Select(p => p.Name)); + Assert.Equal([new ReportChoice { Value = "VME", Label = "VME" }], read.Report.Parameters[0].ChoicesList); + Assert.Empty(read.MissingPermissions); + } + + [Fact] + public async Task Get_Unknown_IsNull() + { + Assert.Null(await _service.GetAsync(999, Ct)); + } + + [Fact] + public async Task Get_ReportWithEmptySettings_UsesTheRunnersDefaults() + { + _context.Reports.Add(new ReportDefinition + { + Id = 7, + Title = "Old", + Source = "FacultyRoster", + Columns = [new ReportColumn { SourceColumn = null, DisplayOrder = 1 }], + Parameters = [new ReportParameter { Name = null }], + }); + await _context.SaveChangesAsync(Ct); + + ReportAdminDefinition read = (await _service.GetAsync(7, Ct))!; + + Assert.Equal((true, false, false), (read.Report.Paginate, read.Report.PdfLandscape, read.Report.OrderByDescending)); + Assert.Equal(("", ReportColumnFormat.Text), (read.Report.Columns[0].SourceColumn, read.Report.Columns[0].Format)); + Assert.Equal(("", ReportParameterType.Text, ReportParameterBinding.UserInput, false), (read.Report.Parameters[0].Name, read.Report.Parameters[0].Type, read.Report.Parameters[0].Binding, read.Report.Parameters[0].Required)); + } + + [Fact] + public async Task List_FlagsPermissionsRapsNoLongerHasAndHidesDeletedReports() + { + ReportAdminDefinition kept = await CreateAsync(); + ReportAdminDefinition removed = await CreateAsync(Roster() with { Title = "Removed" }); + await _service.DeleteAsync(removed.Id, Ct); + _permissions.Names.Remove("SVMSecure.Personnel"); + + IReadOnlyList live = await _service.ListAsync(includeDeleted: false, Ct); + IReadOnlyList all = await _service.ListAsync(includeDeleted: true, Ct); + + ReportAdminListItem item = Assert.Single(live); + Assert.Equal((kept.Id, "Faculty roster", "FacultyRoster"), (item.Id, item.Title, item.Source)); + Assert.Equal(["SVMSecure.Personnel"], item.Permissions); + Assert.Equal(["SVMSecure.Personnel"], item.MissingPermissions); + Assert.Equal(2, all.Count); + } + + // Updating + + [Fact] + public async Task Update_ReplacesColumnsParametersAndPermissions() + { + ReportAdminDefinition created = await CreateAsync(); + _permissions.Names.Add("SVMSecure.Personnel.Reports"); + + ReportAdminOutcome outcome = await _service.UpdateAsync(created.Id, created.Report with + { + Title = "Roster", + Columns = [new ReportColumnEdit { SourceColumn = "Dept", Format = ReportColumnFormat.Text, Sortable = true, Visible = true }], + Parameters = [], + Permissions = ["SVMSecure.Personnel.Reports", "SVMSecure.Personnel"], + }, Ct); + + Assert.Equal(ReportAdminStatus.Ok, outcome.Status); + ReportDefinition stored = Stored(created.Id); + Assert.Equal(("Roster", "Dept"), (stored.Title, Assert.Single(stored.Columns).SourceColumn)); + Assert.Empty(stored.Parameters); + Assert.Equal(["SVMSecure.Personnel", "SVMSecure.Personnel.Reports"], stored.Permissions.Select(p => p.Permission).Order().ToArray()); + } + + [Fact] + public async Task Update_DropsPermissionsNoLongerWanted() + { + ReportAdminDefinition created = await CreateAsync(); + + await _service.UpdateAsync(created.Id, created.Report with { Permissions = [] }, Ct); + + Assert.Empty(Stored(created.Id).Permissions); + } + + [Fact] + public async Task Update_RecordsTheChange() + { + ReportAdminDefinition created = await CreateAsync(); + + await _service.UpdateAsync(created.Id, created.Report with { Title = "Roster" }, Ct); + + IReadOnlyList? history = await _service.GetHistoryAsync(created.Id, Ct); + Assert.Equal([ReportHistoryAction.Updated, ReportHistoryAction.Created], history!.Select(h => h.Action)); + } + + [Fact] + public async Task Update_FromAnOlderCopy_IsAConflict() + { + ReportAdminDefinition created = await CreateAsync(); + + ReportAdminOutcome outcome = await _service.UpdateAsync( + created.Id, created.Report with { Title = "Mine", LastModifiedOn = Now.DateTime.AddMinutes(-5) }, Ct); + + Assert.Equal(ReportAdminStatus.Conflict, outcome.Status); + Assert.Contains("Someone else saved this report", Assert.Single(outcome.Errors)); + Assert.Equal("Faculty roster", Stored(created.Id).Title); + } + + [Fact] + public async Task Update_Invalid_ChangesNothing() + { + ReportAdminDefinition created = await CreateAsync(); + + ReportAdminOutcome outcome = await _service.UpdateAsync(created.Id, created.Report with { Source = "Dropped" }, Ct); + + Assert.Equal(ReportAdminStatus.Invalid, outcome.Status); + Assert.Equal("FacultyRoster", Stored(created.Id).Source); + } + + [Fact] + public async Task Update_Unknown_IsNotFound() + { + ReportAdminOutcome outcome = await _service.UpdateAsync(999, Roster(), Ct); + + Assert.Equal(ReportAdminStatus.NotFound, outcome.Status); + } + + [Fact] + public async Task Update_Deleted_MustBeRestoredFirst() + { + ReportAdminDefinition created = await CreateAsync(); + ReportAdminDefinition deleted = (await _service.DeleteAsync(created.Id, Ct)).Value!; + + ReportAdminOutcome outcome = await _service.UpdateAsync(created.Id, deleted.Report, Ct); + + Assert.Equal(["Restore the report before editing it."], outcome.Errors); + } + + // Deleting and restoring + + [Fact] + public async Task Delete_HidesTheReportAndRestoreBringsItBack() + { + ReportAdminDefinition created = await CreateAsync(); + + ReportAdminDefinition deleted = (await _service.DeleteAsync(created.Id, Ct)).Value!; + ReportAdminDefinition restored = (await _service.RestoreAsync(created.Id, Ct)).Value!; + + Assert.Equal((Now.DateTime, "jdoe"), (deleted.DeletedOn, deleted.DeletedBy)); + Assert.Equal((null, null), (restored.DeletedOn, restored.DeletedBy)); + IReadOnlyList? history = await _service.GetHistoryAsync(created.Id, Ct); + Assert.Equal( + [ReportHistoryAction.Restored, ReportHistoryAction.Deleted, ReportHistoryAction.Created], + history!.OrderByDescending(h => h.Id).Select(h => h.Action)); + } + + [Fact] + public async Task Delete_Twice_RecordsItOnce() + { + ReportAdminDefinition created = await CreateAsync(); + + await _service.DeleteAsync(created.Id, Ct); + await _service.DeleteAsync(created.Id, Ct); + await _service.RestoreAsync(created.Id, Ct); + await _service.RestoreAsync(created.Id, Ct); + + Assert.Equal(3, await _context.ReportHistory.CountAsync(Ct)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task DeleteOrRestore_Unknown_IsNotFound(bool delete) + { + ReportAdminOutcome outcome = delete + ? await _service.DeleteAsync(999, Ct) + : await _service.RestoreAsync(999, Ct); + + Assert.Equal(ReportAdminStatus.NotFound, outcome.Status); + } + + // History + + [Fact] + public async Task HistoryVersion_ShowsTheReportAsItWas() + { + ReportAdminDefinition created = await CreateAsync(); + await _service.UpdateAsync(created.Id, created.Report with { Title = "Renamed" }, Ct); + ReportHistoryItem first = (await _service.GetHistoryAsync(created.Id, Ct))!.Single(h => h.Action == ReportHistoryAction.Created); + + ReportHistoryVersion? version = await _service.GetHistoryVersionAsync(created.Id, first.Id, Ct); + + Assert.NotNull(version); + Assert.Equal(("Faculty roster", ReportHistoryAction.Created), (version.Report?.Title, version.Version.Action)); + Assert.Equal(["Name", "Dept"], version.Report?.Columns.Select(c => c.SourceColumn)); + } + + [Fact] + public async Task HistoryVersion_OfAnotherReportOrUnknown_IsNull() + { + ReportAdminDefinition created = await CreateAsync(); + int historyId = (await _context.ReportHistory.SingleAsync(Ct)).Id; + + Assert.Null(await _service.GetHistoryVersionAsync(created.Id + 1, historyId, Ct)); + Assert.Null(await _service.GetHistoryVersionAsync(created.Id, historyId + 1, Ct)); + } + + [Theory] + [InlineData(null)] + [InlineData("not json")] + public async Task HistoryVersion_WithAnUnreadableSnapshot_HasNoReport(string? snapshot) + { + ReportAdminDefinition created = await CreateAsync(); + _context.ReportHistory.Add(new ReportDefinitionHistory { ReportId = created.Id, Action = ReportHistoryAction.Updated, Snapshot = snapshot }); + await _context.SaveChangesAsync(Ct); + int historyId = await _context.ReportHistory.MaxAsync(h => h.Id, Ct); + + ReportHistoryVersion? version = await _service.GetHistoryVersionAsync(created.Id, historyId, Ct); + + Assert.Null(version?.Report); + Assert.Equal(ReportHistoryAction.Updated, version?.Version.Action); + } + + [Fact] + public async Task History_OfUnknownReport_IsNull() + { + Assert.Null(await _service.GetHistoryAsync(999, Ct)); + } + + // Preview + + [Fact] + public async Task Preview_RunsTheUnsavedReportWithoutSavingIt() + { + ReportRunOutcome outcome = await _service.PreviewAsync(new ReportPreviewRequest { Report = Roster() }, Ct); + + Assert.Equal(ReportRunStatus.Ok, outcome.Status); + Assert.Equal(("FacultyRoster", 2), (_runs.Previewed?.Source, _runs.Previewed?.Columns.Count)); + Assert.Empty(_context.Reports); + } + + [Fact] + public async Task Preview_Invalid_IsNotRun() + { + ReportRunOutcome outcome = await _service.PreviewAsync(new ReportPreviewRequest { Report = Roster() with { Columns = [] } }, Ct); + + Assert.Equal((ReportRunStatus.Invalid, "Show at least one column."), (outcome.Status, Assert.Single(outcome.Errors))); + Assert.Null(_runs.Previewed); + } +} diff --git a/test/ReportBuilder/ReportBuilderAdminControllerTests.cs b/test/ReportBuilder/ReportBuilderAdminControllerTests.cs new file mode 100644 index 000000000..effe97938 --- /dev/null +++ b/test/ReportBuilder/ReportBuilderAdminControllerTests.cs @@ -0,0 +1,296 @@ +using System.Reflection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Controllers; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes; +using Web.Authorization; + +namespace Viper.test.ReportBuilder; + +/// The admin controller passes requests to the services and turns their outcomes into responses. +public sealed class ReportBuilderAdminControllerTests +{ + private readonly StubAdminService _admin = new(); + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportPermissionLookup _permissions = new(); + private readonly StubProblemService _problems = new(); + private readonly ReportBuilderAdminController _controller; + + public ReportBuilderAdminControllerTests() + { + _controller = new ReportBuilderAdminController(_admin, _catalog, _permissions, _problems) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }, + }; + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "FacultyRoster", + Kind = ReportSourceKind.View, + Columns = [], + Parameters = [], + PagesInSql = true, + }); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static readonly ReportEditRequest Fields = new() { Title = "Roster", Source = "FacultyRoster" }; + + private static readonly ReportAdminDefinition Saved = new() { Id = 4, Slug = Guid.Empty, Report = Fields }; + + private static T OkValue(ActionResult result) + { + return Assert.IsAssignableFrom(Assert.IsType(result.Result).Value); + } + + [Fact] + public void Controller_NeedsTheAdminPermission() + { + Assert.Equal(ReportBuilderPermissions.Admin, typeof(ReportBuilderAdminController).GetCustomAttribute()?.Allow); + Assert.Equal("/api/report-builder/admin", typeof(ReportBuilderAdminController).GetCustomAttribute()?.Template); + Assert.True(typeof(ApiController).IsAssignableFrom(typeof(ReportBuilderAdminController))); + } + + [Fact] + public async Task Sources_ListAndDescribe() + { + IReadOnlyList sources = OkValue(await _controller.GetSources(Ct)); + ReportSourceDetail source = OkValue(await _controller.GetSource("FacultyRoster", Ct)); + + Assert.Equal("FacultyRoster", Assert.Single(sources).Name); + Assert.Equal("FacultyRoster", source.Name); + Assert.IsType((await _controller.GetSource("Dropped", Ct)).Result); + } + + [Fact] + public async Task Permissions_AreSearched() + { + IReadOnlyList found = OkValue(await _controller.SearchPermissions("effort", Ct)); + + Assert.Equal("SVMSecure.Effort", Assert.Single(found).Permission); + } + + [Fact] + public async Task List_PassesTheDeletedFlag() + { + OkValue(await _controller.List(includeDeleted: true, Ct)); + + Assert.True(_admin.LastIncludeDeleted); + } + + [Fact] + public async Task Get_ReturnsTheReportOr404() + { + _admin.Definition = Saved; + + Assert.Same(Saved, OkValue(await _controller.Get(4, Ct))); + + _admin.Definition = null; + Assert.IsType((await _controller.Get(4, Ct)).Result); + } + + [Fact] + public async Task Create_Returns201WithTheReport() + { + _admin.Outcome = ReportAdminOutcome.Ok(Saved); + + ActionResult result = await _controller.Create(Fields, Ct); + + CreatedAtActionResult created = Assert.IsType(result.Result); + Assert.Equal((nameof(ReportBuilderAdminController.Get), (object?)4), (created.ActionName, created.RouteValues?["id"])); + Assert.Same(Saved, created.Value); + } + + [Fact] + public async Task Create_Invalid_Returns400WithTheErrors() + { + _admin.Outcome = ReportAdminOutcome.Fail(ReportAdminStatus.Invalid, "Enter a title."); + + ActionResult result = await _controller.Create(Fields, Ct); + + ValidationProblemDetails problem = Assert.IsType(Assert.IsType(result.Result).Value); + Assert.Equal(["Enter a title."], problem.Errors[string.Empty]); + Assert.Equal("The report can't be saved.", problem.Title); + } + + [Fact] + public async Task Update_PassesTheIdAndMapsTheOutcome() + { + _admin.Outcome = ReportAdminOutcome.Ok(Saved); + + Assert.Same(Saved, OkValue(await _controller.Update(4, Fields, Ct))); + Assert.Equal(4, _admin.LastId); + } + + [Fact] + public async Task Update_FromAnOlderCopy_Returns409() + { + _admin.Outcome = ReportAdminOutcome.Fail(ReportAdminStatus.Conflict, "Someone else saved it."); + + ActionResult result = await _controller.Update(4, Fields, Ct); + + Assert.Equal("Someone else saved it.", Assert.IsType(result.Result).Value); + } + + [Fact] + public async Task DeleteAndRestore_MapTheOutcome() + { + _admin.Outcome = ReportAdminOutcome.Fail(ReportAdminStatus.NotFound); + + Assert.IsType((await _controller.Delete(4, Ct)).Result); + Assert.IsType((await _controller.Restore(4, Ct)).Result); + Assert.Equal(["Delete", "Restore"], _admin.Calls); + } + + [Fact] + public async Task History_ReturnsTheVersionsOr404() + { + _admin.History = [new ReportHistoryItem { Id = 1, Action = ReportHistoryAction.Created }]; + + Assert.Single(OkValue(await _controller.GetHistory(4, Ct))); + + _admin.History = null; + Assert.IsType((await _controller.GetHistory(4, Ct)).Result); + } + + [Fact] + public async Task HistoryVersion_ReturnsTheVersionOr404() + { + _admin.Version = new ReportHistoryVersion { Version = new ReportHistoryItem { Id = 9 }, Report = Fields }; + + Assert.Equal(9, OkValue(await _controller.GetHistoryVersion(4, 9, Ct)).Version.Id); + + _admin.Version = null; + Assert.IsType((await _controller.GetHistoryVersion(4, 9, Ct)).Result); + } + + [Fact] + public async Task Preview_ReturnsThePage() + { + var page = new ReportRunResult { Columns = [], Rows = [], Page = 1, PerPage = 50, TotalRows = 0, Truncated = false }; + _admin.Preview = new ReportRunOutcome { Status = ReportRunStatus.Ok, Result = page }; + + Assert.Same(page, OkValue(await _controller.Preview(new ReportPreviewRequest { Report = Fields }, Ct))); + } + + [Theory] + [InlineData(ReportRunStatus.Forbidden, StatusCodes.Status403Forbidden)] + [InlineData(ReportRunStatus.Invalid, StatusCodes.Status400BadRequest)] + [InlineData(ReportRunStatus.Unavailable, StatusCodes.Status503ServiceUnavailable)] + public async Task Preview_MapsFailures(ReportRunStatus status, int expected) + { + _admin.Preview = new ReportRunOutcome { Status = status }; + + ActionResult result = await _controller.Preview(new ReportPreviewRequest { Report = Fields }, Ct); + + Assert.Equal(expected, Assert.IsAssignableFrom(result.Result).StatusCode); + } + + [Fact] + public async Task Preview_Unavailable_SaysWhy() + { + _admin.Preview = new ReportRunOutcome { Status = ReportRunStatus.Unavailable, Errors = ["The source is gone."] }; + + ActionResult result = await _controller.Preview(new ReportPreviewRequest { Report = Fields }, Ct); + + Assert.Equal("The source is gone.", Assert.IsAssignableFrom(result.Result).Value); + } + + /// Returns canned outcomes and records what the controller asked for. + [Fact] + public async Task Failures_PassTheWindowThrough() + { + IReadOnlyList failures = OkValue(await _controller.GetFailures(7, Ct)); + + Assert.Same(_problems.Failures, failures); + Assert.Equal(7, _problems.LastDays); + } + + [Fact] + public async Task Check_ReturnsTheResult() + { + Assert.Same(_problems.Check, OkValue(await _controller.Check(Ct))); + } + + private sealed class StubProblemService : IReportProblemService + { + public IReadOnlyList Failures { get; } = []; + public ReportCheckResult Check { get; } = new() { Checked = 0, CheckedOn = DateTime.MinValue, Failing = [] }; + public int? LastDays { get; private set; } + + public Task> GetFailuresAsync(int? days, CancellationToken ct) + { + LastDays = days; + return Task.FromResult(Failures); + } + + public Task CheckAsync(CancellationToken ct) + { + return Task.FromResult(Check); + } + } + + private sealed class StubAdminService : IReportAdminService + { + public ReportAdminDefinition? Definition { get; set; } + public ReportAdminOutcome Outcome { get; set; } = ReportAdminOutcome.Fail(ReportAdminStatus.NotFound); + public IReadOnlyList? History { get; set; } + public ReportHistoryVersion? Version { get; set; } + public ReportRunOutcome Preview { get; set; } = new() { Status = ReportRunStatus.Ok }; + public bool LastIncludeDeleted { get; private set; } + public int? LastId { get; private set; } + public List Calls { get; } = []; + + public Task> ListAsync(bool includeDeleted, CancellationToken ct) + { + LastIncludeDeleted = includeDeleted; + return Task.FromResult>([]); + } + + public Task GetAsync(int id, CancellationToken ct) + { + return Task.FromResult(Definition); + } + + public Task> CreateAsync(ReportEditRequest request, CancellationToken ct) + { + return Task.FromResult(Outcome); + } + + public Task> UpdateAsync(int id, ReportEditRequest request, CancellationToken ct) + { + LastId = id; + return Task.FromResult(Outcome); + } + + public Task> DeleteAsync(int id, CancellationToken ct) + { + Calls.Add("Delete"); + return Task.FromResult(Outcome); + } + + public Task> RestoreAsync(int id, CancellationToken ct) + { + Calls.Add("Restore"); + return Task.FromResult(Outcome); + } + + public Task?> GetHistoryAsync(int id, CancellationToken ct) + { + return Task.FromResult(History); + } + + public Task GetHistoryVersionAsync(int id, int historyId, CancellationToken ct) + { + return Task.FromResult(Version); + } + + public Task PreviewAsync(ReportPreviewRequest request, CancellationToken ct) + { + return Task.FromResult(Preview); + } + } +} diff --git a/test/ReportBuilder/ReportBuilderControllerTests.cs b/test/ReportBuilder/ReportBuilderControllerTests.cs new file mode 100644 index 000000000..5cc1ef2d8 --- /dev/null +++ b/test/ReportBuilder/ReportBuilderControllerTests.cs @@ -0,0 +1,218 @@ +using System.Reflection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Viper.Areas.ReportBuilder.Controllers; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes; +using Web.Authorization; + +namespace Viper.test.ReportBuilder; + +/// The controller passes requests to the services and turns their outcomes into responses. +public sealed class ReportBuilderControllerTests +{ + private const string Slug = "8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e"; + private readonly StubServices _services = new(); + private readonly ReportBuilderController _controller; + + public ReportBuilderControllerTests() + { + _controller = new ReportBuilderController(_services, _services, _services) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }, + }; + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ReportRunResult EmptyResult() + { + return new ReportRunResult { Columns = [], Rows = [], Page = 1, PerPage = 25, TotalRows = 0, Truncated = false }; + } + + [Fact] + public void Controller_RequiresSignInAndUsesApiConventions() + { + Assert.Equal("SVMSecure", typeof(ReportBuilderController).GetCustomAttribute()?.Allow); + Assert.Equal("/api/report-builder", typeof(ReportBuilderController).GetCustomAttribute()?.Template); + Assert.True(typeof(ApiController).IsAssignableFrom(typeof(ReportBuilderController))); + } + + [Fact] + public async Task GetCatalog_ReturnsTheUsersReports() + { + IReadOnlyList catalog = [new ReportCatalogItem { Slug = Guid.Parse(Slug), Title = "Roster" }]; + _services.Catalog = catalog; + + ActionResult> result = await _controller.GetCatalog(Ct); + + Assert.Same(catalog, Assert.IsType(result.Result).Value); + } + + [Fact] + public async Task GetDefinition_Ok_ReturnsTheDefinition() + { + var definition = new ReportViewerDefinition + { + Slug = Guid.Parse(Slug), + Title = "Roster", + Paginate = true, + PageSize = 25, + AllowExcel = true, + AllowPdf = false, + SortDescending = false, + Columns = [], + Parameters = [], + }; + _services.Definition = new ReportDefinitionOutcome { Status = ReportRunStatus.Ok, Definition = definition }; + + ActionResult result = await _controller.GetDefinition(Slug, Ct); + + Assert.Same(definition, Assert.IsType(result.Result).Value); + Assert.Equal(Slug, _services.LastSlug); + } + + [Fact] + public async Task GetDefinition_NotFound_Returns404() + { + _services.Definition = new ReportDefinitionOutcome { Status = ReportRunStatus.NotFound }; + + ActionResult result = await _controller.GetDefinition(Slug, Ct); + + Assert.IsType(result.Result); + } + + [Fact] + public async Task Run_Ok_ReturnsTheRowsInScreenMode() + { + ReportRunResult rows = EmptyResult(); + _services.Run = new ReportRunOutcome { Status = ReportRunStatus.Ok, Result = rows }; + var request = new ReportRunRequest { Page = 2 }; + + ActionResult result = await _controller.Run(Slug, request, Ct); + + Assert.Same(rows, Assert.IsType(result.Result).Value); + Assert.Same(request, _services.LastRequest); + Assert.Equal(ReportRunMode.Screen, _services.LastMode); + } + + [Fact] + public async Task Run_Forbidden_Returns403() + { + _services.Run = new ReportRunOutcome { Status = ReportRunStatus.Forbidden }; + + ActionResult result = await _controller.Run(Slug, new ReportRunRequest(), Ct); + + Assert.Equal(StatusCodes.Status403Forbidden, Assert.IsType(result.Result).StatusCode); + } + + [Fact] + public async Task Run_Invalid_Returns400WithTheErrors() + { + _services.Run = new ReportRunOutcome { Status = ReportRunStatus.Invalid, Errors = ["Department is required.", "That page doesn't exist."] }; + + ActionResult result = await _controller.Run(Slug, new ReportRunRequest(), Ct); + + ValidationProblemDetails problem = Assert.IsType(Assert.IsType(result.Result).Value); + Assert.Equal(["Department is required.", "That page doesn't exist."], problem.Errors[string.Empty]); + Assert.Equal("The report request is not valid.", problem.Title); + } + + [Theory] + [InlineData("The column 'Salary' is no longer in this report's data source.", "The column 'Salary' is no longer in this report's data source.")] + [InlineData(null, "This report is unavailable.")] + public async Task Run_Unavailable_Returns503(string? error, string expected) + { + _services.Run = new ReportRunOutcome { Status = ReportRunStatus.Unavailable, Errors = error is null ? [] : [error] }; + + ActionResult result = await _controller.Run(Slug, new ReportRunRequest(), Ct); + + ObjectResult unavailable = Assert.IsType(result.Result); + Assert.Equal(StatusCodes.Status503ServiceUnavailable, unavailable.StatusCode); + Assert.Equal(expected, unavailable.Value); + } + + [Fact] + public async Task Export_Ok_ReturnsAnUncachedDownload() + { + _services.Export = new ReportExportOutcome + { + Status = ReportRunStatus.Ok, + File = new ReportFile { Content = [1, 2, 3], ContentType = "application/pdf", FileName = "Roster.pdf" }, + }; + + ActionResult result = await _controller.Export(Slug, "pdf", new ReportRunRequest(), Ct); + + FileContentResult download = Assert.IsType(result); + Assert.Equal("application/pdf", download.ContentType); + Assert.Equal("Roster.pdf", download.FileDownloadName); + Assert.Equal([1, 2, 3], download.FileContents); + Assert.Equal("private, no-store, max-age=0", _controller.Response.Headers.CacheControl.ToString()); + Assert.Equal("pdf", _services.LastFormat); + } + + [Fact] + public async Task Export_NoRows_Returns204() + { + _services.Export = new ReportExportOutcome { Status = ReportRunStatus.Ok }; + + Assert.IsType(await _controller.Export(Slug, "xlsx", new ReportRunRequest(), Ct)); + } + + [Fact] + public async Task Export_Invalid_Returns400() + { + _services.Export = new ReportExportOutcome { Status = ReportRunStatus.Invalid, Errors = ["Choose a download format: xlsx or pdf."] }; + + ActionResult result = await _controller.Export(Slug, "csv", new ReportRunRequest(), Ct); + + Assert.IsType(result); + } + + /// Returns canned outcomes and records what the controller asked for. + private sealed class StubServices : IReportViewerService, IReportRunService, IReportExportService + { + public IReadOnlyList Catalog { get; set; } = []; + public ReportDefinitionOutcome Definition { get; set; } = new() { Status = ReportRunStatus.NotFound }; + public ReportRunOutcome Run { get; set; } = new() { Status = ReportRunStatus.NotFound }; + public ReportExportOutcome Export { get; set; } = new() { Status = ReportRunStatus.NotFound }; + public string? LastSlug { get; private set; } + public ReportRunRequest? LastRequest { get; private set; } + public ReportRunMode? LastMode { get; private set; } + public string? LastFormat { get; private set; } + + public Task> GetCatalogAsync(CancellationToken ct) + { + return Task.FromResult(Catalog); + } + + public Task GetDefinitionAsync(string slug, CancellationToken ct) + { + LastSlug = slug; + return Task.FromResult(Definition); + } + + public Task RunAsync(string slug, ReportRunRequest request, ReportRunMode mode, CancellationToken ct) + { + LastSlug = slug; + LastRequest = request; + LastMode = mode; + return Task.FromResult(Run); + } + + public Task PreviewAsync(ReportDefinition report, ReportRunRequest request, CancellationToken ct) + { + throw new NotSupportedException("The viewer never previews."); + } + + public Task ExportAsync(string slug, string format, ReportRunRequest request, CancellationToken ct) + { + LastSlug = slug; + LastFormat = format; + LastRequest = request; + return Task.FromResult(Export); + } + } +} diff --git a/test/ReportBuilder/ReportBuilderDbContextTests.cs b/test/ReportBuilder/ReportBuilderDbContextTests.cs new file mode 100644 index 000000000..dc0094507 --- /dev/null +++ b/test/ReportBuilder/ReportBuilderDbContextTests.cs @@ -0,0 +1,107 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.test.ReportBuilder; + +/// +/// The entities map to the [report] tables as they were built on Development: their table and +/// column names, varchar text, and enums stored by name. Building the model needs no database. +/// +public sealed class ReportBuilderDbContextTests +{ + private static readonly IModel Model = BuildModel(); + + private static IModel BuildModel() + { + DbContextOptions options = new DbContextOptionsBuilder() + .UseSqlServer("Server=model-only;Database=VIPER") + .Options; + using var context = new ReportBuilderDbContext(options); + return context.Model; + } + + private static IEntityType Entity() + { + return Assert.IsAssignableFrom(Model.FindEntityType(typeof(T))); + } + + private static string? Column(string property) + { + IEntityType entity = Entity(); + IProperty? mapped = entity.FindProperty(property); + Assert.NotNull(mapped); + return mapped.GetColumnName(StoreObjectIdentifier.Table(entity.GetTableName()!, entity.GetSchema())); + } + + [Theory] + [InlineData(typeof(ReportDefinition), "report")] + [InlineData(typeof(ReportPermission), "report_permission")] + [InlineData(typeof(ReportColumn), "report_column")] + [InlineData(typeof(ReportParameter), "report_parameter")] + [InlineData(typeof(ReportDefinitionHistory), "report_history")] + [InlineData(typeof(ReportRunLog), "report_runLog")] + public void EveryTable_IsInTheReportSchema(Type entity, string table) + { + IEntityType type = Assert.IsAssignableFrom(Model.FindEntityType(entity)); + + Assert.Equal("report", type.GetSchema()); + Assert.Equal(table, type.GetTableName()); + } + + [Fact] + public void Properties_MapToTheTablesColumnNames() + { + Assert.Equal("source", Column(nameof(ReportDefinition.Source))); + Assert.Equal("excel", Column(nameof(ReportDefinition.AllowExcel))); + Assert.Equal("sensitive", Column(nameof(ReportDefinition.SensitiveNotice))); + Assert.Equal("orderByDesc", Column(nameof(ReportDefinition.OrderByDescending))); + Assert.Equal("deleted", Column(nameof(ReportDefinition.DeletedOn))); + Assert.Equal("column", Column(nameof(ReportColumn.SourceColumn))); + Assert.Equal("datatype", Column(nameof(ReportColumn.Format))); + Assert.Equal("choicesSource", Column(nameof(ReportParameter.ChoicesSource))); + Assert.Equal("changed", Column(nameof(ReportDefinitionHistory.ChangedOn))); + Assert.Equal("loginID", Column(nameof(ReportRunLog.LoginId))); + Assert.Equal("duration", Column(nameof(ReportRunLog.DurationMs))); + Assert.Equal("errorNumber", Column(nameof(ReportRunLog.ErrorNumber))); + Assert.Equal("errorMessage", Column(nameof(ReportRunLog.ErrorMessage))); + } + + [Fact] + public void Text_IsVarcharAndTimesAreDatetime() + { + IEntityType report = Entity(); + + Assert.False(report.FindProperty(nameof(ReportDefinition.Title))?.IsUnicode()); + Assert.Equal("datetime", report.FindProperty(nameof(ReportDefinition.ModifiedOn))?.GetColumnType()); + } + + [Fact] + public void Enums_AreStoredByName() + { + IEntityType parameter = Entity(); + + Assert.Equal(typeof(string), parameter.FindProperty(nameof(ReportParameter.Binding))?.GetProviderClrType()); + Assert.Equal(typeof(string), parameter.FindProperty(nameof(ReportParameter.Operator))?.GetProviderClrType()); + Assert.Equal(typeof(string), Entity().FindProperty(nameof(ReportColumn.Format))?.GetProviderClrType()); + } + + [Fact] + public void Slugs_AreUniqueAndGeneratedByTheDatabase() + { + IEntityType report = Entity(); + + Assert.Contains(report.GetIndexes(), index => + index.IsUnique && index.Properties.Single().Name == nameof(ReportDefinition.Slug)); + Assert.Equal("newid()", report.FindProperty(nameof(ReportDefinition.Slug))?.GetDefaultValueSql()); + } + + [Fact] + public void Permissions_AreKeyedByReportAndName() + { + Assert.Equal( + [nameof(ReportPermission.ReportId), nameof(ReportPermission.Permission)], + Entity().FindPrimaryKey()!.Properties.Select(p => p.Name)); + } +} diff --git a/test/ReportBuilder/ReportBuilderFakes.cs b/test/ReportBuilder/ReportBuilderFakes.cs new file mode 100644 index 000000000..14cc14ea4 --- /dev/null +++ b/test/ReportBuilder/ReportBuilderFakes.cs @@ -0,0 +1,117 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// A fresh in-memory for a test, isolated from the others. +internal static class ReportBuilderTestDb +{ + public static DbContextOptions CreateOptions() + { + return new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + + // The in-memory provider doesn't support transactions; the admin service wraps a + // mutation and its history write in one so they commit or roll back together on SQL + // Server, where it matters. + .ConfigureWarnings(warnings => warnings.Ignore(InMemoryEventId.TransactionIgnoredWarning)) + .Options; + } +} + +/// A query executor that records each command and answers with prepared rows. +internal sealed class FakeReportQueryExecutor : IReportQueryExecutor +{ + public List<(ReportSqlCommand Command, int MaxRows, TimeSpan Timeout)> Calls { get; } = []; + + /// Picks the answer for a command; by default, no rows. + public Func Answer { get; set; } = + _ => new ReportQueryResult { Rows = [], Truncated = false }; + + public ReportSqlCommand LastCommand => Calls[^1].Command; + + public Task QueryAsync(ReportSqlCommand command, int maxRows, TimeSpan timeout, CancellationToken ct) + { + Calls.Add((command, maxRows, timeout)); + return Task.FromResult(Answer(command)); + } + + public static IReadOnlyDictionary Row(params (string Column, object? Value)[] values) + { + return values.ToDictionary(v => v.Column, v => v.Value, StringComparer.OrdinalIgnoreCase); + } +} + +/// A catalog holding a fixed set of sources. +internal sealed class FakeReportSourceCatalog : IReportSourceCatalogService +{ + public List Sources { get; } = []; + + public Task> GetSourcesAsync(CancellationToken ct) + { + return Task.FromResult>( + [.. Sources.Select(s => new ReportSourceSummary { Name = s.Name, Kind = s.Kind })]); + } + + public Task GetSourceAsync(string name, CancellationToken ct) + { + return Task.FromResult(Sources.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase))); + } + + public static ReportSourceColumn Column(string name, ReportValueKind kind = ReportValueKind.Text) + { + return new ReportSourceColumn { Name = name, SqlType = "varchar", Kind = kind, IsNullable = true, IsSupported = true }; + } + + public static ReportSourceParameter Parameter(string name, bool supported = true) + { + return new ReportSourceParameter { Name = name, SqlType = "varchar", Kind = ReportValueKind.Text, IsSupported = supported }; + } +} + +/// A signed-in user (or no one) with a fixed set of permissions. +internal sealed class FakeReportUserService : IReportUserService +{ + public ReportCurrentUser? User { get; set; } = new() { LoginId = "jdoe", MothraId = "01234567" }; + + public HashSet Permissions { get; } = new(StringComparer.OrdinalIgnoreCase); + + public ReportCurrentUser? GetCurrentUser() + { + return User; + } + + public bool HasPermission(string permission) + { + return User is not null && Permissions.Contains(permission); + } +} + +/// RAPS with a fixed set of permission names. +internal sealed class FakeReportPermissionLookup : IReportPermissionLookupService +{ + public HashSet Names { get; } = new(StringComparer.OrdinalIgnoreCase) { "SVMSecure.Personnel", "SVMSecure.Effort" }; + + public Task> SearchAsync(string? text, CancellationToken ct) + { + return Task.FromResult>( + [.. Names.Where(n => n.Contains(text ?? string.Empty, StringComparison.OrdinalIgnoreCase)).Select(n => new ReportPermissionOption { Permission = n })]); + } + + public Task> FindAsync(IEnumerable names, CancellationToken ct) + { + var found = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (string name in names) + { + if (Names.TryGetValue(name, out string? spelled)) + { + found.TryAdd(name, spelled); + } + } + + return Task.FromResult>(found); + } +} diff --git a/test/ReportBuilder/ReportBuilderJsonTests.cs b/test/ReportBuilder/ReportBuilderJsonTests.cs new file mode 100644 index 000000000..5eecdcaf9 --- /dev/null +++ b/test/ReportBuilder/ReportBuilderJsonTests.cs @@ -0,0 +1,51 @@ +using System.Text.Json; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.test.ReportBuilder; + +/// What the browser receives: enums by name, row values keyed by column name. +public sealed class ReportBuilderJsonTests +{ + private static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web); + + [Fact] + public void Enums_AreSentByName() + { + string json = JsonSerializer.Serialize(new ReportViewerParameter + { + Name = "Dept", + Label = "Department", + Type = ReportParameterType.MultiChoice, + Required = false, + }, Web); + + Assert.Contains("\"type\":\"MultiChoice\"", json); + } + + [Fact] + public void Enums_AreReadByName() + { + Assert.Equal(ReportColumnFormat.YesNo, JsonSerializer.Deserialize("\"YesNo\"", Web)); + } + + [Fact] + public void RunRequest_IsReadFromTheBrowsersShape() + { + ReportRunRequest? request = JsonSerializer.Deserialize( + """{"parameters":{"Dept":["VME","PMI"]},"page":2,"perPage":50,"sortBy":"Name","sortDescending":true,"search":"ada"}""", Web); + + Assert.NotNull(request); + Assert.Equal(["VME", "PMI"], request.Parameters["Dept"]); + Assert.Equal(2, request.Page); + Assert.Equal(50, request.PerPage); + Assert.Equal("Name", request.SortBy); + Assert.True(request.SortDescending); + Assert.Equal("ada", request.Search); + } + + [Fact] + public void RunRequest_WithoutPage_IsRefused() + { + Assert.Throws(() => JsonSerializer.Deserialize("""{"parameters":{},"sortDescending":false}""", Web)); + } +} diff --git a/test/ReportBuilder/ReportCellFormatterTests.cs b/test/ReportBuilder/ReportCellFormatterTests.cs new file mode 100644 index 000000000..98ea345b0 --- /dev/null +++ b/test/ReportBuilder/ReportCellFormatterTests.cs @@ -0,0 +1,108 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// Values as text, the way the PDF download and filter headings show them. +public sealed class ReportCellFormatterTests +{ + private static readonly DateTime Midnight = new(2026, 3, 1, 0, 0, 0, DateTimeKind.Local); + private static readonly DateTime Afternoon = new(2026, 3, 1, 14, 5, 0, DateTimeKind.Local); + + [Fact] + public void Null_IsEmpty() + { + Assert.Equal(string.Empty, ReportCellFormatter.Text(null, ReportColumnFormat.Number)); + } + + [Theory] + [InlineData(ReportColumnFormat.Text, "1,234.5")] + [InlineData(ReportColumnFormat.Number, "1,234.5")] + [InlineData(ReportColumnFormat.Currency, "$1,234.50")] + [InlineData(ReportColumnFormat.Percent, "123,450%")] + public void Numbers_FollowTheColumnFormat(ReportColumnFormat format, string expected) + { + Assert.Equal(expected, ReportCellFormatter.Text(1234.5m, format)); + } + + [Fact] + public void Percent_IsAFraction() + { + Assert.Equal("25.5%", ReportCellFormatter.Text(0.255, ReportColumnFormat.Percent)); + } + + [Theory] + [InlineData(7)] + [InlineData(7L)] + [InlineData((short)7)] + [InlineData((byte)7)] + [InlineData(7.0)] + [InlineData(7f)] + public void EveryNumberType_IsANumber(object value) + { + Assert.Equal("7", ReportCellFormatter.Text(value, ReportColumnFormat.Number)); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(1e30)] + public void DoublesThatDontFitADecimal_AreNotNumbers(double value) + { + Assert.False(ReportCellFormatter.TryGetNumber(value, out _)); + } + + [Fact] + public void Dates_ShowTheTimeOnlyWhenTheyHaveOneOrTheColumnAsks() + { + Assert.Equal("03/01/2026", ReportCellFormatter.Text(Midnight, ReportColumnFormat.Text)); + Assert.Equal("03/01/2026 2:05 PM", ReportCellFormatter.Text(Afternoon, ReportColumnFormat.Text)); + Assert.Equal("03/01/2026", ReportCellFormatter.Text(Afternoon, ReportColumnFormat.Date)); + Assert.Equal("03/01/2026 12:00 AM", ReportCellFormatter.Text(Midnight, ReportColumnFormat.DateTime)); + Assert.Equal("03/01/2026", ReportCellFormatter.Text(new DateTimeOffset(Midnight), ReportColumnFormat.Date)); + Assert.Equal("03/01/2026", ReportCellFormatter.Text(new DateOnly(2026, 3, 1), ReportColumnFormat.Text)); + } + + [Theory] + [InlineData(true, "Yes")] + [InlineData(false, "No")] + [InlineData(1, "Yes")] + [InlineData(0, "No")] + [InlineData(" y ", "Yes")] + [InlineData("TRUE", "Yes")] + [InlineData("n", "No")] + [InlineData("0", "No")] + [InlineData("Maybe", "Maybe")] + public void YesNo_ReadsFlagsNumbersAndWords(object value, string expected) + { + Assert.Equal(expected, ReportCellFormatter.Text(value, ReportColumnFormat.YesNo)); + } + + [Fact] + public void OtherValues_AreShownPlainly() + { + Guid id = Guid.Parse("8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e"); + + Assert.Equal("Yes", ReportCellFormatter.Text(true, ReportColumnFormat.Text)); + Assert.Equal("No", ReportCellFormatter.Text(false, ReportColumnFormat.Number)); + Assert.Equal("1:30 PM", ReportCellFormatter.Text(new TimeSpan(13, 30, 0), ReportColumnFormat.Text)); + Assert.Equal("8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e", ReportCellFormatter.Text(id, ReportColumnFormat.Text)); + Assert.Equal("abc", ReportCellFormatter.Text("abc", ReportColumnFormat.Currency)); + } + + [Theory] + [InlineData(ReportColumnFormat.Number, true)] + [InlineData(ReportColumnFormat.Currency, true)] + [InlineData(ReportColumnFormat.Percent, true)] + [InlineData(ReportColumnFormat.Text, false)] + [InlineData(ReportColumnFormat.Date, false)] + public void IsNumeric(ReportColumnFormat format, bool expected) + { + Assert.Equal(expected, ReportCellFormatter.IsNumeric(format)); + } + + [Fact] + public void TryGetDateTime_OtherValues_AreNotDates() + { + Assert.False(ReportCellFormatter.TryGetDateTime("2026-03-01", out _)); + } +} diff --git a/test/ReportBuilder/ReportChoiceListTests.cs b/test/ReportBuilder/ReportChoiceListTests.cs new file mode 100644 index 000000000..1c6644ae3 --- /dev/null +++ b/test/ReportBuilder/ReportChoiceListTests.cs @@ -0,0 +1,48 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// A parameter's fixed choice list is a JSON array of strings or value/label objects. +public sealed class ReportChoiceListTests +{ + [Fact] + public void Parse_StringsAndObjects() + { + IReadOnlyList? choices = ReportChoiceList.Parse( + """["VME", {"Value": "PMI", "Label": "Pathology"}, {"value": 3}, {"value": "X", "label": " "}, {"value": "Y", "label": 2}]"""); + + Assert.Equal( + [ + new ReportChoice { Value = "VME", Label = "VME" }, + new ReportChoice { Value = "PMI", Label = "Pathology" }, + new ReportChoice { Value = "3", Label = "3" }, + new ReportChoice { Value = "X", Label = "X" }, + new ReportChoice { Value = "Y", Label = "2" }, + ], + choices); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("not json")] + [InlineData("""{"value": "VME"}""")] + [InlineData("""["VME", 3]""")] + [InlineData("""[""]""")] + [InlineData("""[{"label": "No value"}]""")] + public void Parse_AnythingElse_IsNull(string? json) + { + Assert.Null(ReportChoiceList.Parse(json)); + } + + [Fact] + public void Parse_EmptyArray_IsEmpty() + { + IReadOnlyList? choices = ReportChoiceList.Parse("[]"); + + Assert.NotNull(choices); + Assert.Empty(choices); + } +} diff --git a/test/ReportBuilder/ReportChoiceServiceTests.cs b/test/ReportBuilder/ReportChoiceServiceTests.cs new file mode 100644 index 000000000..a217bb089 --- /dev/null +++ b/test/ReportBuilder/ReportChoiceServiceTests.cs @@ -0,0 +1,121 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// Choices come from a parameter's fixed list, or else from a [report] view the catalog lists. +public sealed class ReportChoiceServiceTests +{ + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportQueryExecutor _executor = new(); + private readonly ReportChoiceService _service; + + public ReportChoiceServiceTests() + { + _service = new ReportChoiceService(_catalog, _executor); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "DeptChoices", + Kind = ReportSourceKind.View, + Columns = [], + Parameters = [], + PagesInSql = true, + }); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "usp_Choices", + Kind = ReportSourceKind.Procedure, + Columns = [], + Parameters = [], + PagesInSql = false, + }); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ReportParameter Choice(string name, string? list = null, string? source = null, + ReportParameterType type = ReportParameterType.Choice) + { + return new ReportParameter { Name = name, Type = type, ChoicesList = list, ChoicesSource = source }; + } + + [Fact] + public async Task FixedList_IsUsedWithoutAQuery() + { + IReadOnlyDictionary> choices = await _service.GetChoicesAsync( + [Choice("Dept", list: """["VME"]""", source: "DeptChoices")], Ct); + + Assert.Equal([new ReportChoice { Value = "VME", Label = "VME" }], choices["dept"]); + Assert.Empty(_executor.Calls); + } + + [Fact] + public async Task View_IsReadForValuesAndLabels() + { + _executor.Answer = _ => new ReportQueryResult + { + Rows = + [ + FakeReportQueryExecutor.Row(("value", "VME"), ("label", "Medicine")), + FakeReportQueryExecutor.Row(("Value", 7), ("Label", null)), + FakeReportQueryExecutor.Row(("Value", null), ("Label", "No value")), + FakeReportQueryExecutor.Row(("Label", "No value column")), + ], + Truncated = false, + }; + + IReadOnlyDictionary> choices = await _service.GetChoicesAsync( + [Choice("Dept", list: "not json", source: " deptchoices ", type: ReportParameterType.MultiChoice)], Ct); + + Assert.Equal( + [new ReportChoice { Value = "VME", Label = "Medicine" }, new ReportChoice { Value = "7", Label = "7" }], + choices["Dept"]); + (ReportSqlCommand command, int maxRows, TimeSpan timeout) = Assert.Single(_executor.Calls); + Assert.Equal(ReportSqlBuilder.BuildChoices("DeptChoices").Text, command.Text); + Assert.Equal(ReportLimits.MaxChoices, maxRows); + Assert.Equal(ReportLimits.ScreenTimeout, timeout); + } + + [Theory] + [InlineData("Missing")] + [InlineData("usp_Choices")] + public async Task SourceThatIsNotACatalogView_HasNoChoices(string source) + { + IReadOnlyDictionary> choices = await _service.GetChoicesAsync([Choice("Dept", source: source)], Ct); + + Assert.Empty(choices); + Assert.Empty(_executor.Calls); + } + + [Fact] + public async Task OtherParameters_AreSkipped() + { + IReadOnlyDictionary> choices = await _service.GetChoicesAsync( + [ + new ReportParameter { Name = "Name", Type = ReportParameterType.Text, ChoicesList = """["x"]""" }, + new ReportParameter { Name = " ", Type = ReportParameterType.Choice, ChoicesList = """["x"]""" }, + Choice("Dept"), + ], Ct); + + Assert.Empty(choices); + } + + [Fact] + public async Task LongLists_AreCapped() + { + string list = "[" + string.Join(",", Enumerable.Range(0, ReportLimits.MaxChoices + 5).Select(i => $"\"{i}\"")) + "]"; + + IReadOnlyDictionary> choices = await _service.GetChoicesAsync([Choice("N", list: list)], Ct); + + Assert.Equal(ReportLimits.MaxChoices, choices["N"].Count); + } + + [Fact] + public async Task Catalog_IsReadOnceForSeveralViews() + { + await _service.GetChoicesAsync([Choice("A", source: "DeptChoices"), Choice("B", source: "DeptChoices")], Ct); + + Assert.Equal(2, _executor.Calls.Count); + } +} diff --git a/test/ReportBuilder/ReportDefinitionValidatorTests.cs b/test/ReportBuilder/ReportDefinitionValidatorTests.cs new file mode 100644 index 000000000..cc4bcba59 --- /dev/null +++ b/test/ReportBuilder/ReportDefinitionValidatorTests.cs @@ -0,0 +1,349 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// A report is checked before it's saved or previewed: its source, columns and parameters must +/// exist in the [report] catalog, settings must fit together, and permissions must be RAPS's. +/// +public sealed class ReportDefinitionValidatorTests +{ + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportPermissionLookup _permissions = new(); + private readonly ReportDefinitionValidator _validator; + + public ReportDefinitionValidatorTests() + { + _validator = new ReportDefinitionValidator(_catalog, _permissions); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "FacultyRoster", + Kind = ReportSourceKind.View, + Columns = + [ + FakeReportSourceCatalog.Column("Name"), + FakeReportSourceCatalog.Column("Dept"), + FakeReportSourceCatalog.Column("Hired", ReportValueKind.Date), + FakeReportSourceCatalog.Column("Salary", ReportValueKind.FractionalNumber), + new ReportSourceColumn { Name = "Photo", SqlType = "varbinary", Kind = ReportValueKind.Binary, IsNullable = true, IsSupported = false }, + ], + Parameters = [], + PagesInSql = true, + }); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "usp_Leave", + Kind = ReportSourceKind.Procedure, + Columns = [], + ColumnsError = "Uses a temp table.", + Parameters = [FakeReportSourceCatalog.Parameter("LoginId"), FakeReportSourceCatalog.Parameter("Out", supported: false)], + PagesInSql = false, + }); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "DeptChoices", + Kind = ReportSourceKind.View, + Columns = [FakeReportSourceCatalog.Column("Value"), FakeReportSourceCatalog.Column("Label")], + Parameters = [], + PagesInSql = true, + }); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ReportColumnEdit Column(string name, bool visible = true) + { + return new ReportColumnEdit { SourceColumn = name, Format = ReportColumnFormat.Text, Sortable = true, Visible = visible }; + } + + private static ReportParameterEdit Parameter(string name, ReportParameterType type = ReportParameterType.Text, + ReportFilterOperator? op = null, string? defaultValue = null) + { + return new ReportParameterEdit { Name = name, Type = type, Operator = op, DefaultValue = defaultValue, Binding = ReportParameterBinding.UserInput }; + } + + private static ReportEditRequest Roster(params ReportParameterEdit[] parameters) + { + return new ReportEditRequest + { + Title = "Faculty roster", + Source = "facultyroster", + Columns = [Column("name"), Column("Dept")], + Parameters = parameters, + Permissions = ["svmsecure.personnel", " SVMSecure.Personnel "], + }; + } + + private Task Validate(ReportEditRequest request) + { + return _validator.ValidateAsync(request, Ct); + } + + [Fact] + public async Task ValidReport_HasNoErrorsAndTheCatalogsSpellings() + { + ReportValidation result = await Validate(Roster()); + + Assert.Empty(result.Errors); + Assert.Equal("FacultyRoster", result.Source?.Name); + Assert.Equal("Name", result.SourceNames["name"]); + Assert.Equal(["SVMSecure.Personnel"], result.Permissions); + } + + [Fact] + public async Task ReportFields_AreChecked() + { + ReportValidation result = await Validate(Roster() with + { + Title = " ", + Area = new string('a', 501), + SensitiveNotice = new string('n', 501), + PageSize = 0, + }); + + Assert.Equal( + [ + "Enter a title.", + "The area must be 500 characters or fewer.", + "The confidentiality notice must be 500 characters or fewer.", + "Rows per page must be between 1 and 500.", + ], + result.Errors); + } + + [Theory] + [InlineData("", "Choose a data source.")] + [InlineData("Dropped", "'Dropped' isn't a view or procedure in the [report] schema.")] + public async Task UnknownSource_IsAnErrorAndNothingElseIsChecked(string source, string error) + { + ReportValidation result = await Validate(Roster() with { Source = source, Columns = [] }); + + Assert.Equal([error], result.Errors); + Assert.Null(result.Source); + } + + [Fact] + public async Task Columns_MustExistBeShowableAndListedOnce() + { + ReportValidation result = await Validate(Roster() with + { + Columns = [Column("Name"), Column("NAME"), Column("Salary2"), Column("Photo"), Column(" ")], + OrderBy = "Nope", + }); + + Assert.Equal( + [ + "The column 'NAME' is listed more than once.", + "The source has no column named 'Salary2'.", + "The column 'Photo' holds varbinary values, which a report can't show.", + "Every column needs a source column.", + "The source has no column named 'Nope' to sort by.", + ], + result.Errors); + } + + [Fact] + public async Task Columns_AtLeastOneMustShow() + { + ReportValidation result = await Validate(Roster() with { Columns = [Column("Name", visible: false)] }); + + Assert.Equal(["Show at least one column."], result.Errors); + } + + [Fact] + public async Task ColumnHeadings_HaveALimit() + { + ReportValidation result = await Validate(Roster() with { Columns = [Column("Name") with { Label = new string('x', 501) }] }); + + Assert.Equal(["The heading of 'Name' must be 500 characters or fewer."], result.Errors); + } + + [Fact] + public async Task ProcedureWithUnknownColumns_TakesItsColumnsOnTrust() + { + ReportValidation result = await Validate(new ReportEditRequest + { + Title = "Leave", + Source = "usp_Leave", + Columns = [Column("Anything")], + OrderBy = "Anything", + Parameters = [Parameter("LoginId") with { Binding = ReportParameterBinding.CurrentUserLoginId }], + }); + + Assert.Empty(result.Errors); + } + + [Fact] + public async Task ProcedureParameters_MustBeOnesItTakes() + { + ReportValidation result = await Validate(new ReportEditRequest + { + Title = "Leave", + Source = "usp_Leave", + Columns = [Column("Name")], + Parameters = [Parameter("Out"), Parameter("Year")], + }); + + Assert.Equal( + [ + "The parameter 'Out' doesn't match a parameter the procedure takes.", + "The parameter 'Year' doesn't match a parameter the procedure takes.", + ], + result.Errors); + } + + [Fact] + public async Task ViewParameters_MustBeColumnsAndListedOnce() + { + ReportValidation result = await Validate(Roster(Parameter("Building"), Parameter("Dept"), Parameter("dept"), Parameter(" "))); + + Assert.Equal( + [ + "The parameter 'Building' doesn't match a column of the view.", + "The parameter 'dept' is listed more than once.", + "Every parameter needs a name.", + ], + result.Errors); + } + + [Theory] + [InlineData(ReportParameterType.MultiChoice, ReportFilterOperator.In, true)] + [InlineData(ReportParameterType.MultiChoice, ReportFilterOperator.Equals, false)] + [InlineData(ReportParameterType.Choice, ReportFilterOperator.In, false)] + [InlineData(ReportParameterType.Text, ReportFilterOperator.Contains, true)] + [InlineData(ReportParameterType.Number, ReportFilterOperator.Contains, false)] + [InlineData(ReportParameterType.Date, ReportFilterOperator.From, true)] + [InlineData(ReportParameterType.Number, ReportFilterOperator.To, true)] + [InlineData(ReportParameterType.Text, ReportFilterOperator.From, false)] + [InlineData(ReportParameterType.Boolean, ReportFilterOperator.Equals, true)] + public async Task Operators_MustSuitTheType(ReportParameterType type, ReportFilterOperator op, bool fits) + { + ReportParameterEdit parameter = Parameter("Dept", type, op) with { ChoicesList = [new ReportChoice { Value = "VME", Label = "Medicine" }] }; + + ReportValidation result = await Validate(Roster(parameter)); + + Assert.Equal(fits, result.Errors.Count == 0); + } + + [Fact] + public async Task MultiChoiceWithoutAnOperator_NeedsIn() + { + ReportValidation result = await Validate(Roster(Parameter("Dept", ReportParameterType.MultiChoice) with + { + ChoicesSource = "DeptChoices", + })); + + Assert.Equal(["The parameter 'Dept' can't use 'Equals' with a MultiChoice value."], result.Errors); + } + + [Fact] + public async Task Choices_NeedAListOrACatalogView() + { + ReportValidation result = await Validate(Roster( + Parameter("Name", ReportParameterType.Choice), + Parameter("Dept", ReportParameterType.Choice) with { ChoicesSource = "usp_Leave" }, + Parameter("Hired", ReportParameterType.Choice) with { ChoicesSource = " deptchoices " })); + + Assert.Equal( + [ + "The parameter 'Name' needs a list of choices or a view to read them from.", + "The parameter 'Dept''s choices view 'usp_Leave' isn't a view in the [report] schema.", + ], + result.Errors); + } + + [Fact] + public async Task ChoiceLists_NeedDistinctValues() + { + ReportValidation result = await Validate(Roster(Parameter("Dept", ReportParameterType.Choice) with + { + ChoicesList = [new ReportChoice { Value = "VME", Label = "A" }, new ReportChoice { Value = "vme", Label = "B" }, new ReportChoice { Value = " ", Label = "C" }], + })); + + Assert.Equal( + ["The parameter 'Dept' has a choice without a value.", "The parameter 'Dept' has the same choice more than once."], + result.Errors); + } + + [Fact] + public async Task ChoiceLists_CannotExceedTheMax() + { + ReportChoice[] choices = [.. Enumerable.Range(0, ReportLimits.MaxChoices + 1).Select(i => new ReportChoice { Value = $"{i}", Label = $"{i}" })]; + + ReportValidation result = await Validate(Roster(Parameter("Dept", ReportParameterType.Choice) with { ChoicesList = choices })); + + Assert.Equal([$"The parameter 'Dept' can have at most {ReportLimits.MaxChoices} choices."], result.Errors); + } + + [Theory] + [InlineData(ReportParameterType.Number, "1,000.5", true)] + [InlineData(ReportParameterType.Number, "ten", false)] + [InlineData(ReportParameterType.Date, "2026-03-01", true)] + [InlineData(ReportParameterType.Date, "03/01/2026", false)] + [InlineData(ReportParameterType.Boolean, "true", true)] + [InlineData(ReportParameterType.Boolean, "yes", false)] + [InlineData(ReportParameterType.Choice, "vme", true)] + [InlineData(ReportParameterType.Choice, "XYZ", false)] + [InlineData(ReportParameterType.Text, "anything", true)] + public async Task Defaults_MustFitTheType(ReportParameterType type, string value, bool valid) + { + ReportFilterOperator? op = type is ReportParameterType.Number or ReportParameterType.Date ? ReportFilterOperator.From : null; + ReportParameterEdit parameter = Parameter("Dept", type, op, value) with { ChoicesList = [new ReportChoice { Value = "VME", Label = "Medicine" }] }; + + string[] expected = valid ? [] : [$"The parameter 'Dept''s default '{value}' isn't a valid {type} value."]; + + ReportValidation result = await Validate(Roster(parameter)); + + Assert.Equal(expected, result.Errors); + } + + [Fact] + public async Task DefaultForAChoiceFromAView_IsCheckedWhenRun() + { + ReportValidation result = await Validate(Roster(Parameter("Dept", ReportParameterType.Choice, defaultValue: "Anything") with { ChoicesSource = "DeptChoices" })); + + Assert.Empty(result.Errors); + } + + [Fact] + public async Task CurrentUserParameters_SkipTypeChoiceAndDefaultChecks() + { + ReportValidation result = await Validate(Roster(Parameter("Name", ReportParameterType.MultiChoice, ReportFilterOperator.Contains, "x") with + { + Binding = ReportParameterBinding.CurrentUserLoginId, + })); + + Assert.Empty(result.Errors); + } + + [Fact] + public async Task ParameterText_HasLimits() + { + ReportValidation result = await Validate(Roster(Parameter("Name") with { Label = new string('l', 501), DefaultValue = new string('d', 501) })); + + Assert.Equal( + [ + "The parameter 'Name''s label must be 500 characters or fewer.", + "The parameter 'Name''s default must be 500 characters or fewer.", + ], + result.Errors); + } + + [Fact] + public async Task Permissions_MustBeRapsPermissions() + { + string tooLong = "SVMSecure." + new string('x', 100); + + ReportValidation result = await Validate(Roster() with { Permissions = ["SVMSecure.Personnel", "SVMSecure.Typo", tooLong, " "] }); + + Assert.Equal( + [ + $"The permission '{tooLong[..50]}…' is longer than 100 characters.", + "RAPS has no permission named 'SVMSecure.Typo'.", + $"RAPS has no permission named '{tooLong[..50]}…'.", + ], + result.Errors); + Assert.Equal(["SVMSecure.Personnel"], result.Permissions); + } +} diff --git a/test/ReportBuilder/ReportExcelWriterTests.cs b/test/ReportBuilder/ReportExcelWriterTests.cs new file mode 100644 index 000000000..1f99e1771 --- /dev/null +++ b/test/ReportBuilder/ReportExcelWriterTests.cs @@ -0,0 +1,161 @@ +using ClosedXML.Excel; +using Viper.Areas.ReportBuilder.Exporters; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.test.ReportBuilder; + +/// The Excel download: heading, an accessible table, typed numbers and dates, and safe text. +public sealed class ReportExcelWriterTests +{ + private static readonly DateTimeOffset GeneratedAt = new(2026, 11, 16, 9, 5, 0, TimeSpan.Zero); + private static readonly DateTime Hired = new(2026, 3, 1, 0, 0, 0, DateTimeKind.Local); + private static readonly DateTime Updated = new(2026, 3, 1, 14, 5, 0, DateTimeKind.Local); + + private static ReportResultColumn Column(string name, ReportColumnFormat format, string? label = null) + { + return new ReportResultColumn { Name = name, Label = label ?? name, Format = format, Sortable = true }; + } + + private static ReportExportDocument Document(bool heading = true) + { + return new ReportExportDocument + { + Title = "Faculty roster", + GeneratedAt = GeneratedAt, + Filters = heading ? [new ReportAppliedFilter { Label = "Department", Value = "Pathology" }] : [], + SensitiveNotice = heading ? "Confidential" : null, + Truncated = heading, + Columns = + [ + Column("Name", ReportColumnFormat.Text), + Column("Count", ReportColumnFormat.Number), + Column("Salary", ReportColumnFormat.Currency), + Column("Share", ReportColumnFormat.Percent), + Column("Hired", ReportColumnFormat.Date), + Column("Updated", ReportColumnFormat.DateTime), + Column("Active", ReportColumnFormat.YesNo), + Column("Notes", ReportColumnFormat.Text, "Name"), + ], + Rows = + [ + FakeReportQueryExecutor.Row(("Name", "=SUM(A1)"), ("Count", 3), ("Salary", 1234.5m), ("Share", 0.25m), + ("Hired", Hired), ("Updated", Updated), ("Active", true), ("Notes", Updated)), + FakeReportQueryExecutor.Row(("Name", "Bo"), ("Count", 4), ("Salary", null), ("Share", 0.5m), ("Active", false)), + ], + }; + } + + private static XLWorkbook Open(ReportExportDocument document) + { + return new XLWorkbook(new MemoryStream(ReportExcelWriter.Write(document))); + } + + [Fact] + public void Heading_ShowsTitleGeneratedFiltersNoticeAndTruncation() + { + using XLWorkbook workbook = Open(Document()); + IXLWorksheet sheet = workbook.Worksheet(1); + + Assert.Equal("Faculty roster", sheet.Name); + Assert.Equal("Faculty roster", workbook.Properties.Title); + Assert.Equal("Faculty roster", sheet.Cell(1, 1).GetString()); + Assert.True(sheet.Cell(1, 1).Style.Font.Bold); + Assert.Equal("Generated 11/16/2026 9:05 AM", sheet.Cell(2, 1).GetString()); + Assert.Equal("Filters: Department: Pathology", sheet.Cell(3, 1).GetString()); + Assert.Equal("Confidential", sheet.Cell(4, 1).GetString()); + Assert.True(sheet.Cell(4, 1).Style.Font.Italic); + Assert.Equal("Only the first 50,000 rows are included.", sheet.Cell(5, 1).GetString()); + Assert.Equal("Name", sheet.Cell(7, 1).GetString()); + } + + [Fact] + public void Heading_WithoutExtras_StartsTheTableSooner() + { + using XLWorkbook workbook = Open(Document(heading: false)); + IXLWorksheet sheet = workbook.Worksheet(1); + + Assert.Equal("Name", sheet.Cell(4, 1).GetString()); + Assert.Equal("Bo", sheet.Cell(6, 1).GetString()); + } + + [Fact] + public void Rows_AreAnAccessibleTableWithUniqueHeaders() + { + using XLWorkbook workbook = Open(Document(heading: false)); + IXLWorksheet sheet = workbook.Worksheet(1); + + IXLTable table = Assert.Single(sheet.Tables); + Assert.Equal("ReportTable", table.Name); + Assert.Equal("Name (2)", sheet.Cell(4, 8).GetString()); + Assert.True(sheet.Cell(4, 1).Style.Font.Bold); + } + + [Fact] + public void Values_StayTypedWithFormatsByColumn() + { + using XLWorkbook workbook = Open(Document(heading: false)); + IXLWorksheet sheet = workbook.Worksheet(1); + + // A value that looks like a formula stays text. ClosedXML may keep the sanitizing + // apostrophe in the text or turn it into the cell's quote prefix, so check the outcome. + IXLCell formulaLike = sheet.Cell(5, 1); + Assert.False(formulaLike.HasFormula); + Assert.Equal(XLDataType.Text, formulaLike.DataType); + Assert.EndsWith("=SUM(A1)", formulaLike.GetString(), StringComparison.Ordinal); + Assert.Equal(3d, sheet.Cell(5, 2).GetDouble()); + Assert.Equal("#,##0", sheet.Cell(5, 2).Style.NumberFormat.Format); + Assert.Equal(1234.5d, sheet.Cell(5, 3).GetDouble()); + Assert.Equal("$#,##0.00", sheet.Cell(5, 3).Style.NumberFormat.Format); + Assert.True(sheet.Cell(6, 3).IsEmpty()); + Assert.Equal(0.25d, sheet.Cell(5, 4).GetDouble()); + Assert.Equal("0%", sheet.Cell(5, 4).Style.NumberFormat.Format); + Assert.Equal(Hired, sheet.Cell(5, 5).GetDateTime()); + Assert.Equal("mm/dd/yyyy", sheet.Cell(5, 5).Style.NumberFormat.Format); + Assert.Equal(Updated, sheet.Cell(5, 6).GetDateTime()); + Assert.Equal("mm/dd/yyyy h:mm AM/PM", sheet.Cell(5, 6).Style.NumberFormat.Format); + Assert.Equal("Yes", sheet.Cell(5, 7).GetString()); + Assert.Equal("No", sheet.Cell(6, 7).GetString()); + Assert.Equal("mm/dd/yyyy h:mm AM/PM", sheet.Cell(5, 8).Style.NumberFormat.Format); + } + + [Fact] + public void FractionalNumbers_GetTwoDecimals() + { + ReportExportDocument document = Document(heading: false) with + { + Rows = [FakeReportQueryExecutor.Row(("Count", 2.5), ("Share", 0.255m))], + }; + + using XLWorkbook workbook = Open(document); + IXLWorksheet sheet = workbook.Worksheet(1); + + Assert.Equal("#,##0.00", sheet.Cell(5, 2).Style.NumberFormat.Format); + Assert.Equal("0.00%", sheet.Cell(5, 4).Style.NumberFormat.Format); + } + + [Fact] + public void NoRows_HasNoTable() + { + using XLWorkbook workbook = Open(Document(heading: false) with { Rows = [] }); + + Assert.Empty(workbook.Worksheet(1).Tables); + } + + [Theory] + [InlineData(ReportColumnFormat.Number, true, "#,##0")] + [InlineData(ReportColumnFormat.Number, false, "#,##0.00")] + [InlineData(ReportColumnFormat.Currency, true, "$#,##0.00")] + [InlineData(ReportColumnFormat.Percent, false, "0.00%")] + [InlineData(ReportColumnFormat.Text, true, null)] + [InlineData(ReportColumnFormat.Date, true, null)] + public void NumberFormat_ByColumnFormat(ReportColumnFormat format, bool whole, string? expected) + { + Assert.Equal(expected, ReportExcelWriter.NumberFormat(format, whole)); + } + + [Fact] + public void NullDocument_Throws() + { + Assert.Throws(() => ReportExcelWriter.Write(null!)); + } +} diff --git a/test/ReportBuilder/ReportExportServiceTests.cs b/test/ReportBuilder/ReportExportServiceTests.cs new file mode 100644 index 000000000..cf94dd50c --- /dev/null +++ b/test/ReportBuilder/ReportExportServiceTests.cs @@ -0,0 +1,118 @@ +using System.Text; +using QuestPDF.Infrastructure; +using Viper.Areas.ReportBuilder.Exporters; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// A download runs the report in its own mode and writes the rows to the chosen format. +public sealed class ReportExportServiceTests +{ + private const string Slug = "8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e"; + private readonly FakeReportRunService _runs = new(); + private readonly ReportExportService _service; + + public ReportExportServiceTests() + { + // Program.cs sets this at startup; unit tests don't run Program.cs. + QuestPDF.Settings.License = LicenseType.Community; + _service = new ReportExportService(_runs); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ReportRunOutcome Ok(params IReadOnlyDictionary[] rows) + { + return new ReportRunOutcome + { + Status = ReportRunStatus.Ok, + Result = new ReportRunResult + { + Columns = [new ReportResultColumn { Name = "Name", Label = "Name", Format = ReportColumnFormat.Text, Sortable = true }], + Rows = rows, + Page = 1, + PerPage = rows.Length, + TotalRows = rows.Length, + Truncated = false, + }, + Details = new ReportRunDetails { Title = "Faculty: roster", PdfLandscape = true, Filters = [] }, + }; + } + + [Theory] + [InlineData("xlsx", ReportRunMode.ExportExcel, ReportExcelWriter.ContentType, "Faculty roster.xlsx", "PK")] + [InlineData("PDF", ReportRunMode.ExportPdf, ReportPdfWriter.ContentType, "Faculty roster.pdf", "%PDF-")] + public async Task Export_RunsInItsModeAndWritesTheFile(string format, ReportRunMode mode, string contentType, string fileName, string signature) + { + _runs.Outcome = Ok(FakeReportQueryExecutor.Row(("Name", "Ada"))); + var request = new ReportRunRequest { Search = "Ada" }; + + ReportExportOutcome outcome = await _service.ExportAsync(Slug, format, request, Ct); + + Assert.Equal(ReportRunStatus.Ok, outcome.Status); + ReportFile file = Assert.IsType(outcome.File); + Assert.Equal(contentType, file.ContentType); + Assert.Equal(fileName, file.FileName); + Assert.Equal(signature, Encoding.ASCII.GetString(file.Content, 0, signature.Length)); + Assert.Equal([(Slug, request, mode)], _runs.Calls); + } + + [Fact] + public async Task Export_NoRows_HasNoFile() + { + _runs.Outcome = Ok(); + + ReportExportOutcome outcome = await _service.ExportAsync(Slug, "xlsx", new ReportRunRequest(), Ct); + + Assert.Equal(ReportRunStatus.Ok, outcome.Status); + Assert.Null(outcome.File); + } + + [Theory] + [InlineData("csv")] + [InlineData("")] + public async Task Export_UnknownFormat_IsInvalidWithoutRunning(string format) + { + ReportExportOutcome outcome = await _service.ExportAsync(Slug, format, new ReportRunRequest(), Ct); + + Assert.Equal(ReportRunStatus.Invalid, outcome.Status); + Assert.Equal(["Choose a download format: xlsx or pdf."], outcome.Errors); + Assert.Empty(_runs.Calls); + } + + [Theory] + [InlineData(ReportRunStatus.Forbidden)] + [InlineData(ReportRunStatus.NotFound)] + [InlineData(ReportRunStatus.Invalid)] + [InlineData(ReportRunStatus.Unavailable)] + public async Task Export_RunThatFails_PassesTheFailureOn(ReportRunStatus status) + { + _runs.Outcome = new ReportRunOutcome { Status = status, Errors = ["Why"] }; + + ReportExportOutcome outcome = await _service.ExportAsync(Slug, "pdf", new ReportRunRequest(), Ct); + + Assert.Equal(status, outcome.Status); + Assert.Equal(["Why"], outcome.Errors); + Assert.Null(outcome.File); + } + + private sealed class FakeReportRunService : IReportRunService + { + public ReportRunOutcome Outcome { get; set; } = new() { Status = ReportRunStatus.NotFound }; + + public List<(string Slug, ReportRunRequest Request, ReportRunMode Mode)> Calls { get; } = []; + + public Task RunAsync(string slug, ReportRunRequest request, ReportRunMode mode, CancellationToken ct) + { + Calls.Add((slug, request, mode)); + return Task.FromResult(Outcome); + } + + public Task PreviewAsync(ReportDefinition report, ReportRunRequest request, CancellationToken ct) + { + throw new NotSupportedException("Downloads never preview."); + } + } +} diff --git a/test/ReportBuilder/ReportExportTextTests.cs b/test/ReportBuilder/ReportExportTextTests.cs new file mode 100644 index 000000000..b49d0f164 --- /dev/null +++ b/test/ReportBuilder/ReportExportTextTests.cs @@ -0,0 +1,37 @@ +using Viper.Areas.ReportBuilder.Exporters; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.test.ReportBuilder; + +public sealed class ReportExportTextTests +{ + [Fact] + public void Generated_IsUsDateAndTime() + { + Assert.Equal("Generated 11/16/2026 9:05 AM", ReportExportText.Generated(new DateTimeOffset(2026, 11, 16, 9, 5, 0, TimeSpan.Zero))); + } + + [Fact] + public void Filters_JoinsLabelsAndValues() + { + Assert.Equal( + "Filters: Department: Pathology; From: 07/01/2026", + ReportExportText.Filters( + [ + new ReportAppliedFilter { Label = "Department", Value = "Pathology" }, + new ReportAppliedFilter { Label = "From", Value = "07/01/2026" }, + ])); + } + + [Fact] + public void Filters_None_IsNull() + { + Assert.Null(ReportExportText.Filters([])); + } + + [Fact] + public void Truncated_NamesTheCap() + { + Assert.Equal("Only the first 50,000 rows are included.", ReportExportText.Truncated()); + } +} diff --git a/test/ReportBuilder/ReportParameterBinderTests.cs b/test/ReportBuilder/ReportParameterBinderTests.cs new file mode 100644 index 000000000..fadb0be26 --- /dev/null +++ b/test/ReportBuilder/ReportParameterBinderTests.cs @@ -0,0 +1,260 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// Binding checks every value a user sends against the report's parameters before any of it +/// is used, and fills current-user parameters on the server. +/// +public sealed class ReportParameterBinderTests +{ + private static readonly ReportCurrentUser User = new() { LoginId = "jdoe", MothraId = "01234567" }; + + private static readonly IReadOnlyDictionary> NoChoices = + new Dictionary>(); + + private static readonly IReadOnlyDictionary> DeptChoices = + new Dictionary>(StringComparer.OrdinalIgnoreCase) + { + ["Dept"] = + [ + new ReportChoice { Value = "VME", Label = "Medicine & Epidemiology" }, + new ReportChoice { Value = "PMI", Label = "Pathology" }, + ], + }; + + private static ReportParameter Parameter(string name, ReportParameterType? type = ReportParameterType.Text, + bool? required = null, string? defaultValue = null, ReportParameterBinding? binding = null, string? label = null, + int? order = null) + { + return new ReportParameter + { + Name = name, + Label = label, + Type = type, + Required = required, + DefaultValue = defaultValue, + Binding = binding, + DisplayOrder = order, + Operator = ReportFilterOperator.Equals, + }; + } + + private static Dictionary> Input(params (string Name, string[] Values)[] values) + { + return values.ToDictionary(v => v.Name, v => (IReadOnlyList)v.Values); + } + + private static ReportBindResult Bind(ReportParameter definition, Dictionary> input, + IReadOnlyDictionary>? choices = null) + { + return ReportParameterBinder.Bind([definition], input, User, choices ?? NoChoices); + } + + private static object BoundValue(ReportBindResult result) + { + Assert.Empty(result.Errors); + return Assert.Single(result.Parameters).Value; + } + + [Fact] + public void Text_IsTrimmedAndMatchedIgnoringCase() + { + ReportBindResult result = Bind(Parameter("Name"), Input(("name", [" Smith "]))); + + BoundReportParameter parameter = Assert.Single(result.Parameters); + Assert.Equal("Name", parameter.Name); + Assert.Equal("Smith", parameter.Value); + Assert.Equal(ReportFilterOperator.Equals, parameter.Operator); + Assert.True(parameter.FromUser); + } + + [Fact] + public void Text_TooLong_IsAnError() + { + ReportBindResult result = Bind(Parameter("Name", label: "Last name"), Input(("Name", [new string('x', ReportLimits.MaxTextLength + 1)]))); + + Assert.Equal(["Last name must be 500 characters or fewer."], result.Errors); + Assert.Empty(result.Parameters); + } + + [Fact] + public void NoType_IsText() + { + Assert.Equal("x", BoundValue(Bind(Parameter("Name", type: null), Input(("Name", ["x"]))))); + } + + [Theory] + [InlineData("12.5", "12.5")] + [InlineData("-3", "-3")] + [InlineData("1,000", "1000")] + public void Number_IsParsedInvariantly(string given, string expected) + { + Assert.Equal(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), + BoundValue(Bind(Parameter("Salary", ReportParameterType.Number), Input(("Salary", [given]))))); + } + + [Fact] + public void Number_NotANumber_IsAnError() + { + Assert.Equal(["Salary must be a number."], Bind(Parameter("Salary", ReportParameterType.Number), Input(("Salary", ["ten"]))).Errors); + } + + [Fact] + public void Date_IsIsoDate() + { + Assert.Equal(new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Unspecified), + BoundValue(Bind(Parameter("Hired", ReportParameterType.Date), Input(("Hired", ["2026-03-01"]))))); + } + + [Theory] + [InlineData("03/01/2026")] + [InlineData("2026-3-1")] + [InlineData("2026-02-30")] + public void Date_OtherFormats_AreAnError(string given) + { + Assert.Equal(["Hired must be a date (YYYY-MM-DD)."], Bind(Parameter("Hired", ReportParameterType.Date), Input(("Hired", [given]))).Errors); + } + + [Theory] + [InlineData("true", true)] + [InlineData("False", false)] + public void Boolean_IsParsed(string given, bool expected) + { + Assert.Equal(expected, BoundValue(Bind(Parameter("Active", ReportParameterType.Boolean), Input(("Active", [given]))))); + } + + [Fact] + public void Boolean_Other_IsAnError() + { + Assert.Equal(["Active must be true or false."], Bind(Parameter("Active", ReportParameterType.Boolean), Input(("Active", ["yes"]))).Errors); + } + + [Fact] + public void Choice_MustBeOneOfTheChoices() + { + Assert.Equal("vme", BoundValue(Bind(Parameter("Dept", ReportParameterType.Choice), Input(("Dept", ["vme"])), DeptChoices))); + + Assert.Equal(["Dept has a value that isn't one of its choices."], + Bind(Parameter("Dept", ReportParameterType.Choice), Input(("Dept", ["XYZ"])), DeptChoices).Errors); + } + + [Fact] + public void Choice_UsesOnlyTheFirstValue() + { + Assert.Equal("PMI", BoundValue(Bind(Parameter("Dept", ReportParameterType.Choice), Input(("Dept", ["PMI", "XYZ"])), DeptChoices))); + } + + [Fact] + public void MultiChoice_KeepsDistinctAllowedValues() + { + object value = BoundValue(Bind(Parameter("Dept", ReportParameterType.MultiChoice), Input(("Dept", ["VME", "PMI", "vme", " "])), DeptChoices)); + + Assert.Equal(["VME", "PMI"], Assert.IsAssignableFrom>(value)); + } + + [Fact] + public void MultiChoice_AnyValueNotAllowed_IsAnError() + { + Assert.Equal(["Dept has a value that isn't one of its choices."], + Bind(Parameter("Dept", ReportParameterType.MultiChoice), Input(("Dept", ["VME", "XYZ"])), DeptChoices).Errors); + } + + [Fact] + public void Choice_WithoutChoices_IsAnError() + { + Assert.Equal(["Dept has no choices to pick from."], Bind(Parameter("Dept", ReportParameterType.Choice), Input(("Dept", ["VME"]))).Errors); + } + + [Fact] + public void Missing_UsesTheDefault() + { + BoundReportParameter parameter = Assert.Single(Bind(Parameter("Dept", defaultValue: " VME "), Input()).Parameters); + + Assert.Equal("VME", parameter.Value); + Assert.True(parameter.FromUser); + } + + [Fact] + public void BlankValues_UseTheDefault() + { + Assert.Equal("VME", BoundValue(Bind(Parameter("Dept", defaultValue: "VME"), Input(("Dept", ["", " "]))))); + } + + [Fact] + public void MissingOptional_IsLeftOut() + { + ReportBindResult result = Bind(Parameter("Dept"), Input()); + + Assert.Empty(result.Errors); + Assert.Empty(result.Parameters); + } + + [Fact] + public void MissingRequired_IsAnErrorNamedByLabel() + { + Assert.Equal(["Department is required."], Bind(Parameter("Dept", required: true, label: "Department"), Input()).Errors); + } + + [Theory] + [InlineData(ReportParameterBinding.CurrentUserLoginId, "jdoe")] + [InlineData(ReportParameterBinding.CurrentUserMothraId, "01234567")] + public void CurrentUser_IsFilledOnTheServer(ReportParameterBinding binding, string expected) + { + BoundReportParameter parameter = Assert.Single(Bind(Parameter("Who", binding: binding), Input()).Parameters); + + Assert.Equal(expected, parameter.Value); + Assert.Equal(ReportParameterType.Text, parameter.Type); + Assert.False(parameter.FromUser); + } + + [Fact] + public void CurrentUser_SuppliedByTheClient_IsRefused() + { + ReportBindResult result = Bind(Parameter("Who", binding: ReportParameterBinding.CurrentUserLoginId), Input(("who", ["someoneelse"]))); + + Assert.Equal(["Who is set automatically and can't be supplied."], result.Errors); + Assert.Empty(result.Parameters); + } + + [Fact] + public void CurrentUser_WithoutTheIdentifier_FailsClosed() + { + ReportBindResult result = ReportParameterBinder.Bind( + [Parameter("Who", binding: ReportParameterBinding.CurrentUserMothraId)], Input(), new ReportCurrentUser { LoginId = "jdoe" }, NoChoices); + + Assert.Equal(["Who can't be filled in for your account."], result.Errors); + } + + [Fact] + public void UnknownNames_AreErrorsWithTheNameShortened() + { + string longName = new('n', 60); + ReportBindResult result = Bind(Parameter("Dept"), Input(("Other", ["x"]), (longName, ["x"]))); + + Assert.Equal(["This report has no parameter named 'Other'.", $"This report has no parameter named '{new string('n', 50)}…'."], result.Errors); + } + + [Fact] + public void NamesDifferingOnlyByCase_AreFlaggedAsDuplicatesInsteadOfCrashing() + { + ReportBindResult result = Bind(Parameter("Dept"), Input(("Dept", ["PMI"]), ("dept", ["VME"]))); + + Assert.Equal(["The parameter 'dept' was sent more than once."], result.Errors); + Assert.Equal("PMI", Assert.Single(result.Parameters).Value); + } + + [Fact] + public void Parameters_AreBoundInDisplayOrderAndUnnamedOnesSkipped() + { + ReportBindResult result = ReportParameterBinder.Bind( + [Parameter("B", defaultValue: "b", order: 2), Parameter(" ", defaultValue: "x"), Parameter("A", defaultValue: "a", order: 1)], + Input(), + User, + NoChoices); + + Assert.Equal(["A", "B"], result.Parameters.Select(p => p.Name)); + } +} diff --git a/test/ReportBuilder/ReportPdfWriterTests.cs b/test/ReportBuilder/ReportPdfWriterTests.cs new file mode 100644 index 000000000..aa4ac42df --- /dev/null +++ b/test/ReportBuilder/ReportPdfWriterTests.cs @@ -0,0 +1,60 @@ +using System.Text; +using QuestPDF.Infrastructure; +using Viper.Areas.ReportBuilder.Exporters; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.test.ReportBuilder; + +/// +/// QuestPDF output can't be read back without a PDF parser, so these tests render each layout +/// path (heading variants, both orientations, empty cells, numeric alignment) and check that a +/// PDF comes out. The text in the cells is tested in . +/// +public sealed class ReportPdfWriterTests +{ + public ReportPdfWriterTests() + { + // Program.cs sets this at startup; unit tests don't run Program.cs. + QuestPDF.Settings.License = LicenseType.Community; + } + + private static ReportExportDocument Document(bool heading, bool landscape) + { + return new ReportExportDocument + { + Title = "Faculty roster", + GeneratedAt = new DateTimeOffset(2026, 11, 16, 9, 5, 0, TimeSpan.Zero), + Filters = heading ? [new ReportAppliedFilter { Label = "Department", Value = "Pathology" }] : [], + SensitiveNotice = heading ? "Confidential" : null, + Truncated = heading, + Landscape = landscape, + Columns = + [ + new ReportResultColumn { Name = "Name", Label = "Name", Format = ReportColumnFormat.Text, Sortable = true }, + new ReportResultColumn { Name = "Salary", Label = "Salary", Format = ReportColumnFormat.Currency, Sortable = true }, + ], + Rows = + [ + FakeReportQueryExecutor.Row(("Name", "Ada"), ("Salary", 1234.5m)), + FakeReportQueryExecutor.Row(("Name", null)), + ], + }; + } + + [Theory] + [InlineData(true, true)] + [InlineData(false, false)] + public void Write_RendersAPdf(bool heading, bool landscape) + { + byte[] pdf = ReportPdfWriter.Write(Document(heading, landscape)); + + Assert.True(pdf.Length > 0); + Assert.Equal("%PDF-", Encoding.ASCII.GetString(pdf, 0, 5)); + } + + [Fact] + public void NullDocument_Throws() + { + Assert.Throws(() => ReportPdfWriter.Write(null!)); + } +} diff --git a/test/ReportBuilder/ReportPermissionLookupServiceTests.cs b/test/ReportBuilder/ReportPermissionLookupServiceTests.cs new file mode 100644 index 000000000..1c70081a6 --- /dev/null +++ b/test/ReportBuilder/ReportPermissionLookupServiceTests.cs @@ -0,0 +1,87 @@ +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes.SQLContext; +using Viper.Models.RAPS; + +namespace Viper.test.ReportBuilder; + +/// The admin form picks view permissions from RAPS, and saves only names RAPS has. +public sealed class ReportPermissionLookupServiceTests : IDisposable +{ + private readonly RAPSContext _raps; + private readonly ReportPermissionLookupService _service; + + public ReportPermissionLookupServiceTests() + { + DbContextOptions options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + _raps = new RAPSContext(options); + _service = new ReportPermissionLookupService(_raps); + foreach (string name in new[] { "SVMSecure.Personnel", "SVMSecure.Effort", "SVMSecure.Personnel.Reports", "SVMSecure.CMS" }) + { + _raps.TblPermissions.Add(new TblPermission { Permission = name, Description = $"About {name}" }); + } + + _raps.SaveChanges(); + } + + public void Dispose() + { + _raps.Dispose(); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task Search_FindsNamesContainingTheTextInOrder() + { + IReadOnlyList found = await _service.SearchAsync(" Personnel ", Ct); + + Assert.Equal( + [ + new ReportPermissionOption { Permission = "SVMSecure.Personnel", Description = "About SVMSecure.Personnel" }, + new ReportPermissionOption { Permission = "SVMSecure.Personnel.Reports", Description = "About SVMSecure.Personnel.Reports" }, + ], + found); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task Search_WithoutText_ListsThemAll(string? text) + { + IReadOnlyList found = await _service.SearchAsync(text, Ct); + + Assert.Equal(["SVMSecure.CMS", "SVMSecure.Effort", "SVMSecure.Personnel", "SVMSecure.Personnel.Reports"], found.Select(p => p.Permission)); + } + + [Fact] + public async Task Search_ReturnsAtMostFifty() + { + for (int i = 0; i < 60; i++) + { + _raps.TblPermissions.Add(new TblPermission { Permission = $"SVMSecure.Many.{i:D2}" }); + } + + await _raps.SaveChangesAsync(Ct); + + Assert.Equal(ReportPermissionLookupService.MaxResults, (await _service.SearchAsync("Many", Ct)).Count); + } + + [Fact] + public async Task Find_ReturnsTheNamesRapsHas() + { + IReadOnlyDictionary found = await _service.FindAsync( + ["SVMSecure.Effort", " SVMSecure.CMS ", "SVMSecure.Typo", " "], Ct); + + Assert.Equal(["SVMSecure.CMS", "SVMSecure.Effort"], found.Keys.Order(StringComparer.Ordinal).ToArray()); + } + + [Fact] + public async Task Find_NoNames_IsEmpty() + { + Assert.Empty(await _service.FindAsync([], Ct)); + } +} diff --git a/test/ReportBuilder/ReportProblemServiceTests.cs b/test/ReportBuilder/ReportProblemServiceTests.cs new file mode 100644 index 000000000..e8e9515d1 --- /dev/null +++ b/test/ReportBuilder/ReportProblemServiceTests.cs @@ -0,0 +1,189 @@ +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// The problems page: failed runs from the log, newest first and within a window, and every live +/// report checked against the catalog and RAPS as a save would check it. +/// +public sealed class ReportProblemServiceTests : IDisposable +{ + private static readonly DateTimeOffset Now = new(2026, 11, 17, 9, 30, 0, TimeSpan.Zero); + + private readonly ReportBuilderDbContext _context; + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportPermissionLookup _permissions = new(); + private readonly ReportProblemService _service; + + public ReportProblemServiceTests() + { + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); + _context = new ReportBuilderDbContext(options); + _service = new ReportProblemService(_context, new ReportDefinitionValidator(_catalog, _permissions), new FixedClock()); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "FacultyRoster", + Kind = ReportSourceKind.View, + Columns = [FakeReportSourceCatalog.Column("Name"), FakeReportSourceCatalog.Column("Dept")], + Parameters = [], + PagesInSql = true, + }); + } + + public void Dispose() + { + _context.Dispose(); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class FixedClock : TimeProvider + { + public override DateTimeOffset GetUtcNow() => Now; + + public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; + } + + private static ReportDefinition Report(int id, string title, Action? configure = null) + { + var report = new ReportDefinition + { + Id = id, + Slug = Guid.NewGuid(), + Title = title, + Area = "Personnel", + Source = "FacultyRoster", + PageSize = 25, + Permissions = [new ReportPermission { ReportId = id, Permission = "SVMSecure.Personnel" }], + Columns = [new ReportColumn { ReportId = id, SourceColumn = "Name", Visible = true, DisplayOrder = 1 }], + }; + configure?.Invoke(report); + return report; + } + + private static ReportRunLog Failure(int id, int reportId, int daysAgo, string message = "Invalid column name 'Dept'.") + { + return new ReportRunLog + { + Id = id, + ReportId = reportId, + Action = ReportRunAction.Run, + LoginId = "jdoe", + RanOn = Now.UtcDateTime.AddDays(-daysAgo), + ErrorNumber = 207, + ErrorMessage = message, + }; + } + + private async Task SeedAsync(IEnumerable reports, IEnumerable logs) + { + foreach (ReportDefinition report in reports) + { + _context.Reports.Add(report); + } + + foreach (ReportRunLog log in logs) + { + _context.ReportRunLog.Add(log); + } + + await _context.SaveChangesAsync(Ct); + } + + // Failed runs + + [Fact] + public async Task Failures_AreNewestFirstWithTheirReport_AndSkipSuccessfulRuns() + { + await SeedAsync( + [Report(1, "Roster"), Report(2, "Leave", r => r.DeletedOn = Now.UtcDateTime)], + [ + Failure(10, 1, daysAgo: 3), + Failure(11, 2, daysAgo: 1, "Timeout expired."), + new ReportRunLog { Id = 12, ReportId = 1, RanOn = Now.UtcDateTime, RowsReturned = 5 }, + ]); + + IReadOnlyList failures = await _service.GetFailuresAsync(null, Ct); + + Assert.Equal([11, 10], failures.Select(f => f.Id)); + ReportFailure latest = failures[0]; + Assert.Equal(("Leave", 2, true), (latest.ReportTitle, latest.ReportId, latest.ReportDeleted)); + Assert.Equal(("Timeout expired.", 207, "jdoe"), (latest.ErrorMessage, latest.ErrorNumber, latest.LoginId)); + Assert.False(failures[1].ReportDeleted); + } + + [Theory] + [InlineData(null, new[] { 10, 11 })] + [InlineData(1, new[] { 10 })] + [InlineData(0, new[] { 10 })] + [InlineData(7, new[] { 10, 11 })] + public async Task Failures_WithinTheWindow_CountingToday(int? days, int[] expected) + { + await SeedAsync([Report(1, "Roster")], [Failure(10, 1, 0), Failure(11, 1, 6), Failure(12, 1, 400)]); + + IReadOnlyList failures = await _service.GetFailuresAsync(days, Ct); + + Assert.Equal(expected, failures.Select(f => f.Id)); + } + + [Fact] + public async Task Failures_LookBackAtMostAYear() + { + await SeedAsync([Report(1, "Roster")], [Failure(10, 1, ReportLimits.MaxFailureDays - 1), Failure(11, 1, ReportLimits.MaxFailureDays)]); + + IReadOnlyList failures = await _service.GetFailuresAsync(10_000, Ct); + + Assert.Equal(10, Assert.Single(failures).Id); + } + + [Fact] + public async Task Failures_AreCapped() + { + await SeedAsync([Report(1, "Roster")], Enumerable.Range(1, ReportLimits.MaxFailures + 5).Select(id => Failure(id, 1, 0))); + + IReadOnlyList failures = await _service.GetFailuresAsync(null, Ct); + + Assert.Equal(ReportLimits.MaxFailures, failures.Count); + } + + // Checking every report + + [Fact] + public async Task Check_ListsOnlyLiveReportsWithProblems_ByAreaAndTitle() + { + await SeedAsync( + [ + Report(1, "Roster"), + Report(2, "Zeta", r => r.Columns = [new ReportColumn { ReportId = 2, SourceColumn = "Salary", Visible = true, DisplayOrder = 1 }]), + Report(3, "Alpha", r => r.Source = "Dropped"), + Report(4, "Gone", r => { r.Source = "Dropped"; r.DeletedOn = Now.UtcDateTime; }), + Report(5, "Orphan", r => r.Permissions = [new ReportPermission { ReportId = 5, Permission = "SVMSecure.Retired" }]), + ], + []); + + ReportCheckResult result = await _service.CheckAsync(Ct); + + Assert.Equal(4, result.Checked); + Assert.Equal(Now.UtcDateTime, result.CheckedOn); + Assert.Equal(["Alpha", "Orphan", "Zeta"], result.Failing.Select(p => p.Title)); + Assert.Contains("'Dropped' isn't a view or procedure in the [report] schema.", result.Failing[0].Problems); + Assert.Equal(["RAPS has no permission named 'SVMSecure.Retired'."], result.Failing[1].Problems); + Assert.Equal(("FacultyRoster", "Personnel"), (result.Failing[2].Source, result.Failing[2].Area)); + Assert.Single(result.Failing[2].Problems); + } + + [Fact] + public async Task Check_WithNothingWrong_IsEmpty() + { + await SeedAsync([Report(1, "Roster")], []); + + ReportCheckResult result = await _service.CheckAsync(Ct); + + Assert.Equal(1, result.Checked); + Assert.Empty(result.Failing); + } +} diff --git a/test/ReportBuilder/ReportRunServiceTests.cs b/test/ReportBuilder/ReportRunServiceTests.cs new file mode 100644 index 000000000..0195dc539 --- /dev/null +++ b/test/ReportBuilder/ReportRunServiceTests.cs @@ -0,0 +1,960 @@ +using System.Data.Common; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// Running a saved report: permission first, then the source and columns checked against the +/// catalog, parameters bound, the SQL run (or a procedure paged here), and the run logged. +/// The catalog, user and executor are fakes; the report definitions are in an in-memory database. +/// +public sealed class ReportRunServiceTests : IDisposable +{ + private const string ViewerPermission = "SVMSecure.Personnel.Reports"; + private static readonly Guid RosterSlug = Guid.Parse("8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e"); + private static readonly Guid LeaveSlug = Guid.Parse("1b2c3d4e-5f60-4718-8293-a4b5c6d7e8f9"); + private static readonly DateTimeOffset Now = new(2026, 11, 13, 9, 30, 0, TimeSpan.Zero); + + private readonly ReportBuilderDbContext _context; + private readonly FakeReportUserService _users = new(); + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportQueryExecutor _executor = new(); + private readonly ReportRunService _service; + + // Cancelled from inside a fake query, so it lives as long as the test class. + private readonly CancellationTokenSource _cancel = new(); + + public ReportRunServiceTests() + { + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); + _context = new ReportBuilderDbContext(options); + _service = CreateService(_context); + _users.Permissions.Add(ViewerPermission); + + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "FacultyRoster", + Kind = ReportSourceKind.View, + Columns = + [ + FakeReportSourceCatalog.Column("Name"), + FakeReportSourceCatalog.Column("Dept"), + FakeReportSourceCatalog.Column("Hired", ReportValueKind.Date), + FakeReportSourceCatalog.Column("Notes"), + ], + Parameters = [], + PagesInSql = true, + }); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "usp_Leave", + Kind = ReportSourceKind.Procedure, + Columns = [FakeReportSourceCatalog.Column("Name"), FakeReportSourceCatalog.Column("Hours", ReportValueKind.FractionalNumber)], + Parameters = [FakeReportSourceCatalog.Parameter("LoginId"), FakeReportSourceCatalog.Parameter("Year"), FakeReportSourceCatalog.Parameter("Out", supported: false)], + PagesInSql = false, + }); + } + + public void Dispose() + { + _context.Dispose(); + _cancel.Dispose(); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private ReportRunService CreateService(ReportBuilderDbContext context) + { + return new ReportRunService( + context, + _users, + _catalog, + new ReportChoiceService(_catalog, _executor), + _executor, + NullLogger.Instance, + new StepClock()); + } + + /// Fixed local time (UTC) and a timestamp that moves 15 ms on every read. + private sealed class StepClock : TimeProvider + { + private long _ticks; + + public override DateTimeOffset GetUtcNow() => Now; + + public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; + + public override long TimestampFrequency => 1000; + + public override long GetTimestamp() => _ticks += 15; + } + + private sealed class FakeDbException : DbException + { + public FakeDbException(string message = "timeout") : base(message) + { + } + } + + private sealed class FailingSaveContext : ReportBuilderDbContext + { + public FailingSaveContext(DbContextOptions options) : base(options) + { + } + + public override Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + throw new DbUpdateException("log table is locked"); + } + } + + private static ReportColumn Column(string name, int order, string? label = null, bool visible = true, + bool sortable = true, ReportColumnFormat? format = null) + { + return new ReportColumn { SourceColumn = name, Label = label, DisplayOrder = order, Visible = visible, Sortable = sortable, Format = format }; + } + + private async Task AddRosterAsync(Action? configure = null) + { + var report = new ReportDefinition + { + Id = 1, + Slug = RosterSlug, + Title = "Faculty roster", + Source = "FacultyRoster", + PageSize = 10, + AllowExcel = true, + Permissions = [new ReportPermission { ReportId = 1, Permission = ViewerPermission }], + Columns = + [ + Column("Dept", 2, "Department"), + Column("Name", 1, format: ReportColumnFormat.Text), + Column("Hired", 3, "Hire date", format: ReportColumnFormat.Date), + Column("Notes", 4, visible: false), + Column(" ", 5), + ], + Parameters = + [ + new ReportParameter { Name = "Dept", Label = "Department", Type = ReportParameterType.Text, Operator = ReportFilterOperator.Equals }, + ], + }; + configure?.Invoke(report); + _context.Reports.Add(report); + await _context.SaveChangesAsync(Ct); + } + + private async Task AddLeaveAsync(Action? configure = null) + { + var report = new ReportDefinition + { + Id = 2, + Slug = LeaveSlug, + Title = "My leave", + Source = "usp_Leave", + PageSize = 2, + Permissions = [new ReportPermission { ReportId = 2, Permission = ViewerPermission }], + Columns = [Column("Name", 1), Column("Hours", 2, format: ReportColumnFormat.Number)], + Parameters = + [ + new ReportParameter { Name = "LoginId", Binding = ReportParameterBinding.CurrentUserLoginId }, + new ReportParameter { Name = "Year", Type = ReportParameterType.Number }, + ], + }; + configure?.Invoke(report); + _context.Reports.Add(report); + await _context.SaveChangesAsync(Ct); + } + + private Task RunAsync(Guid slug, ReportRunRequest? request = null, ReportRunMode mode = ReportRunMode.Screen) + { + return _service.RunAsync(slug.ToString(), request ?? new ReportRunRequest(), mode, Ct); + } + + private static Dictionary> Values(params (string Name, string Value)[] values) + { + return values.ToDictionary(v => v.Name, v => (IReadOnlyList)[v.Value]); + } + + private void AnswerRows(params IReadOnlyDictionary[] rows) + { + _executor.Answer = command => new ReportQueryResult + { + Rows = rows, + TotalRows = command.CountText is null ? null : 42, + Truncated = false, + }; + } + + private static ReportRunResult Ok(ReportRunOutcome outcome) + { + Assert.Equal(ReportRunStatus.Ok, outcome.Status); + Assert.Empty(outcome.Errors); + Assert.NotNull(outcome.Result); + return outcome.Result; + } + + private static void AssertFails(ReportRunOutcome outcome, ReportRunStatus status, params string[] errors) + { + Assert.Equal(status, outcome.Status); + Assert.Null(outcome.Result); + Assert.Equal(errors, outcome.Errors); + } + + // Who may run it + + [Fact] + public async Task NoOneSignedIn_IsForbidden() + { + await AddRosterAsync(); + _users.User = null; + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Forbidden); + Assert.Empty(_executor.Calls); + } + + [Theory] + [InlineData("not-a-guid")] + [InlineData("00000000-0000-0000-0000-000000000001")] + public async Task UnknownSlug_IsNotFound(string slug) + { + await AddRosterAsync(); + + AssertFails(await _service.RunAsync(slug, new ReportRunRequest(), ReportRunMode.Screen, Ct), ReportRunStatus.NotFound); + } + + [Fact] + public async Task DeletedReport_IsNotFound() + { + await AddRosterAsync(r => r.DeletedOn = Now.DateTime); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.NotFound); + } + + [Fact] + public async Task WithoutTheReportsPermission_IsForbiddenBeforeParametersAreRead() + { + await AddRosterAsync(r => r.Permissions = [new ReportPermission { ReportId = 1, Permission = "SVMSecure.Other" }, new ReportPermission { ReportId = 1, Permission = " " }]); + + ReportRunOutcome outcome = await RunAsync(RosterSlug, new ReportRunRequest { Parameters = Values(("Nope", "x")) }); + + AssertFails(outcome, ReportRunStatus.Forbidden); + Assert.Empty(_executor.Calls); + } + + [Fact] + public async Task ReportWithoutPermissions_IsForAdminsOnly() + { + await AddRosterAsync(r => r.Permissions = []); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Forbidden); + + _users.Permissions.Add(ReportBuilderPermissions.Admin); + Ok(await RunAsync(RosterSlug)); + } + + [Theory] + [InlineData(ReportRunMode.ExportExcel)] + [InlineData(ReportRunMode.ExportPdf)] + public async Task Downloads_TheReportDoesNotAllow_AreForbidden(ReportRunMode mode) + { + await AddRosterAsync(r => + { + r.AllowExcel = false; + r.AllowPdf = false; + }); + + AssertFails(await RunAsync(RosterSlug, mode: mode), ReportRunStatus.Forbidden); + } + + // Checks against the source and the request + + [Fact] + public async Task SourceGone_IsUnavailable() + { + await AddRosterAsync(r => r.Source = "Dropped"); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Unavailable, "This report's data source is no longer available."); + } + + [Fact] + public async Task BadParameters_AreInvalid() + { + await AddRosterAsync(); + + ReportRunOutcome outcome = await RunAsync(RosterSlug, new ReportRunRequest { Parameters = Values(("Other", "x")) }); + + AssertFails(outcome, ReportRunStatus.Invalid, "This report has no parameter named 'Other'."); + Assert.Empty(_executor.Calls); + } + + [Fact] + public async Task NoVisibleColumns_IsUnavailable() + { + await AddRosterAsync(r => r.Columns = [Column("Name", 1, visible: false)]); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Unavailable, "This report has no columns to show."); + } + + [Fact] + public async Task ColumnGoneFromTheSource_IsUnavailable() + { + await AddRosterAsync(r => r.Columns = [Column("Name", 1), Column("Salary", 2)]); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Unavailable, "The column 'Salary' is no longer in this report's data source."); + } + + [Fact] + public async Task FilterOnAColumnGoneFromTheSource_IsUnavailable() + { + await AddRosterAsync(r => r.Parameters = [new ReportParameter { Name = "Building", DefaultValue = "VM3A" }]); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Unavailable, "The parameter 'Building' is no longer in this report's data source."); + } + + [Fact] + public async Task ProcedureParameterTheSourceCannotTake_IsUnavailable() + { + await AddLeaveAsync(r => r.Parameters = [new ReportParameter { Name = "Out", DefaultValue = "x" }]); + + AssertFails(await RunAsync(LeaveSlug), ReportRunStatus.Unavailable, "The parameter 'Out' is no longer in this report's data source."); + } + + [Fact] + public async Task DefaultSortGoneFromTheSource_IsUnavailable() + { + await AddRosterAsync(r => r.OrderBy = "Salary"); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Unavailable, "The sort column 'Salary' is no longer in this report's data source."); + } + + [Fact] + public async Task BadPagingSortAndSearch_AreInvalidTogether() + { + await AddRosterAsync(); + + ReportRunOutcome outcome = await RunAsync(RosterSlug, new ReportRunRequest + { + Page = 0, + PerPage = ReportLimits.MaxPageSize + 1, + SortBy = "Notes", + Search = new string('x', ReportLimits.MaxTextLength + 1), + }); + + AssertFails(outcome, ReportRunStatus.Invalid, + "This report can't be sorted by that column.", + "Search text must be 500 characters or fewer.", + "Rows per page must be between 1 and 500.", + "That page doesn't exist."); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public async Task PerPageBelowOne_IsInvalid(int perPage) + { + await AddRosterAsync(); + + AssertFails(await RunAsync(RosterSlug, new ReportRunRequest { PerPage = perPage }), ReportRunStatus.Invalid, + "Rows per page must be between 1 and 500."); + } + + [Fact] + public async Task PagePastTheRowCap_IsInvalid() + { + await AddRosterAsync(); + + AssertFails(await RunAsync(RosterSlug, new ReportRunRequest { Page = int.MaxValue, PerPage = 500 }), ReportRunStatus.Invalid, + "That page doesn't exist."); + } + + [Fact] + public async Task UnsortableColumn_CannotBeSortedBy() + { + await AddRosterAsync(r => r.Columns = [Column("Name", 1, sortable: false)]); + + AssertFails(await RunAsync(RosterSlug, new ReportRunRequest { SortBy = "Name" }), ReportRunStatus.Invalid, + "This report can't be sorted by that column."); + } + + // Views + + [Fact] + public async Task View_PagedInSql() + { + await AddRosterAsync(); + AnswerRows(FakeReportQueryExecutor.Row(("Name", "Ada"), ("Dept", "VME"), ("Hired", null), ("Extra", "dropped"))); + + ReportRunResult result = Ok(await RunAsync(RosterSlug, new ReportRunRequest + { + Parameters = Values(("dept", "VME")), + Page = 3, + SortBy = "name", + SortDescending = true, + Search = " ada ", + })); + + (ReportSqlCommand command, int maxRows, TimeSpan timeout) = Assert.Single(_executor.Calls); + Assert.Equal( + "SELECT [Name], [Dept], [Hired] FROM [report].[FacultyRoster] WHERE [Dept] = @p0 " + + "AND ([Name] LIKE @__search ESCAPE '\\' OR [Dept] LIKE @__search ESCAPE '\\') " + + "ORDER BY [Name] DESC OFFSET @__skip ROWS FETCH NEXT @__take ROWS ONLY", + command.Text); + Assert.Equal(20, command.Parameters["@__skip"]); + Assert.Equal(10, command.Parameters["@__take"]); + Assert.Equal("%ada%", command.Parameters["@__search"]); + Assert.Equal(10, maxRows); + Assert.Equal(ReportLimits.ScreenTimeout, timeout); + + Assert.Equal( + [ + new ReportResultColumn { Name = "Name", Label = "Name", Format = ReportColumnFormat.Text, Sortable = true }, + new ReportResultColumn { Name = "Dept", Label = "Department", Format = ReportColumnFormat.Text, Sortable = true }, + new ReportResultColumn { Name = "Hired", Label = "Hire date", Format = ReportColumnFormat.Date, Sortable = true }, + ], + result.Columns); + IReadOnlyDictionary row = Assert.Single(result.Rows); + Assert.Equal(["Name", "Dept", "Hired"], row.Keys); + Assert.Equal("Ada", row["Name"]); + Assert.Null(row["Hired"]); + Assert.Equal(3, result.Page); + Assert.Equal(10, result.PerPage); + Assert.Equal(42, result.TotalRows); + Assert.False(result.Truncated); + Assert.Equal("""{"Dept":"VME"}""", Assert.Single(_context.ReportRunLog).Parameters); + } + + [Fact] + public async Task View_RequestedPageSize_AndDefaultsWhenTheReportHasNone() + { + await AddRosterAsync(r => r.PageSize = null); + + Ok(await RunAsync(RosterSlug, new ReportRunRequest { PerPage = 100 })); + Ok(await RunAsync(RosterSlug)); + + Assert.Equal(100, _executor.Calls[0].Command.Parameters["@__take"]); + Assert.Equal(ReportLimits.DefaultPageSize, _executor.Calls[1].Command.Parameters["@__take"]); + } + + [Fact] + public async Task View_DefaultSort_IsTheReportsOrder() + { + await AddRosterAsync(r => + { + r.OrderBy = " hired "; + r.OrderByDescending = true; + }); + + Ok(await RunAsync(RosterSlug)); + + Assert.Contains("ORDER BY [Hired] DESC", _executor.LastCommand.Text); + } + + [Fact] + public async Task View_Unpaginated_ReadsUpToTheCapAndSaysWhenCut() + { + await AddRosterAsync(r => r.Paginate = false); + _executor.Answer = _ => new ReportQueryResult + { + Rows = [FakeReportQueryExecutor.Row(("Name", "Ada")), FakeReportQueryExecutor.Row(("Name", "Bo"))], + Truncated = true, + }; + + ReportRunResult result = Ok(await RunAsync(RosterSlug, new ReportRunRequest { Page = 7, PerPage = 1 })); + + Assert.StartsWith("SELECT TOP (@__top)", _executor.LastCommand.Text); + Assert.Equal(ReportLimits.MaxRows, _executor.Calls[0].MaxRows); + Assert.Equal(1, result.Page); + Assert.Equal(2, result.PerPage); + Assert.Equal(2, result.TotalRows); + Assert.True(result.Truncated); + } + + [Theory] + [InlineData(ReportRunMode.ExportExcel, ReportRunAction.ExportExcel)] + [InlineData(ReportRunMode.ExportPdf, ReportRunAction.ExportPdf)] + public async Task Downloads_ReadEveryRowWithTheLongerTimeout(ReportRunMode mode, ReportRunAction action) + { + await AddRosterAsync(r => r.AllowPdf = true); + + Ok(await RunAsync(RosterSlug, new ReportRunRequest { Page = 2 }, mode)); + + Assert.StartsWith("SELECT TOP (@__top)", _executor.LastCommand.Text); + Assert.Equal(ReportLimits.ExportTimeout, _executor.Calls[0].Timeout); + Assert.Equal(action, Assert.Single(_context.ReportRunLog).Action); + } + + [Fact] + public async Task View_DatabaseError_IsUnavailableAndLoggedWithSqlServersReason() + { + await AddRosterAsync(); + _executor.Answer = _ => throw new FakeDbException("The SELECT permission was denied on the object 'FacultyRoster'."); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Unavailable, "The report couldn't be run. Try again later."); + + ReportRunLog log = Assert.Single(_context.ReportRunLog); + Assert.Equal("The SELECT permission was denied on the object 'FacultyRoster'.", log.ErrorMessage); + Assert.Null(log.ErrorNumber); + Assert.Null(log.RowsReturned); + Assert.Equal(ReportRunAction.Run, log.Action); + } + + [Fact] + public async Task DatabaseError_LongerThanTheLogKeeps_IsCut() + { + await AddRosterAsync(); + _executor.Answer = _ => throw new FakeDbException(new string('x', ReportLimits.MaxErrorLength + 10)); + + await RunAsync(RosterSlug); + + Assert.Equal(ReportLimits.MaxErrorLength, Assert.Single(_context.ReportRunLog).ErrorMessage?.Length); + } + + [Fact] + public async Task DatabaseError_AfterTheUserCancelled_IsNotLogged() + { + await AddRosterAsync(); + _executor.Answer = _ => + { + _cancel.Cancel(); + throw new FakeDbException("Operation cancelled by user."); + }; + + ReportRunOutcome outcome = await _service.RunAsync(RosterSlug.ToString(), new ReportRunRequest(), ReportRunMode.Screen, _cancel.Token); + + Assert.Equal(ReportRunStatus.Unavailable, outcome.Status); + Assert.Empty(_context.ReportRunLog); + } + + [Fact] + public async Task SourceGone_IsLoggedAsAFailure() + { + await AddRosterAsync(r => r.Source = "Dropped"); + + await RunAsync(RosterSlug, mode: ReportRunMode.ExportExcel); + + ReportRunLog log = Assert.Single(_context.ReportRunLog); + Assert.Equal("This report's data source is no longer available.", log.ErrorMessage); + Assert.Equal(ReportRunAction.ExportExcel, log.Action); + Assert.Null(log.Parameters); + } + + [Fact] + public async Task BadParameters_AreTheUsersMistake_AndNotLogged() + { + await AddRosterAsync(); + + await RunAsync(RosterSlug, new ReportRunRequest { Parameters = Values(("Other", "x")) }); + + Assert.Empty(_context.ReportRunLog); + } + + [Fact] + public async Task ChoiceParameter_IsCheckedAgainstItsChoices() + { + await AddRosterAsync(r => r.Parameters = + [ + new ReportParameter { Name = "Dept", Type = ReportParameterType.MultiChoice, ChoicesList = """["VME","PMI"]""", Operator = ReportFilterOperator.In }, + ]); + + Ok(await RunAsync(RosterSlug, new ReportRunRequest + { + Parameters = new Dictionary> { ["Dept"] = ["PMI", "VME"] }, + })); + + Assert.Contains("WHERE [Dept] IN (@p0_0, @p0_1)", _executor.LastCommand.Text); + } + + // Procedures + + [Fact] + public async Task Procedure_PagedSortedAndSearchedInMemory() + { + await AddLeaveAsync(); + _executor.Answer = _ => new ReportQueryResult + { + Rows = + [ + FakeReportQueryExecutor.Row(("Name", "Cy"), ("Hours", 8m)), + FakeReportQueryExecutor.Row(("Name", "ada"), ("Hours", 2m)), + FakeReportQueryExecutor.Row(("Name", "Bea"), ("Hours", 4m)), + FakeReportQueryExecutor.Row(("Name", "Dee"), ("Hours", 1m)), + FakeReportQueryExecutor.Row(("Name", null), ("Hours", 9m)), + FakeReportQueryExecutor.Row(("Name", "Ed"), ("Hours", 3m)), + ], + Truncated = true, + }; + + ReportRunResult result = Ok(await RunAsync(LeaveSlug, new ReportRunRequest + { + Parameters = Values(("Year", "2026")), + Page = 2, + SortBy = "Name", + SortDescending = true, + Search = "E", + })); + + (ReportSqlCommand command, int maxRows, _) = Assert.Single(_executor.Calls); + Assert.Equal("EXEC [report].[usp_Leave] @LoginId = @p0, @Year = @p1", command.Text); + Assert.Equal("jdoe", command.Parameters["@p0"]); + Assert.Equal(2026m, command.Parameters["@p1"]); + Assert.Equal(ReportLimits.MaxRows, maxRows); + + // "E" matches Ed, Dee and Bea; sorted descending: Ed, Dee, Bea; page 2 of 2 rows each. + Assert.Equal(["Bea"], result.Rows.Select(r => r["Name"])); + Assert.Equal(3, result.TotalRows); + Assert.Equal(2, result.Page); + Assert.Equal(2, result.PerPage); + Assert.True(result.Truncated); + } + + [Fact] + public async Task Procedure_SortedAscendingWithEmptyValuesFirst() + { + await AddLeaveAsync(r => r.Paginate = false); + _executor.Answer = _ => new ReportQueryResult + { + Rows = + [ + FakeReportQueryExecutor.Row(("Name", "d"), ("Hours", 2.5)), + FakeReportQueryExecutor.Row(("Name", "c"), ("Hours", 2m)), + FakeReportQueryExecutor.Row(("Name", "a"), ("Hours", null)), + FakeReportQueryExecutor.Row(("Name", "b"), ("Hours", 1m)), + FakeReportQueryExecutor.Row(("Name", "e"), ("Hours", null)), + ], + Truncated = false, + }; + + ReportRunResult result = Ok(await RunAsync(LeaveSlug, new ReportRunRequest { SortBy = "Hours" })); + + // Values of one type compare as themselves; mixed types (decimal and double) as text. + Assert.Equal(["a", "e", "b", "c", "d"], result.Rows.Select(r => r["Name"])); + Assert.Equal(5, result.PerPage); + } + + [Fact] + public async Task Procedure_ThatPagesItself_GetsSkipAndTakeAndReportsItsTotal() + { + await AddLeaveAsync(r => r.OrderBy = "Name"); + _catalog.Sources[1] = _catalog.Sources[1] with { PagesInSql = true }; + AnswerRows(FakeReportQueryExecutor.Row(("Name", "Ada"), ("Hours", 1m), ("TotalRows", 11))); + + ReportRunResult result = Ok(await RunAsync(LeaveSlug, new ReportRunRequest { Page = 2 })); + + (ReportSqlCommand command, int maxRows, _) = Assert.Single(_executor.Calls); + Assert.Equal("EXEC [report].[usp_Leave] @LoginId = @p0, @Skip = @__skip, @Take = @__take", command.Text); + Assert.Equal(2, command.Parameters["@__skip"]); + Assert.Equal(2, maxRows); + Assert.Equal(11, result.TotalRows); + Assert.Equal(["Name", "Hours"], Assert.Single(result.Rows).Keys); + Assert.False(result.Truncated); + } + + [Theory] + [InlineData(null)] + [InlineData("many")] + public async Task Procedure_ThatPagesItself_WithoutAUsableTotal_HasNoTotal(string? total) + { + await AddLeaveAsync(); + _catalog.Sources[1] = _catalog.Sources[1] with { PagesInSql = true }; + AnswerRows(FakeReportQueryExecutor.Row(("Name", "Ada"), ("TotalRows", total))); + + Assert.Null(Ok(await RunAsync(LeaveSlug)).TotalRows); + } + + [Fact] + public async Task Procedure_ThatPagesItself_PastTheLastPage_HasNoTotal() + { + await AddLeaveAsync(); + _catalog.Sources[1] = _catalog.Sources[1] with { PagesInSql = true }; + + ReportRunResult result = Ok(await RunAsync(LeaveSlug, new ReportRunRequest { Page = 9 })); + + Assert.Empty(result.Rows); + Assert.Null(result.TotalRows); + } + + [Fact] + public async Task Procedure_ThatPagesItself_CannotBeSearched() + { + await AddLeaveAsync(); + _catalog.Sources[1] = _catalog.Sources[1] with { PagesInSql = true }; + + AssertFails(await RunAsync(LeaveSlug, new ReportRunRequest { Search = "x" }), ReportRunStatus.Invalid, + "This report can't be searched."); + } + + [Fact] + public async Task Procedure_ThatPagesItself_CannotBeSortedByRequest() + { + await AddLeaveAsync(); + _catalog.Sources[1] = _catalog.Sources[1] with { PagesInSql = true }; + + AssertFails(await RunAsync(LeaveSlug, new ReportRunRequest { SortBy = "Name" }), ReportRunStatus.Invalid, + "This report's order is set by its data source and can't be changed."); + } + + [Fact] + public async Task Procedure_ThatPagesItself_StillGetsBoundedSkipAndTakeWhenDownloaded() + { + await AddLeaveAsync(); + _catalog.Sources[1] = _catalog.Sources[1] with { PagesInSql = true }; + AnswerRows(FakeReportQueryExecutor.Row(("Name", "Ada"), ("Hours", 1m))); + + Ok(await RunAsync(LeaveSlug, mode: ReportRunMode.ExportExcel)); + + Assert.Equal("EXEC [report].[usp_Leave] @LoginId = @p0, @Skip = @__skip, @Take = @__take", _executor.LastCommand.Text); + Assert.Equal(0, _executor.LastCommand.Parameters["@__skip"]); + Assert.Equal(ReportLimits.MaxRows, _executor.LastCommand.Parameters["@__take"]); + } + + [Fact] + public async Task Procedure_Buffered_SortsByAHiddenDefaultColumnBeforeDroppingIt() + { + await AddLeaveAsync(r => + { + r.Columns = [Column("Name", 1)]; + r.OrderBy = "Hours"; + }); + AnswerRows( + FakeReportQueryExecutor.Row(("Name", "Bea"), ("Hours", 2m)), + FakeReportQueryExecutor.Row(("Name", "Ada"), ("Hours", 1m))); + + ReportRunResult result = Ok(await RunAsync(LeaveSlug)); + + Assert.Equal(["Ada", "Bea"], result.Rows.Select(r => r["Name"])); + } + + [Fact] + public async Task Procedure_WhoseColumnsAreUnknown_TrustsTheReportsColumns() + { + await AddLeaveAsync(r => + { + r.Columns = [Column("Name", 1), Column("Comment", 2)]; + r.OrderBy = "Comment"; + }); + _catalog.Sources[1] = _catalog.Sources[1] with { Columns = [], ColumnsError = "Uses a temp table." }; + AnswerRows(FakeReportQueryExecutor.Row(("Name", "Ada"))); + + ReportRunResult result = Ok(await RunAsync(LeaveSlug)); + + IReadOnlyDictionary row = Assert.Single(result.Rows); + Assert.Equal("Ada", row["Name"]); + Assert.Null(row["Comment"]); + } + + // Preview + + [Fact] + public async Task Preview_RunsAnUnsavedReportAPageAtATimeWithoutLogging() + { + _users.Permissions.Add(ReportBuilderPermissions.Admin); + var report = new ReportDefinition + { + Title = "Draft", + Source = "FacultyRoster", + Paginate = false, + PageSize = 10, + Columns = [Column("Name", 1)], + }; + + ReportRunResult result = Ok(await _service.PreviewAsync(report, new ReportRunRequest { Page = 2, PerPage = 500 }, Ct)); + + (ReportSqlCommand command, int maxRows, _) = Assert.Single(_executor.Calls); + Assert.Equal((50, 50), (command.Parameters["@__skip"], command.Parameters["@__take"])); + Assert.Equal((ReportLimits.PreviewRows, 2), (result.PerPage, result.Page)); + Assert.Equal(ReportLimits.PreviewRows, maxRows); + Assert.Empty(_context.ReportRunLog); + } + + [Fact] + public async Task Preview_DatabaseError_ShowsSqlServersReasonAndIsNotLogged() + { + _users.Permissions.Add(ReportBuilderPermissions.Admin); + _executor.Answer = _ => throw new FakeDbException("Invalid column name 'Dept'."); + var report = new ReportDefinition { Title = "Draft", Source = "FacultyRoster", Columns = [Column("Name", 1)] }; + + ReportRunOutcome outcome = await _service.PreviewAsync(report, new ReportRunRequest(), Ct); + + AssertFails(outcome, ReportRunStatus.Unavailable, "SQL Server couldn't run the report: Invalid column name 'Dept'."); + Assert.Empty(_context.ReportRunLog); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Preview_IsForAdminsOnly(bool signedIn) + { + if (!signedIn) + { + _users.User = null; + } + + ReportRunOutcome outcome = await _service.PreviewAsync(new ReportDefinition { Source = "FacultyRoster" }, new ReportRunRequest(), Ct); + + AssertFails(outcome, ReportRunStatus.Forbidden); + } + + // The run log + + [Fact] + public async Task Run_IsLoggedWithTheUsersOwnValues() + { + await AddLeaveAsync(r => r.Parameters = + [ + new ReportParameter { Name = "LoginId", Binding = ReportParameterBinding.CurrentUserLoginId }, + new ReportParameter { Name = "Year", Type = ReportParameterType.Number }, + new ReportParameter { Name = "From", Type = ReportParameterType.Date }, + new ReportParameter { Name = "Paid", Type = ReportParameterType.Boolean }, + new ReportParameter { Name = "Types", Type = ReportParameterType.MultiChoice, ChoicesList = """["Sick","Vacation"]""" }, + ]); + _catalog.Sources[1] = _catalog.Sources[1] with + { + Parameters = + [ + .. _catalog.Sources[1].Parameters, + FakeReportSourceCatalog.Parameter("From"), + FakeReportSourceCatalog.Parameter("Paid"), + FakeReportSourceCatalog.Parameter("Types"), + ], + }; + AnswerRows(FakeReportQueryExecutor.Row(("Name", "Ada")), FakeReportQueryExecutor.Row(("Name", "Bo"))); + + Ok(await RunAsync(LeaveSlug, new ReportRunRequest + { + Parameters = new Dictionary> + { + ["Year"] = ["2026.0"], + ["From"] = ["2026-01-31"], + ["Paid"] = ["true"], + ["Types"] = ["Vacation", "Sick"], + }, + })); + + ReportRunLog log = Assert.Single(_context.ReportRunLog); + Assert.Equal(2, log.ReportId); + Assert.Equal(ReportRunAction.Run, log.Action); + Assert.Equal("jdoe", log.LoginId); + Assert.Equal(Now.UtcDateTime, log.RanOn); + Assert.Equal("""{"From":"2026-01-31","Paid":true,"Types":["Vacation","Sick"],"Year":"2026.0"}""", log.Parameters); + Assert.Equal(2, log.RowsReturned); + Assert.Equal(15, log.DurationMs); + Assert.Null(log.ErrorMessage); + } + + [Fact] + public async Task Run_DescribesTheReportAndTheUsersFiltersForDownloads() + { + await AddLeaveAsync(r => + { + r.SensitiveNotice = " Confidential "; + r.PdfLandscape = true; + r.Parameters = + [ + new ReportParameter { Name = "LoginId", Binding = ReportParameterBinding.CurrentUserLoginId }, + new ReportParameter { Name = "Year", Label = "Fiscal year", Type = ReportParameterType.Number, DisplayOrder = 1 }, + new ReportParameter { Name = "From", Label = "From", Type = ReportParameterType.Date, DisplayOrder = 2 }, + new ReportParameter { Name = "Paid", Type = ReportParameterType.Boolean, DisplayOrder = 3 }, + new ReportParameter { Name = "Types", Label = "Leave types", Type = ReportParameterType.MultiChoice, ChoicesList = """[{"value":"S","label":"Sick"},{"value":"V","label":"Vacation"}]""", DisplayOrder = 4 }, + new ReportParameter { Name = "Kind", Type = ReportParameterType.Choice, ChoicesList = """[{"value":"F","label":"Full time"}]""", DisplayOrder = 5 }, + new ReportParameter { Name = "Note", DisplayOrder = 6 }, + ]; + }); + _catalog.Sources[1] = _catalog.Sources[1] with + { + Parameters = + [ + .. _catalog.Sources[1].Parameters, + FakeReportSourceCatalog.Parameter("From"), + FakeReportSourceCatalog.Parameter("Paid"), + FakeReportSourceCatalog.Parameter("Types"), + FakeReportSourceCatalog.Parameter("Kind"), + FakeReportSourceCatalog.Parameter("Note"), + ], + }; + + ReportRunOutcome outcome = await RunAsync(LeaveSlug, new ReportRunRequest + { + Parameters = new Dictionary> + { + ["Year"] = ["12345.5"], + ["From"] = ["2026-01-31"], + ["Paid"] = ["false"], + ["Types"] = ["V", "s"], + ["Kind"] = ["f"], + ["Note"] = ["x"], + }, + }); + + Ok(outcome); + ReportRunDetails details = Assert.IsType(outcome.Details); + Assert.Equal("My leave", details.Title); + Assert.Equal("Confidential", details.SensitiveNotice); + Assert.True(details.PdfLandscape); + Assert.Equal( + [ + new ReportAppliedFilter { Label = "Fiscal year", Value = "12,345.5" }, + new ReportAppliedFilter { Label = "From", Value = "01/31/2026" }, + new ReportAppliedFilter { Label = "Paid", Value = "No" }, + new ReportAppliedFilter { Label = "Leave types", Value = "Vacation, Sick" }, + new ReportAppliedFilter { Label = "Kind", Value = "Full time" }, + new ReportAppliedFilter { Label = "Note", Value = "x" }, + ], + details.Filters); + } + + [Fact] + public async Task Run_WithoutANotice_HasNoNoticeAndIsPortrait() + { + await AddRosterAsync(r => r.SensitiveNotice = " "); + + ReportRunOutcome outcome = await RunAsync(RosterSlug); + + ReportRunDetails details = Assert.IsType(outcome.Details); + Assert.Null(details.SensitiveNotice); + Assert.False(details.PdfLandscape); + Assert.Empty(details.Filters); + } + + [Fact] + public async Task Run_WithoutUserValues_LogsNoParameters() + { + await AddLeaveAsync(); + + Ok(await RunAsync(LeaveSlug)); + + Assert.Null(Assert.Single(_context.ReportRunLog).Parameters); + } + + [Fact] + public async Task Run_WhoseLogCannotBeSaved_StillReturnsTheRows() + { + DbContextOptions options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + await using var failing = new FailingSaveContext(options); + await using (var seed = new ReportBuilderDbContext(options)) + { + seed.Reports.Add(new ReportDefinition + { + Id = 9, + Slug = RosterSlug, + Title = "Roster", + Source = "FacultyRoster", + Permissions = [new ReportPermission { ReportId = 9, Permission = ViewerPermission }], + Columns = [Column("Name", 1)], + }); + await seed.SaveChangesAsync(Ct); + } + + AnswerRows(FakeReportQueryExecutor.Row(("Name", "Ada"))); + + ReportRunOutcome outcome = await CreateService(failing).RunAsync(RosterSlug.ToString(), new ReportRunRequest(), ReportRunMode.Screen, Ct); + + Assert.Single(Ok(outcome).Rows); + } +} diff --git a/test/ReportBuilder/ReportSourceCatalogServiceTests.cs b/test/ReportBuilder/ReportSourceCatalogServiceTests.cs new file mode 100644 index 000000000..de75de31d --- /dev/null +++ b/test/ReportBuilder/ReportSourceCatalogServiceTests.cs @@ -0,0 +1,159 @@ +using NSubstitute; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// The catalog lists the [report] views and procedures and describes one at a time, only by +/// names it listed. The metadata reader is a fake, so these tests cover the rules, not the SQL. +/// +public sealed class ReportSourceCatalogServiceTests +{ + private readonly IReportSourceMetadataReader _reader = Substitute.For(); + private readonly ReportSourceCatalogService _catalog; + + public ReportSourceCatalogServiceTests() + { + _catalog = new ReportSourceCatalogService(_reader); + _reader.GetObjectsAsync(Arg.Any()).Returns( + [ + new ReportSourceObjectRow { Name = "FacultyRoster", Type = "V", Description = " Current faculty " }, + new ReportSourceObjectRow { Name = "usp_Leave", Type = "P", Description = " " }, + new ReportSourceObjectRow { Name = "usp_Paged", Type = "P" }, + ]); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task GetSources_ListsViewsAndProceduresWithTrimmedDescriptions() + { + IReadOnlyList sources = await _catalog.GetSourcesAsync(Ct); + + Assert.Equal( + [ + new ReportSourceSummary { Name = "FacultyRoster", Kind = ReportSourceKind.View, Description = "Current faculty" }, + new ReportSourceSummary { Name = "usp_Leave", Kind = ReportSourceKind.Procedure }, + new ReportSourceSummary { Name = "usp_Paged", Kind = ReportSourceKind.Procedure }, + ], + sources); + } + + [Fact] + public async Task GetSource_UnknownName_IsNullAndNeverReachesTheCatalog() + { + Assert.Null(await _catalog.GetSourceAsync("Persons]; DROP TABLE x;--", Ct)); + + await _reader.DidNotReceive().GetViewColumnsAsync(Arg.Any(), Arg.Any()); + await _reader.DidNotReceive().GetProcedureParametersAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetSource_View_DescribesItsColumnsAndPagesInSql() + { + _reader.GetViewColumnsAsync("FacultyRoster", Arg.Any()).Returns( + [ + new ReportSourceColumnRow { Name = "Name", SqlType = "nvarchar", IsNullable = false }, + new ReportSourceColumnRow { Name = "Photo", SqlType = "varbinary", IsNullable = true }, + ]); + + // Matched ignoring case, as SQL Server matches names. + ReportSourceDetail? view = await _catalog.GetSourceAsync("facultyroster", Ct); + + Assert.NotNull(view); + Assert.Equal("FacultyRoster", view.Name); + Assert.Equal(ReportSourceKind.View, view.Kind); + Assert.True(view.PagesInSql); + Assert.Empty(view.Parameters); + Assert.Null(view.ColumnsError); + Assert.Equal( + [ + new ReportSourceColumn { Name = "Name", SqlType = "nvarchar", Kind = ReportValueKind.Text, IsNullable = false, IsSupported = true }, + new ReportSourceColumn { Name = "Photo", SqlType = "varbinary", Kind = ReportValueKind.Binary, IsNullable = true, IsSupported = false }, + ], + view.Columns); + } + + [Fact] + public async Task GetSource_Procedure_DescribesParametersAndResultColumns() + { + _reader.GetProcedureParametersAsync("usp_Leave", Arg.Any()).Returns( + [ + new ReportSourceParameterRow { Name = "@StartDate", SqlType = "date" }, + new ReportSourceParameterRow { Name = "@Count", SqlType = "int", IsOutput = true }, + ]); + _reader.DescribeProcedureResultAsync("usp_Leave", Arg.Any()).Returns( + [ + new ReportSourceColumnRow { Name = "Name", SqlType = "nvarchar(100)" }, + new ReportSourceColumnRow { Name = null, SqlType = "int" }, + ]); + + ReportSourceDetail? procedure = await _catalog.GetSourceAsync("usp_Leave", Ct); + + Assert.NotNull(procedure); + Assert.False(procedure.PagesInSql); + Assert.Equal( + [ + new ReportSourceParameter { Name = "StartDate", SqlType = "date", Kind = ReportValueKind.Date, IsSupported = true }, + new ReportSourceParameter { Name = "Count", SqlType = "int", Kind = ReportValueKind.WholeNumber, IsSupported = false }, + ], + procedure.Parameters); + + // An unnamed result column can't be chosen, and an unknown nullability reads as nullable. + ReportSourceColumn column = Assert.Single(procedure.Columns); + Assert.Equal("Name", column.Name); + Assert.True(column.IsNullable); + } + + [Fact] + public async Task GetSource_ProcedureWithSkipAndTake_PagesInSqlAndHidesThem() + { + _reader.GetProcedureParametersAsync("usp_Paged", Arg.Any()).Returns( + [ + new ReportSourceParameterRow { Name = "@Dept", SqlType = "varchar" }, + new ReportSourceParameterRow { Name = "@skip", SqlType = "int" }, + new ReportSourceParameterRow { Name = "@Take", SqlType = "int" }, + ]); + _reader.DescribeProcedureResultAsync("usp_Paged", Arg.Any()).Returns([]); + + ReportSourceDetail? procedure = await _catalog.GetSourceAsync("usp_Paged", Ct); + + Assert.NotNull(procedure); + Assert.True(procedure.PagesInSql); + Assert.Equal(["Dept"], procedure.Parameters.Select(p => p.Name)); + } + + [Theory] + [InlineData("varchar", "int")] + [InlineData("int", "nvarchar")] + public async Task GetSource_SkipOrTakeThatIsNotAnInteger_DoesNotPageInSql(string skipType, string takeType) + { + _reader.GetProcedureParametersAsync("usp_Paged", Arg.Any()).Returns( + [ + new ReportSourceParameterRow { Name = "@Skip", SqlType = skipType }, + new ReportSourceParameterRow { Name = "@Take", SqlType = takeType }, + ]); + _reader.DescribeProcedureResultAsync("usp_Paged", Arg.Any()).Returns([]); + + ReportSourceDetail? procedure = await _catalog.GetSourceAsync("usp_Paged", Ct); + + Assert.NotNull(procedure); + Assert.False(procedure.PagesInSql); + Assert.Equal(2, procedure.Parameters.Count); + } + + [Fact] + public async Task GetSource_ProcedureSqlServerCannotDescribe_ReportsWhy() + { + _reader.GetProcedureParametersAsync("usp_Leave", Arg.Any()).Returns([]); + _reader.DescribeProcedureResultAsync("usp_Leave", Arg.Any()).Returns( + [new ReportSourceColumnRow { ErrorMessage = "Invalid object name '#people'." }]); + + ReportSourceDetail? procedure = await _catalog.GetSourceAsync("usp_Leave", Ct); + + Assert.NotNull(procedure); + Assert.Empty(procedure.Columns); + Assert.Equal("Invalid object name '#people'.", procedure.ColumnsError); + } +} diff --git a/test/ReportBuilder/ReportSqlBuilderTests.cs b/test/ReportBuilder/ReportSqlBuilderTests.cs new file mode 100644 index 000000000..95e0213bc --- /dev/null +++ b/test/ReportBuilder/ReportSqlBuilderTests.cs @@ -0,0 +1,187 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// +/// The SQL a report runs: names are bracket-quoted, and every value, filter or search text +/// alike, is a parameter, so nothing a user types reaches the SQL text. +/// +public sealed class ReportSqlBuilderTests +{ + private static BoundReportParameter Filter(string name, object value, ReportFilterOperator? op = null, + ReportParameterType type = ReportParameterType.Text) + { + return new BoundReportParameter { Name = name, Type = type, Operator = op, Value = value, FromUser = true }; + } + + private static ReportViewQuery View(params BoundReportParameter[] filters) + { + return new ReportViewQuery { Source = "FacultyRoster", Columns = ["Name", "Dept"], Filters = filters }; + } + + [Fact] + public void BuildView_Unpaged_ReadsOneRowPastTheCap() + { + ReportSqlCommand command = ReportSqlBuilder.BuildView(View()); + + Assert.Equal("SELECT TOP (@__top) [Name], [Dept] FROM [report].[FacultyRoster] ORDER BY (SELECT NULL)", command.Text); + Assert.Null(command.CountText); + Assert.Equal(ReportLimits.MaxRows + 1, command.Parameters["@__top"]); + } + + [Fact] + public void BuildView_Paged_UsesOffsetFetchAndCountsTheSameRows() + { + ReportSqlCommand command = ReportSqlBuilder.BuildView(View(Filter("Dept", "VME")) with + { + SortColumn = "Name", + SortDescending = true, + Skip = 50, + Take = 25, + }); + + Assert.Equal( + "SELECT [Name], [Dept] FROM [report].[FacultyRoster] WHERE [Dept] = @p0 ORDER BY [Name] DESC OFFSET @__skip ROWS FETCH NEXT @__take ROWS ONLY", + command.Text); + Assert.Equal("SELECT COUNT(*) FROM [report].[FacultyRoster] WHERE [Dept] = @p0", command.CountText); + Assert.Equal(50, command.Parameters["@__skip"]); + Assert.Equal(25, command.Parameters["@__take"]); + Assert.Equal("VME", command.Parameters["@p0"]); + } + + [Fact] + public void BuildView_SortsAscendingByDefault() + { + ReportSqlCommand command = ReportSqlBuilder.BuildView(View() with { SortColumn = "Dept" }); + + Assert.Contains("ORDER BY [Dept] ASC", command.Text); + } + + [Fact] + public void BuildView_Operators_EachBecomeTheirComparison() + { + var date = new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Unspecified); + ReportSqlCommand command = ReportSqlBuilder.BuildView(View( + Filter("Name", "o'brien", ReportFilterOperator.Contains), + Filter("Hired", date, ReportFilterOperator.From, ReportParameterType.Date), + Filter("Hired", date, ReportFilterOperator.To, ReportParameterType.Date), + Filter("Salary", 100m, ReportFilterOperator.To, ReportParameterType.Number), + Filter("Dept", new List { "VME", "PMI" }, ReportFilterOperator.In, ReportParameterType.MultiChoice), + Filter("Title", "Professor", ReportFilterOperator.In), + Filter("Active", true))); + + Assert.Equal( + "SELECT TOP (@__top) [Name], [Dept] FROM [report].[FacultyRoster] WHERE " + + "[Name] LIKE @p0 ESCAPE '\\' AND [Hired] >= @p1 AND [Hired] < @p2 AND [Salary] <= @p3 " + + "AND [Dept] IN (@p4_0, @p4_1) AND [Title] IN (@p5_0) AND [Active] = @p6 ORDER BY (SELECT NULL)", + command.Text); + Assert.Equal("%o'brien%", command.Parameters["@p0"]); + Assert.Equal(date, command.Parameters["@p1"]); + Assert.Equal(date.AddDays(1), command.Parameters["@p2"]); + Assert.Equal(100m, command.Parameters["@p3"]); + Assert.Equal("VME", command.Parameters["@p4_0"]); + Assert.Equal("PMI", command.Parameters["@p4_1"]); + Assert.Equal("Professor", command.Parameters["@p5_0"]); + Assert.True(Assert.IsType(command.Parameters["@p6"])); + } + + [Fact] + public void BuildView_Search_LooksInEachSearchColumnWithOneParameter() + { + ReportSqlCommand command = ReportSqlBuilder.BuildView(View(Filter("Dept", "VME")) with + { + SearchColumns = ["Name", "Dept"], + Search = " 50%_off ", + }); + + Assert.Contains( + "WHERE [Dept] = @p0 AND ([Name] LIKE @__search ESCAPE '\\' OR [Dept] LIKE @__search ESCAPE '\\')", + command.Text); + Assert.Equal("%50\\%\\_off%", command.Parameters["@__search"]); + } + + [Fact] + public void BuildView_SearchWithoutTextColumns_AddsNoCondition() + { + ReportSqlCommand command = ReportSqlBuilder.BuildView(View() with { Search = "x" }); + + Assert.DoesNotContain("WHERE", command.Text); + Assert.False(command.Parameters.ContainsKey("@__search")); + } + + [Fact] + public void BuildView_NamesWithBrackets_AreEscapedNotTrusted() + { + ReportSqlCommand command = ReportSqlBuilder.BuildView(new ReportViewQuery + { + Source = "Roster]; DROP TABLE x;--", + Columns = ["Na]me"], + }); + + Assert.Equal("SELECT TOP (@__top) [Na]]me] FROM [report].[Roster]]; DROP TABLE x;--] ORDER BY (SELECT NULL)", command.Text); + } + + [Fact] + public void BuildView_NoColumns_Throws() + { + Assert.Throws(() => ReportSqlBuilder.BuildView(new ReportViewQuery { Source = "V", Columns = [] })); + } + + [Fact] + public void BuildProcedure_PassesEachArgumentAsAParameter() + { + ReportSqlCommand command = ReportSqlBuilder.BuildProcedure("usp_Leave", + [ + Filter("LoginId", "jdoe"), + Filter("@Depts", new List { "VME", "PMI" }, type: ReportParameterType.MultiChoice), + ]); + + Assert.Equal("EXEC [report].[usp_Leave] @LoginId = @p0, @Depts = @p1", command.Text); + Assert.Equal("jdoe", command.Parameters["@p0"]); + Assert.Equal("VME,PMI", command.Parameters["@p1"]); + } + + [Fact] + public void BuildProcedure_NoArguments_IsAPlainExec() + { + Assert.Equal("EXEC [report].[usp_All]", ReportSqlBuilder.BuildProcedure("usp_All", []).Text); + } + + [Fact] + public void BuildProcedure_WithPaging_PassesSkipAndTake() + { + ReportSqlCommand command = ReportSqlBuilder.BuildProcedure("usp_Paged", [], skip: 25, take: 25); + + Assert.Equal("EXEC [report].[usp_Paged] @Skip = @__skip, @Take = @__take", command.Text); + Assert.Equal(25, command.Parameters["@__skip"]); + Assert.Equal(25, command.Parameters["@__take"]); + } + + [Theory] + [InlineData("Login Id")] + [InlineData("x;DROP")] + [InlineData("1abc")] + [InlineData("")] + public void BuildProcedure_ParameterNameThatIsNotAnIdentifier_Throws(string name) + { + Assert.Throws(() => ReportSqlBuilder.BuildProcedure("usp_Leave", [Filter(name, "x")])); + } + + [Fact] + public void BuildChoices_ReadsValueAndLabelUpToTheChoiceLimit() + { + ReportSqlCommand command = ReportSqlBuilder.BuildChoices("DeptChoices"); + + Assert.Equal("SELECT TOP (@__top) [Value], [Label] FROM [report].[DeptChoices] ORDER BY [Label]", command.Text); + Assert.Equal(ReportLimits.MaxChoices, command.Parameters["@__top"]); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Quote_BlankName_Throws(string name) + { + Assert.Throws(() => ReportSqlBuilder.Quote(name)); + } +} diff --git a/test/ReportBuilder/ReportSqlTypesTests.cs b/test/ReportBuilder/ReportSqlTypesTests.cs new file mode 100644 index 000000000..aa67c8a81 --- /dev/null +++ b/test/ReportBuilder/ReportSqlTypesTests.cs @@ -0,0 +1,39 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// SQL Server type names map to the kinds of value a report can show. +public sealed class ReportSqlTypesTests +{ + [Theory] + [InlineData("nvarchar", ReportValueKind.Text)] + [InlineData("nvarchar(50)", ReportValueKind.Text)] + [InlineData("VARCHAR(max)", ReportValueKind.Text)] + [InlineData("int", ReportValueKind.WholeNumber)] + [InlineData("decimal(9,2)", ReportValueKind.FractionalNumber)] + [InlineData("money", ReportValueKind.FractionalNumber)] + [InlineData("date", ReportValueKind.Date)] + [InlineData("datetime2(7)", ReportValueKind.DateTime)] + [InlineData("time", ReportValueKind.Time)] + [InlineData("bit", ReportValueKind.Boolean)] + [InlineData("uniqueidentifier", ReportValueKind.UniqueId)] + [InlineData("varbinary(max)", ReportValueKind.Binary)] + [InlineData("sql_variant", ReportValueKind.Other)] + [InlineData(" ", ReportValueKind.Other)] + [InlineData(null, ReportValueKind.Other)] + public void KindOf_IgnoresLengthAndCase(string? sqlType, ReportValueKind expected) + { + Assert.Equal(expected, ReportSqlTypes.KindOf(sqlType)); + } + + [Theory] + [InlineData(ReportValueKind.Text, true)] + [InlineData(ReportValueKind.UniqueId, true)] + [InlineData(ReportValueKind.Binary, false)] + [InlineData(ReportValueKind.Other, false)] + public void IsSupported_RejectsBinaryAndUnknownValues(ReportValueKind kind, bool expected) + { + Assert.Equal(expected, ReportSqlTypes.IsSupported(kind)); + } +} diff --git a/test/ReportBuilder/ReportUserServiceTests.cs b/test/ReportBuilder/ReportUserServiceTests.cs new file mode 100644 index 000000000..a933502ac --- /dev/null +++ b/test/ReportBuilder/ReportUserServiceTests.cs @@ -0,0 +1,51 @@ +using NSubstitute; +using NSubstitute.ReturnsExtensions; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes.SQLContext; +using Viper.Models.AAUD; + +namespace Viper.test.ReportBuilder; + +/// The report runner sees the signed-in user through UserHelper and RAPS. +public sealed class ReportUserServiceTests : IDisposable +{ + private readonly IUserHelper _userHelper = Substitute.For(); + private readonly RAPSContext _rapsContext = new(); + private readonly ReportUserService _service; + + public ReportUserServiceTests() + { + _service = new ReportUserService(_rapsContext, _userHelper); + } + + public void Dispose() + { + _rapsContext.Dispose(); + } + + [Fact] + public void SignedIn_GivesTheirIdentifiersAndPermissions() + { + var user = new AaudUser { LoginId = "jdoe", MothraId = "01234567" }; + _userHelper.GetCurrentUser().Returns(user); + _userHelper.HasPermission(_rapsContext, user, "SVMSecure.Reports.Admin").Returns(true); + + ReportCurrentUser? current = _service.GetCurrentUser(); + + Assert.NotNull(current); + Assert.Equal("jdoe", current.LoginId); + Assert.Equal("01234567", current.MothraId); + Assert.True(_service.HasPermission("SVMSecure.Reports.Admin")); + Assert.False(_service.HasPermission("SVMSecure.Other")); + } + + [Fact] + public void NoOneSignedIn_HasNoUserAndNoPermissions() + { + _userHelper.GetCurrentUser().ReturnsNull(); + + Assert.Null(_service.GetCurrentUser()); + Assert.False(_service.HasPermission("SVMSecure.Reports.Admin")); + _userHelper.DidNotReceiveWithAnyArgs().HasPermission(default, default, default!); + } +} diff --git a/test/ReportBuilder/ReportViewerServiceTests.cs b/test/ReportBuilder/ReportViewerServiceTests.cs new file mode 100644 index 000000000..96f06b855 --- /dev/null +++ b/test/ReportBuilder/ReportViewerServiceTests.cs @@ -0,0 +1,262 @@ +using System.Data.Common; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// The list of reports and a report's form: only reports the user may view, and only what the viewer needs. +public sealed class ReportViewerServiceTests : IDisposable +{ + private const string ViewerPermission = "SVMSecure.Personnel.Reports"; + private static readonly Guid RosterSlug = Guid.Parse("8a6f1d2e-0b7c-4a59-9d3e-1f2a3b4c5d6e"); + + private readonly ReportBuilderDbContext _context; + private readonly FakeReportUserService _users = new(); + private readonly FakeReportSourceCatalog _catalog = new(); + private readonly FakeReportQueryExecutor _executor = new(); + private readonly ReportViewerService _service; + + public ReportViewerServiceTests() + { + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); + _context = new ReportBuilderDbContext(options); + _service = new ReportViewerService( + _context, _users, new ReportChoiceService(_catalog, _executor), NullLogger.Instance); + _users.Permissions.Add(ViewerPermission); + _catalog.Sources.Add(new ReportSourceDetail + { + Name = "DeptChoices", + Kind = ReportSourceKind.View, + Columns = [], + Parameters = [], + PagesInSql = true, + }); + } + + public void Dispose() + { + _context.Dispose(); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class FakeDbException : DbException + { + public FakeDbException() : base("timeout") + { + } + } + + private async Task AddAsync(params ReportDefinition[] reports) + { + foreach (ReportDefinition report in reports) + { + _context.Reports.Add(report); + } + + await _context.SaveChangesAsync(Ct); + } + + private static ReportDefinition Report(int id, string title, string? area, string? permission = ViewerPermission) + { + return new ReportDefinition + { + Id = id, + Slug = id == 1 ? RosterSlug : Guid.NewGuid(), + Title = title, + Area = area, + Description = $"About {title}", + Source = "FacultyRoster", + Permissions = permission is null ? [] : [new ReportPermission { ReportId = id, Permission = permission }], + }; + } + + private Task DefinitionAsync(Guid? slug = null) + { + return _service.GetDefinitionAsync((slug ?? RosterSlug).ToString(), Ct); + } + + [Fact] + public async Task Catalog_ListsViewableReportsByAreaThenTitle() + { + ReportDefinition deleted = Report(5, "Deleted", "Personnel"); + deleted.DeletedOn = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Local); + await AddAsync( + Report(1, "Roster", "Personnel"), + Report(2, "Leave", "Personnel"), + Report(3, "Courses", "Effort"), + Report(4, "Other people's", "Personnel", "SVMSecure.Other"), + Report(6, "Admins only", "Admin", null), + deleted); + + IReadOnlyList catalog = await _service.GetCatalogAsync(Ct); + + Assert.Equal(["Courses", "Leave", "Roster"], catalog.Select(r => r.Title)); + ReportCatalogItem roster = catalog[2]; + Assert.Equal(RosterSlug, roster.Slug); + Assert.Equal("Personnel", roster.Area); + Assert.Equal("About Roster", roster.Description); + } + + [Fact] + public async Task Catalog_ForAdmins_ListsEveryReport() + { + await AddAsync(Report(1, "Roster", "Personnel", "SVMSecure.Other"), Report(2, "Admins only", null, null)); + _users.Permissions.Add(ReportBuilderPermissions.Admin); + + Assert.Equal(2, (await _service.GetCatalogAsync(Ct)).Count); + } + + [Fact] + public async Task Catalog_NoOneSignedIn_IsEmpty() + { + await AddAsync(Report(1, "Roster", "Personnel")); + _users.User = null; + + Assert.Empty(await _service.GetCatalogAsync(Ct)); + } + + [Fact] + public async Task Definition_DescribesTheFormAndTable() + { + ReportDefinition report = Report(1, "Roster", "Personnel"); + report.SensitiveNotice = " Confidential "; + report.PageSize = 50; + report.AllowExcel = true; + report.AllowPdf = true; + report.OrderBy = " Name "; + report.OrderByDescending = true; + report.Columns = + [ + new ReportColumn { SourceColumn = "Name", DisplayOrder = 1 }, + new ReportColumn { SourceColumn = "Salary", DisplayOrder = 2, Visible = false }, + ]; + report.Parameters = + [ + new ReportParameter { Name = "Dept", Label = "Department", Type = ReportParameterType.Choice, Required = true, ChoicesSource = "DeptChoices", DisplayOrder = 2 }, + new ReportParameter { Name = "Name", DefaultValue = " Smith ", DisplayOrder = 1 }, + new ReportParameter { Name = "LoginId", Binding = ReportParameterBinding.CurrentUserLoginId }, + ]; + await AddAsync(report); + _executor.Answer = _ => new ReportQueryResult + { + Rows = [FakeReportQueryExecutor.Row(("Value", "VME"), ("Label", "Medicine"))], + Truncated = false, + }; + + ReportDefinitionOutcome outcome = await DefinitionAsync(); + + Assert.Equal(ReportRunStatus.Ok, outcome.Status); + ReportViewerDefinition definition = Assert.IsType(outcome.Definition); + Assert.Equal(RosterSlug, definition.Slug); + Assert.Equal("Roster", definition.Title); + Assert.Equal("About Roster", definition.Description); + Assert.Equal("Personnel", definition.Area); + Assert.Equal("Confidential", definition.SensitiveNotice); + Assert.True(definition.Paginate); + Assert.Equal(50, definition.PageSize); + Assert.True(definition.AllowExcel); + Assert.True(definition.AllowPdf); + Assert.Equal("Name", definition.SortBy); + Assert.True(definition.SortDescending); + Assert.Equal(["Name"], definition.Columns.Select(c => c.Name)); + Assert.Equal( + [ + new ReportViewerParameter { Name = "Name", Label = "Name", Type = ReportParameterType.Text, Required = false, DefaultValue = "Smith" }, + new ReportViewerParameter + { + Name = "Dept", + Label = "Department", + Type = ReportParameterType.Choice, + Required = true, + Choices = [new ReportChoice { Value = "VME", Label = "Medicine" }], + }, + ], + definition.Parameters, + new ViewerParameterComparer()); + } + + [Fact] + public async Task Definition_WithDefaultsLeftEmpty() + { + ReportDefinition report = Report(1, "Roster", null); + report.AllowExcel = false; + report.Parameters = [new ReportParameter { Name = "Dept", Type = ReportParameterType.MultiChoice, ChoicesSource = "Missing" }]; + await AddAsync(report); + + ReportViewerDefinition definition = Assert.IsType((await DefinitionAsync()).Definition); + + Assert.Null(definition.SensitiveNotice); + Assert.Null(definition.SortBy); + Assert.False(definition.SortDescending); + Assert.False(definition.AllowExcel); + Assert.False(definition.AllowPdf); + Assert.Equal(ReportLimits.DefaultPageSize, definition.PageSize); + Assert.Empty(definition.Columns); + Assert.Empty(Assert.Single(definition.Parameters).Choices!); + } + + [Fact] + public async Task Definition_NoOneSignedIn_IsForbidden() + { + await AddAsync(Report(1, "Roster", null)); + _users.User = null; + + Assert.Equal(ReportRunStatus.Forbidden, (await DefinitionAsync()).Status); + } + + [Fact] + public async Task Definition_Unknown_IsNotFound() + { + Assert.Equal(ReportRunStatus.NotFound, (await DefinitionAsync(Guid.NewGuid())).Status); + } + + [Fact] + public async Task Definition_WithoutPermission_IsForbiddenAndLoadsNoChoices() + { + ReportDefinition report = Report(1, "Roster", null, "SVMSecure.Other"); + report.Parameters = [new ReportParameter { Name = "Dept", Type = ReportParameterType.Choice, ChoicesSource = "DeptChoices" }]; + await AddAsync(report); + + ReportDefinitionOutcome outcome = await DefinitionAsync(); + + Assert.Equal(ReportRunStatus.Forbidden, outcome.Status); + Assert.Null(outcome.Definition); + Assert.Empty(_executor.Calls); + } + + [Fact] + public async Task Definition_ChoicesFailing_IsUnavailable() + { + ReportDefinition report = Report(1, "Roster", null); + report.Parameters = [new ReportParameter { Name = "Dept", Type = ReportParameterType.Choice, ChoicesSource = "DeptChoices" }]; + await AddAsync(report); + _executor.Answer = _ => throw new FakeDbException(); + + ReportDefinitionOutcome outcome = await DefinitionAsync(); + + Assert.Equal(ReportRunStatus.Unavailable, outcome.Status); + Assert.Equal(["This report's choices couldn't be loaded. Try again later."], outcome.Errors); + } + + /// Compares parameters by value, including their choice lists. + private sealed class ViewerParameterComparer : IEqualityComparer + { + public bool Equals(ReportViewerParameter? x, ReportViewerParameter? y) + { + return x is not null && y is not null + && (x with { Choices = null }) == (y with { Choices = null }) + && (x.Choices ?? []).SequenceEqual(y.Choices ?? []) + && (x.Choices is null) == (y.Choices is null); + } + + public int GetHashCode(ReportViewerParameter obj) + { + return obj.Name.GetHashCode(StringComparison.Ordinal); + } + } +} diff --git a/web/Areas/Personnel/PersonnelPermissions.cs b/web/Areas/Personnel/PersonnelPermissions.cs new file mode 100644 index 000000000..959b1c4e6 --- /dev/null +++ b/web/Areas/Personnel/PersonnelPermissions.cs @@ -0,0 +1,13 @@ +namespace Viper.Areas.Personnel; + +/// +/// RAPS permissions used by the Personnel section, named as they are in the legacy site so the +/// existing role assignments carry over unchanged. Add each one when the page or report that +/// needs it is ported. +/// +public static class PersonnelPermissions +{ + public const string FacultySalary = "SVMSecure.Personnel.FacultySalary"; + public const string Sabbatic = "SVMSecure.Personnel.Sabbatic"; + public const string ServiceCreditAdmin = "SVMSecure.Personnel.ServiceCreditAdmin"; +} diff --git a/web/Areas/ReportBuilder/Controllers/ReportBuilderAdminController.cs b/web/Areas/ReportBuilder/Controllers/ReportBuilderAdminController.cs new file mode 100644 index 000000000..bdd576179 --- /dev/null +++ b/web/Areas/ReportBuilder/Controllers/ReportBuilderAdminController.cs @@ -0,0 +1,165 @@ +using Microsoft.AspNetCore.Mvc; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes; +using Web.Authorization; + +namespace Viper.Areas.ReportBuilder.Controllers; + +/// +/// The Report Builder's admin API: the [report] sources, RAPS permissions to choose from, +/// creating, editing, deleting, restoring and previewing reports, and the reports that are +/// failing. Every action needs the Report Builder admin permission. +/// +[Route("/api/report-builder/admin")] +[Permission(Allow = ReportBuilderPermissions.Admin)] +public class ReportBuilderAdminController : ApiController +{ + private const string NotFoundMessage = "Report not found."; + + private readonly IReportAdminService _admin; + private readonly IReportSourceCatalogService _catalog; + private readonly IReportPermissionLookupService _permissions; + private readonly IReportProblemService _problems; + + public ReportBuilderAdminController( + IReportAdminService admin, + IReportSourceCatalogService catalog, + IReportPermissionLookupService permissions, + IReportProblemService problems) + { + _admin = admin; + _catalog = catalog; + _permissions = permissions; + _problems = problems; + } + + /// The views and procedures in the [report] schema. + [HttpGet("sources")] + public async Task>> GetSources(CancellationToken ct = default) + { + return Ok(await _catalog.GetSourcesAsync(ct)); + } + + /// A source's columns and, for a procedure, its parameters. + [HttpGet("sources/{name}")] + public async Task> GetSource(string name, CancellationToken ct = default) + { + ReportSourceDetail? source = await _catalog.GetSourceAsync(name, ct); + return source is null ? NotFound("Source not found.") : Ok(source); + } + + /// RAPS permissions whose name contains the text. + [HttpGet("permissions")] + public async Task>> SearchPermissions( + [FromQuery] string? search = null, CancellationToken ct = default) + { + return Ok(await _permissions.SearchAsync(search, ct)); + } + + [HttpGet("definitions")] + public async Task>> List( + [FromQuery] bool includeDeleted = false, CancellationToken ct = default) + { + return Ok(await _admin.ListAsync(includeDeleted, ct)); + } + + [HttpGet("definitions/{id:int}")] + public async Task> Get(int id, CancellationToken ct = default) + { + ReportAdminDefinition? report = await _admin.GetAsync(id, ct); + return report is null ? NotFound(NotFoundMessage) : Ok(report); + } + + [HttpPost("definitions")] + public async Task> Create([FromBody] ReportEditRequest request, CancellationToken ct = default) + { + ReportAdminOutcome outcome = await _admin.CreateAsync(request, ct); + return outcome.Value is { } report + ? CreatedAtAction(nameof(Get), new { id = report.Id }, report) + : ToActionResult(outcome); + } + + /// Saves the report; 409 when someone else saved it after the editor loaded it. + [HttpPut("definitions/{id:int}")] + public async Task> Update(int id, [FromBody] ReportEditRequest request, CancellationToken ct = default) + { + return ToActionResult(await _admin.UpdateAsync(id, request, ct)); + } + + /// Hides the report from viewers; it can be restored. + [HttpDelete("definitions/{id:int}")] + public async Task> Delete(int id, CancellationToken ct = default) + { + return ToActionResult(await _admin.DeleteAsync(id, ct)); + } + + [HttpPost("definitions/{id:int}/restore")] + public async Task> Restore(int id, CancellationToken ct = default) + { + return ToActionResult(await _admin.RestoreAsync(id, ct)); + } + + [HttpGet("definitions/{id:int}/history")] + public async Task>> GetHistory(int id, CancellationToken ct = default) + { + IReadOnlyList? history = await _admin.GetHistoryAsync(id, ct); + return history is null ? NotFound(NotFoundMessage) : Ok(history); + } + + [HttpGet("definitions/{id:int}/history/{historyId:int}")] + public async Task> GetHistoryVersion(int id, int historyId, CancellationToken ct = default) + { + ReportHistoryVersion? version = await _admin.GetHistoryVersionAsync(id, historyId, ct); + return version is null ? NotFound("Version not found.") : Ok(version); + } + + /// A page of an unsaved report, so the form can show what it will look like. + [HttpPost("preview")] + public async Task> Preview([FromBody] ReportPreviewRequest request, CancellationToken ct = default) + { + ReportRunOutcome outcome = await _admin.PreviewAsync(request, ct); + return outcome.Status switch + { + ReportRunStatus.Ok => Ok(outcome.Result), + ReportRunStatus.Forbidden => ForbidApi("Only Report Builder admins can preview reports."), + ReportRunStatus.Invalid => BadRequest(Invalid(outcome.Errors, "The report isn't ready to preview.")), + _ => StatusCode( + StatusCodes.Status503ServiceUnavailable, + outcome.Errors.Count > 0 ? string.Join(" ", outcome.Errors) : "The preview couldn't be run."), + }; + } + + /// Runs that failed in the last days, newest first. + [HttpGet("failures")] + public async Task>> GetFailures([FromQuery] int? days = null, CancellationToken ct = default) + { + return Ok(await _problems.GetFailuresAsync(days, ct)); + } + + /// Every live report checked against the [report] catalog and RAPS, as a save would. + [HttpGet("check")] + public async Task> Check(CancellationToken ct = default) + { + return Ok(await _problems.CheckAsync(ct)); + } + + private ActionResult ToActionResult(ReportAdminOutcome outcome) + { + return outcome.Status switch + { + ReportAdminStatus.Ok => Ok(outcome.Value), + ReportAdminStatus.NotFound => NotFound(NotFoundMessage), + ReportAdminStatus.Conflict => Conflict(string.Join(" ", outcome.Errors)), + _ => BadRequest(Invalid(outcome.Errors, "The report can't be saved.")), + }; + } + + private static ValidationProblemDetails Invalid(IReadOnlyList errors, string title) + { + return new ValidationProblemDetails(new Dictionary(StringComparer.Ordinal) { [string.Empty] = [.. errors] }) + { + Title = title, + }; + } +} diff --git a/web/Areas/ReportBuilder/Controllers/ReportBuilderController.cs b/web/Areas/ReportBuilder/Controllers/ReportBuilderController.cs new file mode 100644 index 000000000..b8f9466e8 --- /dev/null +++ b/web/Areas/ReportBuilder/Controllers/ReportBuilderController.cs @@ -0,0 +1,89 @@ +using Microsoft.AspNetCore.Mvc; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes; +using Web.Authorization; + +namespace Viper.Areas.ReportBuilder.Controllers; + +/// +/// Lists, describes, runs and downloads admin-built reports. Signing in is enough to reach the +/// controller; each report's own view permission is checked by the services before anything +/// the user sent is read. +/// +[Route("/api/report-builder")] +[Permission(Allow = "SVMSecure")] +public class ReportBuilderController : ApiController +{ + private readonly IReportViewerService _viewer; + private readonly IReportRunService _runs; + private readonly IReportExportService _exports; + + public ReportBuilderController(IReportViewerService viewer, IReportRunService runs, IReportExportService exports) + { + _viewer = viewer; + _runs = runs; + _exports = exports; + } + + /// The reports the user may view. + [HttpGet] + public async Task>> GetCatalog(CancellationToken ct = default) + { + return Ok(await _viewer.GetCatalogAsync(ct)); + } + + /// A report's form fields, columns and settings. + [HttpGet("{slug:guid}")] + public async Task> GetDefinition(string slug, CancellationToken ct = default) + { + ReportDefinitionOutcome outcome = await _viewer.GetDefinitionAsync(slug, ct); + return outcome.Status == ReportRunStatus.Ok ? Ok(outcome.Definition) : Failure(outcome.Status, outcome.Errors); + } + + /// One page of the report (or all of it, when it isn't paginated). + [HttpPost("{slug:guid}/run")] + public async Task> Run(string slug, [FromBody] ReportRunRequest request, CancellationToken ct = default) + { + ReportRunOutcome outcome = await _runs.RunAsync(slug, request, ReportRunMode.Screen, ct); + return outcome.Status == ReportRunStatus.Ok ? Ok(outcome.Result) : Failure(outcome.Status, outcome.Errors); + } + + /// + /// The report as a download in (xlsx or pdf), or 204 No Content + /// when it has no rows. + /// + [HttpPost("{slug:guid}/export/{format}")] + public async Task Export(string slug, string format, [FromBody] ReportRunRequest request, CancellationToken ct = default) + { + ReportExportOutcome outcome = await _exports.ExportAsync(slug, format, request, ct); + if (outcome.Status != ReportRunStatus.Ok) + { + return Failure(outcome.Status, outcome.Errors); + } + + if (outcome.File is not { } file) + { + return NoContent(); + } + + // Reports can hold confidential data, so neither the browser nor a proxy may keep a copy. + Response.Headers.CacheControl = "private, no-store, max-age=0"; + return File(file.Content, file.ContentType, file.FileName); + } + + private ActionResult Failure(ReportRunStatus status, IReadOnlyList errors) + { + return status switch + { + ReportRunStatus.NotFound => NotFound("Report not found."), + ReportRunStatus.Forbidden => ForbidApi("You do not have access to this report."), + ReportRunStatus.Invalid => BadRequest(new ValidationProblemDetails( + new Dictionary(StringComparer.Ordinal) { [string.Empty] = [.. errors] }) + { + Title = "The report request is not valid.", + }), + _ => StatusCode(StatusCodes.Status503ServiceUnavailable, errors.Count > 0 ? string.Join(" ", errors) : "This report is unavailable."), + }; + } +} diff --git a/web/Areas/ReportBuilder/Exporters/ReportExcelWriter.cs b/web/Areas/ReportBuilder/Exporters/ReportExcelWriter.cs new file mode 100644 index 000000000..dabd11393 --- /dev/null +++ b/web/Areas/ReportBuilder/Exporters/ReportExcelWriter.cs @@ -0,0 +1,179 @@ +using System.Globalization; +using ClosedXML.Excel; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes.Utilities; + +namespace Viper.Areas.ReportBuilder.Exporters; + +/// +/// Writes a report to an Excel workbook: a heading (title, when it was generated, filters, +/// confidentiality notice, truncation note), then the rows as an accessible Excel table. +/// Numbers and dates stay typed so the sheet can be sorted and summed; text is guarded +/// against formula injection. +/// +public static class ReportExcelWriter +{ + public const string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + public const string Extension = ".xlsx"; + + internal const string DateNumberFormat = "mm/dd/yyyy"; + internal const string DateTimeNumberFormat = "mm/dd/yyyy h:mm AM/PM"; + private const int TitleFontSize = 14; + private const double MaxColumnWidth = 60; + + // Widths are measured on the heading and the first rows only; measuring 50,000 rows is slow. + private const int WidthSampleRows = 200; + + public static byte[] Write(ReportExportDocument document) + { + ArgumentNullException.ThrowIfNull(document); + using var workbook = new XLWorkbook(); + ExcelAccessibilityHelper.SetCoreProperties(workbook, document.Title); + IXLWorksheet sheet = workbook.Worksheets.Add(ExcelHelper.SanitizeSheetName(document.Title)); + + int headerRow = WriteHeading(sheet, document) + 1; + int columnCount = document.Columns.Count; + IReadOnlyList headers = UniqueHeaders(document.Columns); + for (int index = 0; index < columnCount; index++) + { + IXLCell header = sheet.Cell(headerRow, index + 1); + header.Value = ExcelHelper.SanitizeStringCell(headers[index]); + header.Style.Font.Bold = true; + } + + var wholeNumbers = new bool[columnCount]; + Array.Fill(wholeNumbers, true); + int row = headerRow; + foreach (IReadOnlyDictionary values in document.Rows) + { + row++; + for (int index = 0; index < columnCount; index++) + { + ReportResultColumn column = document.Columns[index]; + object? value = values.GetValueOrDefault(column.Name); + wholeNumbers[index] &= WriteValue(sheet.Cell(row, index + 1), value, column.Format); + } + } + + if (row > headerRow) + { + for (int index = 0; index < columnCount; index++) + { + if (NumberFormat(document.Columns[index].Format, wholeNumbers[index]) is { } format) + { + sheet.Range(headerRow + 1, index + 1, row, index + 1).Style.NumberFormat.Format = format; + } + } + + ExcelAccessibilityHelper.PromoteToAccessibleTable(sheet.Range(headerRow, 1, row, columnCount), "ReportTable"); + } + + if (columnCount > 0) + { + sheet.Columns(1, columnCount).AdjustToContents(headerRow, Math.Min(row, headerRow + WidthSampleRows), 0, MaxColumnWidth); + } + + using var stream = new MemoryStream(); + workbook.SaveAs(stream); + return stream.ToArray(); + } + + /// + /// The number format for a numeric column: whole numbers without decimals, others with two. + /// Null for columns whose cells are formatted one by one (dates) or hold text. + /// + internal static string? NumberFormat(ReportColumnFormat format, bool wholeNumbers) + { + string fraction = wholeNumbers ? string.Empty : ".00"; + return format switch + { + ReportColumnFormat.Number => "#,##0" + fraction, + ReportColumnFormat.Currency => "$#,##0.00", + ReportColumnFormat.Percent => "0" + fraction + "%", + _ => null, + }; + } + + /// + /// The column labels, with " (2)", " (3)" and so on added to repeats: an Excel table's + /// header names must be unique. + /// + internal static IReadOnlyList UniqueHeaders(IReadOnlyList columns) + { + var used = new HashSet(StringComparer.OrdinalIgnoreCase); + var headers = new List(columns.Count); + foreach (string label in columns.Select(column => column.Label)) + { + string candidate = label; + int copy = 1; + while (!used.Add(candidate)) + { + copy++; + candidate = string.Create(CultureInfo.InvariantCulture, $"{label} ({copy})"); + } + + headers.Add(candidate); + } + + return headers; + } + + private static int WriteHeading(IXLWorksheet sheet, ReportExportDocument document) + { + int row = 1; + IXLCell title = sheet.Cell(row++, 1); + title.Value = ExcelHelper.SanitizeStringCell(document.Title); + title.Style.Font.Bold = true; + title.Style.Font.FontSize = TitleFontSize; + sheet.Cell(row++, 1).Value = ReportExportText.Generated(document.GeneratedAt); + + if (ReportExportText.Filters(document.Filters) is { } filters) + { + sheet.Cell(row++, 1).Value = ExcelHelper.SanitizeStringCell(filters); + } + + if (document.SensitiveNotice is { } notice) + { + IXLCell cell = sheet.Cell(row++, 1); + cell.Value = ExcelHelper.SanitizeStringCell(notice); + cell.Style.Font.Italic = true; + } + + if (document.Truncated) + { + sheet.Cell(row++, 1).Value = ReportExportText.Truncated(); + } + + return row; + } + + /// + /// Writes one value, typed where it can be. Returns false only for a number with a + /// fraction (as the column shows it), which gives the column two decimals. + /// + private static bool WriteValue(IXLCell cell, object? value, ReportColumnFormat format) + { + if (value is null) + { + return true; + } + + if (format != ReportColumnFormat.YesNo && ReportCellFormatter.TryGetDateTime(value, out DateTime dateTime)) + { + cell.Value = dateTime; + cell.Style.NumberFormat.Format = ReportCellFormatter.ShowsTime(format, dateTime) ? DateTimeNumberFormat : DateNumberFormat; + return true; + } + + if (format != ReportColumnFormat.YesNo && value is not bool && ReportCellFormatter.TryGetNumber(value, out decimal number)) + { + cell.Value = (double)number; + decimal shown = format == ReportColumnFormat.Percent ? number * 100 : number; + return shown == decimal.Truncate(shown); + } + + cell.Value = ExcelHelper.SanitizeStringCell(ReportCellFormatter.Text(value, format)); + return true; + } +} diff --git a/web/Areas/ReportBuilder/Exporters/ReportExportDocument.cs b/web/Areas/ReportBuilder/Exporters/ReportExportDocument.cs new file mode 100644 index 000000000..50f16946a --- /dev/null +++ b/web/Areas/ReportBuilder/Exporters/ReportExportDocument.cs @@ -0,0 +1,51 @@ +using System.Globalization; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.Areas.ReportBuilder.Exporters; + +/// Everything a download shows: the heading, the columns and the rows. +public sealed record ReportExportDocument +{ + public required string Title { get; init; } + public required DateTimeOffset GeneratedAt { get; init; } + public IReadOnlyList Filters { get; init; } = []; + + /// The report's confidentiality notice, repeated on every PDF page; null when it has none. + public string? SensitiveNotice { get; init; } + + /// PDF page orientation. + public bool Landscape { get; init; } + + public required IReadOnlyList Columns { get; init; } + public required IReadOnlyList> Rows { get; init; } + + /// True when the row cap cut the report short. + public bool Truncated { get; init; } +} + +/// Wording shared by the Excel and PDF downloads, so both read the same. +public static class ReportExportText +{ + private static readonly CultureInfo UsEnglish = CultureInfo.GetCultureInfo("en-US"); + + public static string Generated(DateTimeOffset generatedAt) + { + return "Generated " + generatedAt.ToString(ReportCellFormatter.DateTimeFormat, UsEnglish); + } + + /// "Filters: Department: Pathology; Hired from: 07/01/2026", or null when nothing was filled in. + public static string? Filters(IReadOnlyList filters) + { + ArgumentNullException.ThrowIfNull(filters); + return filters.Count == 0 + ? null + : "Filters: " + string.Join("; ", filters.Select(filter => $"{filter.Label}: {filter.Value}")); + } + + /// Said when the row cap cut the report short. + public static string Truncated() + { + return string.Create(UsEnglish, $"Only the first {ReportLimits.MaxRows:N0} rows are included."); + } +} diff --git a/web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs b/web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs new file mode 100644 index 000000000..e2c95ea01 --- /dev/null +++ b/web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs @@ -0,0 +1,126 @@ +using QuestPDF.Fluent; +using QuestPDF.Helpers; +using QuestPDF.Infrastructure; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; +using Viper.Classes.Utilities; + +namespace Viper.Areas.ReportBuilder.Exporters; + +/// +/// Writes a report to a Letter PDF tagged for PDF/UA: a heading (title, when it was generated, +/// filters, confidentiality notice, truncation note), then one table whose header repeats on +/// every page. The notice and page numbers are in the footer. +/// +public static class ReportPdfWriter +{ + public const string ContentType = "application/pdf"; + public const string Extension = ".pdf"; + + private const float FontSize = 8f; + private const float TitleFontSize = 13f; + private const float FooterFontSize = 7f; + private const float SectionSpacing = 8f; + private const float CellPaddingVertical = 2f; + private const float CellPaddingHorizontal = 3f; + private const float RuleWidth = 0.5f; + private const string HeaderFill = "#E8E8E8"; + private const string RuleColor = "#CCCCCC"; + + public static byte[] Write(ReportExportDocument document) + { + ArgumentNullException.ThrowIfNull(document); + return Document.Create(container => container.Page(page => + { + page.Size(document.Landscape ? PageSizes.Letter.Landscape() : PageSizes.Letter); + page.MarginHorizontal(0.5f, Unit.Inch); + page.MarginVertical(0.4f, Unit.Inch); + page.DefaultTextStyle(style => style.FontSize(FontSize)); + page.Header().Element(header => ComposeHeading(header, document)); + page.Content().PaddingTop(SectionSpacing).Element(content => ComposeTable(content, document)); + page.Footer().Element(footer => ComposeFooter(footer, document.SensitiveNotice)); + })) + .WithAccessibility(document.Title) + .GeneratePdf(); + } + + private static void ComposeHeading(IContainer container, ReportExportDocument document) + { + container.Column(column => + { + column.Item().SemanticHeading1().Text(document.Title).SemiBold().FontSize(TitleFontSize); + column.Item().Text(ReportExportText.Generated(document.GeneratedAt)); + if (ReportExportText.Filters(document.Filters) is { } filters) + { + column.Item().Text(filters); + } + + if (document.SensitiveNotice is { } notice) + { + column.Item().Text(notice).Italic(); + } + + if (document.Truncated) + { + column.Item().Text(ReportExportText.Truncated()); + } + }); + } + + private static void ComposeTable(IContainer container, ReportExportDocument document) + { + container.SemanticTable().Table(table => + { + table.ColumnsDefinition(definition => + { + for (int index = 0; index < document.Columns.Count; index++) + { + definition.RelativeColumn(); + } + }); + + table.Header(header => + { + foreach (ReportResultColumn column in document.Columns) + { + Align(Padded(header.Cell().Background(HeaderFill)), column.Format) + .Text(column.Label) + .SemiBold(); + } + }); + + foreach (IReadOnlyDictionary row in document.Rows) + { + foreach (ReportResultColumn column in document.Columns) + { + // An empty cell would drop out of the PDF's structure tree, so it shows a dash. + string text = PdfAccessibilityHelper.OrDash(ReportCellFormatter.Text(row.GetValueOrDefault(column.Name), column.Format)); + Align(Padded(table.Cell().BorderBottom(RuleWidth).BorderColor(RuleColor)), column.Format).Text(text); + } + } + }); + } + + private static void ComposeFooter(IContainer container, string? notice) + { + container.Column(column => + { + if (notice is not null) + { + column.Item().AlignCenter().Text(notice).FontSize(FooterFontSize).Italic(); + } + + column.Item().PageNumberFooter(); + }); + } + + private static IContainer Padded(IContainer cell) + { + return cell.PaddingVertical(CellPaddingVertical).PaddingHorizontal(CellPaddingHorizontal); + } + + private static IContainer Align(IContainer cell, ReportColumnFormat format) + { + return ReportCellFormatter.IsNumeric(format) ? cell.AlignRight() : cell.AlignLeft(); + } +} diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs b/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs new file mode 100644 index 000000000..8bd5bca24 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs @@ -0,0 +1,21 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// +/// One column of a report (report.report_column): which source column it shows, its +/// label, order and display format. +/// +public class ReportColumn +{ + public int Id { get; set; } + public int ReportId { get; set; } + public string? SourceColumn { get; set; } + public string? Label { get; set; } + + /// How the values are shown on screen and in exports (the datatype column). + public ReportColumnFormat? Format { get; set; } + + public bool Sortable { get; set; } = true; + public bool Visible { get; set; } = true; + public int DisplayOrder { get; set; } + public ReportDefinition? Report { get; set; } +} diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportDefinition.cs b/web/Areas/ReportBuilder/Models/Entities/ReportDefinition.cs new file mode 100644 index 000000000..d6f97a744 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportDefinition.cs @@ -0,0 +1,54 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// +/// One admin-defined report (report.report): which view or procedure in the [report] +/// schema it reads, who may view it, and how it is laid out. Its is the +/// report's URL. Nullable settings fall back to defaults in the services. +/// +public class ReportDefinition +{ + public int Id { get; set; } + + /// The report's URL key, generated by the database. + public Guid Slug { get; set; } + + public string Title { get; set; } = string.Empty; + public string? Description { get; set; } + + /// Groups reports in the catalog, such as "Effort" or "Personnel". + public string? Area { get; set; } + + /// + /// The view or procedure name in the [report] schema. Whether it is a view or a procedure + /// is read from the catalog when the report runs. + /// + public string Source { get; set; } = string.Empty; + + public bool? Paginate { get; set; } + public int? PageSize { get; set; } + public bool AllowExcel { get; set; } = true; + public bool AllowPdf { get; set; } + public bool? PdfLandscape { get; set; } + + /// Shown above the table and in exports when the data is confidential. + public string? SensitiveNotice { get; set; } + + public string? OrderBy { get; set; } + public bool? OrderByDescending { get; set; } + public DateTime? CreatedOn { get; set; } + public string? CreatedBy { get; set; } + + /// Sent back by the editor to detect a conflicting save, as CMS content does. + public DateTime? ModifiedOn { get; set; } + + public string? ModifiedBy { get; set; } + + /// Set when soft-deleted; the report can be restored until then. + public DateTime? DeletedOn { get; set; } + + public string? DeletedBy { get; set; } + + public ICollection Permissions { get; set; } = []; + public ICollection Columns { get; set; } = []; + public ICollection Parameters { get; set; } = []; +} diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs b/web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs new file mode 100644 index 000000000..1415012dc --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs @@ -0,0 +1,15 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// A saved copy of a report, taken on every change (report.report_history). +public class ReportDefinitionHistory +{ + public int Id { get; set; } + public int ReportId { get; set; } + public ReportHistoryAction? Action { get; set; } + + /// The whole report, with its columns, parameters and permissions, as JSON. + public string? Snapshot { get; set; } + + public DateTime? ChangedOn { get; set; } + public string? ChangedBy { get; set; } +} diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportParameter.cs b/web/Areas/ReportBuilder/Models/Entities/ReportParameter.cs new file mode 100644 index 000000000..80eeddb7b --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportParameter.cs @@ -0,0 +1,33 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// +/// One report parameter (report.report_parameter): a filter on a view column, or a value +/// for a procedure parameter. +/// +public class ReportParameter +{ + public int Id { get; set; } + public int ReportId { get; set; } + + /// The view column to filter, or the procedure parameter name without the @. + public string? Name { get; set; } + + public string? Label { get; set; } + public int? DisplayOrder { get; set; } + public ReportParameterType? Type { get; set; } + + /// How a view column is filtered; null for procedure parameters. + public ReportFilterOperator? Operator { get; set; } + + public bool? Required { get; set; } + public string? DefaultValue { get; set; } + + /// A [report] view returning value and label columns, for choice parameters. + public string? ChoicesSource { get; set; } + + /// A fixed list of choices as JSON, for choice parameters without a view. + public string? ChoicesList { get; set; } + + public ReportParameterBinding? Binding { get; set; } + public ReportDefinition? Report { get; set; } +} diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportPermission.cs b/web/Areas/ReportBuilder/Models/Entities/ReportPermission.cs new file mode 100644 index 000000000..6b6d1d487 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportPermission.cs @@ -0,0 +1,9 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// A RAPS permission that lets a user view a report (report.report_permission). Holding any one is enough. +public class ReportPermission +{ + public int ReportId { get; set; } + public string Permission { get; set; } = string.Empty; + public ReportDefinition? Report { get; set; } +} diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs b/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs new file mode 100644 index 000000000..ca7b30742 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs @@ -0,0 +1,28 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// +/// One run or export of a report (report.report_runLog): who, when, with which +/// parameters, and how many rows; or, for a run that failed, why. +/// +public class ReportRunLog +{ + public int Id { get; set; } + public int ReportId { get; set; } + public ReportRunAction? Action { get; set; } + public string? LoginId { get; set; } + public DateTime? RanOn { get; set; } + + /// The parameter values as JSON. + public string? Parameters { get; set; } + + public int? RowsReturned { get; set; } + + /// How long the run took, in milliseconds. + public int? DurationMs { get; set; } + + /// SQL Server's error number when the database refused the run; null otherwise. + public int? ErrorNumber { get; set; } + + /// Why the run failed; null when it succeeded. + public string? ErrorMessage { get; set; } +} diff --git a/web/Areas/ReportBuilder/Models/ReportAdminDtos.cs b/web/Areas/ReportBuilder/Models/ReportAdminDtos.cs new file mode 100644 index 000000000..37b01a27a --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportAdminDtos.cs @@ -0,0 +1,205 @@ +using System.Text.Json.Serialization; + +namespace Viper.Areas.ReportBuilder.Models; + +/// +/// A report as the admin form edits it: the body of a create or update, and the base of what a +/// read returns. Columns and parameters are in display order. +/// +public sealed record ReportEditRequest +{ + public required string Title { get; init; } + public string? Description { get; init; } + + /// Groups reports in the list, such as "Effort" or "Personnel". + public string? Area { get; init; } + + /// The view or procedure in the [report] schema. + public required string Source { get; init; } + + [JsonRequired] + public bool Paginate { get; init; } + + /// Rows per page; the default when null. + public int? PageSize { get; init; } + + [JsonRequired] + public bool AllowExcel { get; init; } + + [JsonRequired] + public bool AllowPdf { get; init; } + + [JsonRequired] + public bool PdfLandscape { get; init; } + + public string? SensitiveNotice { get; init; } + + /// The source column the report is sorted by until the user picks another. + public string? OrderBy { get; init; } + + [JsonRequired] + public bool OrderByDescending { get; init; } + + /// RAPS permission names; a user needs any one. None means admins only. + public IReadOnlyList Permissions { get; init; } = []; + + public IReadOnlyList Columns { get; init; } = []; + public IReadOnlyList Parameters { get; init; } = []; + + /// + /// The report's last-modified time as the editor loaded it; an update made from an older copy + /// is refused. Not used when creating. + /// + public DateTime? LastModifiedOn { get; init; } +} + +/// One column of the report, as the admin form edits it. +public sealed record ReportColumnEdit +{ + public required string SourceColumn { get; init; } + + /// The heading; the source column's name when empty. + public string? Label { get; init; } + + [JsonRequired] + public ReportColumnFormat Format { get; init; } + + [JsonRequired] + public bool Sortable { get; init; } + + [JsonRequired] + public bool Visible { get; init; } +} + +/// One parameter of the report, as the admin form edits it. +public sealed record ReportParameterEdit +{ + /// The view column to filter, or the procedure parameter without the @. + public required string Name { get; init; } + + public string? Label { get; init; } + + [JsonRequired] + public ReportParameterType Type { get; init; } + + /// How a view column is filtered; ignored for procedures. + public ReportFilterOperator? Operator { get; init; } + + [JsonRequired] + public bool Required { get; init; } + + public string? DefaultValue { get; init; } + + /// A [report] view with Value and Label columns, for choice parameters. + public string? ChoicesSource { get; init; } + + /// A fixed list of choices, used instead of when given. + public IReadOnlyList? ChoicesList { get; init; } + + [JsonRequired] + public ReportParameterBinding Binding { get; init; } +} + +/// A saved report as the admin form loads it: the editable fields and who changed it when. +public sealed record ReportAdminDefinition +{ + public required int Id { get; init; } + public required Guid Slug { get; init; } + public DateTime? CreatedOn { get; init; } + public string? CreatedBy { get; init; } + public DateTime? ModifiedOn { get; init; } + public string? ModifiedBy { get; init; } + public DateTime? DeletedOn { get; init; } + public string? DeletedBy { get; init; } + + /// + /// The editable fields, ready to send back as the update's body; its + /// is this version's. + /// + public required ReportEditRequest Report { get; init; } + + /// Permissions the report names that RAPS no longer has; nobody holds them. + public IReadOnlyList MissingPermissions { get; init; } = []; +} + +/// A report in the admin list. +public sealed record ReportAdminListItem +{ + public required int Id { get; init; } + public required Guid Slug { get; init; } + public required string Title { get; init; } + public string? Area { get; init; } + public required string Source { get; init; } + public DateTime? ModifiedOn { get; init; } + public string? ModifiedBy { get; init; } + public DateTime? DeletedOn { get; init; } + public IReadOnlyList Permissions { get; init; } = []; + + /// Permissions the report names that RAPS no longer has; nobody holds them. + public IReadOnlyList MissingPermissions { get; init; } = []; +} + +/// One saved version of a report. +public sealed record ReportHistoryItem +{ + public required int Id { get; init; } + public ReportHistoryAction? Action { get; init; } + public DateTime? ChangedOn { get; init; } + public string? ChangedBy { get; init; } +} + +/// A saved version with the report as it was then. +public sealed record ReportHistoryVersion +{ + public required ReportHistoryItem Version { get; init; } + + /// The report's fields at that time; null if the snapshot can't be read. + public ReportEditRequest? Report { get; init; } +} + +/// A RAPS permission, for the admin form's permission picker. +public sealed record ReportPermissionOption +{ + public required string Permission { get; init; } + public string? Description { get; init; } +} + +/// A preview of an unsaved report: its fields and the page to show. +public sealed record ReportPreviewRequest +{ + public required ReportEditRequest Report { get; init; } + public ReportRunRequest Run { get; init; } = new(); +} + +/// How an admin request ended, for the controller to turn into a status code. +public enum ReportAdminStatus +{ + Ok, + NotFound, + Invalid, + + /// Someone else saved the report after the editor loaded it. + Conflict, +} + +/// The result of an admin request, or why there is none. +public sealed record ReportAdminOutcome +{ + public required ReportAdminStatus Status { get; init; } + public T? Value { get; init; } + public IReadOnlyList Errors { get; init; } = []; +} + +/// Builds values. +public static class ReportAdminOutcome +{ + public static ReportAdminOutcome Ok(T value) + { + return new ReportAdminOutcome { Status = ReportAdminStatus.Ok, Value = value }; + } + + public static ReportAdminOutcome Fail(ReportAdminStatus status, params string[] errors) + { + return new ReportAdminOutcome { Status = status, Errors = errors }; + } +} diff --git a/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs b/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs new file mode 100644 index 000000000..400fe5550 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs @@ -0,0 +1,99 @@ +using System.Text.Json.Serialization; + +namespace Viper.Areas.ReportBuilder.Models; + +// Every enum is sent to and from the browser by name, as the database stores it. + +/// What kind of object in the [report] schema a report reads. +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportSourceKind +{ + View, + Procedure, +} + +/// +/// The kind of value a source column or parameter holds, from its SQL type. Binary and +/// values can't be shown in a report. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportValueKind +{ + Text, + WholeNumber, + FractionalNumber, + Date, + DateTime, + Time, + Boolean, + UniqueId, + Binary, + Other, +} + +/// How a report column's values are shown on screen and in exports. +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportColumnFormat +{ + Text, + Number, + Currency, + Percent, + Date, + DateTime, + YesNo, +} + +/// The input a report parameter takes. +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportParameterType +{ + Text, + Number, + Date, + Boolean, + Choice, + MultiChoice, +} + +/// How a parameter filters a view's column. Procedure parameters have no operator. +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportFilterOperator +{ + Equals, + Contains, + From, + To, + In, +} + +/// +/// Where a parameter's value comes from. The current-user bindings are filled in on the server +/// and can't be changed by the user, which lets a source return only that user's rows. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportParameterBinding +{ + UserInput, + CurrentUserLoginId, + CurrentUserMothraId, +} + +/// What a user did with a report, for the run log. +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportRunAction +{ + Run, + ExportExcel, + ExportPdf, +} + +/// What happened to a report definition, for its history. +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportHistoryAction +{ + Created, + Updated, + Deleted, + Restored, +} diff --git a/web/Areas/ReportBuilder/Models/ReportBuilderMapper.cs b/web/Areas/ReportBuilder/Models/ReportBuilderMapper.cs new file mode 100644 index 000000000..7d623369d --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportBuilderMapper.cs @@ -0,0 +1,27 @@ +using Riok.Mapperly.Abstractions; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Models; + +/// +/// Maps Report Builder entities to the shapes the API returns, so a property added to an +/// entity can't reach a caller unless the DTO adds it too. +/// +[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.None)] +public static partial class ReportBuilderMapper +{ + // Only what the list of reports shows: the settings, permissions, columns and audit + // fields stay on the server. + public static partial ReportCatalogItem ToCatalogItem(ReportDefinition source); + + // The permission lists are built by the admin service, which checks the names against RAPS. + [MapperIgnoreTarget(nameof(ReportAdminListItem.Permissions))] + [MapperIgnoreTarget(nameof(ReportAdminListItem.MissingPermissions))] + public static partial ReportAdminListItem ToAdminListItem(ReportDefinition source); + + public static partial ReportHistoryItem ToHistoryItem(ReportDefinitionHistory source); + + // The problems come from the validator, which the problem service runs. + [MapperIgnoreTarget(nameof(ReportCheckProblem.Problems))] + public static partial ReportCheckProblem ToCheckProblem(ReportDefinition source); +} diff --git a/web/Areas/ReportBuilder/Models/ReportProblemDtos.cs b/web/Areas/ReportBuilder/Models/ReportProblemDtos.cs new file mode 100644 index 000000000..d50dba40b --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportProblemDtos.cs @@ -0,0 +1,50 @@ +namespace Viper.Areas.ReportBuilder.Models; + +/// A run or download that failed because of the report or its source, newest first. +public sealed record ReportFailure +{ + /// The run log entry. + public required int Id { get; init; } + + public required int ReportId { get; init; } + public required string ReportTitle { get; init; } + + /// When the report has since been deleted. + public bool ReportDeleted { get; init; } + + public ReportRunAction? Action { get; init; } + public string? LoginId { get; init; } + public DateTime? RanOn { get; init; } + + /// The values the user chose, as JSON. + public string? Parameters { get; init; } + + /// SQL Server's error number, when the database refused the run. + public int? ErrorNumber { get; init; } + + public required string ErrorMessage { get; init; } +} + +/// A saved report that wouldn't pass the admin form's checks today. +public sealed record ReportCheckProblem +{ + public required int Id { get; init; } + public required string Title { get; init; } + public string? Area { get; init; } + public required string Source { get; init; } + + /// What the checks found; filled in by the problem service. + public IReadOnlyList Problems { get; init; } = []; +} + +/// Every live report checked against the [report] catalog and RAPS. +public sealed record ReportCheckResult +{ + /// How many reports were checked. + public required int Checked { get; init; } + + public required DateTime CheckedOn { get; init; } + + /// Only the reports with something wrong, by area and title. + public required IReadOnlyList Failing { get; init; } +} diff --git a/web/Areas/ReportBuilder/Models/ReportRunDtos.cs b/web/Areas/ReportBuilder/Models/ReportRunDtos.cs new file mode 100644 index 000000000..d03c890e6 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportRunDtos.cs @@ -0,0 +1,123 @@ +using System.Text.Json.Serialization; + +namespace Viper.Areas.ReportBuilder.Models; + +/// Why a report is being run: on screen, or for one of the downloads. +public enum ReportRunMode +{ + Screen, + ExportExcel, + ExportPdf, +} + +/// What a run asks for: parameter values, and for the screen, a page, sort and search. +public sealed record ReportRunRequest +{ + /// + /// Parameter values by parameter name, ignoring case. Every value is a list so multi-choice + /// parameters fit; single-valued parameters use the first entry. + /// + public IReadOnlyDictionary> Parameters { get; init; } = + new Dictionary>(); + + /// The page to show, counting from 1. Ignored for downloads and unpaginated reports. + [JsonRequired] + public int Page { get; init; } = 1; + + /// Rows per page; the report's page size when not given. + public int? PerPage { get; init; } + + /// A visible, sortable column to sort by; the report's default order when not given. + public string? SortBy { get; init; } + + [JsonRequired] + public bool SortDescending { get; init; } + + /// Text to find in the report's visible text columns (views only). + public string? Search { get; init; } +} + +/// A column of a report's result, as the viewer and the exports show it. +public sealed record ReportResultColumn +{ + /// The source column name; also the key of the value in each row. + public required string Name { get; init; } + + public required string Label { get; init; } + public required ReportColumnFormat Format { get; init; } + public required bool Sortable { get; init; } +} + +/// One page (or, for downloads, all) of a report's rows. +public sealed record ReportRunResult +{ + public required IReadOnlyList Columns { get; init; } + + /// Each row's values by column name. + public required IReadOnlyList> Rows { get; init; } + + public required int Page { get; init; } + public required int PerPage { get; init; } + + /// Rows across all pages; null when the source can't say (a capped procedure). + public int? TotalRows { get; init; } + + /// True when the row cap cut the result short. + public required bool Truncated { get; init; } +} + +/// How a run ended, for the controller to turn into a status code. +public enum ReportRunStatus +{ + Ok, + NotFound, + Forbidden, + Invalid, + + /// The report can't run: its source or a column is gone, or the query failed. + Unavailable, +} + +/// The result of a run, or why there is none. +public sealed record ReportRunOutcome +{ + public required ReportRunStatus Status { get; init; } + public ReportRunResult? Result { get; init; } + + /// What a download's heading needs to say about the run; set with . + public ReportRunDetails? Details { get; init; } + + /// What was wrong, for and . + public IReadOnlyList Errors { get; init; } = []; + + internal static ReportRunOutcome Fail(ReportRunStatus status, params string[] errors) + { + return new ReportRunOutcome { Status = status, Errors = errors }; + } +} + +/// The report's own settings and the filters a run used, for a download's heading. +public sealed record ReportRunDetails +{ + public required string Title { get; init; } + + /// The report's confidentiality notice, or null when it has none. + public string? SensitiveNotice { get; init; } + + public required bool PdfLandscape { get; init; } + public required IReadOnlyList Filters { get; init; } +} + +/// A parameter the user filled in, by its label, with the value as text. +public sealed record ReportAppliedFilter +{ + public required string Label { get; init; } + public required string Value { get; init; } +} + +/// One choice for a choice parameter. +public sealed record ReportChoice +{ + public required string Value { get; init; } + public required string Label { get; init; } +} diff --git a/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs b/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs new file mode 100644 index 000000000..c96238426 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs @@ -0,0 +1,58 @@ +namespace Viper.Areas.ReportBuilder.Models; + +/// A view or procedure in the [report] schema that a report can read. +public sealed record ReportSourceSummary +{ + public required string Name { get; init; } + public required ReportSourceKind Kind { get; init; } + + /// The object's MS_Description extended property, when it has one. + public string? Description { get; init; } +} + +/// A source with the columns it returns and, for procedures, the parameters it takes. +public sealed record ReportSourceDetail +{ + public required string Name { get; init; } + public required ReportSourceKind Kind { get; init; } + public string? Description { get; init; } + public required IReadOnlyList Columns { get; init; } + public required IReadOnlyList Parameters { get; init; } + + /// + /// Why SQL Server couldn't describe a procedure's result columns (for example, it builds its + /// result from a temp table). Null when the columns are known. + /// + public string? ColumnsError { get; init; } + + /// + /// Whether the procedure takes @Skip and @Take, so the builder can page it in SQL like a view. + /// Always true for views. + /// + public required bool PagesInSql { get; init; } +} + +/// One column a source returns. +public sealed record ReportSourceColumn +{ + public required string Name { get; init; } + public required string SqlType { get; init; } + public required ReportValueKind Kind { get; init; } + public required bool IsNullable { get; init; } + + /// False for binary and unknown types, which a report can't show. + public required bool IsSupported { get; init; } +} + +/// One parameter a procedure takes. +public sealed record ReportSourceParameter +{ + /// The name without the leading @. + public required string Name { get; init; } + + public required string SqlType { get; init; } + public required ReportValueKind Kind { get; init; } + + /// False for output parameters and types a report can't supply. + public required bool IsSupported { get; init; } +} diff --git a/web/Areas/ReportBuilder/Models/ReportViewerDtos.cs b/web/Areas/ReportBuilder/Models/ReportViewerDtos.cs new file mode 100644 index 000000000..c15ac1364 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportViewerDtos.cs @@ -0,0 +1,81 @@ +namespace Viper.Areas.ReportBuilder.Models; + +/// A report the user may view, for the list of reports. +public sealed record ReportCatalogItem +{ + /// The report's URL key. + public required Guid Slug { get; init; } + + public required string Title { get; init; } + public string? Description { get; init; } + + /// Groups reports in the list, such as "Effort" or "Personnel". + public string? Area { get; init; } +} + +/// What the viewer needs to show a report's form and table before running it. +public sealed record ReportViewerDefinition +{ + public required Guid Slug { get; init; } + public required string Title { get; init; } + public string? Description { get; init; } + public string? Area { get; init; } + + /// Shown above the table when the data is confidential. + public string? SensitiveNotice { get; init; } + + /// Whether the table shows a page at a time. + public required bool Paginate { get; init; } + + public required int PageSize { get; init; } + public required bool AllowExcel { get; init; } + public required bool AllowPdf { get; init; } + + /// The column the report is sorted by until the user picks another. + public string? SortBy { get; init; } + + public required bool SortDescending { get; init; } + public required IReadOnlyList Columns { get; init; } + + /// The parameters the user fills in; ones set from the signed-in user aren't listed. + public required IReadOnlyList Parameters { get; init; } +} + +/// One field of a report's form. +public sealed record ReportViewerParameter +{ + /// The key to send the value under when running the report. + public required string Name { get; init; } + + public required string Label { get; init; } + public required ReportParameterType Type { get; init; } + public required bool Required { get; init; } + public string? DefaultValue { get; init; } + + /// The choices, for choice parameters; null for the others. + public IReadOnlyList? Choices { get; init; } +} + +/// A report's viewer definition, or why there is none. +public sealed record ReportDefinitionOutcome +{ + public required ReportRunStatus Status { get; init; } + public ReportViewerDefinition? Definition { get; init; } + public IReadOnlyList Errors { get; init; } = []; +} + +/// A download, ready to send. +public sealed record ReportFile +{ + public required byte[] Content { get; init; } + public required string ContentType { get; init; } + public required string FileName { get; init; } +} + +/// A download, or why there is none. An Ok outcome without a file means the report had no rows. +public sealed record ReportExportOutcome +{ + public required ReportRunStatus Status { get; init; } + public ReportFile? File { get; init; } + public IReadOnlyList Errors { get; init; } = []; +} diff --git a/web/Areas/ReportBuilder/ReportBuilderDbContext.cs b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs new file mode 100644 index 000000000..9194796f3 --- /dev/null +++ b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs @@ -0,0 +1,151 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.Areas.ReportBuilder; + +/// +/// The Report Builder's tables in the VIPER database's [report] schema. The same schema holds +/// the views and procedures reports read; those are never mapped here, only listed by the +/// source catalog, which looks at views and procedures and so never offers these tables. +/// +public class ReportBuilderDbContext : DbContext +{ + internal const string Schema = "report"; + + private const int TextLength = 500; + private const int CodeLength = 50; + private const int UserLength = 50; + private const int PermissionLength = 100; + private const string DateTimeType = "datetime"; + + public ReportBuilderDbContext(DbContextOptions options) : base(options) + { + } + + public virtual DbSet Reports { get; set; } + public virtual DbSet ReportPermissions { get; set; } + public virtual DbSet ReportColumns { get; set; } + public virtual DbSet ReportParameters { get; set; } + public virtual DbSet ReportHistory { get; set; } + public virtual DbSet ReportRunLog { get; set; } + + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + // Every text column in [report] is varchar; matching that keeps SQL Server from + // converting the column on every comparison. + configurationBuilder.Properties().AreUnicode(false); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.ToTable("report", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).HasColumnName("id"); + entity.Property(e => e.Slug).HasColumnName("slug").HasDefaultValueSql("newid()"); + entity.HasIndex(e => e.Slug).IsUnique(); + entity.Property(e => e.Title).HasColumnName("title").HasMaxLength(TextLength); + entity.Property(e => e.Description).HasColumnName("description"); + entity.Property(e => e.Area).HasColumnName("area").HasMaxLength(TextLength); + entity.Property(e => e.Source).HasColumnName("source").HasMaxLength(TextLength); + entity.Property(e => e.Paginate).HasColumnName("paginate"); + entity.Property(e => e.PageSize).HasColumnName("pageSize"); + entity.Property(e => e.AllowExcel).HasColumnName("excel"); + entity.Property(e => e.AllowPdf).HasColumnName("pdf"); + entity.Property(e => e.PdfLandscape).HasColumnName("pdfLandscape"); + entity.Property(e => e.SensitiveNotice).HasColumnName("sensitive").HasMaxLength(TextLength); + entity.Property(e => e.OrderBy).HasColumnName("orderBy").HasMaxLength(TextLength); + entity.Property(e => e.OrderByDescending).HasColumnName("orderByDesc"); + Timestamp(entity.Property(e => e.CreatedOn), "created").HasDefaultValueSql("getdate()"); + entity.Property(e => e.CreatedBy).HasColumnName("createdBy").HasMaxLength(UserLength); + Timestamp(entity.Property(e => e.ModifiedOn), "modified") + .HasDefaultValueSql("getdate()") + .IsConcurrencyToken(); + entity.Property(e => e.ModifiedBy).HasColumnName("modifiedBy").HasMaxLength(UserLength); + Timestamp(entity.Property(e => e.DeletedOn), "deleted"); + entity.Property(e => e.DeletedBy).HasColumnName("deletedBy").HasMaxLength(UserLength); + entity.HasMany(e => e.Permissions).WithOne(e => e.Report).HasForeignKey(e => e.ReportId); + entity.HasMany(e => e.Columns).WithOne(e => e.Report).HasForeignKey(e => e.ReportId); + entity.HasMany(e => e.Parameters).WithOne(e => e.Report).HasForeignKey(e => e.ReportId); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("report_permission", Schema); + entity.HasKey(e => new { e.ReportId, e.Permission }); + entity.Property(e => e.ReportId).HasColumnName("reportId"); + entity.Property(e => e.Permission).HasColumnName("permission").HasMaxLength(PermissionLength); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("report_column", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).HasColumnName("id"); + entity.Property(e => e.ReportId).HasColumnName("reportId"); + entity.Property(e => e.SourceColumn).HasColumnName("column").HasMaxLength(TextLength); + entity.Property(e => e.Label).HasColumnName("label").HasMaxLength(TextLength); + entity.Property(e => e.Format).HasColumnName("datatype").HasConversion().HasMaxLength(CodeLength); + entity.Property(e => e.Sortable).HasColumnName("sortable"); + entity.Property(e => e.Visible).HasColumnName("visible"); + entity.Property(e => e.DisplayOrder).HasColumnName("displayOrder"); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("report_parameter", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).HasColumnName("id"); + entity.Property(e => e.ReportId).HasColumnName("reportId"); + entity.Property(e => e.Name).HasColumnName("name").HasMaxLength(TextLength); + entity.Property(e => e.Label).HasColumnName("label").HasMaxLength(TextLength); + entity.Property(e => e.DisplayOrder).HasColumnName("displayOrder"); + entity.Property(e => e.Type).HasColumnName("type").HasConversion().HasMaxLength(CodeLength); + entity.Property(e => e.Operator).HasColumnName("operator").HasConversion().HasMaxLength(CodeLength); + entity.Property(e => e.Required).HasColumnName("required"); + entity.Property(e => e.DefaultValue).HasColumnName("defaultValue").HasMaxLength(TextLength); + entity.Property(e => e.ChoicesSource).HasColumnName("choicesSource").HasMaxLength(TextLength); + entity.Property(e => e.ChoicesList).HasColumnName("choicesList"); + entity.Property(e => e.Binding).HasColumnName("binding").HasConversion().HasMaxLength(TextLength); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("report_history", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).HasColumnName("id"); + entity.Property(e => e.ReportId).HasColumnName("reportId"); + entity.Property(e => e.Action).HasColumnName("action").HasConversion().HasMaxLength(TextLength); + entity.Property(e => e.Snapshot).HasColumnName("snapshot"); + Timestamp(entity.Property(e => e.ChangedOn), "changed").HasDefaultValueSql("getdate()"); + entity.Property(e => e.ChangedBy).HasColumnName("changedBy").HasMaxLength(UserLength); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("report_runLog", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).HasColumnName("id"); + entity.Property(e => e.ReportId).HasColumnName("reportId"); + entity.Property(e => e.Action).HasColumnName("action").HasConversion().HasMaxLength(TextLength); + entity.Property(e => e.LoginId).HasColumnName("loginID").HasMaxLength(UserLength); + Timestamp(entity.Property(e => e.RanOn), "ran").HasDefaultValueSql("getdate()"); + entity.Property(e => e.Parameters).HasColumnName("parameters"); + entity.Property(e => e.RowsReturned).HasColumnName("rowsReturned"); + entity.Property(e => e.DurationMs).HasColumnName("duration"); + entity.Property(e => e.ErrorNumber).HasColumnName("errorNumber"); + entity.Property(e => e.ErrorMessage).HasColumnName("errorMessage").HasMaxLength(ReportLimits.MaxErrorLength); + }); + } + + /// The [report] tables store times as datetime, not EF's default datetime2. + private static PropertyBuilder Timestamp(PropertyBuilder property, string column) + { + return property.HasColumnName(column).HasColumnType(DateTimeType); + } +} diff --git a/web/Areas/ReportBuilder/ReportBuilderPermissions.cs b/web/Areas/ReportBuilder/ReportBuilderPermissions.cs new file mode 100644 index 000000000..989e80b6b --- /dev/null +++ b/web/Areas/ReportBuilder/ReportBuilderPermissions.cs @@ -0,0 +1,11 @@ +namespace Viper.Areas.ReportBuilder; + +/// +/// RAPS permissions for the Report Builder itself. Who may view each report is stored with the +/// report, as one or more ordinary RAPS permission names. +/// +public static class ReportBuilderPermissions +{ + /// Create, edit and delete report definitions. + public const string Admin = "SVMSecure.Reports.Admin"; +} diff --git a/web/Areas/ReportBuilder/Services/ReportAccess.cs b/web/Areas/ReportBuilder/Services/ReportAccess.cs new file mode 100644 index 000000000..6fac8b048 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportAccess.cs @@ -0,0 +1,79 @@ +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// +/// The rules every viewer endpoint shares: how a report is found by its slug, who may view it, +/// and the settings that fall back to defaults when the admin left them empty. +/// +public static class ReportAccess +{ + /// The report with this slug, with its permissions, columns and parameters; null if there's none or it's deleted. + public static async Task FindAsync(ReportBuilderDbContext context, string slug, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(context); + if (!Guid.TryParse(slug, out Guid id)) + { + return null; + } + + return await context.Reports + .AsNoTracking() + .Include(r => r.Permissions) + .Include(r => r.Columns) + .Include(r => r.Parameters) + .AsSplitQuery() + .FirstOrDefaultAsync(r => r.Slug == id && r.DeletedOn == null, ct); + } + + /// Admins see every report; others need one of its permissions. A report with none is admin-only. + public static bool CanView(IReportUserService users, ReportDefinition report) + { + ArgumentNullException.ThrowIfNull(users); + ArgumentNullException.ThrowIfNull(report); + return users.HasPermission(ReportBuilderPermissions.Admin) + || report.Permissions.Any(p => !string.IsNullOrWhiteSpace(p.Permission) && users.HasPermission(p.Permission)); + } + + /// The columns the report shows, in order, named by their source column. + public static IReadOnlyList VisibleColumns(ReportDefinition report) + { + ArgumentNullException.ThrowIfNull(report); + return [.. report.Columns + .Where(c => c.Visible && !string.IsNullOrWhiteSpace(c.SourceColumn)) + .OrderBy(c => c.DisplayOrder) + .ThenBy(c => c.Id) + .Select(c => new ReportResultColumn + { + Name = c.SourceColumn!.Trim(), + Label = string.IsNullOrWhiteSpace(c.Label) ? c.SourceColumn.Trim() : c.Label, + Format = c.Format ?? ReportColumnFormat.Text, + Sortable = c.Sortable, + })]; + } + + /// The parameters the user fills in, in order; current-user parameters are left out. + public static IReadOnlyList UserParameters(ReportDefinition report) + { + ArgumentNullException.ThrowIfNull(report); + return [.. report.Parameters + .Where(p => !string.IsNullOrWhiteSpace(p.Name) && p.Binding is null or ReportParameterBinding.UserInput) + .OrderBy(p => p.DisplayOrder)]; + } + + /// Whether the report is shown a page at a time; on unless the admin turned it off. + public static bool Paginates(ReportDefinition report) + { + ArgumentNullException.ThrowIfNull(report); + return report.Paginate != false; + } + + /// The report's page size, or the default, kept within the allowed range. + public static int PageSize(ReportDefinition report) + { + ArgumentNullException.ThrowIfNull(report); + return Math.Clamp(report.PageSize ?? ReportLimits.DefaultPageSize, 1, ReportLimits.MaxPageSize); + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportAdminService.cs b/web/Areas/ReportBuilder/Services/ReportAdminService.cs new file mode 100644 index 000000000..7f2481dff --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportAdminService.cs @@ -0,0 +1,461 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// Creates, edits, deletes, restores and previews reports, keeping a copy of every version. +public interface IReportAdminService +{ + /// Every report, by area and title; deleted ones only when asked. + Task> ListAsync(bool includeDeleted, CancellationToken ct); + + /// A report for the edit form, deleted or not; null when there's none. + Task GetAsync(int id, CancellationToken ct); + + Task> CreateAsync(ReportEditRequest request, CancellationToken ct); + + /// Saves the form, unless someone else saved the report after the editor loaded it. + Task> UpdateAsync(int id, ReportEditRequest request, CancellationToken ct); + + /// Hides the report from viewers; it can be restored. + Task> DeleteAsync(int id, CancellationToken ct); + + Task> RestoreAsync(int id, CancellationToken ct); + + /// The report's saved versions, newest first; null when there's no such report. + Task?> GetHistoryAsync(int id, CancellationToken ct); + + /// One saved version with the report as it was; null when there's none. + Task GetHistoryVersionAsync(int id, int historyId, CancellationToken ct); + + /// Checks an unsaved report and shows a page of it. + Task PreviewAsync(ReportPreviewRequest request, CancellationToken ct); +} + +public sealed class ReportAdminService : IReportAdminService +{ + private static readonly JsonSerializerOptions SnapshotJson = new(JsonSerializerDefaults.Web); + + private readonly ReportBuilderDbContext _context; + private readonly IReportDefinitionValidator _validator; + private readonly IReportPermissionLookupService _permissions; + private readonly IReportUserService _users; + private readonly IReportRunService _runs; + private readonly TimeProvider _clock; + + public ReportAdminService( + ReportBuilderDbContext context, + IReportDefinitionValidator validator, + IReportPermissionLookupService permissions, + IReportUserService users, + IReportRunService runs, + TimeProvider? clock = null) + { + _context = context; + _validator = validator; + _permissions = permissions; + _users = users; + _runs = runs; + _clock = clock ?? TimeProvider.System; + } + + public async Task> ListAsync(bool includeDeleted, CancellationToken ct) + { + List reports = await _context.Reports + .AsNoTracking() + .Include(r => r.Permissions) + .Where(r => includeDeleted || r.DeletedOn == null) + .OrderBy(r => r.Area) + .ThenBy(r => r.Title) + .ToListAsync(ct); + IReadOnlyDictionary existing = await _permissions.FindAsync( + reports.SelectMany(r => r.Permissions).Select(p => p.Permission), ct); + + return [.. reports.Select(report => + { + IReadOnlyList names = PermissionNames(report); + return ReportBuilderMapper.ToAdminListItem(report) with + { + Permissions = names, + MissingPermissions = [.. names.Where(name => !existing.ContainsKey(name))], + }; + })]; + } + + public async Task GetAsync(int id, CancellationToken ct) + { + ReportDefinition? report = await Load(id).AsNoTracking().FirstOrDefaultAsync(ct); + return report is null ? null : await ToAdminDefinitionAsync(report, ct); + } + + public async Task> CreateAsync(ReportEditRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + ReportValidation validation = await _validator.ValidateAsync(request, ct); + if (validation.Errors.Count > 0) + { + return ReportAdminOutcome.Fail(ReportAdminStatus.Invalid, [.. validation.Errors]); + } + + (DateTime now, string? who) = Stamp(); + var report = new ReportDefinition + { + Slug = Guid.NewGuid(), + CreatedOn = now, + CreatedBy = who, + ModifiedOn = now, + ModifiedBy = who, + }; + Apply(report, request, validation); + report.Permissions = [.. validation.Permissions.Select(name => new ReportPermission { Permission = name })]; + _context.Reports.Add(report); + + await using var transaction = await _context.Database.BeginTransactionAsync(ct); + await _context.SaveChangesAsync(ct); + await AddHistoryAsync(report, ReportHistoryAction.Created, now, who, ct); + await transaction.CommitAsync(ct); + + return ReportAdminOutcome.Ok((await GetAsync(report.Id, ct))!); + } + + public async Task> UpdateAsync(int id, ReportEditRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + ReportDefinition? report = await Load(id).FirstOrDefaultAsync(ct); + if (report is null) + { + return ReportAdminOutcome.Fail(ReportAdminStatus.NotFound); + } + + if (report.DeletedOn is not null) + { + return ReportAdminOutcome.Fail(ReportAdminStatus.Invalid, "Restore the report before editing it."); + } + + if (request.LastModifiedOn != report.ModifiedOn) + { + return ReportAdminOutcome.Fail( + ReportAdminStatus.Conflict, + "Someone else saved this report after you opened it. Reload it to see their changes, then make yours again."); + } + + ReportValidation validation = await _validator.ValidateAsync(request, ct); + if (validation.Errors.Count > 0) + { + return ReportAdminOutcome.Fail(ReportAdminStatus.Invalid, [.. validation.Errors]); + } + + _context.ReportColumns.RemoveRange(report.Columns); + _context.ReportParameters.RemoveRange(report.Parameters); + Apply(report, request, validation); + ReplacePermissions(report, validation.Permissions); + (DateTime now, string? who) = Stamp(); + report.ModifiedOn = now; + report.ModifiedBy = who; + + await using var transaction = await _context.Database.BeginTransactionAsync(ct); + try + { + await _context.SaveChangesAsync(ct); + } + catch (DbUpdateConcurrencyException) + { + // The in-memory check above already catches the common case; this closes the gap + // between that check and the write itself. + return ReportAdminOutcome.Fail( + ReportAdminStatus.Conflict, + "Someone else saved this report after you opened it. Reload it to see their changes, then make yours again."); + } + + await AddHistoryAsync(report, ReportHistoryAction.Updated, now, who, ct); + await transaction.CommitAsync(ct); + return ReportAdminOutcome.Ok((await GetAsync(id, ct))!); + } + + public async Task> DeleteAsync(int id, CancellationToken ct) + { + return await SetDeletedAsync(id, deleted: true, ct); + } + + public async Task> RestoreAsync(int id, CancellationToken ct) + { + return await SetDeletedAsync(id, deleted: false, ct); + } + + public async Task?> GetHistoryAsync(int id, CancellationToken ct) + { + if (!await _context.Reports.AnyAsync(r => r.Id == id, ct)) + { + return null; + } + + List versions = await _context.ReportHistory + .AsNoTracking() + .Where(h => h.ReportId == id) + .OrderByDescending(h => h.ChangedOn) + .ThenByDescending(h => h.Id) + .ToListAsync(ct); + return [.. versions.Select(ReportBuilderMapper.ToHistoryItem)]; + } + + public async Task GetHistoryVersionAsync(int id, int historyId, CancellationToken ct) + { + ReportDefinitionHistory? version = await _context.ReportHistory + .AsNoTracking() + .FirstOrDefaultAsync(h => h.Id == historyId && h.ReportId == id, ct); + if (version is null) + { + return null; + } + + return new ReportHistoryVersion { Version = ReportBuilderMapper.ToHistoryItem(version), Report = ReadSnapshot(version.Snapshot) }; + } + + public async Task PreviewAsync(ReportPreviewRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + ReportValidation validation = await _validator.ValidateAsync(request.Report, ct); + if (validation.Errors.Count > 0) + { + return ReportRunOutcome.Fail(ReportRunStatus.Invalid, [.. validation.Errors]); + } + + var report = new ReportDefinition(); + Apply(report, request.Report, validation); + return await _runs.PreviewAsync(report, request.Run, ct); + } + + private IQueryable Load(int id) + { + return _context.Reports + .Include(r => r.Permissions) + .Include(r => r.Columns) + .Include(r => r.Parameters) + .Where(r => r.Id == id); + } + + private async Task> SetDeletedAsync(int id, bool deleted, CancellationToken ct) + { + ReportDefinition? report = await _context.Reports.FirstOrDefaultAsync(r => r.Id == id, ct); + if (report is null) + { + return ReportAdminOutcome.Fail(ReportAdminStatus.NotFound); + } + + // Deleting a deleted report, or restoring a live one, changes nothing and records nothing. + if ((report.DeletedOn is not null) != deleted) + { + (DateTime now, string? who) = Stamp(); + report.DeletedOn = deleted ? now : null; + report.DeletedBy = deleted ? who : null; + report.ModifiedOn = now; + report.ModifiedBy = who; + + await using var transaction = await _context.Database.BeginTransactionAsync(ct); + try + { + await _context.SaveChangesAsync(ct); + } + catch (DbUpdateConcurrencyException) + { + return ReportAdminOutcome.Fail( + ReportAdminStatus.Conflict, + "Someone else changed this report just now. Reload it and try again."); + } + + await AddHistoryAsync(report, deleted ? ReportHistoryAction.Deleted : ReportHistoryAction.Restored, now, who, ct); + await transaction.CommitAsync(ct); + } + + return ReportAdminOutcome.Ok((await GetAsync(id, ct))!); + } + + private (DateTime Now, string? Who) Stamp() + { + return (_clock.GetLocalNow().DateTime, _users.GetCurrentUser()?.LoginId); + } + + /// Records the report as it now is; the snapshot is read back from the database. + private async Task AddHistoryAsync(ReportDefinition report, ReportHistoryAction action, DateTime now, string? who, CancellationToken ct) + { + ReportDefinition saved = (await Load(report.Id).AsNoTracking().FirstOrDefaultAsync(ct))!; + _context.ReportHistory.Add(new ReportDefinitionHistory + { + ReportId = report.Id, + Action = action, + Snapshot = JsonSerializer.Serialize(ToEditRequest(saved), SnapshotJson), + ChangedOn = now, + ChangedBy = who, + }); + await _context.SaveChangesAsync(ct); + } + + private static ReportEditRequest? ReadSnapshot(string? snapshot) + { + if (string.IsNullOrWhiteSpace(snapshot)) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(snapshot, SnapshotJson); + } + catch (JsonException) + { + return null; + } + } + + /// Keeps the permissions still wanted, removes the rest and adds the new ones. + private void ReplacePermissions(ReportDefinition report, IReadOnlyList names) + { + var wanted = new HashSet(names, StringComparer.OrdinalIgnoreCase); + List removed = [.. report.Permissions.Where(p => !wanted.Contains(p.Permission))]; + _context.ReportPermissions.RemoveRange(removed); + foreach (ReportPermission permission in removed) + { + report.Permissions.Remove(permission); + } + + var kept = new HashSet(report.Permissions.Select(p => p.Permission), StringComparer.OrdinalIgnoreCase); + foreach (string name in names.Where(name => !kept.Contains(name))) + { + report.Permissions.Add(new ReportPermission { ReportId = report.Id, Permission = name }); + } + } + + /// + /// Copies the form onto the entity, with names as the catalog spells them and settings that + /// don't apply (an operator for a procedure, choices for a text field) left empty. + /// + private static void Apply(ReportDefinition report, ReportEditRequest request, ReportValidation validation) + { + ReportSourceDetail source = validation.Source!; + bool isView = source.Kind == ReportSourceKind.View; + report.Title = request.Title.Trim(); + report.Description = Clean(request.Description); + report.Area = Clean(request.Area); + report.Source = source.Name; + report.Paginate = request.Paginate; + report.PageSize = request.PageSize; + report.AllowExcel = request.AllowExcel; + report.AllowPdf = request.AllowPdf; + report.PdfLandscape = request.PdfLandscape; + report.SensitiveNotice = Clean(request.SensitiveNotice); + report.OrderBy = string.IsNullOrWhiteSpace(request.OrderBy) ? null : SourceName(request.OrderBy, validation); + report.OrderByDescending = request.OrderByDescending; + report.Columns = [.. request.Columns.Select((column, index) => new ReportColumn + { + ReportId = report.Id, + SourceColumn = SourceName(column.SourceColumn, validation), + Label = Clean(column.Label), + Format = column.Format, + Sortable = column.Sortable, + Visible = column.Visible, + DisplayOrder = index + 1, + })]; + report.Parameters = [.. request.Parameters.Select((parameter, index) => ToEntity(report.Id, parameter, index + 1, isView, validation))]; + } + + private static ReportParameter ToEntity(int reportId, ReportParameterEdit parameter, int order, bool isView, ReportValidation validation) + { + bool fromUser = parameter.Binding == ReportParameterBinding.UserInput; + bool isChoice = fromUser && ReportDefinitionValidator.IsChoice(parameter.Type); + bool hasList = isChoice && parameter.ChoicesList is { Count: > 0 }; + return new ReportParameter + { + ReportId = reportId, + Name = SourceName(parameter.Name, validation), + Label = Clean(parameter.Label), + DisplayOrder = order, + Type = fromUser ? parameter.Type : ReportParameterType.Text, + Operator = isView ? parameter.Operator ?? ReportFilterOperator.Equals : null, + Required = fromUser && parameter.Required, + DefaultValue = fromUser ? Clean(parameter.DefaultValue) : null, + ChoicesSource = isChoice && !hasList ? Clean(parameter.ChoicesSource) : null, + ChoicesList = hasList + ? JsonSerializer.Serialize(parameter.ChoicesList!.Select(c => new ReportChoice { Value = c.Value.Trim(), Label = Clean(c.Label) ?? c.Value.Trim() }), SnapshotJson) + : null, + Binding = parameter.Binding, + }; + } + + private async Task ToAdminDefinitionAsync(ReportDefinition report, CancellationToken ct) + { + IReadOnlyList names = PermissionNames(report); + IReadOnlyDictionary existing = await _permissions.FindAsync(names, ct); + return new ReportAdminDefinition + { + Id = report.Id, + Slug = report.Slug, + Report = ToEditRequest(report) with { LastModifiedOn = report.ModifiedOn }, + CreatedOn = report.CreatedOn, + CreatedBy = report.CreatedBy, + ModifiedOn = report.ModifiedOn, + ModifiedBy = report.ModifiedBy, + DeletedOn = report.DeletedOn, + DeletedBy = report.DeletedBy, + MissingPermissions = [.. names.Where(name => !existing.ContainsKey(name))], + }; + } + + /// The report as the form edits it, with the defaults the runner applies to empty settings. + internal static ReportEditRequest ToEditRequest(ReportDefinition report) + { + return new ReportEditRequest + { + Title = report.Title, + Description = report.Description, + Area = report.Area, + Source = report.Source, + Paginate = ReportAccess.Paginates(report), + PageSize = report.PageSize, + AllowExcel = report.AllowExcel, + AllowPdf = report.AllowPdf, + PdfLandscape = report.PdfLandscape == true, + SensitiveNotice = report.SensitiveNotice, + OrderBy = report.OrderBy, + OrderByDescending = report.OrderByDescending == true, + Permissions = PermissionNames(report), + Columns = [.. report.Columns.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Id).Select(c => new ReportColumnEdit + { + SourceColumn = c.SourceColumn ?? string.Empty, + Label = c.Label, + Format = c.Format ?? ReportColumnFormat.Text, + Sortable = c.Sortable, + Visible = c.Visible, + })], + Parameters = [.. report.Parameters.OrderBy(p => p.DisplayOrder ?? int.MaxValue).ThenBy(p => p.Id).Select(p => new ReportParameterEdit + { + Name = p.Name ?? string.Empty, + Label = p.Label, + Type = p.Type ?? ReportParameterType.Text, + Operator = p.Operator, + Required = p.Required == true, + DefaultValue = p.DefaultValue, + ChoicesSource = p.ChoicesSource, + ChoicesList = ReportChoiceList.Parse(p.ChoicesList), + Binding = p.Binding ?? ReportParameterBinding.UserInput, + })], + }; + } + + private static IReadOnlyList PermissionNames(ReportDefinition report) + { + return [.. report.Permissions.Select(p => p.Permission).Order(StringComparer.OrdinalIgnoreCase)]; + } + + private static string SourceName(string name, ReportValidation validation) + { + string trimmed = name.Trim(); + return validation.SourceNames.GetValueOrDefault(trimmed, trimmed); + } + + private static string? Clean(string? text) + { + return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportCellFormatter.cs b/web/Areas/ReportBuilder/Services/ReportCellFormatter.cs new file mode 100644 index 000000000..341f011a0 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportCellFormatter.cs @@ -0,0 +1,135 @@ +using System.Globalization; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.Areas.ReportBuilder.Services; + +/// +/// Turns a report value into text for formats without cell types (PDF, filter headings), and +/// tells the Excel export which values are numbers and dates. US English separators; dates as +/// MM/dd/yyyy like the rest of VIPER. Percent columns hold fractions (0.25 shows as 25%). +/// +public static class ReportCellFormatter +{ + public const string DateFormat = "MM/dd/yyyy"; + public const string DateTimeFormat = "MM/dd/yyyy h:mm tt"; + private const string TimeFormat = "h:mm tt"; + private const string Yes = "Yes"; + private const string No = "No"; + + private static readonly CultureInfo UsEnglish = CultureInfo.GetCultureInfo("en-US"); + private static readonly HashSet YesWords = new(StringComparer.OrdinalIgnoreCase) { "Y", "Yes", "True", "1" }; + private static readonly HashSet NoWords = new(StringComparer.OrdinalIgnoreCase) { "N", "No", "False", "0" }; + + public static string Text(object? value, ReportColumnFormat format) + { + if (value is null) + { + return string.Empty; + } + + if (format == ReportColumnFormat.YesNo) + { + return YesNo(value); + } + + if (TryGetDateTime(value, out DateTime dateTime)) + { + return dateTime.ToString(ShowsTime(format, dateTime) ? DateTimeFormat : DateFormat, CultureInfo.InvariantCulture); + } + + if (TryGetNumber(value, out decimal number)) + { + return FormatNumber(number, format); + } + + return value switch + { + bool flag => flag ? Yes : No, + TimeSpan time => DateTime.MinValue.Add(time).ToString(TimeFormat, CultureInfo.InvariantCulture), + _ => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty, + }; + } + + /// Whether the format lines its values up on the right. + public static bool IsNumeric(ReportColumnFormat format) + { + return format is ReportColumnFormat.Number or ReportColumnFormat.Currency or ReportColumnFormat.Percent; + } + + /// Whether a date shows its time: always for DateTime columns, and for text columns when it has one. + public static bool ShowsTime(ReportColumnFormat format, DateTime value) + { + return format == ReportColumnFormat.DateTime || (format != ReportColumnFormat.Date && value.TimeOfDay != TimeSpan.Zero); + } + + public static bool TryGetNumber(object? value, out decimal number) + { + switch (value) + { + case decimal exact: + number = exact; + return true; + case int or long or short or byte: + number = Convert.ToDecimal(value, CultureInfo.InvariantCulture); + return true; + case double or float: + double approximate = Convert.ToDouble(value, CultureInfo.InvariantCulture); + bool fits = double.IsFinite(approximate) && Math.Abs(approximate) < (double)decimal.MaxValue; + number = fits ? (decimal)approximate : 0; + return fits; + default: + number = 0; + return false; + } + } + + public static bool TryGetDateTime(object? value, out DateTime dateTime) + { + switch (value) + { + case DateTime exact: + dateTime = exact; + return true; + case DateTimeOffset offset: + dateTime = offset.DateTime; + return true; + case DateOnly date: + dateTime = date.ToDateTime(TimeOnly.MinValue); + return true; + default: + dateTime = default; + return false; + } + } + + private static string FormatNumber(decimal number, ReportColumnFormat format) + { + return format switch + { + ReportColumnFormat.Currency => number.ToString("C2", UsEnglish), + ReportColumnFormat.Percent => number.ToString("#,##0.##%", UsEnglish), + _ => number.ToString("#,##0.##", UsEnglish), + }; + } + + private static string YesNo(object value) + { + if (value is bool flag) + { + return flag ? Yes : No; + } + + if (TryGetNumber(value, out decimal number)) + { + return number != 0 ? Yes : No; + } + + string text = Convert.ToString(value, CultureInfo.InvariantCulture)?.Trim() ?? string.Empty; + if (YesWords.Contains(text)) + { + return Yes; + } + + return NoWords.Contains(text) ? No : text; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportChoiceList.cs b/web/Areas/ReportBuilder/Services/ReportChoiceList.cs new file mode 100644 index 000000000..2479a7ee5 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportChoiceList.cs @@ -0,0 +1,77 @@ +using System.Text.Json; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.Areas.ReportBuilder.Services; + +/// Reads a parameter's fixed choice list (choicesList), stored as JSON. +public static class ReportChoiceList +{ + /// + /// The choices in a JSON array whose items are strings (value and label alike) or objects + /// with value and label. Null when the JSON isn't such an array. + /// + public static IReadOnlyList? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return null; + } + + try + { + using JsonDocument document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Array) + { + return null; + } + + var choices = new List(); + foreach (JsonElement item in document.RootElement.EnumerateArray()) + { + ReportChoice? choice = ToChoice(item); + if (choice is null) + { + return null; + } + + choices.Add(choice); + } + + return choices; + } + catch (JsonException) + { + return null; + } + } + + private static ReportChoice? ToChoice(JsonElement item) + { + if (item.ValueKind == JsonValueKind.String && item.GetString() is { Length: > 0 } text) + { + return new ReportChoice { Value = text, Label = text }; + } + + if (item.ValueKind != JsonValueKind.Object) + { + return null; + } + + string? value = Text(item, "value"); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + string? label = Text(item, "label"); + return new ReportChoice { Value = value, Label = string.IsNullOrWhiteSpace(label) ? value : label }; + } + + private static string? Text(JsonElement item, string name) + { + return item.EnumerateObject() + .Where(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) + .Select(p => p.Value.ValueKind == JsonValueKind.String ? p.Value.GetString() : p.Value.ToString()) + .FirstOrDefault(); + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportChoiceService.cs b/web/Areas/ReportBuilder/Services/ReportChoiceService.cs new file mode 100644 index 000000000..ef0bc3dc3 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportChoiceService.cs @@ -0,0 +1,98 @@ +using System.Globalization; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// The choices offered by a report's choice parameters. +public interface IReportChoiceService +{ + /// + /// Each choice parameter's choices, by parameter name (ignoring case). A parameter whose + /// list can't be read has no entry, so the binder refuses any value for it. + /// + Task>> GetChoicesAsync( + IEnumerable parameters, CancellationToken ct); +} + +/// +/// Reads choices from the parameter's fixed list (choicesList, JSON) or, when it has +/// none, from a [report] view (choicesSource) with Value and Label columns. +/// +public sealed class ReportChoiceService : IReportChoiceService +{ + private readonly IReportSourceCatalogService _catalog; + private readonly IReportQueryExecutor _executor; + + public ReportChoiceService(IReportSourceCatalogService catalog, IReportQueryExecutor executor) + { + _catalog = catalog; + _executor = executor; + } + + public async Task>> GetChoicesAsync( + IEnumerable parameters, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(parameters); + var choices = new Dictionary>(StringComparer.OrdinalIgnoreCase); + IReadOnlyList? sources = null; + + foreach (ReportParameter parameter in parameters.Where(IsChoice)) + { + IReadOnlyList? list = ReportChoiceList.Parse(parameter.ChoicesList); + if (list is null && !string.IsNullOrWhiteSpace(parameter.ChoicesSource)) + { + sources ??= await _catalog.GetSourcesAsync(ct); + list = await FromViewAsync(sources, parameter.ChoicesSource.Trim(), ct); + } + + if (list is not null) + { + choices[parameter.Name!] = [.. list.Take(ReportLimits.MaxChoices)]; + } + } + + return choices; + } + + private static bool IsChoice(ReportParameter parameter) + { + return parameter.Type is ReportParameterType.Choice or ReportParameterType.MultiChoice + && !string.IsNullOrWhiteSpace(parameter.Name); + } + + private async Task?> FromViewAsync( + IReadOnlyList sources, string name, CancellationToken ct) + { + // Only a view the catalog lists, so a choice list can't read anything outside [report]. + ReportSourceSummary? view = sources.FirstOrDefault(source => + source.Kind == ReportSourceKind.View && string.Equals(source.Name, name, StringComparison.OrdinalIgnoreCase)); + if (view is null) + { + return null; + } + + ReportQueryResult result = await _executor.QueryAsync( + ReportSqlBuilder.BuildChoices(view.Name), ReportLimits.MaxChoices, ReportLimits.ScreenTimeout, ct); + return [.. result.Rows.Select(ToChoice).OfType()]; + } + + private static ReportChoice? ToChoice(IReadOnlyDictionary row) + { + string? value = Text(row, "Value"); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + string? label = Text(row, "Label"); + return new ReportChoice { Value = value, Label = string.IsNullOrWhiteSpace(label) ? value : label }; + } + + private static string? Text(IReadOnlyDictionary row, string column) + { + return row.TryGetValue(column, out object? value) && value is not null + ? Convert.ToString(value, CultureInfo.InvariantCulture) + : null; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs b/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs new file mode 100644 index 000000000..8809f6334 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs @@ -0,0 +1,316 @@ +using System.Globalization; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.Areas.ReportBuilder.Services; + +/// A report's fields checked against the catalog and RAPS: what's wrong, or the names to save. +public sealed record ReportValidation +{ + public required IReadOnlyList Errors { get; init; } + + /// The source as the catalog describes it; null when it isn't in [report]. + public ReportSourceDetail? Source { get; init; } + + /// The view permissions as RAPS spells them, without repeats. + public IReadOnlyList Permissions { get; init; } = []; + + /// Each name the catalog knows, as it spells it, so saved names match the source exactly. + public IReadOnlyDictionary SourceNames { get; init; } = new Dictionary(); +} + +/// Checks a report before it's saved or previewed. +public interface IReportDefinitionValidator +{ + Task ValidateAsync(ReportEditRequest request, CancellationToken ct); +} + +/// +/// Checks a report the way the runner will use it: the source is a [report] view or procedure, +/// every column and parameter exists in it, parameters' types, operators, choices and defaults +/// fit together, and every view permission is one RAPS has. +/// +public sealed class ReportDefinitionValidator : IReportDefinitionValidator +{ + private const int TextLength = 500; + private const int PermissionLength = 100; + private const int MaxEcho = 50; + private const string DateFormat = "yyyy-MM-dd"; + + private readonly IReportSourceCatalogService _catalog; + private readonly IReportPermissionLookupService _permissions; + + public ReportDefinitionValidator(IReportSourceCatalogService catalog, IReportPermissionLookupService permissions) + { + _catalog = catalog; + _permissions = permissions; + } + + public async Task ValidateAsync(ReportEditRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + var errors = new List(); + CheckReportFields(request, errors); + + ReportSourceDetail? source = string.IsNullOrWhiteSpace(request.Source) + ? null + : await _catalog.GetSourceAsync(request.Source.Trim(), ct); + if (source is null) + { + errors.Add(string.IsNullOrWhiteSpace(request.Source) + ? "Choose a data source." + : $"'{Echo(request.Source)}' isn't a view or procedure in the [report] schema."); + } + + var names = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (source is not null) + { + foreach (string name in source.Columns.Select(c => c.Name).Concat(source.Parameters.Select(p => p.Name))) + { + names.TryAdd(name, name); + } + + CheckColumns(request, source, errors); + await CheckParametersAsync(request, source, errors, ct); + } + + IReadOnlyList permissions = await CheckPermissionsAsync(request.Permissions, errors, ct); + return new ReportValidation { Errors = errors, Source = source, Permissions = permissions, SourceNames = names }; + } + + private static void CheckReportFields(ReportEditRequest request, List errors) + { + if (string.IsNullOrWhiteSpace(request.Title)) + { + errors.Add("Enter a title."); + } + + CheckLength("The title", request.Title, errors); + CheckLength("The area", request.Area, errors); + CheckLength("The confidentiality notice", request.SensitiveNotice, errors); + CheckLength("The sort column", request.OrderBy, errors); + if (request.PageSize is < 1 or > ReportLimits.MaxPageSize) + { + errors.Add($"Rows per page must be between 1 and {ReportLimits.MaxPageSize}."); + } + } + + private static void CheckColumns(ReportEditRequest request, ReportSourceDetail source, List errors) + { + // A procedure SQL Server can't describe has no known columns; its columns are taken on trust. + bool known = source.Columns.Count > 0; + var columns = source.Columns.ToDictionary(c => c.Name, StringComparer.OrdinalIgnoreCase); + if (!request.Columns.Any(c => c.Visible && !string.IsNullOrWhiteSpace(c.SourceColumn))) + { + errors.Add("Show at least one column."); + } + + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (ReportColumnEdit column in request.Columns) + { + string name = column.SourceColumn.Trim(); + if (name.Length == 0) + { + errors.Add("Every column needs a source column."); + continue; + } + + if (!seen.Add(name)) + { + errors.Add($"The column '{Echo(name)}' is listed more than once."); + } + + if (known) + { + CheckSourceColumn(name, columns, errors); + } + + CheckLength($"The heading of '{Echo(name)}'", column.Label, errors); + } + + string? orderBy = request.OrderBy?.Trim(); + if (known && !string.IsNullOrEmpty(orderBy) && !columns.ContainsKey(orderBy)) + { + errors.Add($"The source has no column named '{Echo(orderBy)}' to sort by."); + } + } + + private static void CheckSourceColumn(string name, Dictionary columns, List errors) + { + if (!columns.TryGetValue(name, out ReportSourceColumn? column)) + { + errors.Add($"The source has no column named '{Echo(name)}'."); + } + else if (!column.IsSupported) + { + errors.Add($"The column '{Echo(name)}' holds {column.SqlType} values, which a report can't show."); + } + } + + private async Task CheckParametersAsync(ReportEditRequest request, ReportSourceDetail source, List errors, CancellationToken ct) + { + bool isView = source.Kind == ReportSourceKind.View; + bool knownColumns = source.Columns.Count > 0; + var targets = new HashSet( + isView ? source.Columns.Where(c => c.IsSupported).Select(c => c.Name) : source.Parameters.Where(p => p.IsSupported).Select(p => p.Name), + StringComparer.OrdinalIgnoreCase); + IReadOnlyList? sources = null; + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (ReportParameterEdit parameter in request.Parameters) + { + string name = parameter.Name.Trim(); + if (name.Length == 0) + { + errors.Add("Every parameter needs a name."); + continue; + } + + string label = $"The parameter '{Echo(name)}'"; + if (!seen.Add(name)) + { + errors.Add($"{label} is listed more than once."); + } + + if ((!isView || knownColumns) && !targets.Contains(name)) + { + errors.Add(isView + ? $"{label} doesn't match a column of the view." + : $"{label} doesn't match a parameter the procedure takes."); + } + + CheckLength($"{label}'s label", parameter.Label, errors); + CheckLength($"{label}'s default", parameter.DefaultValue, errors); + if (parameter.Binding != ReportParameterBinding.UserInput) + { + continue; // Filled in from the signed-in user; type, choices and default don't apply. + } + + if (isView) + { + CheckOperator(label, parameter, errors); + } + + IReadOnlyList? choices = null; + if (IsChoice(parameter.Type)) + { + sources ??= await _catalog.GetSourcesAsync(ct); + choices = CheckChoices(label, parameter, sources, errors); + } + + CheckDefault(label, parameter, choices, errors); + } + } + + private static void CheckOperator(string label, ReportParameterEdit parameter, List errors) + { + ReportFilterOperator op = parameter.Operator ?? ReportFilterOperator.Equals; + bool fits = op switch + { + ReportFilterOperator.In => parameter.Type == ReportParameterType.MultiChoice, + ReportFilterOperator.Contains => parameter.Type == ReportParameterType.Text, + ReportFilterOperator.From or ReportFilterOperator.To => parameter.Type is ReportParameterType.Number or ReportParameterType.Date, + _ => parameter.Type != ReportParameterType.MultiChoice, + }; + if (!fits) + { + errors.Add($"{label} can't use '{op}' with a {parameter.Type} value."); + } + } + + /// The fixed choices, if the parameter has them; checks that it has some way to get choices. + private static IReadOnlyList? CheckChoices( + string label, ReportParameterEdit parameter, IReadOnlyList sources, List errors) + { + if (parameter.ChoicesList is { Count: > 0 } list) + { + if (list.Any(c => string.IsNullOrWhiteSpace(c.Value))) + { + errors.Add($"{label} has a choice without a value."); + } + + if (list.Select(c => c.Value).Distinct(StringComparer.OrdinalIgnoreCase).Count() != list.Count) + { + errors.Add($"{label} has the same choice more than once."); + } + + if (list.Count > ReportLimits.MaxChoices) + { + errors.Add($"{label} can have at most {ReportLimits.MaxChoices} choices."); + } + + return list; + } + + string? view = parameter.ChoicesSource?.Trim(); + if (string.IsNullOrEmpty(view)) + { + errors.Add($"{label} needs a list of choices or a view to read them from."); + } + else if (!sources.Any(s => s.Kind == ReportSourceKind.View && string.Equals(s.Name, view, StringComparison.OrdinalIgnoreCase))) + { + errors.Add($"{label}'s choices view '{Echo(view)}' isn't a view in the [report] schema."); + } + + return null; + } + + private static void CheckDefault(string label, ReportParameterEdit parameter, IReadOnlyList? choices, List errors) + { + string? value = parameter.DefaultValue?.Trim(); + if (string.IsNullOrEmpty(value)) + { + return; + } + + bool valid = parameter.Type switch + { + ReportParameterType.Number => decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out _), + ReportParameterType.Date => DateTime.TryParseExact(value, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out _), + ReportParameterType.Boolean => bool.TryParse(value, out _), + ReportParameterType.Choice or ReportParameterType.MultiChoice => + choices is null || choices.Any(c => string.Equals(c.Value, value, StringComparison.OrdinalIgnoreCase)), + _ => true, + }; + if (!valid) + { + errors.Add($"{label}'s default '{Echo(value)}' isn't a valid {parameter.Type} value."); + } + } + + private async Task> CheckPermissionsAsync(IReadOnlyList requested, List errors, CancellationToken ct) + { + List names = [.. requested.Where(n => !string.IsNullOrWhiteSpace(n)).Select(n => n.Trim()).Distinct(StringComparer.OrdinalIgnoreCase)]; + foreach (string tooLong in names.Where(n => n.Length > PermissionLength)) + { + errors.Add($"The permission '{Echo(tooLong)}' is longer than {PermissionLength} characters."); + } + + IReadOnlyDictionary found = await _permissions.FindAsync(names, ct); + foreach (string missing in names.Where(n => !found.ContainsKey(n))) + { + errors.Add($"RAPS has no permission named '{Echo(missing)}'."); + } + + return [.. names.Where(found.ContainsKey).Select(n => found[n])]; + } + + internal static bool IsChoice(ReportParameterType type) + { + return type is ReportParameterType.Choice or ReportParameterType.MultiChoice; + } + + private static void CheckLength(string what, string? value, List errors) + { + if (value is { Length: > TextLength }) + { + errors.Add($"{what} must be {TextLength} characters or fewer."); + } + } + + /// Text the user sent, cut short so an error message can't echo large input. + private static string Echo(string value) + { + string trimmed = value.Trim(); + return trimmed.Length <= MaxEcho ? trimmed : trimmed[..MaxEcho] + "…"; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportExportService.cs b/web/Areas/ReportBuilder/Services/ReportExportService.cs new file mode 100644 index 000000000..3cda63f29 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportExportService.cs @@ -0,0 +1,83 @@ +using Viper.Areas.ReportBuilder.Exporters; +using Viper.Areas.ReportBuilder.Models; +using Viper.Classes.Utilities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// Runs a report for a download and writes it as an Excel workbook or a PDF. +public interface IReportExportService +{ + /// + /// The download in ("xlsx" or "pdf"). The run checks the view + /// permission and the report's download flag before anything else. + /// + Task ExportAsync(string slug, string format, ReportRunRequest request, CancellationToken ct); +} + +public sealed class ReportExportService : IReportExportService +{ + internal const string ExcelFormat = "xlsx"; + internal const string PdfFormat = "pdf"; + + private readonly IReportRunService _runs; + private readonly TimeProvider _clock; + + public ReportExportService(IReportRunService runs, TimeProvider? clock = null) + { + _runs = runs; + _clock = clock ?? TimeProvider.System; + } + + public async Task ExportAsync(string slug, string format, ReportRunRequest request, CancellationToken ct) + { + ReportRunMode? mode = null; + if (string.Equals(format, ExcelFormat, StringComparison.OrdinalIgnoreCase)) + { + mode = ReportRunMode.ExportExcel; + } + else if (string.Equals(format, PdfFormat, StringComparison.OrdinalIgnoreCase)) + { + mode = ReportRunMode.ExportPdf; + } + + if (mode is null) + { + return new ReportExportOutcome { Status = ReportRunStatus.Invalid, Errors = ["Choose a download format: xlsx or pdf."] }; + } + + ReportRunOutcome run = await _runs.RunAsync(slug, request, mode.Value, ct); + if (run.Result is not { } result || run.Details is not { } details) + { + return new ReportExportOutcome { Status = run.Status, Errors = run.Errors }; + } + + if (result.Rows.Count == 0) + { + return new ReportExportOutcome { Status = ReportRunStatus.Ok }; + } + + var document = new ReportExportDocument + { + Title = details.Title, + GeneratedAt = _clock.GetLocalNow(), + Filters = details.Filters, + SensitiveNotice = details.SensitiveNotice, + Landscape = details.PdfLandscape, + Columns = result.Columns, + Rows = result.Rows, + Truncated = result.Truncated, + }; + bool excel = mode == ReportRunMode.ExportExcel; + string extension = excel ? ReportExcelWriter.Extension : ReportPdfWriter.Extension; + return new ReportExportOutcome + { + Status = ReportRunStatus.Ok, + File = new ReportFile + { + Content = excel ? ReportExcelWriter.Write(document) : ReportPdfWriter.Write(document), + ContentType = excel ? ReportExcelWriter.ContentType : ReportPdfWriter.ContentType, + FileName = ExcelHelper.BuildExportFilename(new ExportFilenameOptions { ReportName = details.Title, Extension = extension }), + }, + }; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportLimits.cs b/web/Areas/ReportBuilder/Services/ReportLimits.cs new file mode 100644 index 000000000..69f4abb02 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportLimits.cs @@ -0,0 +1,37 @@ +namespace Viper.Areas.ReportBuilder.Services; + +/// How long a report may run and how many rows it may return. +public static class ReportLimits +{ + /// A page on screen. + public static readonly TimeSpan ScreenTimeout = TimeSpan.FromSeconds(30); + + /// An Excel or PDF download. + public static readonly TimeSpan ExportTimeout = TimeSpan.FromMinutes(1); + + /// + /// The most rows a download, an unpaginated report, or a procedure that can't page in SQL + /// returns. Hitting it marks the result as truncated. + /// + public const int MaxRows = 50_000; + + public const int DefaultPageSize = 25; + public const int MaxPageSize = 500; + + /// Rows per page in the admin form's preview of an unsaved report. + public const int PreviewRows = 50; + + /// The most choices a choice parameter's source view may supply. + public const int MaxChoices = 1_000; + + /// The longest text a parameter or search may contain. + public const int MaxTextLength = 500; + + /// The longest failure reason the run log keeps. + public const int MaxErrorLength = 2_000; + + /// The most failed runs the problems page lists, and how far back it may look. + public const int MaxFailures = 500; + public const int DefaultFailureDays = 30; + public const int MaxFailureDays = 365; +} diff --git a/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs b/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs new file mode 100644 index 000000000..ad9e10702 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs @@ -0,0 +1,224 @@ +using System.Globalization; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// The signed-in user's identifiers, for parameters bound to the current user. +public sealed record ReportCurrentUser +{ + public string? LoginId { get; init; } + public string? MothraId { get; init; } +} + +/// +/// A parameter value checked and converted to its type: , +/// , (a date), , or a list of +/// strings for a multi-choice parameter. +/// +public sealed record BoundReportParameter +{ + /// The view column it filters, or the procedure parameter it fills. + public required string Name { get; init; } + + public required ReportParameterType Type { get; init; } + public ReportFilterOperator? Operator { get; init; } + public required object Value { get; init; } + + /// True for values the user supplied, which the run log records. + public required bool FromUser { get; init; } +} + +/// The parameters ready to use, or what was wrong with the request. +public sealed record ReportBindResult +{ + public required IReadOnlyList Parameters { get; init; } + public required IReadOnlyList Errors { get; init; } +} + +/// +/// Checks a run's parameter values against the report's parameters: rejects names the report +/// doesn't have, requires the required ones, falls back to defaults, converts each value to its +/// type, keeps choice values to the allowed list, and fills current-user parameters on the +/// server so the user can't change them. +/// +public static class ReportParameterBinder +{ + private const string DateFormat = "yyyy-MM-dd"; + + public static ReportBindResult Bind( + IEnumerable definitions, + IReadOnlyDictionary> input, + ReportCurrentUser user, + IReadOnlyDictionary> choices) + { + var values = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var bound = new List(); + var errors = new List(); + var known = new HashSet(StringComparer.OrdinalIgnoreCase); + + // input's own keys can differ only by case (it's deserialized case-sensitively); folding + // them here, instead of in the dictionary's constructor, turns a would-be crash into a + // validation error. + foreach ((string name, IReadOnlyList given) in input) + { + if (!values.TryAdd(name, given)) + { + errors.Add($"The parameter '{Shorten(name)}' was sent more than once."); + } + } + + foreach (ReportParameter definition in definitions.Where(d => !string.IsNullOrWhiteSpace(d.Name)).OrderBy(d => d.DisplayOrder)) + { + string name = definition.Name!; + known.Add(name); + values.TryGetValue(name, out IReadOnlyList? given); + BoundReportParameter? parameter = definition.Binding is null or ReportParameterBinding.UserInput + ? BindInput(definition, given, choices, errors) + : BindCurrentUser(definition, given, user, errors); + if (parameter is not null) + { + bound.Add(parameter); + } + } + + errors.AddRange(values.Keys.Where(key => !known.Contains(key)).Select(key => $"This report has no parameter named '{Shorten(key)}'.")); + return new ReportBindResult { Parameters = bound, Errors = errors }; + } + + private static BoundReportParameter? BindCurrentUser( + ReportParameter definition, IReadOnlyList? given, ReportCurrentUser user, List errors) + { + if (given is not null) + { + errors.Add($"{LabelOf(definition)} is set automatically and can't be supplied."); + return null; + } + + string? value = definition.Binding == ReportParameterBinding.CurrentUserLoginId ? user.LoginId : user.MothraId; + if (string.IsNullOrWhiteSpace(value)) + { + // Without the identifier the source can't limit rows to this user, so refuse to run. + errors.Add($"{LabelOf(definition)} can't be filled in for your account."); + return null; + } + + return new BoundReportParameter + { + Name = definition.Name!, + Type = ReportParameterType.Text, + Operator = definition.Operator, + Value = value, + FromUser = false, + }; + } + + private static BoundReportParameter? BindInput( + ReportParameter definition, + IReadOnlyList? given, + IReadOnlyDictionary> choices, + List errors) + { + List raw = [.. (given ?? []).Where(v => !string.IsNullOrWhiteSpace(v)).Select(v => v.Trim())]; + if (raw.Count == 0 && !string.IsNullOrWhiteSpace(definition.DefaultValue)) + { + raw.Add(definition.DefaultValue.Trim()); + } + + if (raw.Count == 0) + { + if (definition.Required == true) + { + errors.Add($"{LabelOf(definition)} is required."); + } + + return null; + } + + ReportParameterType type = definition.Type ?? ReportParameterType.Text; + object? value = Convert(definition, type, raw, choices, errors); + return value is null + ? null + : new BoundReportParameter + { + Name = definition.Name!, + Type = type, + Operator = definition.Operator, + Value = value, + FromUser = true, + }; + } + + private static object? Convert( + ReportParameter definition, + ReportParameterType type, + List raw, + IReadOnlyDictionary> choices, + List errors) + { + string label = LabelOf(definition); + string first = raw[0]; + switch (type) + { + case ReportParameterType.Number: + return decimal.TryParse(first, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal number) + ? number + : Error(errors, $"{label} must be a number."); + case ReportParameterType.Date: + return DateTime.TryParseExact(first, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date) + ? date + : Error(errors, $"{label} must be a date (YYYY-MM-DD)."); + case ReportParameterType.Boolean: + return bool.TryParse(first, out bool flag) ? flag : Error(errors, $"{label} must be true or false."); + case ReportParameterType.Choice: + return AllowedValues(definition, [first], choices, errors) is [{ } choice] ? choice : null; + case ReportParameterType.MultiChoice: + return AllowedValues(definition, raw, choices, errors); + default: + return first.Length <= ReportLimits.MaxTextLength + ? first + : Error(errors, $"{label} must be {ReportLimits.MaxTextLength} characters or fewer."); + } + } + + /// The values, if every one is an allowed choice; otherwise null and an error. + private static IReadOnlyList? AllowedValues( + ReportParameter definition, + IReadOnlyList raw, + IReadOnlyDictionary> choices, + List errors) + { + if (!choices.TryGetValue(definition.Name!, out IReadOnlyList? allowed) || allowed.Count == 0) + { + errors.Add($"{LabelOf(definition)} has no choices to pick from."); + return null; + } + + var allowedValues = new HashSet(allowed.Select(c => c.Value), StringComparer.OrdinalIgnoreCase); + if (raw.Any(value => !allowedValues.Contains(value))) + { + errors.Add($"{LabelOf(definition)} has a value that isn't one of its choices."); + return null; + } + + return [.. raw.Distinct(StringComparer.OrdinalIgnoreCase)]; + } + + private static object? Error(List errors, string message) + { + errors.Add(message); + return null; + } + + private static string LabelOf(ReportParameter definition) + { + return string.IsNullOrWhiteSpace(definition.Label) ? definition.Name! : definition.Label; + } + + /// A user-supplied name, cut short so an error message can't be used to echo large input. + private static string Shorten(string value) + { + const int MaxEcho = 50; + return value.Length <= MaxEcho ? value : value[..MaxEcho] + "…"; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportPermissionLookupService.cs b/web/Areas/ReportBuilder/Services/ReportPermissionLookupService.cs new file mode 100644 index 000000000..24f27034e --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportPermissionLookupService.cs @@ -0,0 +1,67 @@ +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models; +using Viper.Classes.SQLContext; + +namespace Viper.Areas.ReportBuilder.Services; + +/// +/// RAPS permissions, for the admin form: reports may only name permissions RAPS has, so who can +/// view a report is always managed in RAPS. +/// +public interface IReportPermissionLookupService +{ + /// Permissions whose name contains the text, ignoring case, in name order. + Task> SearchAsync(string? text, CancellationToken ct); + + /// The names, as RAPS spells them, of those that exist; matched ignoring case. + Task> FindAsync(IEnumerable names, CancellationToken ct); +} + +public sealed class ReportPermissionLookupService : IReportPermissionLookupService +{ + /// The most permissions one search returns. + internal const int MaxResults = 50; + + private readonly RAPSContext _rapsContext; + + public ReportPermissionLookupService(RAPSContext rapsContext) + { + _rapsContext = rapsContext; + } + + public async Task> SearchAsync(string? text, CancellationToken ct) + { + string search = text?.Trim() ?? string.Empty; + return await _rapsContext.TblPermissions + .AsNoTracking() + .Where(p => search == string.Empty || p.Permission.Contains(search)) + .OrderBy(p => p.Permission) + .Take(MaxResults) + .Select(p => new ReportPermissionOption { Permission = p.Permission, Description = p.Description }) + .ToListAsync(ct); + } + + public async Task> FindAsync(IEnumerable names, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(names); + List wanted = [.. names.Where(n => !string.IsNullOrWhiteSpace(n)).Select(n => n.Trim()).Distinct(StringComparer.OrdinalIgnoreCase)]; + if (wanted.Count == 0) + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + // RAPS compares names without regard to case, as SQL Server's collation does. + List found = await _rapsContext.TblPermissions + .AsNoTracking() + .Where(p => wanted.Contains(p.Permission)) + .Select(p => p.Permission) + .ToListAsync(ct); + var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (string name in found) + { + byName.TryAdd(name, name); + } + + return byName; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportProblemService.cs b/web/Areas/ReportBuilder/Services/ReportProblemService.cs new file mode 100644 index 000000000..e7f1a4c6c --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportProblemService.cs @@ -0,0 +1,86 @@ +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// What's wrong with reports: the runs that failed, and the reports that no longer check out. +public interface IReportProblemService +{ + /// + /// Failed runs from the last days (kept between 1 and a year), + /// newest first; at most . + /// + Task> GetFailuresAsync(int? days, CancellationToken ct); + + /// Checks every live report as the admin form would on save. + Task CheckAsync(CancellationToken ct); +} + +public sealed class ReportProblemService : IReportProblemService +{ + private readonly ReportBuilderDbContext _context; + private readonly IReportDefinitionValidator _validator; + private readonly TimeProvider _clock; + + public ReportProblemService(ReportBuilderDbContext context, IReportDefinitionValidator validator, TimeProvider? clock = null) + { + _context = context; + _validator = validator; + _clock = clock ?? TimeProvider.System; + } + + public async Task> GetFailuresAsync(int? days, CancellationToken ct) + { + int window = Math.Clamp(days ?? ReportLimits.DefaultFailureDays, 1, ReportLimits.MaxFailureDays); + DateTime since = _clock.GetLocalNow().DateTime.Date.AddDays(1 - window); + + return await ( + from log in _context.ReportRunLog.AsNoTracking() + join report in _context.Reports.AsNoTracking() on log.ReportId equals report.Id + where log.ErrorMessage != null && log.RanOn >= since + orderby log.RanOn descending, log.Id descending + select new ReportFailure + { + Id = log.Id, + ReportId = report.Id, + ReportTitle = report.Title, + ReportDeleted = report.DeletedOn != null, + Action = log.Action, + LoginId = log.LoginId, + RanOn = log.RanOn, + Parameters = log.Parameters, + ErrorNumber = log.ErrorNumber, + ErrorMessage = log.ErrorMessage ?? string.Empty, + }) + .Take(ReportLimits.MaxFailures) + .ToListAsync(ct); + } + + public async Task CheckAsync(CancellationToken ct) + { + List reports = await _context.Reports + .AsNoTracking() + .Include(r => r.Permissions) + .Include(r => r.Columns) + .Include(r => r.Parameters) + .AsSplitQuery() + .Where(r => r.DeletedOn == null) + .OrderBy(r => r.Area) + .ThenBy(r => r.Title) + .ToListAsync(ct); + + var failing = new List(); + foreach (ReportDefinition report in reports) + { + // One at a time: the validator shares this request's database connections. + ReportValidation validation = await _validator.ValidateAsync(ReportAdminService.ToEditRequest(report), ct); + if (validation.Errors.Count > 0) + { + failing.Add(ReportBuilderMapper.ToCheckProblem(report) with { Problems = validation.Errors }); + } + } + + return new ReportCheckResult { Checked = reports.Count, CheckedOn = _clock.GetLocalNow().DateTime, Failing = failing }; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs b/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs new file mode 100644 index 000000000..ace8376d5 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs @@ -0,0 +1,118 @@ +using System.Data; +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Data.SqlClient; + +namespace Viper.Areas.ReportBuilder.Services; + +/// The rows a report query returned. +public sealed record ReportQueryResult +{ + /// Each row's values by column name, ignoring case; database nulls are null. + public required IReadOnlyList> Rows { get; init; } + + /// The count query's answer, when the command had one. + public int? TotalRows { get; init; } + + /// True when the query had more rows than the limit; the extra rows aren't read. + public required bool Truncated { get; init; } +} + +/// Runs the SQL a wrote. +public interface IReportQueryExecutor +{ + /// + /// Reads at most rows. Each statement gets + /// ; a timeout or database error is thrown as a . + /// + Task QueryAsync(ReportSqlCommand command, int maxRows, TimeSpan timeout, CancellationToken ct); +} + +/// +/// Runs report queries on ConnectionStrings:VIPERReports when it's set (ideally a login +/// limited to reading [report]), otherwise on VIPER. +/// +[ExcludeFromCodeCoverage(Justification = "Needs a live SQL Server; the SQL it runs is tested in ReportSqlBuilderTests.")] +public sealed class ReportQueryExecutor : IReportQueryExecutor +{ + internal const string ReportsConnectionName = "VIPERReports"; + internal const string FallbackConnectionName = "VIPER"; + + // Long enough for any parameter value the binder allows, and one size for every string so + // SQL Server reuses the cached plan instead of compiling one per value length. + private const int StringParameterSize = 4000; + + private readonly string _connectionString; + + public ReportQueryExecutor(IConfiguration configuration) + { + _connectionString = configuration.GetConnectionString(ReportsConnectionName) + ?? configuration.GetConnectionString(FallbackConnectionName) + ?? throw new InvalidOperationException($"Connection string '{FallbackConnectionName}' not configured"); + } + + public async Task QueryAsync(ReportSqlCommand command, int maxRows, TimeSpan timeout, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(command); + await using var connection = new SqlConnection(_connectionString); + await connection.OpenAsync(ct); + + int? total = null; + if (command.CountText is not null) + { + await using SqlCommand count = Create(connection, command.CountText, command.Parameters, timeout); + total = Convert.ToInt32(await count.ExecuteScalarAsync(ct), System.Globalization.CultureInfo.InvariantCulture); + } + + await using SqlCommand select = Create(connection, command.Text, command.Parameters, timeout); + await using SqlDataReader reader = await select.ExecuteReaderAsync(CommandBehavior.SingleResult, ct); + var rows = new List>(); + bool truncated = false; + while (await reader.ReadAsync(ct)) + { + if (rows.Count >= maxRows) + { + truncated = true; + break; + } + + var row = new Dictionary(reader.FieldCount, StringComparer.OrdinalIgnoreCase); + for (int i = 0; i < reader.FieldCount; i++) + { + row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i); + } + + rows.Add(row); + } + + return new ReportQueryResult { Rows = rows, TotalRows = total, Truncated = truncated }; + } + + private static SqlCommand Create(SqlConnection connection, string text, IReadOnlyDictionary parameters, TimeSpan timeout) + { + // Text is built by ReportSqlBuilder from catalog-checked, bracket-quoted names; values are parameters. +#pragma warning disable CA2100 + var command = new SqlCommand(text, connection) + { + CommandTimeout = (int)Math.Ceiling(timeout.TotalSeconds), + }; +#pragma warning restore CA2100 + foreach ((string name, object value) in parameters) + { + SqlParameter parameter = command.Parameters.AddWithValue(name, value); + if (value is string) + { + parameter.Size = StringParameterSize; + } + else if (value is DateTime) + { + // Every DateTime a report binds is a date-only value (ReportParameterBinder parses + // Date parameters from yyyy-MM-dd); SqlDbType.Date covers 0001-9999, unlike the + // datetime AddWithValue would otherwise infer. + parameter.SqlDbType = SqlDbType.Date; + } + } + + return command; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportRunService.cs b/web/Areas/ReportBuilder/Services/ReportRunService.cs new file mode 100644 index 000000000..f01c8dd22 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportRunService.cs @@ -0,0 +1,675 @@ +using System.Data.Common; +using System.Globalization; +using System.Text.Json; +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// Runs a saved report for the signed-in user, on screen or for a download. +public interface IReportRunService +{ + /// + /// One page of the report (or, for downloads, every row up to the cap). The user's view + /// permission is checked before anything they sent is read. + /// + Task RunAsync(string slug, ReportRunRequest request, ReportRunMode mode, CancellationToken ct); + + /// + /// A page of a report that isn't saved yet, for the admin form's preview: admins only, a + /// fixed page size, and not logged. A database error comes back with SQL Server's message. + /// + Task PreviewAsync(ReportDefinition report, ReportRunRequest request, CancellationToken ct); +} + +/// +/// Runs a report: finds it by slug, checks the user may view it, checks its source and columns +/// against the [report] catalog, binds the parameters, builds and runs the SQL, and logs the run, +/// including why it failed when the report itself is at fault. +/// Views are filtered, searched, sorted and paged in SQL. Procedures that take @Skip and @Take +/// page themselves; other procedures are read up to the row cap and searched, sorted and paged +/// here. +/// +public sealed class ReportRunService : IReportRunService +{ + /// The column a self-paging procedure returns its total row count in. + internal const string TotalRowsColumn = "TotalRows"; + + private const string DateFormat = "yyyy-MM-dd"; + + private readonly ReportBuilderDbContext _context; + private readonly IReportUserService _users; + private readonly IReportSourceCatalogService _catalog; + private readonly IReportChoiceService _choices; + private readonly IReportQueryExecutor _executor; + private readonly ILogger _logger; + private readonly TimeProvider _clock; + + public ReportRunService( + ReportBuilderDbContext context, + IReportUserService users, + IReportSourceCatalogService catalog, + IReportChoiceService choices, + IReportQueryExecutor executor, + ILogger logger, + TimeProvider? clock = null) + { + _context = context; + _users = users; + _catalog = catalog; + _choices = choices; + _executor = executor; + _logger = logger; + _clock = clock ?? TimeProvider.System; + } + + public async Task RunAsync(string slug, ReportRunRequest request, ReportRunMode mode, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + ReportCurrentUser? user = _users.GetCurrentUser(); + if (user is null) + { + return ReportRunOutcome.Fail(ReportRunStatus.Forbidden); + } + + ReportDefinition? report = await ReportAccess.FindAsync(_context, slug, ct); + if (report is null) + { + return ReportRunOutcome.Fail(ReportRunStatus.NotFound); + } + + if (!ReportAccess.CanView(_users, report) || !AllowsMode(report, mode)) + { + return ReportRunOutcome.Fail(ReportRunStatus.Forbidden); + } + + return await ExecuteAsync(report, user, request, mode, logRun: true, ct); + } + + public async Task PreviewAsync(ReportDefinition report, ReportRunRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(report); + ArgumentNullException.ThrowIfNull(request); + ReportCurrentUser? user = _users.GetCurrentUser(); + if (user is null || !_users.HasPermission(ReportBuilderPermissions.Admin)) + { + return ReportRunOutcome.Fail(ReportRunStatus.Forbidden); + } + + report.Paginate = true; + report.PageSize = ReportLimits.PreviewRows; + return await ExecuteAsync(report, user, request with { PerPage = null }, ReportRunMode.Screen, logRun: false, ct); + } + + private async Task ExecuteAsync( + ReportDefinition report, + ReportCurrentUser user, + ReportRunRequest request, + ReportRunMode mode, + bool logRun, + CancellationToken ct) + { + long started = _clock.GetTimestamp(); + var attempt = new RunAttempt(); + ReportRunOutcome outcome; + try + { + outcome = await RunReportAsync(report, request, mode, user, attempt, ct); + } + catch (DbException ex) + { + _logger.LogError(ex, "Report {ReportId} failed to run", report.Id); + attempt.ErrorNumber = (ex as SqlException)?.Number; + attempt.ErrorMessage = ex.Message; + + // Viewers get a general message; an admin previewing a draft sees SQL Server's reason. + outcome = logRun + ? ReportRunOutcome.Fail(ReportRunStatus.Unavailable, "The report couldn't be run. Try again later.") + : ReportRunOutcome.Fail(ReportRunStatus.Unavailable, $"SQL Server couldn't run the report: {ex.Message}"); + } + + // A run that was cancelled tells nothing about the report; one the user sent bad values + // for is the user's mistake, not the report's. + if (logRun && !ct.IsCancellationRequested && (outcome.Result is not null || outcome.Status == ReportRunStatus.Unavailable)) + { + await LogRunAsync(report, user, mode, attempt, outcome, _clock.GetElapsedTime(started), ct); + } + + return outcome; + } + + /// What a run got as far as, for the log: the values bound and any database error. + private sealed class RunAttempt + { + public IReadOnlyList Parameters { get; set; } = []; + public int? ErrorNumber { get; set; } + public string? ErrorMessage { get; set; } + } + + private async Task RunReportAsync( + ReportDefinition report, + ReportRunRequest request, + ReportRunMode mode, + ReportCurrentUser user, + RunAttempt attempt, + CancellationToken ct) + { + ReportSourceDetail? source = await _catalog.GetSourceAsync(report.Source, ct); + if (source is null) + { + return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, "This report's data source is no longer available."); + } + + IReadOnlyDictionary> choices = await _choices.GetChoicesAsync(report.Parameters, ct); + ReportBindResult bound = ReportParameterBinder.Bind(report.Parameters, request.Parameters, user, choices); + if (bound.Errors.Count > 0) + { + return ReportRunOutcome.Fail(ReportRunStatus.Invalid, [.. bound.Errors]); + } + + attempt.Parameters = bound.Parameters; + ReportRunOutcome outcome = Plan(report, source, request, mode, bound.Parameters, out RunPlan? plan); + if (plan is null) + { + return outcome; + } + + return new ReportRunOutcome + { + Status = ReportRunStatus.Ok, + Result = source.Kind == ReportSourceKind.View + ? await RunViewAsync(plan, ct) + : await RunProcedureAsync(plan, ct), + Details = new ReportRunDetails + { + Title = report.Title, + SensitiveNotice = string.IsNullOrWhiteSpace(report.SensitiveNotice) ? null : report.SensitiveNotice.Trim(), + PdfLandscape = report.PdfLandscape == true, + Filters = DescribeFilters(report, bound.Parameters, choices), + }, + }; + } + + private static bool AllowsMode(ReportDefinition report, ReportRunMode mode) + { + return mode switch + { + ReportRunMode.ExportExcel => report.AllowExcel, + ReportRunMode.ExportPdf => report.AllowPdf, + _ => true, + }; + } + + /// Everything a run needs, checked against the catalog and the request. + private sealed record RunPlan + { + public required ReportSourceDetail Source { get; init; } + public required IReadOnlyList Columns { get; init; } + public required IReadOnlyList Parameters { get; init; } + public string? SortColumn { get; init; } + public bool SortDescending { get; init; } + public string? Search { get; init; } + public required bool Paginate { get; init; } + public required int Page { get; init; } + public required int PerPage { get; init; } + public required TimeSpan Timeout { get; init; } + + public int Skip => (Page - 1) * PerPage; + } + + private static ReportRunOutcome Plan( + ReportDefinition report, + ReportSourceDetail source, + ReportRunRequest request, + ReportRunMode mode, + IReadOnlyList parameters, + out RunPlan? plan) + { + plan = null; + var known = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (ReportSourceColumn column in source.Columns) + { + known.TryAdd(column.Name, column); + } + + // A procedure whose result SQL Server couldn't describe has no known columns; its + // columns are then taken on trust and a missing one shows as empty. + bool checkColumns = known.Count > 0; + + List columns = [.. ReportAccess.VisibleColumns(report) + .Select(c => known.TryGetValue(c.Name, out ReportSourceColumn? match) ? c with { Name = match.Name } : c)]; + if (columns.Count == 0) + { + return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, "This report has no columns to show."); + } + + string? missing = columns.Select(c => c.Name).FirstOrDefault(name => checkColumns && !known.ContainsKey(name)); + if (missing is not null) + { + return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, $"The column '{missing}' is no longer in this report's data source."); + } + + if (!TryMatchParameters(source, parameters, known, out IReadOnlyList matched, out string? stale)) + { + return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, $"The parameter '{stale}' is no longer in this report's data source."); + } + + bool screen = mode == ReportRunMode.Screen; + bool paginate = screen && ReportAccess.Paginates(report); + + // A procedure that pages itself in SQL hands back one page in its own order; the + // viewer's search box and an explicit sort request can't reach rows it never returned. + bool sqlPagedProcedure = paginate && source.Kind == ReportSourceKind.Procedure && source.PagesInSql; + + var errors = new List(); + (string? sortColumn, bool descending, bool sortMissing) = Sort(report, request, columns, known, checkColumns, sqlPagedProcedure, errors); + string? search = string.IsNullOrWhiteSpace(request.Search) ? null : request.Search.Trim(); + if (search is { Length: > ReportLimits.MaxTextLength }) + { + errors.Add($"Search text must be {ReportLimits.MaxTextLength} characters or fewer."); + } + else if (search is not null && sqlPagedProcedure) + { + errors.Add("This report can't be searched."); + } + + int perPage = ReportAccess.PageSize(report); + if (paginate && request.PerPage is { } asked) + { + if (asked is < 1 or > ReportLimits.MaxPageSize) + { + errors.Add($"Rows per page must be between 1 and {ReportLimits.MaxPageSize}."); + } + + perPage = asked; + } + + // Pages past the row cap can't hold rows, so they're refused (and the skip can't overflow). + if (paginate && (request.Page < 1 || (long)(request.Page - 1) * perPage >= ReportLimits.MaxRows)) + { + errors.Add("That page doesn't exist."); + } + + if (errors.Count > 0) + { + return ReportRunOutcome.Fail(ReportRunStatus.Invalid, [.. errors]); + } + + if (sortMissing) + { + return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, $"The sort column '{report.OrderBy}' is no longer in this report's data source."); + } + + plan = new RunPlan + { + Source = source, + Columns = columns, + Parameters = matched, + SortColumn = sortColumn, + SortDescending = descending, + Search = search, + Paginate = paginate, + Page = paginate ? request.Page : 1, + PerPage = perPage, + Timeout = screen ? ReportLimits.ScreenTimeout : ReportLimits.ExportTimeout, + }; + return new ReportRunOutcome { Status = ReportRunStatus.Ok }; + } + + /// + /// The requested sort, which must be a visible sortable column, or else the report's default + /// order. Missing is true when the default sort column is no longer in the source. An + /// explicit request is refused for a procedure that pages itself in SQL. + /// + private static (string? Column, bool Descending, bool Missing) Sort( + ReportDefinition report, + ReportRunRequest request, + IReadOnlyList columns, + Dictionary known, + bool checkColumns, + bool sqlPagedProcedure, + List errors) + { + if (!string.IsNullOrWhiteSpace(request.SortBy)) + { + if (sqlPagedProcedure) + { + errors.Add("This report's order is set by its data source and can't be changed."); + return (null, false, false); + } + + ReportResultColumn? column = columns.FirstOrDefault(c => + c.Sortable && string.Equals(c.Name, request.SortBy, StringComparison.OrdinalIgnoreCase)); + if (column is null) + { + errors.Add("This report can't be sorted by that column."); + return (null, false, false); + } + + return (column.Name, request.SortDescending, false); + } + + if (string.IsNullOrWhiteSpace(report.OrderBy)) + { + return (null, false, false); + } + + string orderBy = report.OrderBy.Trim(); + bool descending = report.OrderByDescending == true; + if (!checkColumns) + { + return (orderBy, descending, false); + } + + return known.TryGetValue(orderBy, out ReportSourceColumn? match) + ? (match.Name, descending, false) + : (null, false, true); + } + + /// + /// Each parameter's name as the source spells it: a column for a view's filters, a supported + /// parameter for a procedure. False, with the name, if one is no longer there. + /// + private static bool TryMatchParameters( + ReportSourceDetail source, + IReadOnlyList parameters, + Dictionary columns, + out IReadOnlyList matched, + out string? stale) + { + var names = source.Kind == ReportSourceKind.View + ? columns.Keys.ToDictionary(name => name, StringComparer.OrdinalIgnoreCase) + : source.Parameters.Where(p => p.IsSupported).Select(p => p.Name) + .Distinct(StringComparer.OrdinalIgnoreCase).ToDictionary(name => name, StringComparer.OrdinalIgnoreCase); + var list = new List(); + foreach (BoundReportParameter parameter in parameters) + { + if (!names.TryGetValue(parameter.Name, out string? name)) + { + matched = []; + stale = parameter.Name; + return false; + } + + list.Add(parameter with { Name = name }); + } + + matched = list; + stale = null; + return true; + } + + private async Task RunViewAsync(RunPlan plan, CancellationToken ct) + { + IReadOnlyList textColumns = [.. plan.Columns + .Where(c => plan.Source.Columns.Any(s => s.Kind == ReportValueKind.Text && string.Equals(s.Name, c.Name, StringComparison.OrdinalIgnoreCase))) + .Select(c => c.Name)]; + ReportSqlCommand command = ReportSqlBuilder.BuildView(new ReportViewQuery + { + Source = plan.Source.Name, + Columns = [.. plan.Columns.Select(c => c.Name)], + Filters = plan.Parameters, + SearchColumns = textColumns, + Search = plan.Search, + SortColumn = plan.SortColumn, + SortDescending = plan.SortDescending, + Skip = plan.Paginate ? plan.Skip : null, + Take = plan.Paginate ? plan.PerPage : null, + }); + + ReportQueryResult result = await _executor.QueryAsync( + command, plan.Paginate ? plan.PerPage : ReportLimits.MaxRows, plan.Timeout, ct); + IReadOnlyList> rows = Project(result.Rows, plan.Columns); + return new ReportRunResult + { + Columns = plan.Columns, + Rows = rows, + Page = plan.Page, + PerPage = plan.Paginate ? plan.PerPage : rows.Count, + TotalRows = plan.Paginate ? result.TotalRows : rows.Count, + Truncated = !plan.Paginate && result.Truncated, + }; + } + + private async Task RunProcedureAsync(RunPlan plan, CancellationToken ct) + { + // A procedure that takes @Skip/@Take needs them on every call, not only a paginated + // screen run: a bounded window starting at zero, so a download or an unpaginated run + // doesn't fall back to whatever the procedure defaults to (or fail outright if it must + // have them). + bool needsPagingArgs = plan.Source.PagesInSql; + bool sqlPaged = plan.Paginate && needsPagingArgs; + int? skip = null; + int? take = null; + if (needsPagingArgs) + { + skip = sqlPaged ? plan.Skip : 0; + take = sqlPaged ? plan.PerPage : ReportLimits.MaxRows; + } + + ReportSqlCommand command = ReportSqlBuilder.BuildProcedure(plan.Source.Name, plan.Parameters, skip, take); + ReportQueryResult result = await _executor.QueryAsync( + command, sqlPaged ? plan.PerPage : ReportLimits.MaxRows, plan.Timeout, ct); + + if (sqlPaged) + { + // The procedure picks the page, so its own order stands; it reports the total in a TotalRows column. + IReadOnlyList> page = Project(result.Rows, plan.Columns); + return new ReportRunResult + { + Columns = plan.Columns, + Rows = page, + Page = plan.Page, + PerPage = plan.PerPage, + TotalRows = TotalFrom(result.Rows), + Truncated = false, + }; + } + + // Sorted before it's projected: the report's default sort column may not be one it shows. + IEnumerable> sorted = result.Rows; + if (plan.SortColumn is not null) + { + var comparer = new ReportValueComparer(); + sorted = plan.SortDescending + ? sorted.OrderByDescending(row => Value(row, plan.SortColumn), comparer) + : sorted.OrderBy(row => Value(row, plan.SortColumn), comparer); + } + + List> projected = [.. Project([.. sorted], plan.Columns)]; + IEnumerable> rows = plan.Search is null + ? projected + : projected.Where(row => Matches(row, plan.Search)); + + List> all = [.. rows]; + List> shown = plan.Paginate + ? [.. all.Skip(plan.Skip).Take(plan.PerPage)] + : all; + return new ReportRunResult + { + Columns = plan.Columns, + Rows = shown, + Page = plan.Page, + PerPage = plan.Paginate ? plan.PerPage : shown.Count, + TotalRows = all.Count, + Truncated = result.Truncated, + }; + } + + /// Each row reduced to the report's columns, in order, keyed by column name. + private static IReadOnlyList> Project( + IReadOnlyList> rows, IReadOnlyList columns) + { + return [.. rows.Select(row => + { + var projected = new Dictionary(columns.Count, StringComparer.OrdinalIgnoreCase); + foreach (string name in columns.Select(column => column.Name)) + { + projected[name] = Value(row, name); + } + + return (IReadOnlyDictionary)projected; + })]; + } + + private static object? Value(IReadOnlyDictionary row, string column) + { + return row.TryGetValue(column, out object? value) ? value : null; + } + + private static bool Matches(IReadOnlyDictionary row, string search) + { + return row.Values.OfType().Any(text => text.Contains(search, StringComparison.OrdinalIgnoreCase)); + } + + private static int? TotalFrom(IReadOnlyList> rows) + { + if (rows.Count == 0 || !rows[0].TryGetValue(TotalRowsColumn, out object? total) || total is null) + { + return null; + } + + try + { + return Convert.ToInt32(total, CultureInfo.InvariantCulture); + } + catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException) + { + return null; + } + } + + /// Logs a run: the rows it returned, or why it failed. + private async Task LogRunAsync( + ReportDefinition report, + ReportCurrentUser user, + ReportRunMode mode, + RunAttempt attempt, + ReportRunOutcome outcome, + TimeSpan duration, + CancellationToken ct) + { + string? error = outcome.Result is not null + ? null + : attempt.ErrorMessage ?? string.Join(" ", outcome.Errors); + _context.ReportRunLog.Add(new ReportRunLog + { + ReportId = report.Id, + Action = mode switch + { + ReportRunMode.ExportExcel => ReportRunAction.ExportExcel, + ReportRunMode.ExportPdf => ReportRunAction.ExportPdf, + _ => ReportRunAction.Run, + }, + LoginId = user.LoginId, + RanOn = _clock.GetLocalNow().DateTime, + Parameters = LoggedParameters(attempt.Parameters), + RowsReturned = outcome.Result?.Rows.Count, + DurationMs = (int)Math.Min(int.MaxValue, Math.Round(duration.TotalMilliseconds)), + ErrorNumber = outcome.Result is null ? attempt.ErrorNumber : null, + ErrorMessage = error is { Length: > ReportLimits.MaxErrorLength } ? error[..ReportLimits.MaxErrorLength] : error, + }); + + try + { + await _context.SaveChangesAsync(ct); + } + catch (Exception ex) when (ex is DbUpdateException or DbException) + { + // The user still gets their report (or its error); a missing log entry isn't worth + // failing the request over. + _logger.LogWarning(ex, "Couldn't log a run of report {ReportId}", report.Id); + } + } + + /// + /// The values the user chose, labelled as on the form, for the heading of a download: + /// dates as MM/dd/yyyy, choices by their labels, and true/false as Yes/No. + /// + private static IReadOnlyList DescribeFilters( + ReportDefinition report, + IReadOnlyList parameters, + IReadOnlyDictionary> choices) + { + var labels = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (ReportParameter definition in report.Parameters.Where(p => !string.IsNullOrWhiteSpace(p.Name))) + { + labels.TryAdd(definition.Name!, string.IsNullOrWhiteSpace(definition.Label) ? definition.Name! : definition.Label); + } + + return [.. parameters.Where(p => p.FromUser).Select(parameter => + { + Dictionary choiceLabels = choices.TryGetValue(parameter.Name, out IReadOnlyList? list) + ? list.GroupBy(c => c.Value, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => g.First().Label, StringComparer.OrdinalIgnoreCase) + : []; + return new ReportAppliedFilter + { + Label = labels.GetValueOrDefault(parameter.Name, parameter.Name), + Value = FilterValue(parameter.Value, choiceLabels), + }; + })]; + } + + private static string FilterValue(object value, Dictionary choiceLabels) + { + return value switch + { + DateTime date => ReportCellFormatter.Text(date, ReportColumnFormat.Date), + bool flag => ReportCellFormatter.Text(flag, ReportColumnFormat.YesNo), + IReadOnlyList values => string.Join(", ", values.Select(v => choiceLabels.GetValueOrDefault(v, v))), + string text => choiceLabels.GetValueOrDefault(text, text), + _ => ReportCellFormatter.Text(value, ReportColumnFormat.Number), + }; + } + + /// The values the user chose, as JSON; current-user values aren't repeated. + private static string? LoggedParameters(IReadOnlyList parameters) + { + var values = new SortedDictionary(StringComparer.OrdinalIgnoreCase); + foreach (BoundReportParameter parameter in parameters.Where(p => p.FromUser)) + { + values[parameter.Name] = parameter.Value switch + { + DateTime date => date.ToString(DateFormat, CultureInfo.InvariantCulture), + decimal number => number.ToString(CultureInfo.InvariantCulture), + bool flag => flag, + IReadOnlyList list => list, + _ => Convert.ToString(parameter.Value, CultureInfo.InvariantCulture) ?? string.Empty, + }; + } + + return values.Count == 0 ? null : JsonSerializer.Serialize(values); + } + + /// + /// Orders a column's values for in-memory sorting: empty values first, then by the values' + /// own order, with text compared ignoring case. + /// + private sealed class ReportValueComparer : IComparer + { + public int Compare(object? x, object? y) + { + if (x is null || y is null) + { + return (x is null ? 0 : 1) - (y is null ? 0 : 1); + } + + if (x is string a && y is string b) + { + return string.Compare(a, b, StringComparison.OrdinalIgnoreCase); + } + + if (x.GetType() == y.GetType() && x is IComparable comparable) + { + return comparable.CompareTo(y); + } + + return string.Compare( + Convert.ToString(x, CultureInfo.InvariantCulture), + Convert.ToString(y, CultureInfo.InvariantCulture), + StringComparison.OrdinalIgnoreCase); + } + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs b/web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs new file mode 100644 index 000000000..3cd08f81c --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs @@ -0,0 +1,146 @@ +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.Areas.ReportBuilder.Services; + +/// +/// The allow-list of report sources: the views and procedures in the [report] schema, with the +/// columns they return and the parameters they take. +/// +public interface IReportSourceCatalogService +{ + /// Every view and procedure in [report], by name. + Task> GetSourcesAsync(CancellationToken ct); + + /// One source's columns and parameters, or null when [report] has no such object. + Task GetSourceAsync(string name, CancellationToken ct); +} + +public sealed class ReportSourceCatalogService : IReportSourceCatalogService +{ + /// Procedure parameters the builder fills itself to page in SQL. + internal const string SkipParameter = "Skip"; + + internal const string TakeParameter = "Take"; + + private const string ViewType = "V"; + + private readonly IReportSourceMetadataReader _reader; + + public ReportSourceCatalogService(IReportSourceMetadataReader reader) + { + _reader = reader; + } + + public async Task> GetSourcesAsync(CancellationToken ct) + { + IReadOnlyList objects = await _reader.GetObjectsAsync(ct); + return [.. objects.Select(ToSummary)]; + } + + public async Task GetSourceAsync(string name, CancellationToken ct) + { + // Only names the catalog lists are looked up, so a caller can't probe other objects. + IReadOnlyList objects = await _reader.GetObjectsAsync(ct); + ReportSourceObjectRow? source = objects.FirstOrDefault(row => + string.Equals(row.Name, name, StringComparison.OrdinalIgnoreCase)); + if (source is null) + { + return null; + } + + ReportSourceSummary summary = ToSummary(source); + return summary.Kind == ReportSourceKind.View + ? await DescribeViewAsync(summary, ct) + : await DescribeProcedureAsync(summary, ct); + } + + private async Task DescribeViewAsync(ReportSourceSummary view, CancellationToken ct) + { + IReadOnlyList columns = await _reader.GetViewColumnsAsync(view.Name, ct); + return new ReportSourceDetail + { + Name = view.Name, + Kind = view.Kind, + Description = view.Description, + Columns = ToColumns(columns), + Parameters = [], + PagesInSql = true, + }; + } + + private async Task DescribeProcedureAsync(ReportSourceSummary procedure, CancellationToken ct) + { + IReadOnlyList parameters = + [.. (await _reader.GetProcedureParametersAsync(procedure.Name, ct)).Select(ToParameter)]; + IReadOnlyList result = await _reader.DescribeProcedureResultAsync(procedure.Name, ct); + string? error = result.Select(row => row.ErrorMessage).FirstOrDefault(message => message is not null); + bool pagesInSql = IsPagingParameter(parameters, SkipParameter) && IsPagingParameter(parameters, TakeParameter); + + return new ReportSourceDetail + { + Name = procedure.Name, + Kind = procedure.Kind, + Description = procedure.Description, + Columns = error is null ? ToColumns(result) : [], + ColumnsError = error, + + // @Skip and @Take are filled by the builder, so an admin never maps them. + Parameters = pagesInSql + ? [.. parameters.Where(p => !IsNamed(p, SkipParameter) && !IsNamed(p, TakeParameter))] + : parameters, + PagesInSql = pagesInSql, + }; + } + + private static ReportSourceSummary ToSummary(ReportSourceObjectRow row) + { + return new ReportSourceSummary + { + Name = row.Name, + Kind = string.Equals(row.Type, ViewType, StringComparison.OrdinalIgnoreCase) + ? ReportSourceKind.View + : ReportSourceKind.Procedure, + Description = string.IsNullOrWhiteSpace(row.Description) ? null : row.Description.Trim(), + }; + } + + private static IReadOnlyList ToColumns(IEnumerable rows) + { + return [.. rows + .Where(row => !string.IsNullOrEmpty(row.Name)) + .Select(row => + { + ReportValueKind kind = ReportSqlTypes.KindOf(row.SqlType); + return new ReportSourceColumn + { + Name = row.Name!, + SqlType = row.SqlType ?? string.Empty, + Kind = kind, + IsNullable = row.IsNullable ?? true, + IsSupported = ReportSqlTypes.IsSupported(kind), + }; + })]; + } + + private static ReportSourceParameter ToParameter(ReportSourceParameterRow row) + { + ReportValueKind kind = ReportSqlTypes.KindOf(row.SqlType); + return new ReportSourceParameter + { + Name = row.Name.TrimStart('@'), + SqlType = row.SqlType, + Kind = kind, + IsSupported = !row.IsOutput && ReportSqlTypes.IsSupported(kind), + }; + } + + private static bool IsPagingParameter(IEnumerable parameters, string name) + { + return parameters.Any(p => IsNamed(p, name) && p.IsSupported && p.Kind == ReportValueKind.WholeNumber); + } + + private static bool IsNamed(ReportSourceParameter parameter, string name) + { + return string.Equals(parameter.Name, name, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs b/web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs new file mode 100644 index 000000000..3f7ad5478 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs @@ -0,0 +1,111 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.EntityFrameworkCore; + +namespace Viper.Areas.ReportBuilder.Services; + +/// An object in the [report] schema, as sys.objects lists it. +public sealed class ReportSourceObjectRow +{ + public string Name { get; set; } = string.Empty; + + /// sys.objects type: V for a view, P for a procedure. + public string Type { get; set; } = string.Empty; + + public string? Description { get; set; } +} + +/// A view column, or a column of a procedure's first result set. +public sealed class ReportSourceColumnRow +{ + public string? Name { get; set; } + public string? SqlType { get; set; } + public bool? IsNullable { get; set; } + + /// Set instead of the other values when SQL Server can't describe a procedure's result. + public string? ErrorMessage { get; set; } +} + +/// A procedure parameter, as sys.parameters lists it (name includes the @). +public sealed class ReportSourceParameterRow +{ + public string Name { get; set; } = string.Empty; + public string SqlType { get; set; } = string.Empty; + public bool IsOutput { get; set; } +} + +/// +/// Reads the shape of the [report] schema from SQL Server's catalog views. Names are always +/// passed as parameters, never written into the SQL. +/// +public interface IReportSourceMetadataReader +{ + Task> GetObjectsAsync(CancellationToken ct); + Task> GetViewColumnsAsync(string name, CancellationToken ct); + Task> GetProcedureParametersAsync(string name, CancellationToken ct); + Task> DescribeProcedureResultAsync(string name, CancellationToken ct); +} + +[ExcludeFromCodeCoverage(Justification = "Only issues catalog SQL against SQL Server; ReportSourceCatalogService is tested against a fake.")] +public sealed class ReportSourceMetadataReader : IReportSourceMetadataReader +{ + private readonly ReportBuilderDbContext _context; + + public ReportSourceMetadataReader(ReportBuilderDbContext context) + { + _context = context; + } + + public async Task> GetObjectsAsync(CancellationToken ct) + { + return await _context.Database.SqlQuery($""" + SELECT o.name AS Name, RTRIM(o.type) AS Type, CAST(ep.value AS nvarchar(2000)) AS Description + FROM sys.objects o + LEFT JOIN sys.extended_properties ep + ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description' + WHERE o.schema_id = SCHEMA_ID({ReportBuilderDbContext.Schema}) AND o.type IN ('V', 'P') + ORDER BY o.name + """).ToListAsync(ct); + } + + public async Task> GetViewColumnsAsync(string name, CancellationToken ct) + { + string qualified = Qualify(name); + return await _context.Database.SqlQuery($""" + SELECT c.name AS Name, TYPE_NAME(c.system_type_id) AS SqlType, c.is_nullable AS IsNullable, + CAST(NULL AS nvarchar(4000)) AS ErrorMessage + FROM sys.columns c + WHERE c.object_id = OBJECT_ID({qualified}) + ORDER BY c.column_id + """).ToListAsync(ct); + } + + public async Task> GetProcedureParametersAsync(string name, CancellationToken ct) + { + string qualified = Qualify(name); + return await _context.Database.SqlQuery($""" + SELECT p.name AS Name, TYPE_NAME(p.system_type_id) AS SqlType, p.is_output AS IsOutput + FROM sys.parameters p + WHERE p.object_id = OBJECT_ID({qualified}) + ORDER BY p.parameter_id + """).ToListAsync(ct); + } + + public async Task> DescribeProcedureResultAsync(string name, CancellationToken ct) + { + // The batch is just the procedure name, which SQL Server reads as EXEC of that procedure. + string qualified = Qualify(name); + return await _context.Database.SqlQuery($""" + SELECT r.name AS Name, r.system_type_name AS SqlType, r.is_nullable AS IsNullable, + r.error_message AS ErrorMessage + FROM sys.dm_exec_describe_first_result_set({qualified}, NULL, 0) r + WHERE r.is_hidden = 0 OR r.error_number IS NOT NULL + ORDER BY r.column_ordinal + """).ToListAsync(ct); + } + + /// [report].[name], with any ] in the name doubled, for OBJECT_ID. + private static string Qualify(string name) + { + return $"[{ReportBuilderDbContext.Schema}].[{name.Replace("]", "]]", StringComparison.Ordinal)}]"; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs b/web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs new file mode 100644 index 000000000..660d0c194 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs @@ -0,0 +1,261 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.Areas.ReportBuilder.Services; + +/// A SQL statement and its parameter values, ready for the query executor. +public sealed record ReportSqlCommand +{ + public required string Text { get; init; } + + /// A second statement returning the total row count, for paged views. + public string? CountText { get; init; } + + public required IReadOnlyDictionary Parameters { get; init; } +} + +/// What to read from a view: columns, filters, search, order and paging. +public sealed record ReportViewQuery +{ + public required string Source { get; init; } + public required IReadOnlyList Columns { get; init; } + public IReadOnlyList Filters { get; init; } = []; + + /// Text columns the search looks in. + public IReadOnlyList SearchColumns { get; init; } = []; + + public string? Search { get; init; } + public string? SortColumn { get; init; } + public bool SortDescending { get; init; } + + /// Rows to skip and take for one page; both null to read up to . + public int? Skip { get; init; } + + public int? Take { get; init; } + + /// The cap when not paging. One extra row is read so the caller can tell it was hit. + public int MaxRows { get; init; } = ReportLimits.MaxRows; +} + +/// +/// Writes the SQL that reads a report. Object, column and parameter names come only from the +/// saved report, already checked against the [report] catalog, and are always bracket-quoted; +/// every value is a SQL parameter, never part of the SQL text. +/// +public static partial class ReportSqlBuilder +{ + internal const string SkipParameter = "@__skip"; + internal const string TakeParameter = "@__take"; + internal const string TopParameter = "@__top"; + internal const string SearchParameter = "@__search"; + + private const char LikeEscape = '\\'; + + /// The SELECT (and, when paged, the COUNT) for a view. + public static ReportSqlCommand BuildView(ReportViewQuery query) + { + ArgumentNullException.ThrowIfNull(query); + if (query.Columns.Count == 0) + { + throw new ArgumentException("A report needs at least one column.", nameof(query)); + } + + var parameters = new Dictionary(StringComparer.Ordinal); + string where = WhereClause(query, parameters); + string source = Qualified(query.Source); + string columns = string.Join(", ", query.Columns.Select(Quote)); + string direction = query.SortDescending ? "DESC" : "ASC"; + string orderBy = query.SortColumn is null + ? "ORDER BY (SELECT NULL)" + : $"ORDER BY {Quote(query.SortColumn)} {direction}"; + + if (query.Skip is { } skip && query.Take is { } take) + { + parameters[SkipParameter] = skip; + parameters[TakeParameter] = take; + return new ReportSqlCommand + { + Text = $"SELECT {columns} FROM {source}{where} {orderBy} OFFSET {SkipParameter} ROWS FETCH NEXT {TakeParameter} ROWS ONLY", + CountText = $"SELECT COUNT(*) FROM {source}{where}", + Parameters = parameters, + }; + } + + parameters[TopParameter] = query.MaxRows + 1; + return new ReportSqlCommand + { + Text = $"SELECT TOP ({TopParameter}) {columns} FROM {source}{where} {orderBy}", + Parameters = parameters, + }; + } + + /// + /// The EXEC for a procedure. Skip and take are passed only to procedures that page in SQL; + /// their names are the catalog's @Skip and @Take. + /// + public static ReportSqlCommand BuildProcedure( + string source, IReadOnlyList arguments, int? skip = null, int? take = null) + { + ArgumentNullException.ThrowIfNull(arguments); + var parameters = new Dictionary(StringComparer.Ordinal); + var assignments = new List(); + for (int i = 0; i < arguments.Count; i++) + { + string placeholder = Placeholder(i); + assignments.Add($"{ParameterName(arguments[i].Name)} = {placeholder}"); + parameters[placeholder] = ScalarValue(arguments[i]); + } + + if (skip is { } skipRows && take is { } takeRows) + { + assignments.Add($"@{ReportSourceCatalogService.SkipParameter} = {SkipParameter}"); + assignments.Add($"@{ReportSourceCatalogService.TakeParameter} = {TakeParameter}"); + parameters[SkipParameter] = skipRows; + parameters[TakeParameter] = takeRows; + } + + string call = $"EXEC {Qualified(source)}"; + return new ReportSqlCommand + { + Text = assignments.Count == 0 ? call : $"{call} {string.Join(", ", assignments)}", + Parameters = parameters, + }; + } + + /// The value and label columns of a choice list's view, ordered by label. + public static ReportSqlCommand BuildChoices(string source) + { + return new ReportSqlCommand + { + Text = $"SELECT TOP ({TopParameter}) [Value], [Label] FROM {Qualified(source)} ORDER BY [Label]", + Parameters = new Dictionary { [TopParameter] = ReportLimits.MaxChoices }, + }; + } + + /// A name in brackets, with any closing bracket doubled. + public static string Quote(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + return $"[{name.Replace("]", "]]", StringComparison.Ordinal)}]"; + } + + private static string Qualified(string source) + { + return $"{Quote(ReportBuilderDbContext.Schema)}.{Quote(source)}"; + } + + private static string WhereClause(ReportViewQuery query, Dictionary parameters) + { + var conditions = new List(); + for (int i = 0; i < query.Filters.Count; i++) + { + conditions.Add(Condition(query.Filters[i], Placeholder(i), parameters)); + } + + if (!string.IsNullOrWhiteSpace(query.Search) && query.SearchColumns.Count > 0) + { + parameters[SearchParameter] = ContainsPattern(query.Search.Trim()); + conditions.Add("(" + string.Join(" OR ", query.SearchColumns.Select(c => Like(Quote(c), SearchParameter))) + ")"); + } + + return conditions.Count == 0 ? string.Empty : " WHERE " + string.Join(" AND ", conditions); + } + + private static string Condition(BoundReportParameter filter, string placeholder, Dictionary parameters) + { + string column = Quote(filter.Name); + if (filter.Value is IReadOnlyList list) + { + return InList(column, placeholder, list, parameters); + } + + ReportFilterOperator op = filter.Operator ?? ReportFilterOperator.Equals; + switch (op) + { + case ReportFilterOperator.Contains: + parameters[placeholder] = ContainsPattern(Convert.ToString(filter.Value, CultureInfo.InvariantCulture) ?? string.Empty); + return Like(column, placeholder); + case ReportFilterOperator.From: + parameters[placeholder] = filter.Value; + return $"{column} >= {placeholder}"; + case ReportFilterOperator.To when filter.Value is DateTime date: + // A date's whole day counts, whatever time of day the column holds. + parameters[placeholder] = date.Date.AddDays(1); + return $"{column} < {placeholder}"; + case ReportFilterOperator.To: + parameters[placeholder] = filter.Value; + return $"{column} <= {placeholder}"; + case ReportFilterOperator.In: + return InList(column, placeholder, [Convert.ToString(filter.Value, CultureInfo.InvariantCulture) ?? string.Empty], parameters); + default: + parameters[placeholder] = filter.Value; + return $"{column} = {placeholder}"; + } + } + + private static string InList(string column, string placeholder, IReadOnlyList values, Dictionary parameters) + { + var names = new List(); + for (int i = 0; i < values.Count; i++) + { + string name = $"{placeholder}_{i}"; + parameters[name] = values[i]; + names.Add(name); + } + + return $"{column} IN ({string.Join(", ", names)})"; + } + + private static string Like(string column, string placeholder) + { + return $"{column} LIKE {placeholder} ESCAPE '{LikeEscape}'"; + } + + /// %text%, with LIKE's own wildcards in the text escaped so they match literally. + internal static string ContainsPattern(string text) + { + var escaped = new StringBuilder(text.Length + 2).Append('%'); + foreach (char c in text) + { + if (c is '%' or '_' or '[' or LikeEscape) + { + escaped.Append(LikeEscape); + } + + escaped.Append(c); + } + + return escaped.Append('%').ToString(); + } + + private static object ScalarValue(BoundReportParameter argument) + { + // A procedure takes one value per parameter, so a multi-choice list is passed comma-separated. + return argument.Value is IReadOnlyList list ? string.Join(",", list) : argument.Value; + } + + private static string Placeholder(int index) + { + return string.Create(CultureInfo.InvariantCulture, $"@p{index}"); + } + + /// + /// A procedure parameter name for EXEC. Names come from sys.parameters, but they can't be + /// bracket-quoted, so anything other than a plain identifier is refused. + /// + private static string ParameterName(string name) + { + string bare = name.TrimStart('@'); + if (!IdentifierPattern().IsMatch(bare)) + { + throw new ArgumentException($"'{bare}' is not a valid parameter name.", nameof(name)); + } + + return "@" + bare; + } + + [GeneratedRegex(@"^[A-Za-z_][A-Za-z0-9_]*\z", RegexOptions.None, matchTimeoutMilliseconds: 100)] + private static partial Regex IdentifierPattern(); +} diff --git a/web/Areas/ReportBuilder/Services/ReportSqlTypes.cs b/web/Areas/ReportBuilder/Services/ReportSqlTypes.cs new file mode 100644 index 000000000..3ef742327 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportSqlTypes.cs @@ -0,0 +1,64 @@ +using Viper.Areas.ReportBuilder.Models; + +namespace Viper.Areas.ReportBuilder.Services; + +/// Maps SQL Server type names to the kinds of value a report can show or take. +public static class ReportSqlTypes +{ + private static readonly Dictionary Kinds = new(StringComparer.OrdinalIgnoreCase) + { + ["char"] = ReportValueKind.Text, + ["varchar"] = ReportValueKind.Text, + ["nchar"] = ReportValueKind.Text, + ["nvarchar"] = ReportValueKind.Text, + ["text"] = ReportValueKind.Text, + ["ntext"] = ReportValueKind.Text, + ["sysname"] = ReportValueKind.Text, + ["xml"] = ReportValueKind.Text, + ["tinyint"] = ReportValueKind.WholeNumber, + ["smallint"] = ReportValueKind.WholeNumber, + ["int"] = ReportValueKind.WholeNumber, + ["bigint"] = ReportValueKind.WholeNumber, + ["decimal"] = ReportValueKind.FractionalNumber, + ["numeric"] = ReportValueKind.FractionalNumber, + ["money"] = ReportValueKind.FractionalNumber, + ["smallmoney"] = ReportValueKind.FractionalNumber, + ["float"] = ReportValueKind.FractionalNumber, + ["real"] = ReportValueKind.FractionalNumber, + ["date"] = ReportValueKind.Date, + ["datetime"] = ReportValueKind.DateTime, + ["datetime2"] = ReportValueKind.DateTime, + ["smalldatetime"] = ReportValueKind.DateTime, + ["datetimeoffset"] = ReportValueKind.DateTime, + ["time"] = ReportValueKind.Time, + ["bit"] = ReportValueKind.Boolean, + ["uniqueidentifier"] = ReportValueKind.UniqueId, + ["binary"] = ReportValueKind.Binary, + ["varbinary"] = ReportValueKind.Binary, + ["image"] = ReportValueKind.Binary, + ["timestamp"] = ReportValueKind.Binary, + ["rowversion"] = ReportValueKind.Binary, + }; + + /// + /// The kind of a type such as "nvarchar(50)" or "decimal(9,2)"; the length or precision is + /// ignored. Unknown types (sql_variant, geography, ...) are . + /// + public static ReportValueKind KindOf(string? sqlType) + { + if (string.IsNullOrWhiteSpace(sqlType)) + { + return ReportValueKind.Other; + } + + int paren = sqlType.IndexOf('(', StringComparison.Ordinal); + string baseType = (paren < 0 ? sqlType : sqlType[..paren]).Trim(); + return Kinds.TryGetValue(baseType, out ReportValueKind kind) ? kind : ReportValueKind.Other; + } + + /// Whether a report can show or take values of this kind. + public static bool IsSupported(ReportValueKind kind) + { + return kind is not (ReportValueKind.Binary or ReportValueKind.Other); + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportUserService.cs b/web/Areas/ReportBuilder/Services/ReportUserService.cs new file mode 100644 index 000000000..1fa60b284 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportUserService.cs @@ -0,0 +1,38 @@ +using Viper.Classes.SQLContext; +using Viper.Models.AAUD; + +namespace Viper.Areas.ReportBuilder.Services; + +/// The signed-in user, as the report runner needs them: who they are and what they may do. +public interface IReportUserService +{ + /// The signed-in user's identifiers, or null when no one is signed in. + ReportCurrentUser? GetCurrentUser(); + + /// Whether the signed-in user has a RAPS permission. + bool HasPermission(string permission); +} + +public sealed class ReportUserService : IReportUserService +{ + private readonly RAPSContext _rapsContext; + private readonly IUserHelper _userHelper; + + public ReportUserService(RAPSContext rapsContext, IUserHelper userHelper) + { + _rapsContext = rapsContext; + _userHelper = userHelper; + } + + public ReportCurrentUser? GetCurrentUser() + { + AaudUser? user = _userHelper.GetCurrentUser(); + return user is null ? null : new ReportCurrentUser { LoginId = user.LoginId, MothraId = user.MothraId }; + } + + public bool HasPermission(string permission) + { + AaudUser? user = _userHelper.GetCurrentUser(); + return user is not null && _userHelper.HasPermission(_rapsContext, user, permission); + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportViewerService.cs b/web/Areas/ReportBuilder/Services/ReportViewerService.cs new file mode 100644 index 000000000..c55a838c5 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportViewerService.cs @@ -0,0 +1,126 @@ +using System.Data.Common; +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder.Services; + +/// The reports the signed-in user may view, and what the viewer needs to show one. +public interface IReportViewerService +{ + /// The reports the user may view, by area and then title. + Task> GetCatalogAsync(CancellationToken ct); + + /// A report's form and columns; its view permission is checked first. + Task GetDefinitionAsync(string slug, CancellationToken ct); +} + +public sealed class ReportViewerService : IReportViewerService +{ + private readonly ReportBuilderDbContext _context; + private readonly IReportUserService _users; + private readonly IReportChoiceService _choices; + private readonly ILogger _logger; + + public ReportViewerService( + ReportBuilderDbContext context, + IReportUserService users, + IReportChoiceService choices, + ILogger logger) + { + _context = context; + _users = users; + _choices = choices; + _logger = logger; + } + + public async Task> GetCatalogAsync(CancellationToken ct) + { + if (_users.GetCurrentUser() is null) + { + return []; + } + + List reports = await _context.Reports + .AsNoTracking() + .Include(r => r.Permissions) + .Where(r => r.DeletedOn == null) + .OrderBy(r => r.Area) + .ThenBy(r => r.Title) + .ToListAsync(ct); + + return [.. reports.Where(report => ReportAccess.CanView(_users, report)).Select(ReportBuilderMapper.ToCatalogItem)]; + } + + public async Task GetDefinitionAsync(string slug, CancellationToken ct) + { + if (_users.GetCurrentUser() is null) + { + return new ReportDefinitionOutcome { Status = ReportRunStatus.Forbidden }; + } + + ReportDefinition? report = await ReportAccess.FindAsync(_context, slug, ct); + if (report is null) + { + return new ReportDefinitionOutcome { Status = ReportRunStatus.NotFound }; + } + + if (!ReportAccess.CanView(_users, report)) + { + return new ReportDefinitionOutcome { Status = ReportRunStatus.Forbidden }; + } + + IReadOnlyList parameters = ReportAccess.UserParameters(report); + IReadOnlyDictionary> choices; + try + { + choices = await _choices.GetChoicesAsync(parameters, ct); + } + catch (DbException ex) + { + _logger.LogError(ex, "Couldn't load the choices for report {ReportId}", report.Id); + return new ReportDefinitionOutcome + { + Status = ReportRunStatus.Unavailable, + Errors = ["This report's choices couldn't be loaded. Try again later."], + }; + } + + return new ReportDefinitionOutcome + { + Status = ReportRunStatus.Ok, + Definition = new ReportViewerDefinition + { + Slug = report.Slug, + Title = report.Title, + Description = report.Description, + Area = report.Area, + SensitiveNotice = string.IsNullOrWhiteSpace(report.SensitiveNotice) ? null : report.SensitiveNotice.Trim(), + Paginate = ReportAccess.Paginates(report), + PageSize = ReportAccess.PageSize(report), + AllowExcel = report.AllowExcel, + AllowPdf = report.AllowPdf, + SortBy = string.IsNullOrWhiteSpace(report.OrderBy) ? null : report.OrderBy.Trim(), + SortDescending = report.OrderByDescending == true, + Columns = ReportAccess.VisibleColumns(report), + Parameters = [.. parameters.Select(p => ToViewerParameter(p, choices))], + }, + }; + } + + private static ReportViewerParameter ToViewerParameter( + ReportParameter parameter, IReadOnlyDictionary> choices) + { + ReportParameterType type = parameter.Type ?? ReportParameterType.Text; + bool isChoice = type is ReportParameterType.Choice or ReportParameterType.MultiChoice; + return new ReportViewerParameter + { + Name = parameter.Name!, + Label = string.IsNullOrWhiteSpace(parameter.Label) ? parameter.Name! : parameter.Label, + Type = type, + Required = parameter.Required == true, + DefaultValue = string.IsNullOrWhiteSpace(parameter.DefaultValue) ? null : parameter.DefaultValue.Trim(), + Choices = isChoice ? choices.GetValueOrDefault(parameter.Name!, []) : null, + }; + } +} diff --git a/web/Program.cs b/web/Program.cs index cb4838321..d8acc108f 100644 --- a/web/Program.cs +++ b/web/Program.cs @@ -40,6 +40,8 @@ using Viper.Areas.Effort.Services.Harvest; using Viper.Areas.Personnel; using Viper.Areas.RAPS.Services; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Services; using Viper.Classes; using Viper.Classes.HealthChecks; using Viper.Classes.Scheduler; @@ -62,7 +64,7 @@ } // Centralized SPA application names to avoid duplication -string[] VueAppNames = { "CAHFS", "ClinicalScheduler", "CMS", "Computing", "CTS", "Effort", "Students", "Personnel" }; +string[] VueAppNames = { "CAHFS", "ClinicalScheduler", "CMS", "Computing", "CTS", "Effort", "Students", "Personnel", "Reports" }; var builder = WebApplication.CreateBuilder(args); string awsCredentialsFilePath = Directory.GetCurrentDirectory() + "\\awscredentials.xml"; @@ -314,11 +316,18 @@ void RegisterDbContext(string connectionStringKey, Action("VIPER"); // Phone tables are in the VIPER database's [phones] schema. RegisterDbContext("VIPER"); + // Report Builder tables (and the views and procedures reports read) are in the VIPER database's [report] schema. + RegisterDbContext("VIPER"); RegisterDbContext("EvalHarvest"); // Register UserHelper service (must be before Scrutor to take precedence) builder.Services.AddScoped(); + // Report Builder: reads the [report] schema's shape. Not a *Service, so Scrutor skips it. + builder.Services.AddScoped(); + // Report Builder: runs report queries on VIPERReports (or VIPER). Not a *Service either. + builder.Services.AddScoped(); + // UserInfo feature: its EF contexts (equipment loans, ID cards, keys, PPS), // HttpClient factory, and service. See UserInfoServiceCollectionExtensions. builder.AddUserInfoServices(enableDetailedErrors); @@ -345,6 +354,7 @@ void RegisterDbContext(string connectionStringKey, Action type.Name.EndsWith("Service") || type.Name.EndsWith("Validator"))) diff --git a/web/appsettings.Development.json b/web/appsettings.Development.json index 293266c63..bd31f19df 100644 --- a/web/appsettings.Development.json +++ b/web/appsettings.Development.json @@ -16,6 +16,7 @@ "Effort": "", "EvalHarvest": "", "PhoneLists": "", + "PPS": "", "RAPS": "", "SIS": "", "VIPER": "" diff --git a/web/appsettings.Production.json b/web/appsettings.Production.json index 64612f34b..b105018d6 100644 --- a/web/appsettings.Production.json +++ b/web/appsettings.Production.json @@ -25,6 +25,7 @@ "Effort": "", "EvalHarvest": "", "PhoneLists": "", + "PPS": "", "RAPS": "", "SIS": "", "VIPER": "" diff --git a/web/appsettings.Test.json b/web/appsettings.Test.json index 564f85587..0064988b1 100644 --- a/web/appsettings.Test.json +++ b/web/appsettings.Test.json @@ -23,6 +23,7 @@ "Effort": "", "EvalHarvest": "", "PhoneLists": "", + "PPS": "", "RAPS": "", "SIS": "", "VIPER": ""