From 2616f032b7338080a70669375d1b2b03add3c0fe Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:26:09 -0700 Subject: [PATCH 01/12] Personnel reports and site-wide report builder --- .../__tests__/personnel-home.test.ts | 35 ++ .../__tests__/personnel-report.test.ts | 18 + VueApp/src/Personnel/pages/Home.vue | 5 + .../src/Personnel/pages/PersonnelReport.vue | 17 + VueApp/src/Personnel/router/routes.ts | 8 + VueApp/src/shared/reports/ReportCatalog.vue | 96 +++++ .../src/shared/reports/ReportGroupTable.vue | 65 ++++ .../src/shared/reports/ReportNumberTable.vue | 59 +++ .../shared/reports/ReportParameterForm.vue | 123 ++++++ VueApp/src/shared/reports/ReportRunner.vue | 124 ++++++ VueApp/src/shared/reports/ReportTotals.vue | 52 +++ VueApp/src/shared/reports/ReportView.vue | 86 +++++ .../reports/__tests__/report-catalog.test.ts | 141 +++++++ .../reports/__tests__/report-columns.test.ts | 81 ++++ .../reports/__tests__/report-fixtures.ts | 66 ++++ .../reports/__tests__/report-format.test.ts | 105 ++++++ .../__tests__/report-number-tables.test.ts | 24 ++ .../__tests__/report-parameter-form.test.ts | 139 +++++++ .../reports/__tests__/report-query.test.ts | 121 ++++++ .../reports/__tests__/report-runner.test.ts | 183 +++++++++ .../reports/__tests__/report-service.test.ts | 181 +++++++++ .../reports/__tests__/report-tables.test.ts | 98 +++++ .../reports/__tests__/report-tones.test.ts | 73 ++++ .../reports/__tests__/report-view.test.ts | 58 +++ .../reports/__tests__/use-report.test.ts | 220 +++++++++++ VueApp/src/shared/reports/report-columns.ts | 51 +++ VueApp/src/shared/reports/report-format.ts | 79 ++++ .../shared/reports/report-number-tables.ts | 39 ++ VueApp/src/shared/reports/report-query.ts | 85 +++++ VueApp/src/shared/reports/report-service.ts | 81 ++++ VueApp/src/shared/reports/report-tones.css | 23 ++ VueApp/src/shared/reports/report-tones.ts | 64 ++++ VueApp/src/shared/reports/report-types.ts | 153 ++++++++ VueApp/src/shared/reports/use-report.ts | 82 ++++ test/Personnel/EmployeesOnLeaveReportTests.cs | 93 +++++ test/Personnel/ExemptStatusReportTests.cs | 105 ++++++ test/Personnel/FacultyProfileReportTests.cs | 126 +++++++ test/Personnel/FacultyProfileRowsTests.cs | 75 ++++ test/Personnel/FiscalYearTests.cs | 19 + .../PersonnelReportDataServiceTests.cs | 161 ++++++++ test/Personnel/PersonnelTestDoubles.cs | 41 ++ .../Reports/Data/DataRecordExtensionsTests.cs | 105 ++++++ test/Reports/Data/FakeDb.cs | 166 ++++++++ .../Data/StoredProcedureParameterTests.cs | 43 +++ .../Data/StoredProcedureRunnerTests.cs | 85 +++++ test/Reports/ReportBuilderTests.cs | 248 ++++++++++++ test/Reports/ReportContextTests.cs | 70 ++++ test/Reports/ReportCsvExporterTests.cs | 76 ++++ test/Reports/ReportDefinitionContractTests.cs | 87 +++++ test/Reports/ReportDefinitionTests.cs | 263 +++++++++++++ test/Reports/ReportDescribeParametersTests.cs | 73 ++++ test/Reports/ReportExcelExporterTests.cs | 194 ++++++++++ test/Reports/ReportExportTestData.cs | 98 +++++ test/Reports/ReportExportTextTests.cs | 119 ++++++ test/Reports/ReportKeyTests.cs | 35 ++ test/Reports/ReportLayoutBuilderTests.cs | 157 ++++++++ test/Reports/ReportMeasureTests.cs | 90 +++++ test/Reports/ReportParameterBinderTests.cs | 107 ++++++ test/Reports/ReportPdfExporterTests.cs | 61 +++ test/Reports/ReportPipelineTests.cs | 264 +++++++++++++ test/Reports/ReportRegistryTests.cs | 156 ++++++++ test/Reports/ReportRunTests.cs | 45 +++ test/Reports/ReportServiceTests.cs | 283 ++++++++++++++ test/Reports/ReportTestDoubles.cs | 105 ++++++ test/Reports/ReportTestFixtures.cs | 169 +++++++++ test/Reports/ReportUserServiceTests.cs | 41 ++ test/Reports/ReportValueFormatterTests.cs | 113 ++++++ test/Reports/ReportsControllerTests.cs | 195 ++++++++++ test/Reports/ReportsRegistrationTests.cs | 61 +++ .../Personnel/Models/EmployeeOnLeaveRow.cs | 12 + .../Personnel/Models/FacultyAppointmentRow.cs | 13 + web/Areas/Personnel/Models/FlsaEmployeeRow.cs | 13 + web/Areas/Personnel/PersonnelDatabases.cs | 12 + web/Areas/Personnel/PersonnelPermissions.cs | 13 + .../Reports/EmployeesOnLeaveReport.cs | 77 ++++ .../Personnel/Reports/ExemptStatusReport.cs | 82 ++++ .../Personnel/Reports/FacultyProfileReport.cs | 92 +++++ .../Personnel/Reports/FacultyProfileRows.cs | 94 +++++ web/Areas/Personnel/Reports/FiscalYear.cs | 20 + .../Personnel/Reports/PersonnelOptions.cs | 29 ++ .../Personnel/Reports/PersonnelReports.cs | 12 + .../Services/PersonnelReportDataService.cs | 124 ++++++ .../Reports/Controllers/ReportsController.cs | 91 +++++ .../Reports/Data/DataRecordExtensions.cs | 49 +++ web/Areas/Reports/Data/DbConnectionFactory.cs | 44 +++ .../Reports/Data/StoredProcedureParameter.cs | 60 +++ .../Reports/Data/StoredProcedureRunner.cs | 65 ++++ web/Areas/Reports/Engine/PlannedReport.cs | 38 ++ .../Reports/Engine/ReportBuilder.Layout.cs | 209 ++++++++++ web/Areas/Reports/Engine/ReportBuilder.cs | 131 +++++++ web/Areas/Reports/Engine/ReportColumn.cs | 106 ++++++ web/Areas/Reports/Engine/ReportContext.cs | 30 ++ web/Areas/Reports/Engine/ReportDefinition.cs | 155 ++++++++ web/Areas/Reports/Engine/ReportExpressions.cs | 43 +++ web/Areas/Reports/Engine/ReportFilter.cs | 7 + web/Areas/Reports/Engine/ReportKey.cs | 42 +++ web/Areas/Reports/Engine/ReportLayoutRules.cs | 140 +++++++ web/Areas/Reports/Engine/ReportMeasure.cs | 64 ++++ web/Areas/Reports/Engine/ReportMetadata.cs | 85 +++++ web/Areas/Reports/Engine/ReportParameter.cs | 151 ++++++++ .../Reports/Engine/ReportParameterBinder.cs | 77 ++++ web/Areas/Reports/Engine/ReportPipeline.cs | 157 ++++++++ web/Areas/Reports/Engine/ReportRegistry.cs | 101 +++++ web/Areas/Reports/Engine/ReportResult.cs | 87 +++++ .../Reports/Engine/ReportValueFormatter.cs | 79 ++++ .../Reports/Exporters/ReportCsvExporter.cs | 89 +++++ .../Reports/Exporters/ReportExcelExporter.cs | 357 ++++++++++++++++++ web/Areas/Reports/Exporters/ReportExport.cs | 135 +++++++ .../Reports/Exporters/ReportPdfExporter.cs | 333 ++++++++++++++++ .../ReportsServiceCollectionExtensions.cs | 41 ++ web/Areas/Reports/Services/ReportOutcome.cs | 49 +++ web/Areas/Reports/Services/ReportService.cs | 199 ++++++++++ .../Reports/Services/ReportUserService.cs | 37 ++ web/Program.cs | 5 + web/appsettings.Development.json | 1 + web/appsettings.Production.json | 1 + web/appsettings.Test.json | 1 + 117 files changed, 10816 insertions(+) create mode 100644 VueApp/src/Personnel/__tests__/personnel-home.test.ts create mode 100644 VueApp/src/Personnel/__tests__/personnel-report.test.ts create mode 100644 VueApp/src/Personnel/pages/PersonnelReport.vue create mode 100644 VueApp/src/shared/reports/ReportCatalog.vue create mode 100644 VueApp/src/shared/reports/ReportGroupTable.vue create mode 100644 VueApp/src/shared/reports/ReportNumberTable.vue create mode 100644 VueApp/src/shared/reports/ReportParameterForm.vue create mode 100644 VueApp/src/shared/reports/ReportRunner.vue create mode 100644 VueApp/src/shared/reports/ReportTotals.vue create mode 100644 VueApp/src/shared/reports/ReportView.vue create mode 100644 VueApp/src/shared/reports/__tests__/report-catalog.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-columns.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-fixtures.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-format.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-number-tables.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-query.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-runner.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-service.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-tables.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-tones.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/report-view.test.ts create mode 100644 VueApp/src/shared/reports/__tests__/use-report.test.ts create mode 100644 VueApp/src/shared/reports/report-columns.ts create mode 100644 VueApp/src/shared/reports/report-format.ts create mode 100644 VueApp/src/shared/reports/report-number-tables.ts create mode 100644 VueApp/src/shared/reports/report-query.ts create mode 100644 VueApp/src/shared/reports/report-service.ts create mode 100644 VueApp/src/shared/reports/report-tones.css create mode 100644 VueApp/src/shared/reports/report-tones.ts create mode 100644 VueApp/src/shared/reports/report-types.ts create mode 100644 VueApp/src/shared/reports/use-report.ts create mode 100644 test/Personnel/EmployeesOnLeaveReportTests.cs create mode 100644 test/Personnel/ExemptStatusReportTests.cs create mode 100644 test/Personnel/FacultyProfileReportTests.cs create mode 100644 test/Personnel/FacultyProfileRowsTests.cs create mode 100644 test/Personnel/FiscalYearTests.cs create mode 100644 test/Personnel/PersonnelReportDataServiceTests.cs create mode 100644 test/Personnel/PersonnelTestDoubles.cs create mode 100644 test/Reports/Data/DataRecordExtensionsTests.cs create mode 100644 test/Reports/Data/FakeDb.cs create mode 100644 test/Reports/Data/StoredProcedureParameterTests.cs create mode 100644 test/Reports/Data/StoredProcedureRunnerTests.cs create mode 100644 test/Reports/ReportBuilderTests.cs create mode 100644 test/Reports/ReportContextTests.cs create mode 100644 test/Reports/ReportCsvExporterTests.cs create mode 100644 test/Reports/ReportDefinitionContractTests.cs create mode 100644 test/Reports/ReportDefinitionTests.cs create mode 100644 test/Reports/ReportDescribeParametersTests.cs create mode 100644 test/Reports/ReportExcelExporterTests.cs create mode 100644 test/Reports/ReportExportTestData.cs create mode 100644 test/Reports/ReportExportTextTests.cs create mode 100644 test/Reports/ReportKeyTests.cs create mode 100644 test/Reports/ReportLayoutBuilderTests.cs create mode 100644 test/Reports/ReportMeasureTests.cs create mode 100644 test/Reports/ReportParameterBinderTests.cs create mode 100644 test/Reports/ReportPdfExporterTests.cs create mode 100644 test/Reports/ReportPipelineTests.cs create mode 100644 test/Reports/ReportRegistryTests.cs create mode 100644 test/Reports/ReportRunTests.cs create mode 100644 test/Reports/ReportServiceTests.cs create mode 100644 test/Reports/ReportTestDoubles.cs create mode 100644 test/Reports/ReportTestFixtures.cs create mode 100644 test/Reports/ReportUserServiceTests.cs create mode 100644 test/Reports/ReportValueFormatterTests.cs create mode 100644 test/Reports/ReportsControllerTests.cs create mode 100644 test/Reports/ReportsRegistrationTests.cs create mode 100644 web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs create mode 100644 web/Areas/Personnel/Models/FacultyAppointmentRow.cs create mode 100644 web/Areas/Personnel/Models/FlsaEmployeeRow.cs create mode 100644 web/Areas/Personnel/PersonnelDatabases.cs create mode 100644 web/Areas/Personnel/PersonnelPermissions.cs create mode 100644 web/Areas/Personnel/Reports/EmployeesOnLeaveReport.cs create mode 100644 web/Areas/Personnel/Reports/ExemptStatusReport.cs create mode 100644 web/Areas/Personnel/Reports/FacultyProfileReport.cs create mode 100644 web/Areas/Personnel/Reports/FacultyProfileRows.cs create mode 100644 web/Areas/Personnel/Reports/FiscalYear.cs create mode 100644 web/Areas/Personnel/Reports/PersonnelOptions.cs create mode 100644 web/Areas/Personnel/Reports/PersonnelReports.cs create mode 100644 web/Areas/Personnel/Services/PersonnelReportDataService.cs create mode 100644 web/Areas/Reports/Controllers/ReportsController.cs create mode 100644 web/Areas/Reports/Data/DataRecordExtensions.cs create mode 100644 web/Areas/Reports/Data/DbConnectionFactory.cs create mode 100644 web/Areas/Reports/Data/StoredProcedureParameter.cs create mode 100644 web/Areas/Reports/Data/StoredProcedureRunner.cs create mode 100644 web/Areas/Reports/Engine/PlannedReport.cs create mode 100644 web/Areas/Reports/Engine/ReportBuilder.Layout.cs create mode 100644 web/Areas/Reports/Engine/ReportBuilder.cs create mode 100644 web/Areas/Reports/Engine/ReportColumn.cs create mode 100644 web/Areas/Reports/Engine/ReportContext.cs create mode 100644 web/Areas/Reports/Engine/ReportDefinition.cs create mode 100644 web/Areas/Reports/Engine/ReportExpressions.cs create mode 100644 web/Areas/Reports/Engine/ReportFilter.cs create mode 100644 web/Areas/Reports/Engine/ReportKey.cs create mode 100644 web/Areas/Reports/Engine/ReportLayoutRules.cs create mode 100644 web/Areas/Reports/Engine/ReportMeasure.cs create mode 100644 web/Areas/Reports/Engine/ReportMetadata.cs create mode 100644 web/Areas/Reports/Engine/ReportParameter.cs create mode 100644 web/Areas/Reports/Engine/ReportParameterBinder.cs create mode 100644 web/Areas/Reports/Engine/ReportPipeline.cs create mode 100644 web/Areas/Reports/Engine/ReportRegistry.cs create mode 100644 web/Areas/Reports/Engine/ReportResult.cs create mode 100644 web/Areas/Reports/Engine/ReportValueFormatter.cs create mode 100644 web/Areas/Reports/Exporters/ReportCsvExporter.cs create mode 100644 web/Areas/Reports/Exporters/ReportExcelExporter.cs create mode 100644 web/Areas/Reports/Exporters/ReportExport.cs create mode 100644 web/Areas/Reports/Exporters/ReportPdfExporter.cs create mode 100644 web/Areas/Reports/ReportsServiceCollectionExtensions.cs create mode 100644 web/Areas/Reports/Services/ReportOutcome.cs create mode 100644 web/Areas/Reports/Services/ReportService.cs create mode 100644 web/Areas/Reports/Services/ReportUserService.cs 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..93dd31a8e --- /dev/null +++ b/VueApp/src/Personnel/__tests__/personnel-home.test.ts @@ -0,0 +1,35 @@ +import { mount } from "@vue/test-utils" +import { createMemoryHistory, createRouter } from "vue-router" +import Home from "../pages/Home.vue" +import { routes } from "../router/routes" + +/** + * The Personnel home page shows its CMS content and the Personnel report catalog, whose links + * go to the PersonnelReport route. + */ + +describe("personnel home page", () => { + it("shows the CMS content and the Personnel reports", () => { + const wrapper = mount(Home, { + global: { stubs: { CmsContent: true, ReportCatalog: true } }, + }) + + expect(wrapper.findComponent({ name: "CmsContent" }).props("contentName")).toBe("personnel-home") + const catalog = wrapper.findComponent({ name: "ReportCatalog" }) + expect(catalog.props("area")).toBe("Personnel") + expect(catalog.props("reportRoute")).toBe("PersonnelReport") + }) +}) + +describe("personnel report route", () => { + it("resolves a report key to the PersonnelReport route", () => { + const router = createRouter({ history: createMemoryHistory(), routes }) + const resolved = router.resolve({ + name: "PersonnelReport", + params: { key: "personnel.faculty-profile" }, + }) + + expect(resolved.path).toBe("/Personnel/Reports/personnel.faculty-profile") + expect(resolved.meta.allowUnAuth).toBeFalsy() + }) +}) diff --git a/VueApp/src/Personnel/__tests__/personnel-report.test.ts b/VueApp/src/Personnel/__tests__/personnel-report.test.ts new file mode 100644 index 000000000..c2b7e90bd --- /dev/null +++ b/VueApp/src/Personnel/__tests__/personnel-report.test.ts @@ -0,0 +1,18 @@ +import { mount } from "@vue/test-utils" +import PersonnelReport from "../pages/PersonnelReport.vue" + +vi.mock("vue-router", () => ({ + useRoute: () => ({ params: { key: "personnel.visa-audit" } }), +})) + +describe("personnel report page", () => { + it("runs the report named by the route, with a breadcrumb back to Personnel", () => { + expect.hasAssertions() + const wrapper = mount(PersonnelReport, { global: { stubs: { ReportRunner: true } } }) + const runner = wrapper.findComponent({ name: "ReportRunner" }) + + expect(runner.props("reportKey")).toBe("personnel.visa-audit") + expect(runner.props("parentLabel")).toBe("Personnel") + expect(runner.props("parentTo")).toStrictEqual({ name: "PersonnelHome" }) + }) +}) diff --git a/VueApp/src/Personnel/pages/Home.vue b/VueApp/src/Personnel/pages/Home.vue index a7254de06..0f8f24f61 100644 --- a/VueApp/src/Personnel/pages/Home.vue +++ b/VueApp/src/Personnel/pages/Home.vue @@ -1,6 +1,11 @@ diff --git a/VueApp/src/Personnel/pages/PersonnelReport.vue b/VueApp/src/Personnel/pages/PersonnelReport.vue new file mode 100644 index 000000000..907b9a8e0 --- /dev/null +++ b/VueApp/src/Personnel/pages/PersonnelReport.vue @@ -0,0 +1,17 @@ + + + diff --git a/VueApp/src/Personnel/router/routes.ts b/VueApp/src/Personnel/router/routes.ts index 9de63e03c..d40168387 100644 --- a/VueApp/src/Personnel/router/routes.ts +++ b/VueApp/src/Personnel/router/routes.ts @@ -47,6 +47,14 @@ const routes = [ component: () => import("@/Personnel/pages/SVMPhonesMaintain.vue"), name: "MaintainSchoolwidePhones", }, + { + // Any Personnel report, by key. The API enforces each report's own permissions, so the + // route needs none of its own; a report the user can't run shows as not available. + path: "/Personnel/Reports/:key", + meta: { layout: ViperLayout, allowUnAuth: false }, + component: () => import("@/Personnel/pages/PersonnelReport.vue"), + name: "PersonnelReport", + }, { path: "/:catchAll(.*)*", meta: { layout: ViperLayout }, diff --git a/VueApp/src/shared/reports/ReportCatalog.vue b/VueApp/src/shared/reports/ReportCatalog.vue new file mode 100644 index 000000000..dad018cc5 --- /dev/null +++ b/VueApp/src/shared/reports/ReportCatalog.vue @@ -0,0 +1,96 @@ + + + diff --git a/VueApp/src/shared/reports/ReportGroupTable.vue b/VueApp/src/shared/reports/ReportGroupTable.vue new file mode 100644 index 000000000..5b1c456f4 --- /dev/null +++ b/VueApp/src/shared/reports/ReportGroupTable.vue @@ -0,0 +1,65 @@ + + + + + diff --git a/VueApp/src/shared/reports/ReportNumberTable.vue b/VueApp/src/shared/reports/ReportNumberTable.vue new file mode 100644 index 000000000..714437083 --- /dev/null +++ b/VueApp/src/shared/reports/ReportNumberTable.vue @@ -0,0 +1,59 @@ + + + diff --git a/VueApp/src/shared/reports/ReportParameterForm.vue b/VueApp/src/shared/reports/ReportParameterForm.vue new file mode 100644 index 000000000..df4d028cc --- /dev/null +++ b/VueApp/src/shared/reports/ReportParameterForm.vue @@ -0,0 +1,123 @@ + + + diff --git a/VueApp/src/shared/reports/ReportRunner.vue b/VueApp/src/shared/reports/ReportRunner.vue new file mode 100644 index 000000000..ae2da367a --- /dev/null +++ b/VueApp/src/shared/reports/ReportRunner.vue @@ -0,0 +1,124 @@ + + + diff --git a/VueApp/src/shared/reports/ReportTotals.vue b/VueApp/src/shared/reports/ReportTotals.vue new file mode 100644 index 000000000..0878b231d --- /dev/null +++ b/VueApp/src/shared/reports/ReportTotals.vue @@ -0,0 +1,52 @@ + + + + + diff --git a/VueApp/src/shared/reports/ReportView.vue b/VueApp/src/shared/reports/ReportView.vue new file mode 100644 index 000000000..0ee0e5e73 --- /dev/null +++ b/VueApp/src/shared/reports/ReportView.vue @@ -0,0 +1,86 @@ + + + diff --git a/VueApp/src/shared/reports/__tests__/report-catalog.test.ts b/VueApp/src/shared/reports/__tests__/report-catalog.test.ts new file mode 100644 index 000000000..d06b472cb --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-catalog.test.ts @@ -0,0 +1,141 @@ +import { flushPromises, mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import { createMemoryHistory, createRouter } from "vue-router" +import ReportCatalog from "../ReportCatalog.vue" +import { reportService } from "../report-service" +import type { ReportCatalogItem } from "../report-types" + +/** + * ReportCatalog lists an area's reports as links to the area's report route. It stays visible + * while loading and after a failed load, but disappears for a user who may run none of the + * area's reports. + */ + +vi.mock("../report-service", () => ({ + reportService: { getCatalog: vi.fn<(...args: unknown[]) => unknown>() }, +})) + +const built: ReportCatalogItem = { + key: "personnel.employees-on-leave", + title: "Employees on Leave", + area: "Personnel", + description: "Faculty and staff on leave.", + available: true, +} + +const planned: ReportCatalogItem = { + key: "personnel.visa-audit", + title: "Visa Audit", + area: "Personnel", + description: "Visa types and end dates.", + available: false, +} + +// Never resolves, to hold the component in its loading state. +function neverResolves(): Promise { + // eslint-disable-next-line avoid-new, no-empty-function -- deliberately pending forever, to simulate an in-flight fetch + return new Promise(() => {}) +} + +async function mountCatalog(props: Record = {}) { + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: "/", component: { template: "
" } }, + { path: "/reports/:key", component: { template: "
" }, name: "TestReport" }, + ], + }) + await router.push("/") + const wrapper = mount(ReportCatalog, { + props: { area: "Personnel", reportRoute: "TestReport", ...props }, + global: { plugins: [[Quasar, {}], router] }, + }) + await flushPromises() + return wrapper +} + +describe("ReportCatalog", () => { + it("asks for the catalog of its area", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockResolvedValue([]) + + await mountCatalog({ area: "Effort" }) + + expect(reportService.getCatalog).toHaveBeenCalledWith("Effort") + }) + + it("links each report to the area's report route", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockResolvedValue([built, planned]) + + const wrapper = await mountCatalog() + const links = wrapper.findAll("a") + + expect(links.map((link) => link.attributes("href"))).toStrictEqual([ + "/reports/personnel.employees-on-leave", + "/reports/personnel.visa-audit", + ]) + expect(links.map((link) => link.attributes("role"))).toStrictEqual(["link", "link"]) + expect(links[0]?.text()).toContain("Faculty and staff on leave.") + }) + + it("marks only planned reports as coming soon", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockResolvedValue([built, planned]) + + const wrapper = await mountCatalog() + const links = wrapper.findAll("a") + + expect(links[0]?.text()).not.toContain("Coming soon") + expect(links[1]?.text()).toContain("Coming soon") + }) + + it("labels the section with its heading", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockResolvedValue([built]) + + const wrapper = await mountCatalog({ heading: "Personnel reports" }) + const heading = wrapper.get("h2") + + expect(heading.text()).toBe("Personnel reports") + expect(wrapper.get("section").attributes("aria-labelledby")).toBe(heading.attributes("id")) + }) + + it("uses a default heading", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockResolvedValue([built]) + + const wrapper = await mountCatalog() + + expect(wrapper.get("h2").text()).toBe("Reports") + }) + + it("announces that it is loading until the catalog arrives", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockReturnValue(neverResolves()) + + const wrapper = await mountCatalog() + + expect(wrapper.get("[role='status']").text()).toBe("Loading reports") + expect(wrapper.find("a").exists()).toBeFalsy() + }) + + it("reports a failed load instead of hiding", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockResolvedValue(null) + + const wrapper = await mountCatalog() + + expect(wrapper.find("h2").exists()).toBeTruthy() + expect(wrapper.text()).toContain("The report list could not be loaded.") + }) + + it("renders nothing when the user may run none of the area's reports", async () => { + expect.hasAssertions() + vi.mocked(reportService.getCatalog).mockResolvedValue([]) + + const wrapper = await mountCatalog() + + expect(wrapper.find("section").exists()).toBeFalsy() + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-columns.test.ts b/VueApp/src/shared/reports/__tests__/report-columns.test.ts new file mode 100644 index 000000000..31563c7fe --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-columns.test.ts @@ -0,0 +1,81 @@ +import { NOTES_COLUMN, ROW_NUMBER_COLUMN, hasNotes, toTableColumns } from "../report-columns" +import type { ReportResult, ReportRowResult } from "../report-types" + +const ada: ReportRowResult = { + number: 1, + values: { name: "Ada", salary: 120_000 }, + flags: [{ kind: "Highlight", tone: "Warning", label: "60+", columnKey: null }], +} +const bo: ReportRowResult = { number: 2, values: { name: "Bo" }, flags: [] } + +function resultWith(rows: ReportRowResult[], rowNumbers = false): ReportResult { + return { + key: "test.sample", + title: "Sample", + generatedAt: "2026-09-30T14:00:00-07:00", + rowCount: rows.length, + rowNumbers, + columns: [ + { key: "name", label: "Name", format: "Text", align: "Left", decimals: null }, + { key: "salary", label: "Salary", format: "Currency", align: "Right", decimals: 2 }, + ], + summary: [], + groups: [{ label: null, rows, subtotals: [], charts: [] }], + totals: [], + pivots: [], + charts: [], + } +} + +describe("toTableColumns()", () => { + it("maps each report column to a sortable table column", () => { + const [name, salary] = toTableColumns(resultWith([bo])) + + expect(name).toMatchObject({ name: "name", label: "Name", align: "left", sortable: true }) + expect(salary).toMatchObject({ name: "salary", label: "Salary", align: "right" }) + }) + + it("reads values by column key, treating missing values as empty", () => { + const [name, salary] = toTableColumns(resultWith([bo])) + const readName = name?.field as (row: ReportRowResult) => unknown + const readSalary = salary?.field as (row: ReportRowResult) => unknown + + expect(readName(ada)).toBe("Ada") + expect(readSalary(bo)).toBeNull() + }) + + it("formats values like the exports", () => { + const [, salary] = toTableColumns(resultWith([bo])) + + expect(salary?.format?.(120_000, ada)).toBe("$120,000.00") + }) + + it("adds a row number column first when the report numbers its rows", () => { + const columns = toTableColumns(resultWith([bo], true)) + const [numberColumn] = columns + const readNumber = numberColumn?.field as (row: ReportRowResult) => unknown + + expect(numberColumn).toMatchObject({ name: ROW_NUMBER_COLUMN, label: "#", align: "right" }) + expect(readNumber(bo)).toBe(2) + }) + + it("adds a Notes column last when any row has a flag", () => { + const columns = toTableColumns(resultWith([ada, bo])) + const notes = columns.at(-1) + const readNotes = notes?.field as (row: ReportRowResult) => unknown + + expect(notes).toMatchObject({ name: NOTES_COLUMN, label: "Notes" }) + expect(readNotes(ada)).toBe("60+") + }) + + it("leaves out the extra columns when they aren't needed", () => { + expect(toTableColumns(resultWith([bo])).map((column) => column.name)).toStrictEqual(["name", "salary"]) + }) +}) + +describe("hasNotes()", () => { + it("is true only when a row has a flag", () => { + expect(hasNotes(resultWith([bo, ada]))).toBeTruthy() + expect(hasNotes(resultWith([bo]))).toBeFalsy() + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-fixtures.ts b/VueApp/src/shared/reports/__tests__/report-fixtures.ts new file mode 100644 index 000000000..20fa2fdf0 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-fixtures.ts @@ -0,0 +1,66 @@ +import type { + ReportChartResult, + ReportGroupResult, + ReportPivotResult, + ReportResult, + ReportRowResult, +} from "../report-types" + +/** A small grouped result with every kind of section, shared by the component tests. */ + +const ada: ReportRowResult = { + number: 1, + values: { name: "Ada", salary: 120_000, hired: "1995-07-01" }, + flags: [ + { kind: "Highlight", tone: "Warning", label: "60+", columnKey: null }, + { kind: "Badge", tone: "Info", label: "Emeritus", columnKey: null }, + ], +} + +const bo: ReportRowResult = { + number: 2, + values: { name: "Bo", salary: 90_000, hired: null }, + flags: [{ kind: "Highlight", tone: "Negative", label: "Retirement age", columnKey: "salary" }], +} + +const vmeGroup: ReportGroupResult = { + label: "VME", + rows: [ada, bo], + subtotals: [{ label: "Salaries", columnKey: "salary", value: 210_000 }], + charts: [{ title: "Ages: VME", kind: "Bar", points: [{ category: "60+", value: 1 }] }], +} + +const samplePivot: ReportPivotResult = { + title: "Age by department", + columnKeys: ["APC", "VME"], + rows: [{ key: "60+", values: [0, 1], total: 1 }], + columnTotals: [1, 2], + grandTotal: 3, +} + +const sampleChart: ReportChartResult = { title: "Ages", kind: "Pie", points: [{ category: "Under 30", value: 2 }] } + +const cy: ReportRowResult = { number: 3, values: { name: "Cy", salary: 150_000, hired: "2010-01-15" }, flags: [] } + +function sampleResult(overrides: Partial = {}): ReportResult { + return { + key: "test.sample", + title: "Sample report", + generatedAt: "2026-09-30T14:05:00", + rowCount: 3, + rowNumbers: true, + columns: [ + { key: "name", label: "Name", format: "Text", align: "Left", decimals: null }, + { key: "salary", label: "Salary", format: "Currency", align: "Right", decimals: 2 }, + { key: "hired", label: "Hired", format: "Date", align: "Left", decimals: null }, + ], + summary: [{ label: "People", columnKey: null, value: 3 }], + groups: [vmeGroup, { label: "APC", rows: [cy], subtotals: [], charts: [] }], + totals: [{ label: "All salaries", columnKey: "salary", value: 360_000 }], + pivots: [samplePivot], + charts: [sampleChart], + ...overrides, + } +} + +export { ada, bo, cy, sampleChart, samplePivot, sampleResult, vmeGroup } diff --git a/VueApp/src/shared/reports/__tests__/report-format.test.ts b/VueApp/src/shared/reports/__tests__/report-format.test.ts new file mode 100644 index 000000000..a5324684b --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-format.test.ts @@ -0,0 +1,105 @@ +import { + formatGeneratedAt, + formatPlainNumber, + formatReportDate, + formatReportTotal, + formatReportValue, + isNumericFormat, +} from "../report-format" +import type { ReportColumnFormat, ReportColumnMetadata } from "../report-types" + +/** + * These cases mirror ReportValueFormatterTests and ReportExportTextTests on the server, so the + * screen shows values the same way the CSV and PDF exports do. + */ + +function column(format: ReportColumnFormat, decimals: number | null = null, key = "value"): ReportColumnMetadata { + return { key, label: "Value", format, align: "Right", decimals } +} + +describe("formatReportValue()", () => { + it.each([ + [1234.5, column("Number"), "1,235"], + [1234.5, column("Number", 2), "1,234.50"], + [120_000, column("Currency", 2), "$120,000.00"], + [0.125, column("Percent", 1), "12.5%"], + [0.5, column("Percent"), "50%"], + [61, column("Text"), "61"], + ])("formats the number %s for a %o column as %s", (value, format, expected) => { + expect(formatReportValue(value, format)).toBe(expected) + }) + + it.each([ + [null, ""], + [undefined, ""], + [["Asian", "White"], "Asian, White"], + [true, "Yes"], + [false, "No"], + ["pending", "pending"], + ])("formats %o as %o", (value, expected) => { + expect(formatReportValue(value, column("Text"))).toBe(expected) + }) + + it("formats dates only in date columns", () => { + expect(formatReportValue("2026-07-01", column("Date"))).toBe("07/01/2026") + expect(formatReportValue("2026-07-01", column("Text"))).toBe("2026-07-01") + }) +}) + +describe("formatReportDate()", () => { + it.each([ + ["2026-07-01", "07/01/2026"], + ["1995-07-01T00:00:00", "07/01/1995"], + ["not a date", "not a date"], + ])("formats %s as %s", (value, expected) => { + expect(formatReportDate(value)).toBe(expected) + }) +}) + +describe("formatReportTotal()", () => { + const columns = [column("Currency", 2, "salary"), column("Text", null, "name")] + + it("formats a total like the column it sits under", () => { + expect(formatReportTotal({ label: "Salaries", columnKey: "salary", value: 430_000 }, columns)).toBe( + "$430,000.00", + ) + expect(formatReportTotal({ label: "People", columnKey: "name", value: 5 }, columns)).toBe("5") + }) + + it("formats a total without a column as a plain number", () => { + expect(formatReportTotal({ label: "Average age", columnKey: null, value: 48.256 }, columns)).toBe("48.26") + expect(formatReportTotal({ label: "Hidden", columnKey: "ssn", value: 1234 }, columns)).toBe("1,234") + }) + + it("leaves a missing total blank", () => { + expect(formatReportTotal({ label: "Unknown", columnKey: "salary", value: null }, columns)).toBe("") + }) +}) + +describe("formatPlainNumber()", () => { + it("uses separators and up to two decimals, and blanks null", () => { + expect(formatPlainNumber(1234.5)).toBe("1,234.5") + expect(formatPlainNumber(null)).toBe("") + }) +}) + +describe("isNumericFormat()", () => { + it.each([ + ["Number", true], + ["Currency", true], + ["Percent", true], + ["Text", false], + ["Date", false], + ["List", false], + ] as const)("treats %s as numeric: %s", (format, expected) => { + expect(isNumericFormat(format)).toBe(expected) + }) +}) + +describe("formatGeneratedAt()", () => { + it("matches the export header wording", () => { + const local = new Date(2026, 8, 30, 14, 5) + + expect(formatGeneratedAt(local.toISOString())).toBe("Generated 09/30/2026 2:05 PM") + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-number-tables.test.ts b/VueApp/src/shared/reports/__tests__/report-number-tables.test.ts new file mode 100644 index 000000000..662191207 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-number-tables.test.ts @@ -0,0 +1,24 @@ +import { chartTable, pivotTable } from "../report-number-tables" +import { sampleChart, samplePivot } from "./report-fixtures" + +describe("pivotTable()", () => { + it("adds a total to every row and a totals row, as the PDF export does", () => { + expect.hasAssertions() + expect(pivotTable(samplePivot)).toStrictEqual({ + headers: ["Category", "APC", "VME", "Total"], + rows: [{ label: "60+", values: [0, 1, 1] }], + total: { label: "Total", values: [1, 2, 3] }, + }) + }) +}) + +describe("chartTable()", () => { + it("lists each chart point as a category and value", () => { + expect.hasAssertions() + expect(chartTable(sampleChart)).toStrictEqual({ + headers: ["Category", "Value"], + rows: [{ label: "Under 30", values: [2] }], + total: null, + }) + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts b/VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts new file mode 100644 index 000000000..e8f2074cc --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts @@ -0,0 +1,139 @@ +import { flushPromises, mount } from "@vue/test-utils" +import { QSelect, Quasar } from "quasar" +import ReportParameterForm from "../ReportParameterForm.vue" +import type { ReportParameterMetadata, ReportParameterType, ReportParameterValues } from "../report-types" + +function parameter(name: string, type: ReportParameterType, required = false): ReportParameterMetadata { + return { + name, + label: name, + type, + required, + defaultValue: null, + options: [ + { value: "S", label: "Senate" }, + { value: "F", label: "Federation" }, + ], + } +} + +const parameters = [ + parameter("facultyType", "Choice", true), + parameter("departments", "MultiChoice"), + parameter("startDate", "Date"), + parameter("search", "Text"), + parameter("minimumAge", "Number"), + parameter("includeEmeriti", "Boolean"), +] + +const empty: ReportParameterValues = { + facultyType: null, + departments: [], + startDate: null, + search: null, + minimumAge: null, + includeEmeriti: null, +} + +function mountForm(modelValue: ReportParameterValues = empty) { + return mount(ReportParameterForm, { + props: { parameters, modelValue, running: false }, + global: { plugins: [[Quasar, {}]] }, + }) +} + +function lastModel(wrapper: ReturnType): ReportParameterValues | undefined { + return wrapper.emitted("update:modelValue")?.at(-1)?.[0] as ReportParameterValues | undefined +} + +describe("ReportParameterForm", () => { + it("renders an input for each parameter type", () => { + expect.hasAssertions() + const wrapper = mountForm() + + expect(wrapper.findAll(".q-select")).toHaveLength(2) + expect(wrapper.find("input[type='date']").exists()).toBeTruthy() + expect(wrapper.find("input[type='text']").exists()).toBeTruthy() + expect(wrapper.find("input[type='number']").exists()).toBeTruthy() + expect(wrapper.find(".q-checkbox").exists()).toBeTruthy() + }) + + it("marks required fields in their labels", () => { + expect.hasAssertions() + const wrapper = mountForm() + + expect(wrapper.text()).toContain("facultyType *") + expect(wrapper.text()).not.toContain("search *") + }) + + it("shows the current text, date and number values", () => { + expect.hasAssertions() + const wrapper = mountForm({ ...empty, startDate: "2026-07-01", search: "smith", minimumAge: 60 }) + + expect((wrapper.get("input[type='date']").element as HTMLInputElement).value).toBe("2026-07-01") + expect((wrapper.get("input[type='text']").element as HTMLInputElement).value).toBe("smith") + expect((wrapper.get("input[type='number']").element as HTMLInputElement).value).toBe("60") + }) + + it("stores numbers as numbers and cleared inputs as null", async () => { + expect.hasAssertions() + const wrapper = mountForm() + const input = wrapper.get("input[type='number']") + + await input.setValue("60") + expect(lastModel(wrapper)?.minimumAge).toBe(60) + await input.setValue("") + expect(lastModel(wrapper)?.minimumAge).toBeNull() + }) + + it("keeps text and dates as strings", async () => { + expect.hasAssertions() + const wrapper = mountForm() + + await wrapper.get("input[type='date']").setValue("2026-07-01") + expect(lastModel(wrapper)?.startDate).toBe("2026-07-01") + await wrapper.get("input[type='text']").setValue("smith") + expect(lastModel(wrapper)?.search).toBe("smith") + }) + + it("stores the chosen options of a select", () => { + expect.hasAssertions() + const wrapper = mountForm() + const [choice, multiChoice] = wrapper.findAllComponents(QSelect) + + choice?.vm.$emit("update:modelValue", "F") + expect(lastModel(wrapper)?.facultyType).toBe("F") + multiChoice?.vm.$emit("update:modelValue", ["S", "F"]) + expect(lastModel(wrapper)?.departments).toStrictEqual(["S", "F"]) + }) + + it("updates a checkbox value without losing the others", async () => { + expect.hasAssertions() + const wrapper = mountForm({ ...empty, search: "smith" }) + + await wrapper.get(".q-checkbox").trigger("click") + + expect(lastModel(wrapper)).toStrictEqual({ ...empty, search: "smith", includeEmeriti: true }) + }) + + it("blocks submitting until required fields are filled", async () => { + expect.hasAssertions() + const wrapper = mountForm() + + await wrapper.get("form").trigger("submit") + await flushPromises() + + expect(wrapper.emitted("submit")).toBeUndefined() + expect(wrapper.text()).toContain("facultyType is required.") + }) + + it("submits when the required fields are filled", async () => { + expect.hasAssertions() + const wrapper = mountForm({ ...empty, facultyType: "S" }) + + await wrapper.get("form").trigger("submit") + await flushPromises() + + expect(wrapper.emitted("submit")).toHaveLength(1) + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-query.test.ts b/VueApp/src/shared/reports/__tests__/report-query.test.ts new file mode 100644 index 000000000..80a206064 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-query.test.ts @@ -0,0 +1,121 @@ +import { hasQueryParameters, initialValues, toQuery, toRequestBody } from "../report-query" +import type { ReportParameterMetadata, ReportParameterType, ReportParameterValue } from "../report-types" + +function parameter( + name: string, + type: ReportParameterType, + defaultValue: ReportParameterValue = null, +): ReportParameterMetadata { + return { name, label: name, type, required: false, defaultValue, options: [] } +} + +const parameters = [ + parameter("facultyType", "Choice", "S"), + parameter("departments", "MultiChoice"), + parameter("startDate", "Date", "2026-07-01"), + parameter("search", "Text"), + parameter("minimumAge", "Number"), + parameter("includeEmeriti", "Boolean"), +] + +describe("initialValues()", () => { + it("uses the report's defaults, or empty values, when the query is empty", () => { + expect(initialValues(parameters, {})).toStrictEqual({ + facultyType: "S", + departments: [], + startDate: "2026-07-01", + search: null, + minimumAge: null, + includeEmeriti: null, + }) + }) + + it("reads each parameter type from the query", () => { + const values = initialValues(parameters, { + facultyType: "F", + departments: ["VME", "APC"], + startDate: "2025-07-01", + search: "smith", + minimumAge: "60", + includeEmeriti: "true", + }) + + expect(values).toStrictEqual({ + facultyType: "F", + departments: ["VME", "APC"], + startDate: "2025-07-01", + search: "smith", + minimumAge: 60, + includeEmeriti: true, + }) + }) + + it("accepts a single value for a list and a list for a single value", () => { + const values = initialValues(parameters, { departments: "VME", search: ["first", "second"] }) + + expect(values.departments).toStrictEqual(["VME"]) + expect(values.search).toBe("first") + }) + + it.each([ + ["minimumAge", "old", null], + ["minimumAge", "", null], + ["minimumAge", null, null], + ["includeEmeriti", "false", false], + ["includeEmeriti", null, null], + ["facultyType", null, null], + ["startDate", null, null], + ["search", null, null], + ["departments", null, []], + ])("reads %s=%o as %o", (name, raw, expected) => { + expect(initialValues(parameters, { [name]: raw })[name]).toStrictEqual(expected) + }) +}) + +describe("toQuery()", () => { + it("writes the non-empty values, repeating the key for lists", () => { + const query = toQuery(parameters, { + facultyType: "F", + departments: ["VME", "APC"], + startDate: "2025-07-01", + search: "", + minimumAge: 60, + includeEmeriti: false, + }) + + expect(query).toStrictEqual({ + facultyType: "F", + departments: ["VME", "APC"], + startDate: "2025-07-01", + minimumAge: "60", + includeEmeriti: "false", + }) + }) + + it("round-trips through initialValues", () => { + const values = { ...initialValues(parameters, {}), minimumAge: 45, includeEmeriti: true } + + expect(initialValues(parameters, toQuery(parameters, values) as never)).toStrictEqual(values) + }) +}) + +describe("toRequestBody()", () => { + it("sends only the report's non-empty parameters", () => { + const body = toRequestBody(parameters, { + facultyType: "F", + departments: [], + search: "smith", + includeEmeriti: false, + unknown: "ignored", + }) + + expect(body).toStrictEqual({ facultyType: "F", search: "smith", includeEmeriti: false }) + }) +}) + +describe("hasQueryParameters()", () => { + it("is true when the query names one of the report's parameters", () => { + expect(hasQueryParameters(parameters, { search: "smith" })).toBeTruthy() + expect(hasQueryParameters(parameters, { tab: "2" })).toBeFalsy() + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-runner.test.ts b/VueApp/src/shared/reports/__tests__/report-runner.test.ts new file mode 100644 index 000000000..79454609e --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-runner.test.ts @@ -0,0 +1,183 @@ +import { flushPromises, mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import { ref } from "vue" +import ReportRunner from "../ReportRunner.vue" +import ReportParameterForm from "../ReportParameterForm.vue" +import { sampleResult } from "./report-fixtures" +import type { ReportDefinitionMetadata, ReportExportFormat, ReportResult } from "../report-types" + +/** + * ReportRunner only arranges what useReport provides, so useReport is replaced by plain refs + * the tests set directly. + */ + +const { state, keyGetter } = vi.hoisted(() => ({ + state: {} as Record, + keyGetter: { current: null as (() => string) | null }, +})) +vi.mock("../use-report", () => ({ + useReport: (key: () => string) => { + keyGetter.current = key + return state + }, +})) + +const definition: ReportDefinitionMetadata = { + key: "test.sample", + title: "Sample report", + area: "Test", + description: "A report used by tests.", + parameters: [{ name: "search", label: "Search", type: "Text", required: false, defaultValue: null, options: [] }], + columns: [], +} + +function setState(overrides: Record = {}) { + const values = { + definition: ref(definition), + values: ref({ search: null }), + result: ref(null), + errors: ref([]), + loading: ref(false), + notFound: ref(false), + running: ref(false), + exporting: ref(null), + run: vi.fn<() => Promise>(), + exportAs: vi.fn<(format: ReportExportFormat) => Promise>(), + } + Object.assign(state, values, overrides) + return values +} + +function mountRunner() { + return mount(ReportRunner, { + props: { reportKey: "test.sample", parentLabel: "Test", parentTo: "/" }, + global: { plugins: [[Quasar, {}]], stubs: { RouterLink: { template: "" } } }, + }) +} + +describe("ReportRunner - states", () => { + it("announces that the report is loading", () => { + expect.hasAssertions() + setState({ loading: ref(true) }) + + expect(mountRunner().get("[role='status']").text()).toBe("Loading report") + }) + + it("explains a report that isn't available", () => { + expect.hasAssertions() + setState({ notFound: ref(true), definition: ref(null) }) + const wrapper = mountRunner() + + expect(wrapper.get("h1").text()).toContain("Report not available") + expect(wrapper.text()).toContain("may not be built yet") + }) + + it("shows the title, description and parameter form", () => { + expect.hasAssertions() + setState() + const wrapper = mountRunner() + + expect(wrapper.get("h1").text()).toContain("Sample report") + expect(wrapper.text()).toContain("A report used by tests.") + expect(wrapper.find("form").exists()).toBeTruthy() + }) + + it("loads the report named by its key", () => { + expect.hasAssertions() + setState() + mountRunner() + + expect(keyGetter.current?.()).toBe("test.sample") + }) + + it("keeps the form's values in the report state", () => { + expect.hasAssertions() + const { values } = setState() + const wrapper = mountRunner() + + wrapper.findComponent(ReportParameterForm).vm.$emit("update:modelValue", { search: "smith" }) + + expect(values.value).toStrictEqual({ search: "smith" }) + }) + + it("leaves out the form for a report without parameters", () => { + expect.hasAssertions() + setState({ definition: ref({ ...definition, parameters: [] }) }) + + expect(mountRunner().find("form").exists()).toBeFalsy() + }) + + it("lists the server's messages", () => { + expect.hasAssertions() + setState({ errors: ref(["Start date is required.", "End date is required."]) }) + + expect( + mountRunner() + .findAll("li") + .map((item) => item.text()), + ).toStrictEqual(["Start date is required.", "End date is required."]) + }) + + it("announces a run in progress", () => { + expect.hasAssertions() + setState({ running: ref(true) }) + + expect(mountRunner().get("[role='status']").text()).toBe("Running report") + }) +}) + +describe("ReportRunner - results and exports", () => { + it("runs the report when the form is submitted", async () => { + expect.hasAssertions() + const { run } = setState() + const wrapper = mountRunner() + + await wrapper.get("form").trigger("submit") + await flushPromises() + + expect(run).toHaveBeenCalledOnce() + }) + + it("shows the result with its export buttons", () => { + expect.hasAssertions() + setState({ result: ref(sampleResult()) }) + const wrapper = mountRunner() + + expect(wrapper.find(".report-view").exists()).toBeTruthy() + expect(wrapper.find(".export-excel").exists()).toBeTruthy() + expect(wrapper.find(".export-pdf").exists()).toBeTruthy() + }) + + it.each([ + [".export-excel", "xlsx"], + [".export-pdf", "pdf"], + ])("exports from %s as %s", async (selector, format) => { + expect.hasAssertions() + const { exportAs } = setState({ result: ref(sampleResult()) }) + + await mountRunner().get(selector).trigger("click") + + expect(exportAs).toHaveBeenCalledWith(format) + }) + + it("shows which export is in progress and blocks the others", () => { + expect.hasAssertions() + setState({ result: ref(sampleResult()), exporting: ref("csv") }) + const wrapper = mountRunner() + const csv = wrapper.findAll("button").find((button) => button.text().endsWith("CSV")) + + expect(csv?.find(".q-spinner").exists()).toBeTruthy() + expect(wrapper.get(".export-excel").attributes("disabled")).toBeDefined() + }) + + it("exports CSV from its own button", async () => { + expect.hasAssertions() + const { exportAs } = setState({ result: ref(sampleResult()) }) + const wrapper = mountRunner() + const csv = wrapper.findAll("button").find((button) => button.text().endsWith("CSV")) + + await csv?.trigger("click") + + expect(exportAs).toHaveBeenCalledWith("csv") + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-service.test.ts b/VueApp/src/shared/reports/__tests__/report-service.test.ts new file mode 100644 index 000000000..843ab9521 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-service.test.ts @@ -0,0 +1,181 @@ +import { reportService } from "../report-service" +import type { ReportDefinitionMetadata, ReportResult } from "../report-types" + +/** + * The service returns null or an outcome instead of throwing, so pages can tell "failed" apart + * from "empty": ReportCatalog shows an error instead of hiding, and the report page shows the + * server's validation 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 catalog = [ + { + key: "personnel.faculty-profile", + title: "Faculty Profile", + area: "Personnel", + description: "Faculty by department.", + available: false, + }, +] + +const definition: ReportDefinitionMetadata = { + key: "personnel.employees-on-leave", + title: "Employees on Leave", + area: "Personnel", + description: "Faculty and staff on leave.", + parameters: [], + columns: [], +} + +const result = { key: definition.key, title: definition.title, rowCount: 0 } as ReportResult + +describe("reportService.getCatalog()", () => { + it("returns the catalog for the area", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result: catalog }) + + const catalogResult = await reportService.getCatalog("Personnel") + + expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/reports\?area=Personnel$/u)) + expect(catalogResult).toStrictEqual(catalog) + }) + + it("percent-encodes the area so it stays one query value", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result: [] }) + + await reportService.getCatalog("a&b c") + + expect(mockGet).toHaveBeenCalledWith(expect.stringContaining("?area=a%26b%20c")) + }) + + it("returns an empty list when the user may run none of the area's reports", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result: [] }) + + await expect(reportService.getCatalog("Personnel")).resolves.toStrictEqual([]) + }) + + it("returns null when the request fails", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: false, result: null }) + + await expect(reportService.getCatalog("Personnel")).resolves.toBeNull() + }) + + it("returns null when the response is not a list", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result: { key: "personnel.faculty-profile" } }) + + await expect(reportService.getCatalog("Personnel")).resolves.toBeNull() + }) +}) + +describe("reportService.getDefinition()", () => { + it("returns the report's definition", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result: definition }) + + await expect(reportService.getDefinition("personnel.employees-on-leave")).resolves.toStrictEqual(definition) + expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/reports\/personnel\.employees-on-leave$/u)) + }) + + it("percent-encodes the key so it stays one path segment", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: true, result: definition }) + + await reportService.getDefinition("a/b") + + expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/reports\/a%2Fb$/u)) + }) + + it("returns null for an unknown, planned or forbidden report", async () => { + expect.hasAssertions() + mockGet.mockResolvedValue({ success: false, result: null, errors: [""] }) + + await expect(reportService.getDefinition("personnel.visa-audit")).resolves.toBeNull() + }) +}) + +describe("reportService.run()", () => { + it("posts the parameters and returns the result", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: true, result, errors: [] }) + + const outcome = await reportService.run(definition.key, { startDate: "2026-07-01" }) + + expect(mockPost).toHaveBeenCalledWith(expect.stringMatching(/employees-on-leave\/run$/u), { + startDate: "2026-07-01", + }) + expect(outcome).toStrictEqual({ result, errors: [] }) + }) + + it("returns the server's validation messages", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: false, result: null, errors: ["Start date is required."] }) + + await expect(reportService.run(definition.key, {})).resolves.toStrictEqual({ + result: null, + errors: ["Start date is required."], + }) + }) + + it("falls back to a general message when the server gives none", async () => { + expect.hasAssertions() + mockPost.mockResolvedValue({ success: false, result: null, errors: [""] }) + + await expect(reportService.run(definition.key, {})).resolves.toStrictEqual({ + result: null, + errors: ["The report could not be run."], + }) + }) +}) + +describe("reportService.exportReport()", () => { + it("downloads the file under the server's filename", async () => { + expect.hasAssertions() + const blob = new Blob(["a,b"]) + mockPostForBlob.mockResolvedValue({ blob, filename: "Employees on Leave.csv" }) + + const exported = await reportService.exportReport(definition.key, "csv", { search: "smith" }) + + expect(exported).toBeTruthy() + expect(mockPostForBlob).toHaveBeenCalledWith(expect.stringMatching(/employees-on-leave\/export\/csv$/u), { + search: "smith", + }) + expect(mockDownloadBlob).toHaveBeenCalledWith(blob, "Employees on Leave.csv") + }) + + it("names the file after the report when the server sends no filename", async () => { + expect.hasAssertions() + const blob = new Blob(["%PDF"]) + mockPostForBlob.mockResolvedValue({ blob, filename: null }) + + await reportService.exportReport(definition.key, "pdf", {}) + + expect(mockDownloadBlob).toHaveBeenCalledWith(blob, "personnel.employees-on-leave.pdf") + }) + + it("returns false when the export fails", async () => { + expect.hasAssertions() + mockDownloadBlob.mockClear() + mockPostForBlob.mockRejectedValue(new Error("Bad Request")) + + await expect(reportService.exportReport(definition.key, "xlsx", {})).resolves.toBeFalsy() + expect(mockDownloadBlob).not.toHaveBeenCalled() + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-tables.test.ts b/VueApp/src/shared/reports/__tests__/report-tables.test.ts new file mode 100644 index 000000000..250349762 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-tables.test.ts @@ -0,0 +1,98 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportGroupTable from "../ReportGroupTable.vue" +import ReportNumberTable from "../ReportNumberTable.vue" +import ReportTotals from "../ReportTotals.vue" +import { ada, bo, sampleResult } from "./report-fixtures" + +/** + * The building blocks of a report on screen. Highlights must carry their label as text (the + * Notes column or a badge), never color alone. + */ + +const global = { plugins: [[Quasar, {}]] as [typeof Quasar, object][] } + +// Sortable headers carry Quasar's sort icon, whose ligature name shows up in the text. +function headerText(wrapper: ReturnType): string[] { + return wrapper.findAll("th").map((th) => th.text().replace("arrow_upward", "")) +} + +function rowCells(wrapper: ReturnType, index: number) { + return wrapper.findAll("tbody tr")[index]?.findAll("td") ?? [] +} + +describe("ReportGroupTable", () => { + it("shows row numbers, formatted values and a Notes column", () => { + expect.hasAssertions() + const wrapper = mount(ReportGroupTable, { props: { result: sampleResult(), rows: [ada, bo] }, global }) + + expect(headerText(wrapper)).toStrictEqual(["#", "Name", "Salary", "Hired", "Notes"]) + expect(rowCells(wrapper, 0).map((td) => td.text())).toStrictEqual([ + "1", + "Ada Emeritus", + "$120,000.00", + "07/01/1995", + "60+; Emeritus", + ]) + }) + + it("tints highlighted cells by tone", () => { + expect.hasAssertions() + const wrapper = mount(ReportGroupTable, { props: { result: sampleResult(), rows: [ada, bo] }, global }) + const [, name] = rowCells(wrapper, 0) + const [, boName, boSalary] = rowCells(wrapper, 1) + + expect(name?.classes()).toContain("report-tone-warning") + expect(boSalary?.classes()).toContain("report-tone-negative") + expect(boName?.classes()).not.toContain("report-tone-negative") + }) + + it("puts badges beside the first column only", () => { + expect.hasAssertions() + const wrapper = mount(ReportGroupTable, { props: { result: sampleResult(), rows: [ada] }, global }) + + expect(wrapper.findAll(".q-badge").map((badge) => badge.text())).toStrictEqual(["Emeritus"]) + }) +}) + +describe("ReportTotals", () => { + it("lists each total with its column's format", () => { + expect.hasAssertions() + const result = sampleResult() + const wrapper = mount(ReportTotals, { props: { totals: result.totals, columns: result.columns } }) + + expect(wrapper.get("dt").text()).toBe("All salaries") + expect(wrapper.get("dd").text()).toBe("$360,000.00") + }) + + it("renders nothing when there are no totals", () => { + expect.hasAssertions() + const wrapper = mount(ReportTotals, { props: { totals: [], columns: [] } }) + + expect(wrapper.find("dl").exists()).toBeFalsy() + }) +}) + +describe("ReportNumberTable", () => { + it("shows each row and a bold totals row", () => { + expect.hasAssertions() + const table = { + headers: ["Category", "APC", "Total"], + rows: [{ label: "60+", values: [1234.5, null] }], + total: { label: "Total", values: [1234.5, 7] }, + } + const wrapper = mount(ReportNumberTable, { props: { table }, global }) + + expect(headerText(wrapper)).toStrictEqual(["Category", "APC", "Total"]) + expect(rowCells(wrapper, 0).map((td) => td.text())).toStrictEqual(["60+", "1,234.5", ""]) + expect(wrapper.get("tr.text-weight-bold").text()).toBe("Total1,234.57") + }) + + it("leaves out the totals row when there is none", () => { + expect.hasAssertions() + const table = { headers: ["Category", "Value"], rows: [], total: null } + const wrapper = mount(ReportNumberTable, { props: { table }, global }) + + expect(wrapper.find("tr.text-weight-bold").exists()).toBeFalsy() + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-tones.test.ts b/VueApp/src/shared/reports/__tests__/report-tones.test.ts new file mode 100644 index 000000000..87fcc2ed5 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-tones.test.ts @@ -0,0 +1,73 @@ +import { badgeColor, cellBadges, flagText, highlightClass } from "../report-tones" +import type { ReportFlag, ReportRowResult } from "../report-types" + +/** + * Highlights follow the export rules (ReportExportText.CellFill), so a row is emphasized the + * same way on screen and in Excel and PDF. + */ + +const visible = new Set(["name", "age", "salary"]) + +const rowWarning: ReportFlag = { kind: "Highlight", tone: "Warning", label: "60+", columnKey: null } +const ageNegative: ReportFlag = { kind: "Highlight", tone: "Negative", label: "Retirement age", columnKey: "age" } +const hiddenMuted: ReportFlag = { kind: "Highlight", tone: "Muted", label: "Retired", columnKey: "ssn" } +const neutral: ReportFlag = { kind: "Highlight", tone: "Neutral", label: "Reviewed", columnKey: null } +const emeritusBadge: ReportFlag = { kind: "Badge", tone: "Info", label: "Emeritus", columnKey: null } +const salaryBadge: ReportFlag = { kind: "Badge", tone: "Positive", label: "Raised", columnKey: "salary" } + +describe("highlightClass()", () => { + it("applies a whole-row highlight to every cell, including the row number", () => { + expect(highlightClass([rowWarning], "name", visible)).toBe("report-tone-warning") + expect(highlightClass([rowWarning], null, visible)).toBe("report-tone-warning") + }) + + it("applies a column highlight only to its column", () => { + expect(highlightClass([ageNegative], "age", visible)).toBe("report-tone-negative") + expect(highlightClass([ageNegative], "name", visible)).toBeNull() + }) + + it("lets the last highlight covering a cell win", () => { + expect(highlightClass([rowWarning, ageNegative], "age", visible)).toBe("report-tone-negative") + expect(highlightClass([ageNegative, rowWarning], "age", visible)).toBe("report-tone-warning") + }) + + it("spreads a highlight on a hidden column across the row", () => { + expect(highlightClass([hiddenMuted], "name", visible)).toBe("report-tone-muted") + }) + + it("adds no class for neutral highlights or badges", () => { + expect(highlightClass([rowWarning, neutral], "name", visible)).toBe("report-tone-warning") + expect(highlightClass([neutral, emeritusBadge], "name", visible)).toBeNull() + }) +}) + +describe("cellBadges()", () => { + it("puts column badges beside their column and row badges beside the first column", () => { + const flags = [rowWarning, emeritusBadge, salaryBadge] + + expect(cellBadges(flags, "name", true)).toStrictEqual([emeritusBadge]) + expect(cellBadges(flags, "salary", false)).toStrictEqual([salaryBadge]) + expect(cellBadges(flags, "age", false)).toStrictEqual([]) + }) +}) + +describe("badgeColor()", () => { + it.each([ + ["Neutral", "grey-7"], + ["Info", "info"], + ["Positive", "positive"], + ["Warning", "warning"], + ["Negative", "negative"], + ["Muted", "grey-7"], + ] as const)("uses %s -> %s", (tone, color) => { + expect(badgeColor(tone)).toBe(color) + }) +}) + +describe("flagText()", () => { + it("lists each label once, in order", () => { + const row: ReportRowResult = { number: 1, values: {}, flags: [ageNegative, rowWarning, { ...rowWarning }] } + + expect(flagText(row)).toBe("Retirement age; 60+") + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/report-view.test.ts b/VueApp/src/shared/reports/__tests__/report-view.test.ts new file mode 100644 index 000000000..e94d28560 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/report-view.test.ts @@ -0,0 +1,58 @@ +import { mount } from "@vue/test-utils" +import { Quasar } from "quasar" +import ReportView from "../ReportView.vue" +import { sampleResult, vmeGroup } from "./report-fixtures" + +function mountView(result = sampleResult()) { + return mount(ReportView, { props: { result }, global: { plugins: [[Quasar, {}]] } }) +} + +describe("ReportView", () => { + it("says when the report was generated and how many rows it has", () => { + expect.hasAssertions() + const wrapper = mountView() + + expect(wrapper.get("p").text()).toBe("Generated 09/30/2026 2:05 PM · 3 rows") + }) + + it("uses the singular for one row", () => { + expect.hasAssertions() + const wrapper = mountView(sampleResult({ rowCount: 1 })) + + expect(wrapper.get("p").text()).toContain("1 row") + }) + + it("lays out the sections in export order", () => { + expect.hasAssertions() + const wrapper = mountView() + + expect(wrapper.findAll("h2, h3").map((heading) => heading.text())).toStrictEqual([ + "VME", + "Ages: VME", + "APC", + "Age by department", + "Ages", + ]) + expect(wrapper.findAll("dt").map((term) => term.text())).toStrictEqual(["People", "Salaries", "All salaries"]) + }) + + it("gives an ungrouped report no group heading", () => { + expect.hasAssertions() + const ungrouped = sampleResult({ + groups: [{ ...vmeGroup, label: null, charts: [] }], + pivots: [], + charts: [], + }) + + expect(mountView(ungrouped).find("h2").exists()).toBeFalsy() + }) + + it("says so when no rows match, but still shows the summary", () => { + expect.hasAssertions() + const wrapper = mountView(sampleResult({ rowCount: 0, groups: [] })) + + expect(wrapper.text()).toContain("No rows match these parameters.") + expect(wrapper.get("dt").text()).toBe("People") + expect(wrapper.find("table").exists()).toBeFalsy() + }) +}) diff --git a/VueApp/src/shared/reports/__tests__/use-report.test.ts b/VueApp/src/shared/reports/__tests__/use-report.test.ts new file mode 100644 index 000000000..817450e79 --- /dev/null +++ b/VueApp/src/shared/reports/__tests__/use-report.test.ts @@ -0,0 +1,220 @@ +import { flushPromises } from "@vue/test-utils" +import { ref } from "vue" +import { useReport } from "../use-report" +import { reportService } from "../report-service" +import type { ReportDefinitionMetadata, ReportResult } from "../report-types" + +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-service", () => ({ + reportService: { + getDefinition: vi.fn<(...args: unknown[]) => unknown>(), + run: vi.fn<(...args: unknown[]) => unknown>(), + exportReport: vi.fn<(...args: unknown[]) => unknown>(), + }, +})) + +const onLeave: ReportDefinitionMetadata = { + key: "personnel.employees-on-leave", + title: "Employees on Leave", + area: "Personnel", + description: "Faculty and staff on leave.", + parameters: [ + { + name: "startDate", + label: "Start date", + type: "Date", + required: true, + defaultValue: "2026-07-01", + options: [], + }, + { name: "search", label: "Search", type: "Text", required: false, defaultValue: null, options: [] }, + ], + columns: [], +} +const noParameters: ReportDefinitionMetadata = { ...onLeave, key: "personnel.vmdo-birthdays", parameters: [] } +const result = { key: onLeave.key, rowCount: 3 } as ReportResult + +/** Fresh mocks and query, with the given definition coming back from the API. */ +function reset(definition: ReportDefinitionMetadata | null, query: Record = {}): void { + vi.clearAllMocks() + route.query = query + mockReplace.mockResolvedValue() + vi.mocked(reportService.getDefinition).mockResolvedValue(definition) + vi.mocked(reportService.run).mockResolvedValue({ result, errors: [] }) +} + +/** 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) } +} + +async function loadedReport() { + reset(onLeave) + const report = useReport(onLeave.key) + await flushPromises() + return report +} + +describe("useReport() - loading", () => { + it("is loading until the definition arrives", async () => { + expect.hasAssertions() + reset(onLeave) + + const report = useReport(onLeave.key) + expect(report.loading.value).toBeTruthy() + await flushPromises() + + expect(report.loading.value).toBeFalsy() + expect(reportService.getDefinition).toHaveBeenCalledWith(onLeave.key) + }) + + it("fills the form with the report's defaults and waits to be run", async () => { + expect.hasAssertions() + + const report = await loadedReport() + + expect(report.definition.value).toStrictEqual(onLeave) + expect(report.values.value).toStrictEqual({ startDate: "2026-07-01", search: null }) + expect(reportService.run).not.toHaveBeenCalled() + }) + + it("fills the form from the query and runs straight away for a bookmarked URL", async () => { + expect.hasAssertions() + reset(onLeave, { search: "smith" }) + + const report = useReport(onLeave.key) + await flushPromises() + + expect(report.values.value.search).toBe("smith") + expect(reportService.run).toHaveBeenCalledWith(onLeave.key, { startDate: "2026-07-01", search: "smith" }) + expect(report.result.value).toStrictEqual(result) + }) + + it("runs a report that has no parameters straight away", async () => { + expect.hasAssertions() + reset(noParameters) + + useReport(noParameters.key) + await flushPromises() + + expect(reportService.run).toHaveBeenCalledWith(noParameters.key, {}) + }) + + it("reports a missing report", async () => { + expect.hasAssertions() + reset(null) + + const report = useReport("personnel.visa-audit") + await flushPromises() + + expect(report.notFound.value).toBeTruthy() + expect(report.values.value).toStrictEqual({}) + }) + + it("reloads when the key changes and ignores an earlier load that finishes late", async () => { + expect.hasAssertions() + reset(noParameters) + const first = deferred() + vi.mocked(reportService.getDefinition).mockReturnValueOnce(first.promise) + const key = ref(onLeave.key) + + const report = useReport(key) + key.value = noParameters.key + await flushPromises() + first.resolve(onLeave) + await flushPromises() + + expect(reportService.getDefinition).toHaveBeenLastCalledWith(noParameters.key) + expect(report.definition.value).toStrictEqual(noParameters) + }) +}) + +describe("useReport() - running and exporting", () => { + it("writes the parameters to the query before running", async () => { + expect.hasAssertions() + const report = await loadedReport() + report.values.value = { startDate: "2025-07-01", search: "" } + + await report.run() + + expect(mockReplace).toHaveBeenCalledWith({ query: { startDate: "2025-07-01" } }) + expect(reportService.run).toHaveBeenCalledWith(onLeave.key, { startDate: "2025-07-01" }) + expect(report.running.value).toBeFalsy() + }) + + it("shows the server's messages when the run is refused", async () => { + expect.hasAssertions() + const report = await loadedReport() + vi.mocked(reportService.run).mockResolvedValue({ result: null, errors: ["Start date is required."] }) + + await report.run() + + expect(report.result.value).toBeNull() + expect(report.errors.value).toStrictEqual(["Start date is required."]) + }) + + it("marks the format being exported until the download finishes", async () => { + expect.hasAssertions() + const report = await loadedReport() + await report.run() + const download = deferred() + vi.mocked(reportService.exportReport).mockReturnValue(download.promise) + + const exported = report.exportAs("xlsx") + expect(report.exporting.value).toBe("xlsx") + download.resolve(true) + await exported + + expect(reportService.exportReport).toHaveBeenCalledWith(onLeave.key, "xlsx", { startDate: "2026-07-01" }) + expect(report.exporting.value).toBeNull() + }) + + it("exports with the parameters of the run on screen, not later form edits", async () => { + expect.hasAssertions() + const report = await loadedReport() + report.values.value = { startDate: "2025-07-01", search: "smith" } + await report.run() + report.values.value = { startDate: "2020-01-01", search: "jones" } + + await report.exportAs("csv") + + expect(reportService.exportReport).toHaveBeenCalledWith(onLeave.key, "csv", { + startDate: "2025-07-01", + search: "smith", + }) + }) + + it("does not export before the report has run", async () => { + expect.hasAssertions() + const report = await loadedReport() + + await report.exportAs("pdf") + + expect(reportService.exportReport).not.toHaveBeenCalled() + }) + + it("does nothing before a report has loaded", async () => { + expect.hasAssertions() + reset(null) + const report = useReport("personnel.visa-audit") + await flushPromises() + + await report.run() + await report.exportAs("pdf") + + expect(reportService.run).not.toHaveBeenCalled() + expect(reportService.exportReport).not.toHaveBeenCalled() + }) +}) diff --git a/VueApp/src/shared/reports/report-columns.ts b/VueApp/src/shared/reports/report-columns.ts new file mode 100644 index 000000000..aa93e0f64 --- /dev/null +++ b/VueApp/src/shared/reports/report-columns.ts @@ -0,0 +1,51 @@ +import type { QTableColumn } from "quasar" +import { formatReportValue } from "./report-format" +import { flagText } from "./report-tones" +import type { ReportAlignment, ReportCellValue, ReportResult, ReportRowResult } from "./report-types" + +/** + * Turns a report result's columns into Quasar table columns. Report column keys are camelCase + * property names, so the two extra columns use names no report column can have. + */ + +const ROW_NUMBER_COLUMN = "#number" +const NOTES_COLUMN = "#notes" + +const ALIGNMENTS: Record = { + Left: "left", + Center: "center", + Right: "right", +} + +/** True when any row has a highlight or badge, which adds a Notes column as in the exports. */ +function hasNotes(result: ReportResult): boolean { + return result.groups.some((group) => group.rows.some((row) => row.flags.length > 0)) +} + +function toTableColumns(result: ReportResult): QTableColumn[] { + const columns: QTableColumn[] = result.columns.map((column) => ({ + name: column.key, + label: column.label, + field: (row: ReportRowResult): ReportCellValue => row.values[column.key] ?? null, + align: ALIGNMENTS[column.align], + format: (value: ReportCellValue) => formatReportValue(value, column), + sortable: true, + })) + + if (result.rowNumbers) { + columns.unshift({ + name: ROW_NUMBER_COLUMN, + label: "#", + field: (row: ReportRowResult) => row.number, + align: "right", + sortable: true, + }) + } + + if (hasNotes(result)) { + columns.push({ name: NOTES_COLUMN, label: "Notes", field: flagText, align: "left" }) + } + return columns +} + +export { NOTES_COLUMN, ROW_NUMBER_COLUMN, hasNotes, toTableColumns } diff --git a/VueApp/src/shared/reports/report-format.ts b/VueApp/src/shared/reports/report-format.ts new file mode 100644 index 000000000..eabef6e9d --- /dev/null +++ b/VueApp/src/shared/reports/report-format.ts @@ -0,0 +1,79 @@ +import type { ReportCellValue, ReportColumnFormat, ReportColumnMetadata, ReportTotal } from "./report-types" + +/** + * Formats report values for display the way the server formats them for CSV and PDF exports + * (ReportValueFormatter and ReportExportText), so the screen and the files agree. + */ + +const LOCALE = "en-US" +const ISO_DATE = /^(?\d{4})-(?\d{2})-(?\d{2})/u +const TOTAL_MAX_DECIMALS = 2 +const NUMERIC_FORMATS: ReadonlySet = new Set(["Number", "Currency", "Percent"]) + +const STYLE_OPTIONS: Partial> = { + Currency: { style: "currency", currency: "USD" }, + Percent: { style: "percent" }, +} + +type ColumnFormat = Pick + +function isNumericFormat(format: ReportColumnFormat): boolean { + return NUMERIC_FORMATS.has(format) +} + +/** "2026-07-01" or "2026-07-01T00:00:00" becomes "07/01/2026"; anything else is left alone. */ +function formatReportDate(value: string): string { + const parts = ISO_DATE.exec(value)?.groups + return parts ? `${parts.month}/${parts.day}/${parts.year}` : value +} + +function formatColumnNumber(value: number, column: ColumnFormat): string { + const digits = column.decimals ?? 0 + return new Intl.NumberFormat(LOCALE, { + ...STYLE_OPTIONS[column.format], + minimumFractionDigits: digits, + maximumFractionDigits: digits, + }).format(value) +} + +/** A number with no column format: thousands separators and up to two decimals. */ +function formatPlainNumber(value: number | null): string { + return value === null + ? "" + : new Intl.NumberFormat(LOCALE, { maximumFractionDigits: TOTAL_MAX_DECIMALS }).format(value) +} + +function formatReportValue(value: ReportCellValue | undefined, column: ColumnFormat): string { + if (value === null || value === undefined) { + return "" + } + if (Array.isArray(value)) { + return value.join(", ") + } + if (typeof value === "number") { + return isNumericFormat(column.format) ? formatColumnNumber(value, column) : String(value) + } + if (typeof value === "boolean") { + return value ? "Yes" : "No" + } + return column.format === "Date" ? formatReportDate(value) : value +} + +/** A total formatted like the column it sits under, or as a plain number when it has none. */ +function formatReportTotal(total: ReportTotal, columns: ReportColumnMetadata[]): string { + const column = columns.find((candidate) => candidate.key === total.columnKey) + if (total.value === null) { + return "" + } + return column ? formatReportValue(total.value, column) : formatPlainNumber(total.value) +} + +/** "Generated 09/30/2026 2:15 PM", matching the export headers. */ +function formatGeneratedAt(generatedAt: string): string { + const date = new Date(generatedAt) + const day = date.toLocaleDateString(LOCALE, { month: "2-digit", day: "2-digit", year: "numeric" }) + const time = date.toLocaleTimeString(LOCALE, { hour: "numeric", minute: "2-digit" }) + return `Generated ${day} ${time}` +} + +export { formatGeneratedAt, formatPlainNumber, formatReportDate, formatReportTotal, formatReportValue, isNumericFormat } diff --git a/VueApp/src/shared/reports/report-number-tables.ts b/VueApp/src/shared/reports/report-number-tables.ts new file mode 100644 index 000000000..511a44832 --- /dev/null +++ b/VueApp/src/shared/reports/report-number-tables.ts @@ -0,0 +1,39 @@ +import type { ReportChartResult, ReportPivotResult } from "./report-types" + +/** + * Pivots and chart data as simple labelled-number tables, the way the PDF export shows them. + */ + +interface NumberRow { + label: string + values: (number | null)[] +} + +interface NumberTable { + /** The label column's header, then one header per value. */ + headers: string[] + rows: NumberRow[] + total: NumberRow | null +} + +const CATEGORY_LABEL = "Category" +const TOTAL_LABEL = "Total" + +function pivotTable(pivot: ReportPivotResult): NumberTable { + return { + headers: [CATEGORY_LABEL, ...pivot.columnKeys, TOTAL_LABEL], + rows: pivot.rows.map((row) => ({ label: row.key, values: [...row.values, row.total] })), + total: { label: TOTAL_LABEL, values: [...pivot.columnTotals, pivot.grandTotal] }, + } +} + +function chartTable(chart: ReportChartResult): NumberTable { + return { + headers: [CATEGORY_LABEL, "Value"], + rows: chart.points.map((point) => ({ label: point.category, values: [point.value] })), + total: null, + } +} + +export { chartTable, pivotTable } +export type { NumberRow, NumberTable } diff --git a/VueApp/src/shared/reports/report-query.ts b/VueApp/src/shared/reports/report-query.ts new file mode 100644 index 000000000..a2f855163 --- /dev/null +++ b/VueApp/src/shared/reports/report-query.ts @@ -0,0 +1,85 @@ +import type { LocationQuery, LocationQueryRaw } from "vue-router" +import type { + ReportParameterMetadata, + ReportParameterType, + ReportParameterValue, + ReportParameterValues, +} from "./report-types" + +/** + * Moves report parameter values between the form, the URL query and the request body, so a + * report page can be bookmarked or shared with its parameters filled in. + */ + +type QueryValue = LocationQuery[string] + +const PARSERS: Record ReportParameterValue> = { + Choice: (values) => values[0] ?? null, + MultiChoice: (values) => values, + Date: (values) => values[0] ?? null, + Text: (values) => values[0] ?? null, + Number: (values) => { + const number = Number(values[0]) + return values[0] !== undefined && values[0] !== "" && Number.isFinite(number) ? number : null + }, + Boolean: (values) => (values[0] === undefined ? null : values[0] === "true"), +} + +function queryStrings(value: QueryValue): string[] { + const list = Array.isArray(value) ? value : [value] + return list.filter((item): item is string => typeof item === "string") +} + +/** 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) +} + +function emptyValue(parameter: ReportParameterMetadata): ReportParameterValue { + return parameter.type === "MultiChoice" ? [] : null +} + +/** True when the query carries at least one of the report's parameters. */ +function hasQueryParameters(parameters: ReportParameterMetadata[], query: LocationQuery): boolean { + return parameters.some((parameter) => query[parameter.name] !== undefined) +} + +/** + * The form's starting values: from the query when it has the parameter, otherwise the report's + * default, otherwise empty. + */ +function initialValues(parameters: ReportParameterMetadata[], query: LocationQuery): ReportParameterValues { + return Object.fromEntries( + parameters.map((parameter) => { + const fromQuery = query[parameter.name] + const value = + fromQuery === undefined + ? (parameter.defaultValue ?? emptyValue(parameter)) + : PARSERS[parameter.type](queryStrings(fromQuery)) + return [parameter.name, value] + }), + ) +} + +/** The non-empty values as query parameters; lists repeat the key. */ +function toQuery(parameters: ReportParameterMetadata[], values: ReportParameterValues): LocationQueryRaw { + const entries = parameters + .map((parameter) => [parameter.name, values[parameter.name]] as const) + .filter(([, value]) => !isEmptyValue(value)) + .map(([name, value]) => [name, Array.isArray(value) ? value : String(value)]) + return Object.fromEntries(entries) +} + +/** + * The run request body. Empty values are left out, so the server applies its defaults and its + * own required checks, and names it doesn't know are never sent. + */ +function toRequestBody(parameters: ReportParameterMetadata[], values: ReportParameterValues): ReportParameterValues { + return Object.fromEntries( + parameters + .map((parameter) => [parameter.name, values[parameter.name] ?? null] as const) + .filter(([, value]) => !isEmptyValue(value)), + ) +} + +export { hasQueryParameters, initialValues, isEmptyValue, toQuery, toRequestBody } diff --git a/VueApp/src/shared/reports/report-service.ts b/VueApp/src/shared/reports/report-service.ts new file mode 100644 index 000000000..49b058b24 --- /dev/null +++ b/VueApp/src/shared/reports/report-service.ts @@ -0,0 +1,81 @@ +import { downloadBlob, postForBlob, useFetch } from "@/composables/ViperFetch" +import type { + ReportCatalogItem, + ReportDefinitionMetadata, + ReportExportFormat, + ReportParameterValues, + ReportResult, +} from "./report-types" + +const { get, post } = useFetch() + +const RUN_FAILED = "The report could not be run." + +/** + * A finished run has a result and no errors; a refused or failed run has messages instead. + * Validation messages name the parameter they concern, so they read well as a list. + */ +type ReportRunOutcome = { result: ReportResult; errors: [] } | { result: null; errors: string[] } + +/** + * Client for the site-wide reports API. + */ +class ReportService { + private baseUrl = `${import.meta.env.VITE_API_URL}reports` + + /** + * The reports in one area that the signed-in user may run. The server filters by permission, + * so the list needs no checks here. Returns null when the request fails, so the caller can + * tell a failed load apart from an area with no reports for this user. + */ + async getCatalog(area: string): Promise { + const r = await get(`${this.baseUrl}?area=${encodeURIComponent(area)}`) + if (!r.success || !Array.isArray(r.result)) { + return null + } + return r.result as ReportCatalogItem[] + } + + /** + * A report's parameters and columns. Null when the report doesn't exist, is only planned, + * or the user may not run it; the API doesn't say which, and the page treats all three alike. + */ + async getDefinition(key: string): Promise { + const r = await get(this.reportUrl(key)) + if (!r.success || !r.result) { + return null + } + return r.result as ReportDefinitionMetadata + } + + async run(key: string, parameters: ReportParameterValues): Promise { + const r = await post(`${this.reportUrl(key)}/run`, parameters) + if (r.success && r.result) { + return { result: r.result as ReportResult, 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 downloads it in the chosen format. Returns false if the + * export failed; the shared error handler has already told the user why. + */ + async exportReport(key: string, format: ReportExportFormat, parameters: ReportParameterValues): Promise { + try { + const { blob, filename } = await postForBlob(`${this.reportUrl(key)}/export/${format}`, parameters) + downloadBlob(blob, filename ?? `${key}.${format}`) + return true + } catch { + return false + } + } + + private reportUrl(key: string): string { + return `${this.baseUrl}/${encodeURIComponent(key)}` + } +} + +const reportService = new ReportService() +export { reportService } +export type { ReportRunOutcome } diff --git a/VueApp/src/shared/reports/report-tones.css b/VueApp/src/shared/reports/report-tones.css new file mode 100644 index 000000000..974cd533a --- /dev/null +++ b/VueApp/src/shared/reports/report-tones.css @@ -0,0 +1,23 @@ +/* Report highlight tints (report-tones.ts). Light enough that ink text clears WCAG AA, and each + highlight's label is also listed in the Notes column, so color is never the only signal. The + tints match StatusBanner's, so a warning row reads like a warning banner. */ + +.report-tone-info { + background-color: color-mix(in srgb, var(--q-info) 12%, white); +} + +.report-tone-positive { + background-color: color-mix(in srgb, var(--q-positive) 12%, white); +} + +.report-tone-warning { + background-color: color-mix(in srgb, var(--q-warning) 15%, white); +} + +.report-tone-negative { + background-color: color-mix(in srgb, var(--q-negative) 12%, white); +} + +.report-tone-muted { + background-color: var(--ucdavis-black-10); +} diff --git a/VueApp/src/shared/reports/report-tones.ts b/VueApp/src/shared/reports/report-tones.ts new file mode 100644 index 000000000..fecd8e5c8 --- /dev/null +++ b/VueApp/src/shared/reports/report-tones.ts @@ -0,0 +1,64 @@ +import type { ReportFlag, ReportRowResult, ReportTone } from "./report-types" + +/** + * Maps report highlight and badge tones to page styling. Tones are semantic, never raw colors, + * and every flag also carries a text label, so no meaning depends on color alone. + */ + +const HIGHLIGHT_CLASSES: Record = { + Neutral: null, + Info: "report-tone-info", + Positive: "report-tone-positive", + Warning: "report-tone-warning", + Negative: "report-tone-negative", + Muted: "report-tone-muted", +} + +// Quasar palette names; StatusBadge picks a readable text color for each. +const BADGE_COLORS: Record = { + Neutral: "grey-7", + Info: "info", + Positive: "positive", + Warning: "warning", + Negative: "negative", + Muted: "grey-7", +} + +/** + * The highlight class for one cell, following the exports: highlights apply in declared order, + * so the last one covering the cell wins. A highlight covers a cell when it targets the whole + * row, this column, or a column the user can't see. Pass null for cells outside any column. + */ +function highlightClass( + flags: ReportFlag[], + columnKey: string | null, + visibleKeys: ReadonlySet, +): string | null { + const classes = flags + .filter( + (flag) => + flag.kind === "Highlight" && + (flag.columnKey === null || flag.columnKey === columnKey || !visibleKeys.has(flag.columnKey)), + ) + .map((flag) => HIGHLIGHT_CLASSES[flag.tone]) + .filter((name): name is string => name !== null) + return classes.at(-1) ?? null +} + +/** Badges shown beside one cell. Whole-row badges go beside the first column. */ +function cellBadges(flags: ReportFlag[], columnKey: string, isFirstColumn: boolean): ReportFlag[] { + return flags.filter( + (flag) => flag.kind === "Badge" && (flag.columnKey === columnKey || (isFirstColumn && flag.columnKey === null)), + ) +} + +function badgeColor(tone: ReportTone): string { + return BADGE_COLORS[tone] +} + +/** Every flag label on a row, once each, as the exports' Notes column lists them. */ +function flagText(row: ReportRowResult): string { + return [...new Set(row.flags.map((flag) => flag.label))].join("; ") +} + +export { badgeColor, cellBadges, flagText, highlightClass } diff --git a/VueApp/src/shared/reports/report-types.ts b/VueApp/src/shared/reports/report-types.ts new file mode 100644 index 000000000..e66707a65 --- /dev/null +++ b/VueApp/src/shared/reports/report-types.ts @@ -0,0 +1,153 @@ +/** + * Types mirroring the reports API (web/Areas/Reports). Enum values arrive as their C# names. + */ + +type ReportParameterType = "Choice" | "MultiChoice" | "Date" | "Text" | "Number" | "Boolean" +type ReportColumnFormat = "Text" | "Number" | "Currency" | "Percent" | "Date" | "List" +type ReportAlignment = "Left" | "Center" | "Right" +type ReportTone = "Neutral" | "Info" | "Positive" | "Warning" | "Negative" | "Muted" +type ReportFlagKind = "Highlight" | "Badge" +type ReportChartKind = "Bar" | "Line" | "Pie" +type ReportExportFormat = "csv" | "xlsx" | "pdf" + +/** A parameter value as the form holds it; dates are "yyyy-MM-dd" strings. */ +type ReportParameterValue = string | string[] | number | boolean | null +type ReportParameterValues = Record + +/** A cell value as the API sends it; dates are ISO strings. */ +type ReportCellValue = string | string[] | number | boolean | null + +/** + * A report the signed-in user may run, as listed by the reports catalog. `available` is false + * for a planned report that is listed ahead of time but not built yet. + */ +interface ReportCatalogItem { + key: string + title: string + area: string + description: string + available: boolean +} + +interface ReportOption { + value: string + label: string +} + +interface ReportParameterMetadata { + name: string + label: string + type: ReportParameterType + required: boolean + defaultValue: ReportParameterValue + options: ReportOption[] +} + +interface ReportColumnMetadata { + key: string + label: string + format: ReportColumnFormat + align: ReportAlignment + decimals: number | null +} + +interface ReportDefinitionMetadata { + key: string + title: string + area: string + description: string + parameters: ReportParameterMetadata[] + columns: ReportColumnMetadata[] +} + +interface ReportFlag { + kind: ReportFlagKind + tone: ReportTone + label: string + columnKey: string | null +} + +interface ReportRowResult { + number: number + values: Record + flags: ReportFlag[] +} + +interface ReportTotal { + label: string + columnKey: string | null + value: number | null +} + +interface ReportChartPoint { + category: string + value: number | null +} + +interface ReportChartResult { + title: string + kind: ReportChartKind + points: ReportChartPoint[] +} + +interface ReportGroupResult { + label: string | null + rows: ReportRowResult[] + subtotals: ReportTotal[] + charts: ReportChartResult[] +} + +interface ReportPivotRow { + key: string + values: (number | null)[] + total: number | null +} + +interface ReportPivotResult { + title: string + columnKeys: string[] + rows: ReportPivotRow[] + columnTotals: (number | null)[] + grandTotal: number | null +} + +interface ReportResult { + key: string + title: string + generatedAt: string + rowCount: number + rowNumbers: boolean + columns: ReportColumnMetadata[] + summary: ReportTotal[] + groups: ReportGroupResult[] + totals: ReportTotal[] + pivots: ReportPivotResult[] + charts: ReportChartResult[] +} + +export type { + ReportAlignment, + ReportCatalogItem, + ReportCellValue, + ReportChartKind, + ReportChartPoint, + ReportChartResult, + ReportColumnFormat, + ReportColumnMetadata, + ReportDefinitionMetadata, + ReportExportFormat, + ReportFlag, + ReportFlagKind, + ReportGroupResult, + ReportOption, + ReportParameterMetadata, + ReportParameterType, + ReportParameterValue, + ReportParameterValues, + ReportPivotResult, + ReportPivotRow, + ReportResult, + ReportRowResult, + ReportTone, + ReportTotal, +} diff --git a/VueApp/src/shared/reports/use-report.ts b/VueApp/src/shared/reports/use-report.ts new file mode 100644 index 000000000..4ca138740 --- /dev/null +++ b/VueApp/src/shared/reports/use-report.ts @@ -0,0 +1,82 @@ +import { ref, toValue, watch } from "vue" +import type { MaybeRefOrGetter } from "vue" +import { useRoute, useRouter } from "vue-router" +import { hasQueryParameters, initialValues, toQuery, toRequestBody } from "./report-query" +import { reportService } from "./report-service" +import type { ReportDefinitionMetadata, ReportExportFormat, ReportParameterValues, ReportResult } from "./report-types" + +/** + * State for a report page: loads the report's definition whenever the key changes, fills the + * form from the URL query or the report's defaults, and runs or exports the report. Running + * writes the parameters back to the query so the page can be bookmarked; opening a URL that + * carries parameters, or a report that has none, runs it straight away. + */ +export function useReport(key: MaybeRefOrGetter) { + const route = useRoute() + const router = useRouter() + + 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) + // The body of the run on screen, so an export matches what the user sees even after the + // form has been edited. + let shownBody: ReportParameterValues = {} + + // Only the latest load may update the page, if the key changes while one is in flight. + let loadId = 0 + + async function run(): Promise { + const report = definition.value + if (report === null) { + return + } + running.value = true + errors.value = [] + await router.replace({ query: toQuery(report.parameters, values.value) }) + const body = toRequestBody(report.parameters, values.value) + const outcome = await reportService.run(report.key, body) + result.value = outcome.result + shownBody = body + errors.value = outcome.errors + running.value = false + } + + /** Exports the report on screen; does nothing until a run has produced one. */ + async function exportAs(format: ReportExportFormat): Promise { + const report = definition.value + if (report === null || result.value === null) { + return + } + exporting.value = format + await reportService.exportReport(report.key, format, shownBody) + exporting.value = null + } + + async function load(reportKey: string): Promise { + loadId += 1 + const id = loadId + loading.value = true + result.value = null + errors.value = [] + const report = await reportService.getDefinition(reportKey) + if (id !== loadId) { + return + } + definition.value = report + notFound.value = report === null + values.value = report ? initialValues(report.parameters, route.query) : {} + loading.value = false + if (report && (report.parameters.length === 0 || hasQueryParameters(report.parameters, route.query))) { + await run() + } + } + + watch(() => toValue(key), load, { immediate: true }) + + return { definition, values, result, errors, loading, notFound, running, exporting, run, exportAs } +} diff --git a/test/Personnel/EmployeesOnLeaveReportTests.cs b/test/Personnel/EmployeesOnLeaveReportTests.cs new file mode 100644 index 000000000..d8ec10281 --- /dev/null +++ b/test/Personnel/EmployeesOnLeaveReportTests.cs @@ -0,0 +1,93 @@ +using Viper.Areas.Personnel; +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Reports; +using Viper.Areas.Reports.Engine; +using Viper.test.Reports; + +namespace Viper.test.Personnel; + +public sealed class EmployeesOnLeaveReportTests +{ + // A February date, so the default range is the fiscal year that began the previous July. + private static readonly DateTimeOffset Now = new(2027, 2, 15, 9, 0, 0, TimeSpan.Zero); + + private readonly StubPersonnelReportDataService _data = new() + { + PeopleOnLeave = + [ + new EmployeeOnLeaveRow( + "Lovelace, Ada", "VME", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), "Sabbatical", "With pay"), + ], + }; + + private EmployeesOnLeaveReport Report() + { + return new EmployeesOnLeaveReport(_data, new FixedTimeProvider(Now)); + } + + private static ReportContext Context() + { + return new ReportContext("tester", permission => permission == PersonnelPermissions.Sabbatic); + } + + [Fact] + public void Identity_MatchesTheLegacyPage() + { + EmployeesOnLeaveReport report = Report(); + + Assert.Equal("personnel.employees-on-leave", report.Key); + Assert.Equal("Personnel", report.Area); + Assert.Equal([PersonnelPermissions.Sabbatic], report.Permissions); + Assert.True(report.IsSensitive); + Assert.True(report.CanRun(Context())); + } + + [Fact] + public void Metadata_DefaultsToFacultyAndTheCurrentFiscalYear() + { + ReportDefinitionMetadata metadata = Report().GetMetadata(Context()); + + Assert.Equal( + [("employeeType", (object?)"F"), ("startDate", new DateOnly(2026, 7, 1)), ("endDate", new DateOnly(2027, 6, 30))], + metadata.Parameters.Select(parameter => (parameter.Name, parameter.DefaultValue))); + Assert.All(metadata.Parameters, parameter => Assert.True(parameter.Required)); + Assert.Equal( + ["name", "homeDepartment", "leaveStart", "returnDate", "description", "payStatus"], + metadata.Columns.Select(column => column.Key)); + } + + [Fact] + public void PrepareParameters_EndBeforeStart_IsInvalid() + { + var parameters = new EmployeesOnLeaveParameters + { + StartDate = new DateOnly(2026, 7, 1), + EndDate = new DateOnly(2026, 6, 30), + }; + + ReportValidationError error = Assert.Single(Report().PrepareParameters(parameters)); + + Assert.Equal("endDate", error.Parameter); + } + + [Fact] + public async Task RunAsync_PassesThePreparedParametersToTheDataService() + { + EmployeesOnLeaveReport report = Report(); + var parameters = new EmployeesOnLeaveParameters { EmployeeType = "B", StartDate = new DateOnly(2025, 1, 1) }; + Assert.Empty(report.PrepareParameters(parameters)); + + ReportResult result = await report.RunAsync(parameters, Context(), Now, TestContext.Current.CancellationToken); + + Assert.Equal(("B", new DateOnly(2025, 1, 1), new DateOnly(2027, 6, 30)), _data.LeaveRequest); + Assert.Equal(1, result.RowCount); + Assert.Equal("Lovelace, Ada", Assert.Single(Assert.Single(result.Groups).Rows).Values["name"]); + } + + [Fact] + public async Task RunAsync_WithoutPreparedParameters_Throws() + { + await Assert.ThrowsAsync(() => Report().RunAsync( + new EmployeesOnLeaveParameters(), Context(), Now, TestContext.Current.CancellationToken)); + } +} diff --git a/test/Personnel/ExemptStatusReportTests.cs b/test/Personnel/ExemptStatusReportTests.cs new file mode 100644 index 000000000..48a6b186a --- /dev/null +++ b/test/Personnel/ExemptStatusReportTests.cs @@ -0,0 +1,105 @@ +using Viper.Areas.Personnel; +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Reports; +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Personnel; + +public sealed class ExemptStatusReportTests +{ + private static readonly DateTimeOffset Now = new(2026, 9, 30, 9, 0, 0, TimeSpan.Zero); + + // Ada holds two exempt appointments in VME, so VME counts her once. + private readonly StubPersonnelReportDataService _data = new() + { + FlsaEmployees = + [ + new FlsaEmployeeRow("1", "Lovelace, Ada", "VME", "Professor", ExemptStatusReport.Exempt, "ada@ucdavis.edu"), + new FlsaEmployeeRow("1", "Lovelace, Ada", "VME", "Chair", ExemptStatusReport.Exempt, "ada@ucdavis.edu"), + new FlsaEmployeeRow("2", "Byron, Bo", "VME", "Analyst", ExemptStatusReport.NonExempt, null), + new FlsaEmployeeRow("3", "Curie, Cy", "APC", "Assistant", ExemptStatusReport.NonExempt, null), + ], + }; + + private ExemptStatusReport Report() + { + return new ExemptStatusReport(_data); + } + + private static ReportContext Context() + { + return new ReportContext("tester", permission => permission == PersonnelPermissions.ServiceCreditAdmin); + } + + private async Task RunAsync(string statusType) + { + ExemptStatusReport report = Report(); + var parameters = new ExemptStatusParameters { StatusType = statusType }; + Assert.Empty(report.PrepareParameters(parameters)); + return await report.RunAsync(parameters, Context(), Now, TestContext.Current.CancellationToken); + } + + [Fact] + public void Identity_UsesTheDecidedPermission() + { + ExemptStatusReport report = Report(); + + Assert.Equal("personnel.exempt-non-exempt", report.Key); + Assert.Equal([PersonnelPermissions.ServiceCreditAdmin], report.Permissions); + Assert.False(report.IsSensitive); + Assert.True(report.CanRun(Context())); + } + + [Fact] + public void Metadata_DefaultsToBoth() + { + ReportDefinitionMetadata metadata = Report().GetMetadata(Context()); + + ReportParameterMetadata status = Assert.Single(metadata.Parameters); + Assert.Equal("statusType", status.Name); + Assert.Equal("B", status.DefaultValue); + Assert.Equal(["E", "N", "B"], status.Options.Select(option => option.Value)); + Assert.Equal(["name", "department", "title", "flsa", "email"], metadata.Columns.Select(column => column.Key)); + } + + [Fact] + public async Task RunAsync_AsksForTheChosenStatus() + { + await RunAsync("E"); + + Assert.Equal("E", _data.FlsaRequest); + } + + [Fact] + public async Task RunAsync_CountsPeopleForTheSchool() + { + ReportResult result = await RunAsync("B"); + + Assert.Equal( + [new ReportTotal("Exempt employees", null, 1), new ReportTotal("Non-exempt employees", null, 2)], + result.Summary); + Assert.True(result.RowNumbers); + } + + [Fact] + public async Task RunAsync_GroupsByDepartmentWithNonExemptFirst() + { + ReportResult result = await RunAsync("B"); + + Assert.Equal(["APC", "VME"], result.Groups.Select(group => group.Label)); + ReportGroupResult vme = result.Groups[1]; + Assert.Equal( + ["Byron, Bo", "Lovelace, Ada", "Lovelace, Ada"], + vme.Rows.Select(row => row.Values["name"])); + Assert.Equal( + [new ReportTotal("Exempt employees", null, 1), new ReportTotal("Non-exempt employees", null, 1)], + vme.Subtotals); + } + + [Fact] + public async Task RunAsync_WithoutPreparedParameters_Throws() + { + await Assert.ThrowsAsync(() => Report().RunAsync( + new ExemptStatusParameters(), Context(), Now, TestContext.Current.CancellationToken)); + } +} diff --git a/test/Personnel/FacultyProfileReportTests.cs b/test/Personnel/FacultyProfileReportTests.cs new file mode 100644 index 000000000..f90717c00 --- /dev/null +++ b/test/Personnel/FacultyProfileReportTests.cs @@ -0,0 +1,126 @@ +using Viper.Areas.Personnel; +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Reports; +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Personnel; + +public sealed class FacultyProfileReportTests +{ + private static readonly DateTimeOffset Now = new(2026, 9, 30, 9, 0, 0, TimeSpan.Zero); + + // VME: Ada (two appointments, 61), Bo (45), Cy (emeritus, 70), Di (recalled, 66), Ed (33). + // APC: Ada again, through her second appointment. + private readonly StubPersonnelReportDataService _data = new() + { + FacultyAppointments = + [ + new FacultyAppointmentRow("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "VME", "PROF-AY"), + new FacultyAppointmentRow("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "APC", "CHAIR"), + new FacultyAppointmentRow("2", "Byron, Bo", 45, new DateOnly(2010, 1, 15), "VME", "ASSOC PROF"), + new FacultyAppointmentRow("3", "Curie, Cy", 70, new DateOnly(1985, 9, 1), "VME", "PROF EMERITUS"), + new FacultyAppointmentRow("4", "Dirac, Di", 66, new DateOnly(1990, 3, 1), "VME", "PROF-RECALL"), + new FacultyAppointmentRow("5", "Euler, Ed", 33, new DateOnly(2022, 8, 15), "VME", "ASST PROF"), + ], + }; + + private FacultyProfileReport Report() + { + return new FacultyProfileReport(_data); + } + + private static ReportContext Context() + { + return new ReportContext("tester", permission => permission == PersonnelPermissions.FacultySalary); + } + + private async Task RunAsync(string facultyType = "B") + { + FacultyProfileReport report = Report(); + var parameters = new FacultyProfileParameters { FacultyType = facultyType }; + Assert.Empty(report.PrepareParameters(parameters)); + return await report.RunAsync(parameters, Context(), Now, TestContext.Current.CancellationToken); + } + + [Fact] + public void Identity_IsSensitiveAndNeedsFacultySalary() + { + FacultyProfileReport report = Report(); + + Assert.Equal("personnel.faculty-profile", report.Key); + Assert.Equal([PersonnelPermissions.FacultySalary], report.Permissions); + Assert.True(report.IsSensitive); + Assert.True(report.CanRun(Context())); + } + + [Fact] + public void Metadata_DefaultsToBothFacultyTypes() + { + ReportDefinitionMetadata metadata = Report().GetMetadata(Context()); + + ReportParameterMetadata type = Assert.Single(metadata.Parameters); + Assert.Equal("B", type.DefaultValue); + Assert.Equal(["S", "F", "B"], type.Options.Select(option => option.Value)); + Assert.Equal( + ["name", "age", "hireDate", "appointmentDepartment", "title"], + metadata.Columns.Select(column => column.Key)); + } + + [Fact] + public async Task RunAsync_AsksForTheChosenFacultyType() + { + await RunAsync("S"); + + Assert.Equal("S", _data.FacultyRequest); + } + + [Fact] + public async Task RunAsync_CountsPeopleNotAppointments() + { + ReportResult result = await RunAsync(); + + Assert.Equal( + [new ReportTotal("Faculty", null, 5), new ReportTotal("Emeriti", null, 1), new ReportTotal("Recalled", null, 1)], + result.Summary); + Assert.Equal(["APC", "VME"], result.Groups.Select(group => group.Label)); + Assert.Equal( + [new ReportTotal("Faculty", null, 5), new ReportTotal("Emeriti", null, 1), new ReportTotal("Recalled", null, 1)], + result.Groups[1].Subtotals); + } + + [Fact] + public async Task RunAsync_ChartsActiveFacultyOnly() + { + ReportResult result = await RunAsync(); + + ReportChartResult school = Assert.Single(result.Charts); + Assert.Equal( + [new ReportChartPoint("30-34", 1), new ReportChartPoint("45-49", 1), new ReportChartPoint("60-64", 1)], + school.Points); + Assert.Empty(result.Groups[0].Charts); + Assert.Empty(result.Groups[1].Charts); + } + + [Fact] + public async Task RunAsync_MutesRetiredFacultyAndHighlightsAgeSixtyAndOver() + { + ReportResult result = await RunAsync(); + IReadOnlyList vme = result.Groups[1].Rows; + + Assert.Equal( + ["Curie, Cy", "Dirac, Di", "Lovelace, Ada", "Lovelace, Ada", "Byron, Bo", "Euler, Ed"], + vme.Select(row => row.Values["name"])); + Assert.Equal( + [ReportTone.Muted, ReportTone.Warning], + vme[0].Flags.Select(flag => flag.Tone)); + Assert.Equal([ReportTone.Warning], vme[2].Flags.Select(flag => flag.Tone)); + Assert.Empty(vme[4].Flags); + } + + [Fact] + public async Task RunAsync_WithoutPreparedParameters_Throws() + { + await Assert.ThrowsAsync(() => Report().RunAsync( + new FacultyProfileParameters(), Context(), Now, TestContext.Current.CancellationToken)); + } +} diff --git a/test/Personnel/FacultyProfileRowsTests.cs b/test/Personnel/FacultyProfileRowsTests.cs new file mode 100644 index 000000000..9b6cc2e72 --- /dev/null +++ b/test/Personnel/FacultyProfileRowsTests.cs @@ -0,0 +1,75 @@ +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Reports; + +namespace Viper.test.Personnel; + +public sealed class FacultyProfileRowsTests +{ + [Theory] + [InlineData(null, null)] + [InlineData(19, null)] + [InlineData(20, "20-24")] + [InlineData(24, "20-24")] + [InlineData(25, "25-29")] + [InlineData(60, "60-64")] + [InlineData(99, "95-99")] + [InlineData(100, null)] + public void AgeGroup_UsesTheLegacyFiveYearBrackets(int? age, string? expected) + { + Assert.Equal(expected, FacultyProfileRows.AgeGroup(age)); + } + + [Theory] + [InlineData("PROF EMERITUS", true, false)] + [InlineData("Prof-Emeri/Recall", true, true)] + [InlineData("PROF-RECALL", false, true)] + [InlineData("PROF-AY", false, false)] + [InlineData(null, false, false)] + public void Titles_IdentifyEmeritiAndRecalledFaculty(string? title, bool emeritus, bool recalled) + { + var row = new FacultyProfileRow("VME", "1", "Ada", 70, null, "VME", title); + + Assert.Equal(emeritus, FacultyProfileRows.IsEmeritusTitle(title)); + Assert.Equal(recalled, FacultyProfileRows.IsRecalledTitle(title)); + Assert.Equal(emeritus, row.IsEmeritus); + Assert.Equal(recalled, row.IsRecalled); + Assert.Equal(emeritus || recalled, row.IsRetired); + Assert.Equal("70-74", row.AgeGroup); + } + + [Fact] + public void Expand_ListsEachPersonWithAllAppointmentsUnderEveryDepartment() + { + FacultyAppointmentRow[] appointments = + [ + new("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "VME", "PROF-AY"), + new("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "APC ", "CHAIR"), + new("2", "Byron, Bo", 45, null, "VME", "ASSOC PROF"), + new("3", "Curie, Cy", 70, null, null, "PROF EMERITUS"), + ]; + + IReadOnlyList rows = FacultyProfileRows.Expand(appointments); + + Assert.Equal( + [ + ("", "3", "PROF EMERITUS"), + ("APC", "1", "CHAIR"), + ("APC", "1", "PROF-AY"), + ("VME", "1", "CHAIR"), + ("VME", "1", "PROF-AY"), + ("VME", "2", "ASSOC PROF"), + ], + rows.Select(row => (row.Department, row.EmployeeId, row.Title ?? string.Empty)) + .OrderBy(row => row.Department, StringComparer.Ordinal) + .ThenBy(row => row.EmployeeId, StringComparer.Ordinal) + .ThenBy(row => row.Item3, StringComparer.Ordinal)); + Assert.Equal(["3", "1", "1", "1", "1", "2"], rows.Select(row => row.EmployeeId)); + Assert.Equal("APC ", rows.First(row => row.Title == "CHAIR").AppointmentDepartment); + } + + [Fact] + public void Expand_Null_Throws() + { + Assert.Throws(() => FacultyProfileRows.Expand(null!)); + } +} diff --git a/test/Personnel/FiscalYearTests.cs b/test/Personnel/FiscalYearTests.cs new file mode 100644 index 000000000..c39b8fe39 --- /dev/null +++ b/test/Personnel/FiscalYearTests.cs @@ -0,0 +1,19 @@ +using Viper.Areas.Personnel.Reports; + +namespace Viper.test.Personnel; + +public sealed class FiscalYearTests +{ + [Theory] + [InlineData(2026, 7, 1, 2026)] + [InlineData(2026, 12, 31, 2026)] + [InlineData(2027, 1, 1, 2026)] + [InlineData(2027, 6, 30, 2026)] + public void StartOf_IsTheMostRecentJulyFirst(int year, int month, int day, int startYear) + { + var date = new DateOnly(year, month, day); + + Assert.Equal(new DateOnly(startYear, 7, 1), FiscalYear.StartOf(date)); + Assert.Equal(new DateOnly(startYear + 1, 6, 30), FiscalYear.EndOf(date)); + } +} diff --git a/test/Personnel/PersonnelReportDataServiceTests.cs b/test/Personnel/PersonnelReportDataServiceTests.cs new file mode 100644 index 000000000..94a4623e0 --- /dev/null +++ b/test/Personnel/PersonnelReportDataServiceTests.cs @@ -0,0 +1,161 @@ +using System.Data; +using Viper.Areas.Personnel; +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Services; +using Viper.Areas.Reports.Data; + +namespace Viper.test.Personnel; + +public sealed class PersonnelReportDataServiceTests +{ + /// + /// Records the call and maps the rows it is given, standing in for SQL Server. + /// + private sealed class RecordingRunner(DataTable rows) : IStoredProcedureRunner + { + public string? ConnectionName { get; private set; } + + public string? Procedure { get; private set; } + + public IReadOnlyList Parameters { get; private set; } = []; + + public Task> QueryAsync( + string connectionStringName, + string procedure, + IReadOnlyList parameters, + Func map, + CancellationToken ct) + { + ConnectionName = connectionStringName; + Procedure = procedure; + Parameters = parameters; + using DataTableReader reader = rows.CreateDataReader(); + var mapped = new List(); + while (reader.Read()) + { + mapped.Add(map(reader)); + } + + return Task.FromResult>(mapped); + } + } + + private static DataTable LeaveTable() + { + var table = new DataTable(); + table.Columns.Add("Name", typeof(string)); + table.Columns.Add("homeDept", typeof(string)); + table.Columns.Add("loa_begin_date", typeof(DateTime)); + table.Columns.Add("loa_return_date", typeof(DateTime)); + table.Columns.Add("loa_description", typeof(string)); + table.Columns.Add("pay_status", typeof(string)); + table.Rows.Add( + "Lovelace, Ada ", + "VME ", + new DateTime(2026, 7, 1, 0, 0, 0, DateTimeKind.Local), + new DateTime(2027, 6, 30, 0, 0, 0, DateTimeKind.Local), + "Sabbatical ", + "With pay"); + table.Rows.Add(DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value); + return table; + } + + [Fact] + public async Task GetPeopleOnLeaveAsync_CallsTheLegacyProcedureOnPps() + { + var runner = new RecordingRunner(LeaveTable()); + var service = new PersonnelReportDataService(runner); + + await service.GetPeopleOnLeaveAsync( + "S", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), TestContext.Current.CancellationToken); + + Assert.Equal(PersonnelDatabases.Pps, runner.ConnectionName); + Assert.Equal("usp_get_peopleOnLeave", runner.Procedure); + Assert.Equal( + [ + StoredProcedureParameter.Text("fYear", null, 4), + StoredProcedureParameter.Text("employeeType", "S", 1), + StoredProcedureParameter.Date("startDate", new DateOnly(2026, 7, 1)), + StoredProcedureParameter.Date("endDate", new DateOnly(2027, 6, 30)), + ], + runner.Parameters); + } + + [Fact] + public async Task GetPeopleOnLeaveAsync_MapsAndTrimsEachRow() + { + var service = new PersonnelReportDataService(new RecordingRunner(LeaveTable())); + + IReadOnlyList rows = await service.GetPeopleOnLeaveAsync( + "F", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), TestContext.Current.CancellationToken); + + Assert.Equal( + [ + new EmployeeOnLeaveRow( + "Lovelace, Ada", "VME", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), "Sabbatical", "With pay"), + new EmployeeOnLeaveRow(string.Empty, null, null, null, null, null), + ], + rows); + } + + [Fact] + public async Task GetFlsaAsync_CallsTheLegacyProcedureAndTrimsEachRow() + { + var table = new DataTable(); + foreach (string column in new[] { "employee_id", "emp_name", "department", "title", "flsa", "email" }) + { + table.Columns.Add(column, typeof(string)); + } + + table.Rows.Add("000123456 ", "Lovelace, Ada ", "VME ", "Professor ", "EXEMPT ", "ada@ucdavis.edu"); + table.Rows.Add(DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value); + var runner = new RecordingRunner(table); + var service = new PersonnelReportDataService(runner); + + IReadOnlyList rows = await service.GetFlsaAsync("E", TestContext.Current.CancellationToken); + + Assert.Equal(PersonnelDatabases.Pps, runner.ConnectionName); + Assert.Equal("usp_get_flsa", runner.Procedure); + Assert.Equal([StoredProcedureParameter.Text("statusType", "E", 1)], runner.Parameters); + Assert.Equal( + [ + new FlsaEmployeeRow("000123456", "Lovelace, Ada", "VME", "Professor", "EXEMPT", "ada@ucdavis.edu"), + new FlsaEmployeeRow(null, string.Empty, null, null, null, null), + ], + rows); + } + + [Fact] + public async Task GetFacultyAppointmentsAsync_AsksForEveryEmployeeInOneCall() + { + var table = new DataTable(); + foreach (string column in new[] { "EMPLOYEE_ID", "EMP_NAME", "APPT_DEPT", "TITLE", "HIRE_DATE" }) + { + table.Columns.Add(column, typeof(string)); + } + + table.Columns.Add("AGE", typeof(decimal)); + table.Rows.Add("000123456", "Lovelace, Ada", "VME", "PROF-AY ", "07/01/1995", 61m); + table.Rows.Add(DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, string.Empty, DBNull.Value); + var runner = new RecordingRunner(table); + var service = new PersonnelReportDataService(runner); + + IReadOnlyList rows = + await service.GetFacultyAppointmentsAsync("B", TestContext.Current.CancellationToken); + + Assert.Equal("usp_get_facultyList", runner.Procedure); + Assert.Equal( + [ + StoredProcedureParameter.Text("facultyType", "B", 1), + StoredProcedureParameter.Text("deptCode", string.Empty, 6), + StoredProcedureParameter.Text("employeeID", "All", 11), + ], + runner.Parameters); + Assert.Equal( + [ + new FacultyAppointmentRow("000123456", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "VME", "PROF-AY"), + new FacultyAppointmentRow(string.Empty, string.Empty, null, null, null, null), + ], + rows); + } +} diff --git a/test/Personnel/PersonnelTestDoubles.cs b/test/Personnel/PersonnelTestDoubles.cs new file mode 100644 index 000000000..a1cf9067e --- /dev/null +++ b/test/Personnel/PersonnelTestDoubles.cs @@ -0,0 +1,41 @@ +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Services; + +namespace Viper.test.Personnel; + +/// +/// Returns canned rows and records what each report asked for. +/// +internal sealed class StubPersonnelReportDataService : IPersonnelReportDataService +{ + public IReadOnlyList PeopleOnLeave { get; init; } = []; + + public (string Type, DateOnly Start, DateOnly End)? LeaveRequest { get; private set; } + + public IReadOnlyList FlsaEmployees { get; init; } = []; + + public string? FlsaRequest { get; private set; } + + public IReadOnlyList FacultyAppointments { get; init; } = []; + + public string? FacultyRequest { get; private set; } + + public Task> GetPeopleOnLeaveAsync( + string employeeType, DateOnly startDate, DateOnly endDate, CancellationToken ct) + { + LeaveRequest = (employeeType, startDate, endDate); + return Task.FromResult(PeopleOnLeave); + } + + public Task> GetFlsaAsync(string statusType, CancellationToken ct) + { + FlsaRequest = statusType; + return Task.FromResult(FlsaEmployees); + } + + public Task> GetFacultyAppointmentsAsync(string facultyType, CancellationToken ct) + { + FacultyRequest = facultyType; + return Task.FromResult(FacultyAppointments); + } +} diff --git a/test/Reports/Data/DataRecordExtensionsTests.cs b/test/Reports/Data/DataRecordExtensionsTests.cs new file mode 100644 index 000000000..0d6b8eac9 --- /dev/null +++ b/test/Reports/Data/DataRecordExtensionsTests.cs @@ -0,0 +1,105 @@ +using System.Data; +using Viper.Areas.Reports.Data; + +namespace Viper.test.Reports; + +public sealed class DataRecordExtensionsTests +{ + private static DataTableReader Reader(object text, object date, object number) + { + var table = new DataTable(); + table.Columns.Add("text", typeof(string)); + table.Columns.Add("date", typeof(DateTime)); + table.Columns.Add("number", typeof(int)); + table.Rows.Add(text, date, number); + DataTableReader reader = table.CreateDataReader(); + reader.Read(); + return reader; + } + + [Fact] + public void GetTrimmedString_TrimsCharPadding() + { + using DataTableReader reader = Reader("Medicine ", DBNull.Value, 7); + + Assert.Equal("Medicine", reader.GetTrimmedString("text")); + Assert.Equal("7", reader.GetTrimmedString("number")); + } + + [Fact] + public void GetTrimmedString_Null_IsNull() + { + using DataTableReader reader = Reader(DBNull.Value, DBNull.Value, 7); + + Assert.Null(reader.GetTrimmedString("text")); + } + + [Fact] + public void GetDateOnly_DropsTheTime() + { + using DataTableReader reader = Reader("a", new DateTime(2026, 7, 1, 13, 30, 0, DateTimeKind.Local), 7); + + Assert.Equal(new DateOnly(2026, 7, 1), reader.GetDateOnly("date")); + } + + [Fact] + public void GetDateOnly_Null_IsNull() + { + using DataTableReader reader = Reader("a", DBNull.Value, 7); + + Assert.Null(reader.GetDateOnly("date")); + } + + [Theory] + [InlineData("07/01/1995 ", 1995, 7, 1)] + [InlineData("12/31/2020", 2020, 12, 31)] + public void GetDateOnlyFromText_ReadsTheFormat(string text, int year, int month, int day) + { + using DataTableReader reader = Reader(text, DBNull.Value, 7); + + Assert.Equal(new DateOnly(year, month, day), reader.GetDateOnlyFromText("text", "MM/dd/yyyy")); + } + + [Theory] + [InlineData("")] + [InlineData("not a date")] + public void GetDateOnlyFromText_BlankOrUnreadable_IsNull(string text) + { + using DataTableReader reader = Reader(text, DBNull.Value, 7); + + Assert.Null(reader.GetDateOnlyFromText("text", "MM/dd/yyyy")); + } + + [Fact] + public void GetDateOnlyFromText_Null_IsNull() + { + using DataTableReader reader = Reader(DBNull.Value, DBNull.Value, 7); + + Assert.Null(reader.GetDateOnlyFromText("text", "MM/dd/yyyy")); + } + + [Fact] + public void GetNullableInt32_ConvertsAnyNumber() + { + var table = new DataTable(); + table.Columns.Add("whole", typeof(decimal)); + table.Columns.Add("missing", typeof(decimal)); + table.Rows.Add(61m, DBNull.Value); + using DataTableReader reader = table.CreateDataReader(); + reader.Read(); + + Assert.Equal(61, reader.GetNullableInt32("whole")); + Assert.Null(reader.GetNullableInt32("missing")); + } + + [Fact] + public void NullRecord_Throws() + { + IDataRecord record = null!; + + Assert.Throws(() => record.GetTrimmedString("text")); + Assert.Throws(() => record.GetDateOnly("date")); + Assert.Throws(() => record.GetDateOnlyFromText("text", "MM/dd/yyyy")); + Assert.Throws(() => record.GetNullableInt32("number")); + } +} diff --git a/test/Reports/Data/FakeDb.cs b/test/Reports/Data/FakeDb.cs new file mode 100644 index 000000000..5740e0518 --- /dev/null +++ b/test/Reports/Data/FakeDb.cs @@ -0,0 +1,166 @@ +using System.Data; +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Data.SqlClient; +using Viper.Areas.Reports.Data; + +namespace Viper.test.Reports; + +/// +/// Hands out one and records the name it was asked for. +/// +internal sealed class FakeDbConnectionFactory : IDbConnectionFactory +{ + public FakeDbConnectionFactory(DataTable result) + { + Connection = new FakeDbConnection(result); + } + + public FakeDbConnection Connection { get; } + + public string? RequestedName { get; private set; } + + public DbConnection Create(string connectionStringName) + { + RequestedName = connectionStringName; + return Connection; + } +} + +/// +/// A connection whose commands return a fixed table, so the stored procedure runner can be +/// tested without SQL Server. It records whether it was opened and disposed, and the last command. +/// +internal sealed class FakeDbConnection : DbConnection +{ + private readonly DataTable _result; + private ConnectionState _state = ConnectionState.Closed; + + public FakeDbConnection(DataTable result) + { + _result = result; + } + + public FakeDbCommand? LastCommand { get; private set; } + + public bool WasDisposed { get; private set; } + + [AllowNull] + public override string ConnectionString { get; set; } = string.Empty; + + public override string Database => "Fake"; + + public override string DataSource => "Fake"; + + public override string ServerVersion => "0"; + + public override ConnectionState State => _state; + + public override void ChangeDatabase(string databaseName) + { + throw new NotSupportedException(); + } + + public override void Close() + { + _state = ConnectionState.Closed; + } + + public override void Open() + { + _state = ConnectionState.Open; + } + + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) + { + throw new NotSupportedException(); + } + + protected override DbCommand CreateDbCommand() + { + LastCommand = new FakeDbCommand(this, _result); + return LastCommand; + } + + protected override void Dispose(bool disposing) + { + WasDisposed = true; + base.Dispose(disposing); + } +} + +/// +/// A command that returns its table's rows. Parameters use a real SqlCommand's collection, so +/// they behave exactly as they would against SQL Server. +/// +internal sealed class FakeDbCommand : DbCommand +{ + private readonly DataTable _result; + private readonly SqlCommand _parameters = new(); + + public FakeDbCommand(DbConnection connection, DataTable result) + { + DbConnection = connection; + _result = result; + } + + public bool WasDisposed { get; private set; } + + [AllowNull] + public override string CommandText { get; set; } = string.Empty; + + public override int CommandTimeout { get; set; } + + public override CommandType CommandType { get; set; } + + public override bool DesignTimeVisible { get; set; } + + public override UpdateRowSource UpdatedRowSource { get; set; } + + protected override DbConnection? DbConnection { get; set; } + + protected override DbParameterCollection DbParameterCollection => _parameters.Parameters; + + protected override DbTransaction? DbTransaction { get; set; } + + public override void Cancel() + { + throw new NotSupportedException(); + } + + public override int ExecuteNonQuery() + { + throw new NotSupportedException(); + } + + public override object? ExecuteScalar() + { + throw new NotSupportedException(); + } + + public override void Prepare() + { + throw new NotSupportedException(); + } + + protected override DbParameter CreateDbParameter() + { + return new SqlParameter(); + } + + protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) + { + return _result.CreateDataReader(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _parameters.Dispose(); + } + + WasDisposed = true; + base.Dispose(disposing); + } +} diff --git a/test/Reports/Data/StoredProcedureParameterTests.cs b/test/Reports/Data/StoredProcedureParameterTests.cs new file mode 100644 index 000000000..1b8e74c4a --- /dev/null +++ b/test/Reports/Data/StoredProcedureParameterTests.cs @@ -0,0 +1,43 @@ +using System.Data; +using Viper.Areas.Reports.Data; + +namespace Viper.test.Reports; + +public sealed class StoredProcedureParameterTests +{ + [Fact] + public void Text_IsAnAnsiStringWithItsDeclaredSize() + { + StoredProcedureParameter parameter = StoredProcedureParameter.Text("employeeType", "F", 1); + + Assert.Equal("@employeeType", parameter.Name); + Assert.Equal(DbType.AnsiString, parameter.Type); + Assert.Equal("F", parameter.Value); + Assert.Equal(1, parameter.Size); + } + + [Fact] + public void Date_IsMidnightOnTheDate() + { + StoredProcedureParameter parameter = StoredProcedureParameter.Date("@startDate", new DateOnly(2026, 7, 1)); + + Assert.Equal("@startDate", parameter.Name); + Assert.Equal(DbType.DateTime, parameter.Type); + Assert.Equal(new DateTime(2026, 7, 1, 0, 0, 0, DateTimeKind.Unspecified), parameter.Value); + Assert.Null(parameter.Size); + } + + [Fact] + public void Date_Null_HasNoValue() + { + Assert.Null(StoredProcedureParameter.Date("endDate", null).Value); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void BlankName_Throws(string name) + { + Assert.Throws(() => StoredProcedureParameter.Text(name, "F", 1)); + } +} diff --git a/test/Reports/Data/StoredProcedureRunnerTests.cs b/test/Reports/Data/StoredProcedureRunnerTests.cs new file mode 100644 index 000000000..15faed833 --- /dev/null +++ b/test/Reports/Data/StoredProcedureRunnerTests.cs @@ -0,0 +1,85 @@ +using System.Data; +using System.Data.Common; +using Viper.Areas.Reports.Data; + +namespace Viper.test.Reports; + +public sealed class StoredProcedureRunnerTests +{ + private static DataTable People() + { + var table = new DataTable(); + table.Columns.Add("Name", typeof(string)); + table.Rows.Add("Ada"); + table.Rows.Add("Bo"); + return table; + } + + [Fact] + public async Task QueryAsync_CallsTheProcedureWithTypedParameters() + { + var connections = new FakeDbConnectionFactory(People()); + var runner = new StoredProcedureRunner(connections); + + await runner.QueryAsync( + "PPS", + "usp_get_people", + [StoredProcedureParameter.Text("type", "F", 1), StoredProcedureParameter.Date("from", null)], + record => record.GetString(0), + TestContext.Current.CancellationToken); + + FakeDbCommand command = Assert.IsType(connections.Connection.LastCommand); + Assert.Equal("PPS", connections.RequestedName); + Assert.Equal(CommandType.StoredProcedure, command.CommandType); + Assert.Equal("usp_get_people", command.CommandText); + Assert.Equal(StoredProcedureRunner.CommandTimeoutSeconds, command.CommandTimeout); + + DbParameter[] parameters = [.. command.Parameters.Cast()]; + Assert.Equal(["@type", "@from"], parameters.Select(parameter => parameter.ParameterName)); + Assert.Equal("F", parameters[0].Value); + Assert.Equal(DBNull.Value, parameters[1].Value); + } + + [Fact] + public async Task QueryAsync_MapsEveryRowAndClosesUp() + { + var connections = new FakeDbConnectionFactory(People()); + var runner = new StoredProcedureRunner(connections); + + IReadOnlyList names = await runner.QueryAsync( + "PPS", "usp_get_people", [], record => record.GetString(0), TestContext.Current.CancellationToken); + + Assert.Equal(["Ada", "Bo"], names); + Assert.True(connections.Connection.WasDisposed); + Assert.True(connections.Connection.LastCommand is { WasDisposed: true }); + } + + [Fact] + public async Task QueryAsync_OpensTheConnectionFirst() + { + var connections = new FakeDbConnectionFactory(People()); + var runner = new StoredProcedureRunner(connections); + ConnectionState stateWhileReading = ConnectionState.Closed; + + await runner.QueryAsync( + "PPS", + "usp_get_people", + [], + _ => stateWhileReading = connections.Connection.State, + TestContext.Current.CancellationToken); + + Assert.Equal(ConnectionState.Open, stateWhileReading); + } + + [Fact] + public async Task QueryAsync_BadArguments_Throw() + { + var runner = new StoredProcedureRunner(new FakeDbConnectionFactory(People())); + CancellationToken ct = TestContext.Current.CancellationToken; + + await Assert.ThrowsAsync(() => runner.QueryAsync("PPS", " ", [], record => 1, ct)); + await Assert.ThrowsAsync(() => runner.QueryAsync("PPS", "usp_x", null!, record => 1, ct)); + await Assert.ThrowsAsync( + () => runner.QueryAsync("PPS", "usp_x", [], null!, ct)); + } +} diff --git a/test/Reports/ReportBuilderTests.cs b/test/Reports/ReportBuilderTests.cs new file mode 100644 index 000000000..eccf3b6d5 --- /dev/null +++ b/test/Reports/ReportBuilderTests.cs @@ -0,0 +1,248 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportBuilderTests +{ + private static readonly IReadOnlyList SingleOption = [new("X", "Option X")]; + + #region Parameters + + [Fact] + public void Parameters_UseCamelCasePropertyNamesAndDeclaredTypes() + { + var builder = new ReportBuilder(); + TestReport.Standard(builder); + + Assert.Equal( + ["facultyType", "departments", "startDate", "endDate", "search", "minimumAge", "includeEmeriti"], + builder.Parameters.Select(parameter => parameter.Name)); + Assert.Equal( + [ + ReportParameterType.Choice, + ReportParameterType.MultiChoice, + ReportParameterType.Date, + ReportParameterType.Date, + ReportParameterType.Text, + ReportParameterType.Number, + ReportParameterType.Boolean, + ], + builder.Parameters.Select(parameter => parameter.Type)); + } + + [Fact] + public void Choice_EmptyOptions_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Choice(p => p.FacultyType, "Faculty type", [])); + } + + [Fact] + public void MultiChoice_NullOptions_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.MultiChoice(p => p.Departments, "Departments", null!)); + } + + [Fact] + public void Parameter_BlankLabel_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Text(p => p.Search, " ")); + } + + [Fact] + public void Parameter_NullSelector_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Text(null!, "Search")); + } + + [Fact] + public void Parameter_ComputedExpression_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Text(p => p.Search + "x", "Search")); + } + + [Fact] + public void Parameter_NestedProperty_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Text(p => p.Inner.Value, "Inner value")); + } + + [Fact] + public void Parameter_ReadOnlyProperty_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Text(p => p.Computed, "Computed")); + } + + [Fact] + public void Default_NullFactory_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Choice(p => p.FacultyType, "Type", SingleOption).Default(null!)); + } + + [Fact] + public void Parameter_WithoutDefault_HasNullDefaultInMetadata() + { + var builder = new ReportBuilder(); + builder.Number(p => p.MinimumAge, "Minimum age"); + + ReportParameterMetadata metadata = builder.Parameters[0].ToMetadata(); + + Assert.Null(metadata.DefaultValue); + Assert.False(metadata.Required); + Assert.Empty(metadata.Options); + } + + [Fact] + public void Validate_NullRuleOrBlankMessage_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Validate(null!, "Message")); + Assert.Throws(() => builder.Validate(_ => true, " ")); + } + + #endregion + + #region Columns + + [Fact] + public void Column_DefaultsToTextLeftAlignedWithPropertyKey() + { + var builder = new ReportBuilder(); + builder.Column(r => r.Department, "Department"); + + ReportColumnMetadata metadata = builder.Columns[0].ToMetadata(); + + Assert.Equal(new ReportColumnMetadata("department", "Department", ReportColumnFormat.Text, ReportAlignment.Left, null), metadata); + } + + [Fact] + public void Column_ValueReadsFromRow() + { + var builder = new ReportBuilder(); + builder.Column(r => r.Age, "Age"); + var row = new SampleRow("Ada", "APC", 61, 100_000m, new DateOnly(2001, 9, 1)); + + Assert.Equal(61, builder.Columns[0].Value(row)); + } + + [Fact] + public void Column_ComputedSelectorWithKey_UsesKey() + { + var builder = new ReportBuilder(); + builder.Column(r => r.Name + " (" + r.Department + ")", "Name and department", "nameAndDepartment"); + var row = new SampleRow("Ada", "APC", 61, 100_000m, new DateOnly(2001, 9, 1)); + + Assert.Equal("nameAndDepartment", builder.Columns[0].Key); + Assert.Equal("Ada (APC)", builder.Columns[0].Value(row)); + } + + [Fact] + public void Column_ComputedSelectorWithoutKey_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Column(r => r.Name.Length, "Name length")); + } + + [Fact] + public void Column_FieldSelectorWithoutKey_Throws() + { + var builder = new ReportBuilder<(string Code, int Count), SampleParams>(); + + Assert.Throws(() => builder.Column(r => r.Code, "Code")); + } + + [Fact] + public void Column_InvalidArguments_Throw() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Column(null!, "Name")); + Assert.Throws(() => builder.Column(r => r.Name, " ")); + Assert.Throws(() => builder.Column(r => r.Name, "Name", " ")); + } + + [Fact] + public void ColumnFormats_SetFormatAlignmentAndDecimals() + { + var builder = new ReportBuilder(); + builder.Column(r => r.Age, "Age").AsNumber(1); + builder.Column(r => r.Salary, "Salary").AsCurrency(); + builder.Column(r => r.Age, "Share", "share").AsPercent(2); + builder.Column(r => r.HireDate, "Hire date").AsDate(); + builder.Column(r => r.Department, "Departments", "departments").AsList(); + + ReportColumnMetadata[] columns = [.. builder.Columns.Select(column => column.ToMetadata())]; + + Assert.Equal((ReportColumnFormat.Number, ReportAlignment.Right, 1), Describe(columns[0])); + Assert.Equal((ReportColumnFormat.Currency, ReportAlignment.Right, 2), Describe(columns[1])); + Assert.Equal((ReportColumnFormat.Percent, ReportAlignment.Right, 2), Describe(columns[2])); + Assert.Equal((ReportColumnFormat.Date, ReportAlignment.Center, (int?)null), Describe(columns[3])); + Assert.Equal((ReportColumnFormat.List, ReportAlignment.Left, (int?)null), Describe(columns[4])); + } + + [Fact] + public void Align_OverridesFormatAlignment() + { + var builder = new ReportBuilder(); + builder.Column(r => r.HireDate, "Hire date").AsDate().Align(ReportAlignment.Left); + + Assert.Equal(ReportAlignment.Left, builder.Columns[0].Align); + } + + [Fact] + public void NegativeDecimals_Throw() + { + var builder = new ReportBuilder(); + ReportColumnBuilder column = builder.Column(r => r.Age, "Age"); + + Assert.Throws(() => column.AsNumber(-1)); + Assert.Throws(() => column.AsPercent(-1)); + } + + [Fact] + public void VisibleWhen_ControlsVisibility() + { + var builder = new ReportBuilder(); + builder.Column(r => r.Name, "Name"); + builder.Column(r => r.Salary, "Salary").VisibleWhen(context => context.HasPermission(TestReport.SalaryPermission)); + + ReportContext withSalary = TestReport.ContextWith(TestReport.SalaryPermission); + ReportContext withoutSalary = TestReport.ContextWith(); + + Assert.True(builder.Columns[0].IsVisible(withoutSalary)); + Assert.True(builder.Columns[1].IsVisible(withSalary)); + Assert.False(builder.Columns[1].IsVisible(withoutSalary)); + } + + [Fact] + public void VisibleWhen_NullPredicate_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Column(r => r.Name, "Name").VisibleWhen(null!)); + } + + #endregion + + private static (ReportColumnFormat Format, ReportAlignment Align, int? Decimals) Describe(ReportColumnMetadata column) + { + return (column.Format, column.Align, column.Decimals); + } +} diff --git a/test/Reports/ReportContextTests.cs b/test/Reports/ReportContextTests.cs new file mode 100644 index 000000000..9775569f1 --- /dev/null +++ b/test/Reports/ReportContextTests.cs @@ -0,0 +1,70 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportContextTests +{ + [Fact] + public void Constructor_NullPermissionCheck_Throws() + { + Assert.Throws(() => new ReportContext("user", null!)); + } + + [Fact] + public void LoginId_ReturnsSuppliedValue() + { + var context = new ReportContext("jdoe", _ => false); + + Assert.Equal("jdoe", context.LoginId); + } + + [Fact] + public void HasPermission_DelegatesToPermissionCheck() + { + ReportContext context = TestReport.ContextWith("SVMSecure.A"); + + Assert.True(context.HasPermission("SVMSecure.A")); + Assert.False(context.HasPermission("SVMSecure.B")); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void HasPermission_BlankPermission_ReturnsFalseWithoutCheckingUser(string permission) + { + int checks = 0; + var context = new ReportContext("jdoe", _ => + { + checks++; + return true; + }); + + Assert.False(context.HasPermission(permission)); + Assert.Equal(0, checks); + } + + [Fact] + public void HasAnyPermission_OneMatch_ReturnsTrue() + { + ReportContext context = TestReport.ContextWith("SVMSecure.B"); + + Assert.True(context.HasAnyPermission(["SVMSecure.A", "SVMSecure.B"])); + } + + [Fact] + public void HasAnyPermission_NoMatchOrEmptyList_ReturnsFalse() + { + ReportContext context = TestReport.ContextWith("SVMSecure.C"); + + Assert.False(context.HasAnyPermission(["SVMSecure.A", "SVMSecure.B"])); + Assert.False(context.HasAnyPermission([])); + } + + [Fact] + public void HasAnyPermission_NullList_Throws() + { + ReportContext context = TestReport.ContextWith(); + + Assert.Throws(() => context.HasAnyPermission(null!)); + } +} diff --git a/test/Reports/ReportCsvExporterTests.cs b/test/Reports/ReportCsvExporterTests.cs new file mode 100644 index 000000000..00569c1af --- /dev/null +++ b/test/Reports/ReportCsvExporterTests.cs @@ -0,0 +1,76 @@ +using System.Text; +using Viper.Areas.Reports.Exporters; + +namespace Viper.test.Reports; + +public sealed class ReportCsvExporterTests +{ + private readonly ReportCsvExporter _exporter = new(); + + private string[] Lines(ReportExport export) + { + byte[] bytes = _exporter.Export(export); + Assert.Equal(Encoding.UTF8.GetPreamble(), bytes[..3]); + string text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3); + Assert.EndsWith("\r\n", text, StringComparison.Ordinal); + return text[..^2].Split("\r\n"); + } + + [Fact] + public void Describes_ItsFormat() + { + Assert.Equal("csv", _exporter.Format); + Assert.Equal("text/csv", _exporter.ContentType); + Assert.Equal(".csv", _exporter.Extension); + } + + [Fact] + public void Plain_WritesHeaderAndOneLinePerRow() + { + string[] lines = Lines(ReportExportTestData.Export(ReportExportTestData.Plain())); + + Assert.Equal("Name,Department,Salary", lines[0]); + Assert.Equal("Ada,VME,\"$120,000.00\"", lines[1]); + Assert.Equal("Cy,VME ,", lines[3]); + Assert.Equal(6, lines.Length); + } + + [Fact] + public void Grouped_AddsGroupAndNotesColumns() + { + string[] lines = Lines(ReportExportTestData.Export(ReportExportTestData.Full(), confidential: true)); + + Assert.Equal("Group,Name,Age,Salary,Hire date,Ethnicities,Notes", lines[0]); + Assert.Equal("(Not specified),Ed,29,\"$70,000.00\",08/15/2022,White,Under 30", lines[1]); + Assert.Equal("VME,Ada,61,\"$120,000.00\",07/01/1995,\"Asian, White\",60+", lines[3]); + Assert.Equal("VME,Cy,38,,09/01/2018,Hispanic,No salary", lines[4]); + Assert.Equal("VME,Di,66,\"$150,000.00\",03/01/1990,,Retirement age; 60+", lines[5]); + } + + [Fact] + public void EdgeCases_SanitizeFormulasAndKeepTextInNumericColumns() + { + string[] lines = Lines(ReportExportTestData.Export(ReportExportTestData.EdgeCases())); + + Assert.Equal("Name,When,Share,Amount,Notes", lines[0]); + Assert.StartsWith("'=cmd|' /C calc'!A0,01/02/2026,", lines[1], StringComparison.Ordinal); + Assert.EndsWith(",pending,Check", lines[1], StringComparison.Ordinal); + Assert.Equal(2, lines.Length); + } + + [Theory] + [InlineData("plain", "plain")] + [InlineData("a,b", "\"a,b\"")] + [InlineData("say \"hi\"", "\"say \"\"hi\"\"\"")] + [InlineData("line\nbreak", "\"line\nbreak\"")] + public void Quote_FollowsRfc4180(string value, string expected) + { + Assert.Equal(expected, ReportCsvExporter.Quote(value)); + } + + [Fact] + public void NullExport_Throws() + { + Assert.Throws(() => _exporter.Export(null!)); + } +} diff --git a/test/Reports/ReportDefinitionContractTests.cs b/test/Reports/ReportDefinitionContractTests.cs new file mode 100644 index 000000000..5d9f1b2a2 --- /dev/null +++ b/test/Reports/ReportDefinitionContractTests.cs @@ -0,0 +1,87 @@ +using System.Text.Json; +using Viper.Areas.Personnel.Reports; +using Viper.Areas.Reports.Engine; +using Viper.test.Personnel; + +namespace Viper.test.Reports; + +/// +/// Checks every report definition against the rules the engine relies on but the compiler can't +/// enforce. New reports join by being added to , so each one gets these +/// checks without writing them again. +/// +public sealed class ReportDefinitionContractTests +{ + private static readonly JsonSerializerOptions WebJson = new(JsonSerializerDefaults.Web); + + private static readonly Dictionary> Definitions = new(StringComparer.Ordinal) + { + ["test.sample"] = () => new TestReport(), + ["personnel.employees-on-leave"] = () => + new EmployeesOnLeaveReport(new StubPersonnelReportDataService(), new FixedTimeProvider(DateTimeOffset.UnixEpoch)), + ["personnel.exempt-non-exempt"] = () => new ExemptStatusReport(new StubPersonnelReportDataService()), + ["personnel.faculty-profile"] = () => new FacultyProfileReport(new StubPersonnelReportDataService()), + }; + + public static TheoryData DefinitionKeys() + { + return [.. Definitions.Keys]; + } + + private static ReportContext Everyone() + { + return new ReportContext("contract", _ => true); + } + + [Theory] + [MemberData(nameof(DefinitionKeys))] + public void Definition_HasAValidRegistryIdentity(string key) + { + IReportDefinition definition = Definitions[key](); + + var registry = new ReportRegistry([definition]); + + Assert.Same(definition, registry.Find(key)); + } + + [Theory] + [MemberData(nameof(DefinitionKeys))] + public void Metadata_SerializesToJson(string key) + { + IReportDefinition definition = Definitions[key](); + + string json = JsonSerializer.Serialize(definition.GetMetadata(Everyone()), WebJson); + + Assert.Contains($"\"key\":\"{key}\"", json, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(DefinitionKeys))] + public void EveryParameterName_BindsFromJson(string key) + { + IReportDefinition definition = Definitions[key](); + IEnumerable names = definition.GetMetadata(Everyone()).Parameters.Select(parameter => parameter.Name); + using JsonDocument body = JsonDocument.Parse("{" + string.Join(",", names.Select(name => $"\"{name}\":null")) + "}"); + + bool bound = ReportParameterBinder.TryBind(definition.ParametersType, body.RootElement, out _, out ReportValidationError? error); + + Assert.True(bound, error?.Message); + } + + [Theory] + [MemberData(nameof(DefinitionKeys))] + public async Task DefaultParameters_RunAndSerialize(string key) + { + IReportDefinition definition = Definitions[key](); + ReportContext context = Everyone(); + bool bound = ReportParameterBinder.TryBind(definition.ParametersType, null, out object? parameters, out _); + Assert.True(bound); + Assert.NotNull(parameters); + Assert.Empty(definition.PrepareParameters(parameters)); + + ReportResult result = await definition.RunAsync(parameters, context, DateTimeOffset.UnixEpoch, TestContext.Current.CancellationToken); + + Assert.Equal(key, result.Key); + Assert.NotEmpty(JsonSerializer.Serialize(result, WebJson)); + } +} diff --git a/test/Reports/ReportDefinitionTests.cs b/test/Reports/ReportDefinitionTests.cs new file mode 100644 index 000000000..2ab2d2732 --- /dev/null +++ b/test/Reports/ReportDefinitionTests.cs @@ -0,0 +1,263 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportDefinitionTests +{ + #region Metadata and access + + [Fact] + public void GetMetadata_DescribesReportParametersAndColumns() + { + var report = new TestReport(); + + ReportDefinitionMetadata metadata = report.GetMetadata( + TestReport.ContextWith(TestReport.RunPermission, TestReport.SalaryPermission)); + + Assert.Equal("test.sample", metadata.Key); + Assert.Equal("Sample report", metadata.Title); + Assert.Equal("Test", metadata.Area); + Assert.Equal("A report used by tests.", metadata.Description); + Assert.Equal(7, metadata.Parameters.Count); + Assert.Equal( + new ReportParameterMetadata("facultyType", "Faculty type", ReportParameterType.Choice, true, "S", TestReport.FacultyTypes), + metadata.Parameters[0]); + Assert.Equal(TestReport.DefaultStart, metadata.Parameters[2].DefaultValue); + Assert.Equal(["name", "department", "age", "salary", "hireDate"], metadata.Columns.Select(column => column.Key)); + } + + [Fact] + public void GetMetadata_HidesColumnsTheUserCannotSee() + { + var report = new TestReport(); + + ReportDefinitionMetadata metadata = report.GetMetadata(TestReport.ContextWith(TestReport.RunPermission)); + + Assert.DoesNotContain(metadata.Columns, column => column.Key == "salary"); + } + + [Fact] + public void GetMetadata_NullContext_Throws() + { + var report = new TestReport(); + + Assert.Throws(() => report.GetMetadata(null!)); + } + + [Fact] + public void Layout_IsConfiguredOnce() + { + var report = new TestReport(); + ReportContext context = TestReport.ContextWith(); + + report.GetMetadata(context); + report.PrepareParameters(new SampleParams()); + + Assert.Equal(1, report.ConfigureCalls); + } + + [Fact] + public void CanRun_RequiresAnyReportPermission() + { + var report = new TestReport(permissions: ["SVMSecure.Test.A", "SVMSecure.Test.B"]); + + Assert.True(report.CanRun(TestReport.ContextWith("SVMSecure.Test.B"))); + Assert.False(report.CanRun(TestReport.ContextWith("SVMSecure.Test.C"))); + } + + [Fact] + public void CanRun_NullContext_Throws() + { + var report = new TestReport(); + + Assert.Throws(() => report.CanRun(null!)); + } + + #endregion + + #region Layout validation + + [Fact] + public void Layout_WithoutColumns_Throws() + { + var report = new TestReport(report => report.Text(p => p.Search, "Search")); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + [Fact] + public void Layout_DuplicateColumnKey_Throws() + { + var report = new TestReport(report => + { + report.Column(r => r.Name, "Name"); + report.Column(r => r.Department, "Also name", "NAME"); + }); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + [Fact] + public void Layout_DuplicateParameter_Throws() + { + var report = new TestReport(report => + { + report.Text(p => p.Search, "Search"); + report.Text(p => p.Search, "Search again"); + report.Column(r => r.Name, "Name"); + }); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + #endregion + + #region Parameter preparation + + [Fact] + public void PrepareParameters_FillsEmptyValuesWithDefaults() + { + var report = new TestReport(); + var parameters = new SampleParams { FacultyType = " " }; + + IReadOnlyList errors = report.PrepareParameters(parameters); + + Assert.Empty(errors); + Assert.Equal("S", parameters.FacultyType); + Assert.Equal(TestReport.DefaultStart, parameters.StartDate); + } + + [Fact] + public void PrepareParameters_KeepsSuppliedValues() + { + var report = new TestReport(); + var parameters = new SampleParams + { + FacultyType = "F", + Departments = ["APC", "VME"], + StartDate = new DateOnly(2025, 1, 1), + EndDate = new DateOnly(2025, 6, 30), + Search = "smith", + MinimumAge = 60, + IncludeEmeriti = false, + }; + + IReadOnlyList errors = report.PrepareParameters(parameters); + + Assert.Empty(errors); + Assert.Equal("F", parameters.FacultyType); + Assert.Equal(new DateOnly(2025, 1, 1), parameters.StartDate); + } + + [Theory] + [InlineData(null)] + [InlineData(" ")] + public void PrepareParameters_MissingRequiredValue_ReturnsFieldError(string? search) + { + var report = new TestReport(report => + { + report.Text(p => p.Search, "Search").Required(); + report.Column(r => r.Name, "Name"); + }); + + IReadOnlyList errors = report.PrepareParameters(new SampleParams { Search = search }); + + Assert.Equal([new ReportValidationError("search", "Search is required.")], errors); + } + + [Fact] + public void PrepareParameters_EmptyRequiredList_ReturnsFieldError() + { + var report = new TestReport(report => + { + report.MultiChoice(p => p.Departments, "Departments", TestReport.DepartmentOptions).Required(); + report.Column(r => r.Name, "Name"); + }); + + IReadOnlyList errors = report.PrepareParameters(new SampleParams { Departments = [] }); + + Assert.Equal([new ReportValidationError("departments", "Departments is required.")], errors); + } + + [Fact] + public void PrepareParameters_UnknownChoice_ReturnsFieldError() + { + var report = new TestReport(); + + IReadOnlyList errors = report.PrepareParameters(new SampleParams { FacultyType = "X" }); + + Assert.Equal( + [new ReportValidationError("facultyType", "Faculty type contains a value that is not an allowed option.")], + errors); + } + + [Fact] + public void PrepareParameters_UnknownValueInMultiChoice_ReturnsFieldError() + { + var report = new TestReport(); + + IReadOnlyList errors = + report.PrepareParameters(new SampleParams { Departments = ["APC", "XYZ"] }); + + Assert.Equal( + [new ReportValidationError("departments", "Departments contains a value that is not an allowed option.")], + errors); + } + + [Fact] + public void PrepareParameters_FailingRule_ReturnsRuleError() + { + var report = new TestReport(); + var parameters = new SampleParams { StartDate = new DateOnly(2025, 7, 1), EndDate = new DateOnly(2025, 6, 30) }; + + IReadOnlyList errors = report.PrepareParameters(parameters); + + Assert.Equal([new ReportValidationError("endDate", "End date must be on or after the start date.")], errors); + } + + [Fact] + public void PrepareParameters_RuleWithoutParameter_ReturnsFormLevelError() + { + var report = new TestReport(report => + { + report.Validate(p => p.Search is not null || p.MinimumAge is not null, "Enter a search or a minimum age."); + report.Column(r => r.Name, "Name"); + }); + + IReadOnlyList errors = report.PrepareParameters(new SampleParams()); + + Assert.Equal([new ReportValidationError(null, "Enter a search or a minimum age.")], errors); + } + + [Fact] + public void PrepareParameters_FieldErrors_SkipRules() + { + int ruleCalls = 0; + var report = new TestReport(report => + { + report.Text(p => p.Search, "Search").Required(); + report.Validate(_ => + { + ruleCalls++; + return false; + }, "Never reported."); + report.Column(r => r.Name, "Name"); + }); + + IReadOnlyList errors = report.PrepareParameters(new SampleParams()); + + Assert.Single(errors); + Assert.Equal(0, ruleCalls); + } + + [Fact] + public void PrepareParameters_WrongParameterType_Throws() + { + var report = new TestReport(); + + Assert.Throws(() => report.PrepareParameters("not parameters")); + Assert.Throws(() => report.PrepareParameters(null!)); + } + + #endregion +} diff --git a/test/Reports/ReportDescribeParametersTests.cs b/test/Reports/ReportDescribeParametersTests.cs new file mode 100644 index 000000000..f723f718a --- /dev/null +++ b/test/Reports/ReportDescribeParametersTests.cs @@ -0,0 +1,73 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportDescribeParametersTests +{ + [Fact] + public void DescribeParameters_UsesLabelsAndReadableValues() + { + var report = new TestReport(); + var parameters = new SampleParams + { + FacultyType = "F", + Departments = ["VME", "APC"], + StartDate = new DateOnly(2025, 7, 1), + Search = "smith", + MinimumAge = 60, + IncludeEmeriti = true, + }; + + IReadOnlyList filters = report.DescribeParameters(parameters); + + Assert.Equal( + [ + new ReportFilter("Faculty type", "Federation"), + new ReportFilter("Departments", "Medicine and Epidemiology, Anatomy, Physiology and Cell Biology"), + new ReportFilter("Start date", "07/01/2025"), + new ReportFilter("Search", "smith"), + new ReportFilter("Minimum age", "60"), + new ReportFilter("Include emeriti", "Yes"), + ], + filters); + } + + [Fact] + public void DescribeParameters_SkipsEmptyValuesAndShowsNo() + { + var report = new TestReport(); + + IReadOnlyList filters = report.DescribeParameters(new SampleParams { IncludeEmeriti = false, Search = " " }); + + Assert.Equal([new ReportFilter("Include emeriti", "No")], filters); + } + + [Fact] + public void DescribeParameters_UnknownChoice_ShowsTheRawValue() + { + var report = new TestReport(); + + IReadOnlyList filters = report.DescribeParameters(new SampleParams { FacultyType = "Z" }); + + Assert.Equal([new ReportFilter("Faculty type", "Z")], filters); + } + + [Fact] + public void DescribeParameters_WrongType_Throws() + { + Assert.Throws(() => new TestReport().DescribeParameters("parameters")); + } + + [Fact] + public void IsSensitive_FollowsTheLayout() + { + var sensitive = new TestReport(report => + { + report.Sensitive(); + report.Column(row => row.Name, "Name"); + }); + + Assert.False(new TestReport().IsSensitive); + Assert.True(sensitive.IsSensitive); + } +} diff --git a/test/Reports/ReportExcelExporterTests.cs b/test/Reports/ReportExcelExporterTests.cs new file mode 100644 index 000000000..37674857b --- /dev/null +++ b/test/Reports/ReportExcelExporterTests.cs @@ -0,0 +1,194 @@ +using ClosedXML.Excel; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Exporters; + +namespace Viper.test.Reports; + +public sealed class ReportExcelExporterTests +{ + private readonly ReportExcelExporter _exporter = new(); + + private MemoryStream Export(ReportExport export) + { + return new MemoryStream(_exporter.Export(export)); + } + + private static IXLCell FindCell(IXLWorksheet sheet, string text) + { + return sheet.CellsUsed().First(cell => cell.GetString() == text); + } + + private static int Argb(string html) + { + return XLColor.FromHtml(html).Color.ToArgb(); + } + + private static int FillArgb(IXLCell cell) + { + return cell.Style.Fill.BackgroundColor.Color.ToArgb(); + } + + [Fact] + public void Describes_ItsFormat() + { + Assert.Equal("xlsx", _exporter.Format); + Assert.Equal("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", _exporter.ContentType); + Assert.Equal(".xlsx", _exporter.Extension); + } + + [Fact] + public void Header_ShowsTitleGeneratedFiltersAndNotice() + { + using MemoryStream stream = Export(ReportExportTestData.Export( + ReportExportTestData.Full(), confidential: true, filters: ReportExportTestData.Filters)); + using var workbook = new XLWorkbook(stream); + IXLWorksheet sheet = workbook.Worksheet(1); + + Assert.Equal("Sample report", sheet.Name); + Assert.Equal("Sample report", sheet.Cell(1, 1).GetString()); + Assert.True(sheet.Cell(1, 1).Style.Font.Bold); + Assert.Equal(ReportExportText.Generated(TestReport.GeneratedAt), sheet.Cell(2, 1).GetString()); + Assert.Equal("Filters: Faculty type: Senate; Start date: 07/01/2026", sheet.Cell(3, 1).GetString()); + Assert.Equal(ReportExportText.ConfidentialNotice, sheet.Cell(4, 1).GetString()); + Assert.Equal("Sample report", workbook.Properties.Title); + } + + [Fact] + public void Header_WithoutFiltersOrNotice_StartsDataSooner() + { + using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Plain())); + using var workbook = new XLWorkbook(stream); + IXLWorksheet sheet = workbook.Worksheet(1); + + Assert.Equal("Name", sheet.Cell(4, 1).GetString()); + Assert.Equal("Ada", sheet.Cell(5, 1).GetString()); + Assert.Equal(120_000d, sheet.Cell(5, 3).GetDouble()); + Assert.Equal("$#,##0.00", sheet.Cell(5, 3).Style.NumberFormat.Format); + Assert.True(sheet.Cell(7, 3).IsEmpty()); + Assert.Single(sheet.Tables); + Assert.Single(workbook.Worksheets); + } + + [Fact] + public void Groups_WriteLabelsTypedRowsSubtotalsAndTotals() + { + using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Full())); + using var workbook = new XLWorkbook(stream); + IXLWorksheet sheet = workbook.Worksheet(1); + + IXLCell people = FindCell(sheet, "People"); + Assert.Equal(5d, people.CellRight().GetDouble()); + + IXLCell vme = FindCell(sheet, "VME"); + IXLCell header = vme.CellBelow(); + Assert.Equal("#", header.GetString()); + Assert.Equal("Notes", header.WorksheetRow().Cell(7).GetString()); + + IXLRow ada = header.WorksheetRow().RowBelow(); + Assert.Equal(1d, ada.Cell(1).GetDouble()); + Assert.Equal("Ada", ada.Cell(2).GetString()); + Assert.Equal(61d, ada.Cell(3).GetDouble()); + Assert.Equal(new DateTime(1995, 7, 1), ada.Cell(5).GetDateTime()); + Assert.Equal("mm/dd/yyyy", ada.Cell(5).Style.NumberFormat.Format); + Assert.Equal("Asian, White", ada.Cell(6).GetString()); + + IXLCell subtotal = sheet.CellsUsed().Last(cell => cell.GetString() == "Salaries"); + Assert.Equal(270_000d, subtotal.WorksheetRow().Cell(4).GetDouble()); + IXLCell total = FindCell(sheet, "All salaries"); + Assert.Equal(430_000d, total.WorksheetRow().Cell(4).GetDouble()); + Assert.Equal(3, sheet.Tables.Count()); + } + + [Fact] + public void Highlights_FillRowsAndCellsAndListLabelsInNotes() + { + using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Full())); + using var workbook = new XLWorkbook(stream); + IXLWorksheet sheet = workbook.Worksheet(1); + + IXLRow ada = FindCell(sheet, "Ada").WorksheetRow(); + Assert.Equal(Argb("#FFF4CE"), FillArgb(ada.Cell(3))); + Assert.Equal("60+", ada.Cell(7).GetString()); + + IXLRow di = FindCell(sheet, "Di").WorksheetRow(); + Assert.Equal(Argb("#EDEBE9"), FillArgb(di.Cell(2))); + Assert.Equal("Retirement age; 60+", di.Cell(7).GetString()); + + IXLRow ed = FindCell(sheet, "Ed").WorksheetRow(); + Assert.Equal("Under 30", ed.Cell(7).GetString()); + } + + [Fact] + public void PivotsAndCharts_GetTheirOwnSheets() + { + using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Full())); + using var workbook = new XLWorkbook(stream); + + Assert.Equal(["Sample report", "Sample report (2)", "Charts"], workbook.Worksheets.Select(sheet => sheet.Name)); + + IXLWorksheet pivot = workbook.Worksheet(2); + Assert.Equal("Total", pivot.Cell(2, 5).GetString()); + Assert.Equal("60+", pivot.Cell(3, 1).GetString()); + Assert.Equal(2d, pivot.Cell(3, 4).GetDouble()); + Assert.Equal(5d, pivot.Cell(5, 5).GetDouble()); + + IXLWorksheet charts = workbook.Worksheet(3); + Assert.Equal("Ages", charts.Cell(1, 1).GetString()); + Assert.Equal("Department ages: VME", FindCell(charts, "Department ages: VME").GetString()); + } + + [Fact] + public void EdgeCases_AreHandledWithoutErrors() + { + using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.EdgeCases())); + using var workbook = new XLWorkbook(stream); + IXLWorksheet sheet = workbook.Worksheet(1); + + // ClosedXML stores a leading apostrophe as Excel's quote prefix rather than as text, so + // find the row through its header and check the value can't run as a formula. + IXLRow row = FindCell(sheet, "Name").CellBelow().WorksheetRow(); + Assert.EndsWith("=cmd|' /C calc'!A0", row.Cell(1).GetString(), StringComparison.Ordinal); + Assert.False(row.Cell(1).HasFormula); + Assert.Equal(new DateTime(2026, 1, 2), row.Cell(2).GetDateTime()); + Assert.Equal(0.125d, row.Cell(3).GetDouble()); + Assert.Equal("0.0%", row.Cell(3).Style.NumberFormat.Format); + Assert.Equal("pending", row.Cell(4).GetString()); + Assert.Equal(Argb("#FDE7E9"), FillArgb(row.Cell(1))); + + Assert.Equal(3d, FindCell(sheet, "Unplaced").CellRight().GetDouble()); + Assert.True(FindCell(sheet, "Unknown").CellRight().IsEmpty()); + Assert.Single(sheet.Tables); + } + + [Fact] + public void NullExport_Throws() + { + Assert.Throws(() => _exporter.Export(null!)); + } + + [Fact] + public void UniqueSheetName_AddsNumberedSuffixWithinTheLengthLimit() + { + var used = new HashSet(StringComparer.OrdinalIgnoreCase); + string longName = new('x', 40); + + Assert.Equal("Report", ReportExcelExporter.UniqueSheetName("Report", used)); + Assert.Equal("Report (2)", ReportExcelExporter.UniqueSheetName("Report", used)); + Assert.Equal("Report (3)", ReportExcelExporter.UniqueSheetName("Report", used)); + Assert.Equal(new string('x', 31), ReportExcelExporter.UniqueSheetName(longName, used)); + Assert.Equal(new string('x', 27) + " (2)", ReportExcelExporter.UniqueSheetName(longName, used)); + } + + [Theory] + [InlineData(ReportColumnFormat.Number, null, "#,##0")] + [InlineData(ReportColumnFormat.Number, 2, "#,##0.00")] + [InlineData(ReportColumnFormat.Currency, 2, "$#,##0.00")] + [InlineData(ReportColumnFormat.Percent, 0, "0%")] + [InlineData(ReportColumnFormat.Percent, 1, "0.0%")] + public void NumberFormat_MatchesColumnFormat(ReportColumnFormat format, int? decimals, string expected) + { + var column = new ReportColumnMetadata("value", "Value", format, ReportAlignment.Right, decimals); + + Assert.Equal(expected, ReportExcelExporter.NumberFormat(column)); + } +} diff --git a/test/Reports/ReportExportTestData.cs b/test/Reports/ReportExportTestData.cs new file mode 100644 index 000000000..fb54ff52c --- /dev/null +++ b/test/Reports/ReportExportTestData.cs @@ -0,0 +1,98 @@ +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Exporters; + +namespace Viper.test.Reports; + +/// +/// Report results shaped for exporter tests, built through the real pipeline where possible. +/// +internal static class ReportExportTestData +{ + public static readonly IReadOnlyList Filters = [new("Faculty type", "Senate"), new("Start date", "07/01/2026")]; + + /// + /// Grouped by department with row numbers, subtotals, totals, a summary, flags, a pivot and + /// per-group and whole-report charts. + /// + public static ReportResult Full() + { + var report = new TestReport(report => + { + report.Sensitive(); + report.RowNumbers(); + report.Column(row => row.Name, "Name"); + report.Column(row => row.Age, "Age").AsNumber(); + report.Column(row => row.Salary, "Salary").AsCurrency(); + report.Column(row => row.HireDate, "Hire date").AsDate(); + report.Column(row => row.Ethnicities, "Ethnicities").AsList(); + report.Summary("People", report.Count()); + report.GroupBy(row => row.Department).Subtotal("Salaries", report.Sum(row => row.Salary), "salary"); + report.Total("All salaries", report.Sum(row => row.Salary), "salary"); + report.Highlight(row => row.Age >= 65, ReportTone.Muted, "Retirement age"); + report.Highlight(row => row.Age >= 60, ReportTone.Warning, "60+", "age"); + report.Highlight(row => row.Age < 30, ReportTone.Neutral, "Under 30"); + report.Badge(row => row.Salary is null, ReportTone.Info, "No salary", "salary"); + report.Pivot("Sample report", row => row.Age >= 60 ? "60+" : "Under 60", row => row.Department, report.Count()); + report.Chart("Ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()); + report.Chart("Department ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) + .PerGroup(minimumRows: 2); + }); + return TestReport.Run(report); + } + + /// + /// Ungrouped, no row numbers, no flags or totals. + /// + public static ReportResult Plain() + { + var report = new TestReport(report => + { + report.Column(row => row.Name, "Name"); + report.Column(row => row.Department, "Department"); + report.Column(row => row.Salary, "Salary").AsCurrency(); + }); + return TestReport.Run(report); + } + + /// + /// A hand-built result covering cases the pipeline never produces, so exporters handle any + /// well-formed result: unknown column keys, null totals, empty groups and text in numeric columns. + /// + public static ReportResult EdgeCases() + { + ReportColumnMetadata[] columns = + [ + new("name", "Name", ReportColumnFormat.Text, ReportAlignment.Left, null), + new("when", "When", ReportColumnFormat.Date, ReportAlignment.Center, null), + new("share", "Share", ReportColumnFormat.Percent, ReportAlignment.Right, 1), + new("amount", "Amount", ReportColumnFormat.Number, ReportAlignment.Right, null), + ]; + var row = new ReportRowResult( + 1, + new Dictionary + { + ["name"] = "=cmd|' /C calc'!A0", + ["when"] = new DateTime(2026, 1, 2, 0, 0, 0, DateTimeKind.Local), + ["share"] = 0.125m, + ["amount"] = "pending", + }, + [new ReportFlag(ReportFlagKind.Highlight, ReportTone.Negative, "Check", "missing")]); + return new ReportResult( + "test.edge", + "Edge cases", + TestReport.GeneratedAt, + 1, + false, + columns, + [], + [new ReportGroupResult(null, [row], [], []), new ReportGroupResult(null, [], [], [])], + [new ReportTotal("Unplaced", "missing", 3m), new ReportTotal("Unknown", null, null)], + [], + []); + } + + public static ReportExport Export(ReportResult result, bool confidential = false, IReadOnlyList? filters = null) + { + return new ReportExport(result, filters ?? [], confidential); + } +} diff --git a/test/Reports/ReportExportTextTests.cs b/test/Reports/ReportExportTextTests.cs new file mode 100644 index 000000000..f7e07ff42 --- /dev/null +++ b/test/Reports/ReportExportTextTests.cs @@ -0,0 +1,119 @@ +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Exporters; + +namespace Viper.test.Reports; + +public sealed class ReportExportTextTests +{ + private static readonly HashSet Columns = new(["name", "age"], StringComparer.Ordinal); + + private static readonly ReportColumnMetadata[] SalaryColumn = + [ + new("salary", "Salary", ReportColumnFormat.Currency, ReportAlignment.Right, 2), + ]; + + private static ReportFlag Highlight(ReportTone tone, string? columnKey = null) + { + return new ReportFlag(ReportFlagKind.Highlight, tone, tone.ToString(), columnKey); + } + + [Fact] + public void Generated_UsesUsDateAndTime() + { + Assert.Equal("Generated 09/29/2026 8:00 AM", ReportExportText.Generated(TestReport.GeneratedAt)); + } + + [Fact] + public void Filters_JoinsLabelsOrReturnsNull() + { + Assert.Null(ReportExportText.Filters([])); + Assert.Equal( + "Filters: Faculty type: Senate; Start date: 07/01/2026", + ReportExportText.Filters(ReportExportTestData.Filters)); + Assert.Throws(() => ReportExportText.Filters(null!)); + } + + [Fact] + public void HasNotes_NullResult_Throws() + { + Assert.Throws(() => ReportExportText.HasNotes(null!)); + } + + [Theory] + [InlineData(ReportTone.Neutral, null)] + [InlineData(ReportTone.Warning, "#FFF4CE")] + [InlineData(ReportTone.Muted, "#EDEBE9")] + public void ToneFill_MapsTonesToLightFills(ReportTone tone, string? expected) + { + Assert.Equal(expected, ReportExportText.ToneFill(tone)); + } + + [Fact] + public void CellFill_RowHighlightCoversEveryCell() + { + ReportFlag[] flags = [Highlight(ReportTone.Muted)]; + + Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, "name", Columns)); + Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, null, Columns)); + } + + [Fact] + public void CellFill_ColumnHighlightCoversOnlyItsColumn() + { + ReportFlag[] flags = [Highlight(ReportTone.Muted), Highlight(ReportTone.Warning, "age")]; + + Assert.Equal("#FFF4CE", ReportExportText.CellFill(flags, "age", Columns)); + Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, "name", Columns)); + Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, null, Columns)); + } + + [Fact] + public void CellFill_HighlightOnUnknownColumnCoversTheRow() + { + Assert.Equal("#FDE7E9", ReportExportText.CellFill([Highlight(ReportTone.Negative, "missing")], "name", Columns)); + } + + [Fact] + public void CellFill_IgnoresBadgesAndNeutralHighlights() + { + ReportFlag[] flags = + [ + Highlight(ReportTone.Info), + new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "Badge", "name"), + Highlight(ReportTone.Neutral), + ]; + + Assert.Equal("#DEECF9", ReportExportText.CellFill(flags, "name", Columns)); + Assert.Null(ReportExportText.CellFill([], "name", Columns)); + } + + [Fact] + public void CellFill_NullArguments_Throw() + { + Assert.Throws(() => ReportExportText.CellFill(null!, "name", Columns)); + Assert.Throws(() => ReportExportText.CellFill([], "name", null!)); + } + + [Fact] + public void FormatTotal_UsesTheColumnFormatWhenThereIsOne() + { + Assert.Equal("$1,234.50", ReportExportText.FormatTotal(new ReportTotal("Salaries", "salary", 1234.5m), SalaryColumn)); + Assert.Equal("1,234.5", ReportExportText.FormatTotal(new ReportTotal("People", null, 1234.5m), SalaryColumn)); + Assert.Equal("7", ReportExportText.FormatTotal(new ReportTotal("Other", "missing", 7m), SalaryColumn)); + Assert.Equal(string.Empty, ReportExportText.FormatTotal(new ReportTotal("None", "salary", null), SalaryColumn)); + } + + [Fact] + public void FormatTotal_NullArguments_Throw() + { + Assert.Throws(() => ReportExportText.FormatTotal(null!, SalaryColumn)); + Assert.Throws(() => ReportExportText.FormatTotal(new ReportTotal("T", null, 1m), null!)); + } + + [Fact] + public void FormatNumber_BlankForNull() + { + Assert.Equal(string.Empty, ReportExportText.FormatNumber(null)); + Assert.Equal("12,345.68", ReportExportText.FormatNumber(12345.678m)); + } +} diff --git a/test/Reports/ReportKeyTests.cs b/test/Reports/ReportKeyTests.cs new file mode 100644 index 000000000..c5323ef48 --- /dev/null +++ b/test/Reports/ReportKeyTests.cs @@ -0,0 +1,35 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportKeyTests +{ + [Theory] + [InlineData("personnel.employees-on-leave")] + [InlineData("a.b")] + [InlineData("clinical-scheduler.rotation-2")] + [InlineData("a1.b2")] + public void IsValid_WellFormedKey_ReturnsTrue(string key) + { + Assert.True(ReportKey.IsValid(key)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("nodot")] + [InlineData(".report")] + [InlineData("area.")] + [InlineData("a.b.c")] + [InlineData("-a.b")] + [InlineData("a-.b")] + [InlineData("a.-b")] + [InlineData("a.b-")] + [InlineData("Personnel.report")] + [InlineData("a.b_c")] + [InlineData("a.b c")] + public void IsValid_MalformedKey_ReturnsFalse(string? key) + { + Assert.False(ReportKey.IsValid(key)); + } +} diff --git a/test/Reports/ReportLayoutBuilderTests.cs b/test/Reports/ReportLayoutBuilderTests.cs new file mode 100644 index 000000000..2a6dd74bf --- /dev/null +++ b/test/Reports/ReportLayoutBuilderTests.cs @@ -0,0 +1,157 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportLayoutBuilderTests +{ + #region Argument validation + + [Fact] + public void GroupBy_Twice_Throws() + { + var builder = new ReportBuilder(); + builder.GroupBy(row => row.Department); + + Assert.Throws(() => builder.GroupBy(row => row.Name)); + } + + [Fact] + public void GroupBy_NullKey_Throws() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.GroupBy(null!)); + } + + [Fact] + public void Totals_InvalidArguments_Throw() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Total(" ", builder.Count())); + Assert.Throws(() => builder.Summary("People", null!)); + Assert.Throws(() => builder.GroupBy(row => row.Department).Subtotal("", builder.Count())); + } + + [Fact] + public void Flags_InvalidArguments_Throw() + { + var builder = new ReportBuilder(); + + Assert.Throws(() => builder.Highlight(null!, ReportTone.Warning, "Old")); + Assert.Throws(() => builder.Highlight(_ => true, ReportTone.Warning, " ")); + Assert.Throws(() => builder.Badge(_ => true, ReportTone.Info, "Emeritus", " ")); + } + + [Fact] + public void Pivots_InvalidArguments_Throw() + { + var builder = new ReportBuilder(); + ReportMeasure count = builder.Count(); + + Assert.Throws(() => builder.Pivot("Pivot", null!, row => row.Name, count)); + Assert.Throws(() => builder.PivotEach("Pivot", null!, row => row.Name, count)); + Assert.Throws(() => builder.Pivot(" ", row => row.Name, row => row.Name, count)); + Assert.Throws(() => builder.Pivot("Pivot", row => row.Name, null!, count)); + Assert.Throws(() => builder.Pivot("Pivot", row => row.Name, row => row.Name, null!)); + } + + [Fact] + public void Charts_InvalidArguments_Throw() + { + var builder = new ReportBuilder(); + ReportMeasure count = builder.Count(); + + Assert.Throws(() => builder.Chart(" ", ReportChartKind.Bar, row => row.Name, count)); + Assert.Throws(() => builder.Chart("Chart", ReportChartKind.Bar, null!, count)); + Assert.Throws(() => builder.Chart("Chart", ReportChartKind.Bar, row => row.Name, null!)); + + ReportChartBuilder chart = builder.Chart("Chart", ReportChartKind.Pie, row => row.Name, count); + Assert.Throws(() => chart.PerGroup(-1)); + Assert.Throws(() => chart.CategoryOrder(null!)); + } + + #endregion + + #region Layout validation + + [Fact] + public void UnknownTotalColumn_Throws() + { + var report = new TestReport(report => + { + report.Column(row => row.Name, "Name"); + report.Total("Total", report.Count(), "missing"); + }); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + [Fact] + public void UnknownSummaryColumn_Throws() + { + var report = new TestReport(report => + { + report.Column(row => row.Name, "Name"); + report.Summary("People", report.Count(), "missing"); + }); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + [Fact] + public void UnknownSubtotalColumn_Throws() + { + var report = new TestReport(report => + { + report.Column(row => row.Name, "Name"); + report.GroupBy(row => row.Department).Subtotal("People", report.Count(), "missing"); + }); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + [Fact] + public void UnknownFlagColumn_Throws() + { + var report = new TestReport(report => + { + report.Column(row => row.Name, "Name"); + report.Badge(_ => true, ReportTone.Info, "Badge", "missing"); + }); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + [Fact] + public void PerGroupChartWithoutGrouping_Throws() + { + var report = new TestReport(report => + { + report.Column(row => row.Name, "Name"); + report.Chart("Ages", ReportChartKind.Bar, row => row.Name, report.Count()).PerGroup(); + }); + + Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); + } + + [Fact] + public void KnownColumnsAndGroupedCharts_AreValid() + { + var report = new TestReport(report => + { + report.Column(row => row.Name, "Name"); + report.Column(row => row.Salary, "Salary"); + report.Total("Salaries", report.Sum(row => row.Salary), "salary"); + report.Highlight(row => row.Age > 60, ReportTone.Warning, "Over 60"); + report.GroupBy(row => row.Department).Subtotal("People", report.Count()); + report.Chart("Ages", ReportChartKind.Bar, row => row.Name, report.Count()).PerGroup(2); + }); + + ReportDefinitionMetadata metadata = report.GetMetadata(TestReport.ContextWith()); + + Assert.Equal(2, metadata.Columns.Count); + } + + #endregion +} diff --git a/test/Reports/ReportMeasureTests.cs b/test/Reports/ReportMeasureTests.cs new file mode 100644 index 000000000..4bd84cc25 --- /dev/null +++ b/test/Reports/ReportMeasureTests.cs @@ -0,0 +1,90 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportMeasureTests +{ + private static readonly ReportBuilder Builder = new(); + + #region ReportMath + + [Fact] + public void Sum_EmptyIsZero() + { + Assert.Equal(0m, ReportMath.Sum([])); + Assert.Equal(6m, ReportMath.Sum([1m, 2m, 3m])); + } + + [Fact] + public void AverageMinimumMaximum_EmptyIsNull() + { + Assert.Null(ReportMath.Average([])); + Assert.Null(ReportMath.Minimum([])); + Assert.Null(ReportMath.Maximum([])); + } + + [Fact] + public void AverageMinimumMaximum_ComputeFromValues() + { + decimal[] values = [4m, 1m, 7m]; + + Assert.Equal(4m, ReportMath.Average(values)); + Assert.Equal(1m, ReportMath.Minimum(values)); + Assert.Equal(7m, ReportMath.Maximum(values)); + } + + [Fact] + public void StandardDeviation_FewerThanTwoValues_IsNull() + { + Assert.Null(ReportMath.StandardDeviation([])); + Assert.Null(ReportMath.StandardDeviation([5m])); + } + + [Fact] + public void StandardDeviation_IsSampleStandardDeviation() + { + decimal? deviation = ReportMath.StandardDeviation([1m, 2m, 3m, 4m]); + + Assert.NotNull(deviation); + Assert.Equal(1.2910m, Math.Round(deviation.Value, 4)); + } + + #endregion + + #region Measure factories + + [Fact] + public void Count_CountsRows() + { + Assert.Equal(5m, Builder.Count().Compute(TestReport.Rows())); + } + + [Fact] + public void CountDistinct_IgnoresNullKeys() + { + ReportMeasure measure = Builder.CountDistinct(row => row.Salary); + + Assert.Equal(4m, measure.Compute(TestReport.Rows())); + } + + [Fact] + public void NumericMeasures_IgnoreNullValues() + { + IReadOnlyList rows = TestReport.Rows(); + + Assert.Equal(430_000m, Builder.Sum(row => row.Salary).Compute(rows)); + Assert.Equal(107_500m, Builder.Average(row => row.Salary).Compute(rows)); + Assert.Equal(70_000m, Builder.Minimum(row => row.Salary).Compute(rows)); + Assert.Equal(150_000m, Builder.Maximum(row => row.Salary).Compute(rows)); + Assert.NotNull(Builder.StandardDeviation(row => row.Age).Compute(rows)); + } + + [Fact] + public void MeasureFactories_NullSelector_Throws() + { + Assert.Throws(() => Builder.CountDistinct(null!)); + Assert.Throws(() => Builder.Sum(null!)); + } + + #endregion +} diff --git a/test/Reports/ReportParameterBinderTests.cs b/test/Reports/ReportParameterBinderTests.cs new file mode 100644 index 000000000..4bf2f1613 --- /dev/null +++ b/test/Reports/ReportParameterBinderTests.cs @@ -0,0 +1,107 @@ +using System.Text.Json; +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportParameterBinderTests +{ + private static JsonElement Json(string json) + { + using JsonDocument document = JsonDocument.Parse(json); + return document.RootElement.Clone(); + } + + [Fact] + public void TryBind_MissingBody_BindsEmptyParameters() + { + bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), null, out object? parameters, out ReportValidationError? error); + + Assert.True(bound); + Assert.Null(error); + Assert.Equal(new SampleParams(), parameters); + } + + [Fact] + public void TryBind_JsonNull_BindsEmptyParameters() + { + bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), Json("null"), out object? parameters, out _); + + Assert.True(bound); + Assert.IsType(parameters); + } + + [Fact] + public void TryBind_Object_BindsCamelCaseValues() + { + JsonElement json = Json("""{ "facultyType": "F", "departments": ["APC"], "startDate": "2025-07-01", "MinimumAge": 60 }"""); + + bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), json, out object? parameters, out _); + + Assert.True(bound); + SampleParams typed = Assert.IsType(parameters); + Assert.Equal("F", typed.FacultyType); + Assert.NotNull(typed.Departments); + Assert.Equal(["APC"], typed.Departments); + Assert.Equal(new DateOnly(2025, 7, 1), typed.StartDate); + Assert.Equal(60, typed.MinimumAge); + } + + [Fact] + public void TryBind_NonObject_ReturnsError() + { + bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), Json("[1, 2]"), out object? parameters, out ReportValidationError? error); + + Assert.False(bound); + Assert.Null(parameters); + Assert.Equal(new ReportValidationError(null, ReportParameterBinder.NotAnObjectMessage), error); + } + + [Fact] + public void TryBind_WrongValueType_ReturnsErrorForThatParameter() + { + bool bound = ReportParameterBinder.TryBind( + typeof(SampleParams), Json("""{ "minimumAge": "sixty" }"""), out _, out ReportValidationError? error); + + Assert.False(bound); + Assert.Equal(new ReportValidationError("minimumAge", ReportParameterBinder.UnreadableMessage), error); + } + + [Fact] + public void TryBind_UnknownParameter_ReturnsError() + { + bool bound = ReportParameterBinder.TryBind( + typeof(SampleParams), Json("""{ "facultyTyp": "S" }"""), out _, out ReportValidationError? error); + + Assert.False(bound); + Assert.NotNull(error); + Assert.Equal(ReportParameterBinder.UnreadableMessage, error.Message); + } + + [Fact] + public void TryBind_NullResult_ReturnsError() + { + bool bound = ReportParameterBinder.TryBind(typeof(NullParams), Json("{}"), out _, out ReportValidationError? error); + + Assert.False(bound); + Assert.NotNull(error); + } + + [Fact] + public void TryBind_NullType_Throws() + { + Assert.Throws(() => ReportParameterBinder.TryBind(null!, null, out _, out _)); + } + + [Theory] + [InlineData(null, null)] + [InlineData("$", null)] + [InlineData("$.", null)] + [InlineData("$.startDate", "startDate")] + [InlineData("$.departments[1]", "departments")] + [InlineData("$.inner.value", "inner")] + [InlineData("startDate", null)] + public void ParameterName_ExtractsTopLevelName(string? path, string? expected) + { + Assert.Equal(expected, ReportParameterBinder.ParameterName(path)); + } +} diff --git a/test/Reports/ReportPdfExporterTests.cs b/test/Reports/ReportPdfExporterTests.cs new file mode 100644 index 000000000..fa6843633 --- /dev/null +++ b/test/Reports/ReportPdfExporterTests.cs @@ -0,0 +1,61 @@ +using System.Text; +using QuestPDF.Infrastructure; +using Viper.Areas.Reports.Exporters; + +namespace Viper.test.Reports; + +/// +/// QuestPDF output can't be read back without a PDF parser, so these tests render every layout +/// path (groups, row numbers, notes, fills, totals, pivots, charts, header variants) and check +/// that a PDF comes out. The layout decisions themselves are unit-tested in +/// . +/// +public sealed class ReportPdfExporterTests +{ + private readonly ReportPdfExporter _exporter = new(); + + public ReportPdfExporterTests() + { + // Program.cs sets this at startup; unit tests don't run Program.cs. + QuestPDF.Settings.License = LicenseType.Community; + } + + private static void AssertIsPdf(byte[] bytes) + { + Assert.True(bytes.Length > 0); + Assert.Equal("%PDF-", Encoding.ASCII.GetString(bytes, 0, 5)); + } + + [Fact] + public void Describes_ItsFormat() + { + Assert.Equal("pdf", _exporter.Format); + Assert.Equal("application/pdf", _exporter.ContentType); + Assert.Equal(".pdf", _exporter.Extension); + } + + [Fact] + public void Full_WithFiltersAndNotice_RendersPdf() + { + AssertIsPdf(_exporter.Export(ReportExportTestData.Export( + ReportExportTestData.Full(), confidential: true, filters: ReportExportTestData.Filters))); + } + + [Fact] + public void Plain_RendersPdf() + { + AssertIsPdf(_exporter.Export(ReportExportTestData.Export(ReportExportTestData.Plain()))); + } + + [Fact] + public void EdgeCases_RenderPdf() + { + AssertIsPdf(_exporter.Export(ReportExportTestData.Export(ReportExportTestData.EdgeCases()))); + } + + [Fact] + public void NullExport_Throws() + { + Assert.Throws(() => _exporter.Export(null!)); + } +} diff --git a/test/Reports/ReportPipelineTests.cs b/test/Reports/ReportPipelineTests.cs new file mode 100644 index 000000000..47150dcea --- /dev/null +++ b/test/Reports/ReportPipelineTests.cs @@ -0,0 +1,264 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportPipelineTests +{ + private static void BasicColumns(ReportBuilder report) + { + report.Column(row => row.Name, "Name"); + report.Column(row => row.Age, "Age").AsNumber(); + report.Column(row => row.Salary, "Salary").AsCurrency() + .VisibleWhen(context => context.HasPermission(TestReport.SalaryPermission)); + } + + #region Ungrouped reports + + [Fact] + public void Ungrouped_ReturnsOneUnlabelledGroupWithNumberedRows() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.RowNumbers(); + }); + + ReportResult result = TestReport.Run(report); + + Assert.Equal("test.sample", result.Key); + Assert.Equal("Sample report", result.Title); + Assert.Equal(TestReport.GeneratedAt, result.GeneratedAt); + Assert.Equal(5, result.RowCount); + Assert.True(result.RowNumbers); + ReportGroupResult group = Assert.Single(result.Groups); + Assert.Null(group.Label); + Assert.Equal([1, 2, 3, 4, 5], group.Rows.Select(row => row.Number)); + Assert.Equal("Ada", group.Rows[0].Values["name"]); + Assert.Equal(120_000m, group.Rows[0].Values["salary"]); + Assert.Empty(group.Subtotals); + Assert.Empty(group.Charts); + } + + [Fact] + public void RowNumbers_DefaultToOff() + { + ReportResult result = TestReport.Run(new TestReport(BasicColumns)); + + Assert.False(result.RowNumbers); + } + + [Fact] + public void HiddenColumn_RemovesItsValuesTotalsSummariesAndFlags() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.Summary("People", report.Count()); + report.Summary("Top salary", report.Maximum(row => row.Salary), "salary"); + report.Total("Ages", report.Sum(row => row.Age), "age"); + report.Total("Salaries", report.Sum(row => row.Salary), "salary"); + report.Highlight(row => row.Salary > 100_000m, ReportTone.Info, "High salary", "salary"); + }); + + ReportResult result = TestReport.Run(report, TestReport.ContextWith(TestReport.RunPermission)); + + Assert.Equal(["name", "age"], result.Columns.Select(column => column.Key)); + Assert.DoesNotContain("salary", result.Groups[0].Rows[0].Values.Keys); + Assert.Equal([new ReportTotal("People", null, 5m)], result.Summary); + Assert.Equal([new ReportTotal("Ages", "age", 239m)], result.Totals); + Assert.All(result.Groups[0].Rows, row => Assert.Empty(row.Flags)); + } + + [Fact] + public void Flags_MarkMatchingRowsAndCells() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.Highlight(row => row.Age >= 65, ReportTone.Muted, "Retirement age"); + report.Badge(row => row.Age >= 60, ReportTone.Warning, "60+", "age"); + }); + + IReadOnlyList rows = TestReport.Run(report).Groups[0].Rows; + + Assert.Equal([new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "60+", "age")], rows[0].Flags); + Assert.Empty(rows[1].Flags); + Assert.Equal( + [ + new ReportFlag(ReportFlagKind.Highlight, ReportTone.Muted, "Retirement age", null), + new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "60+", "age"), + ], + rows[3].Flags); + } + + #endregion + + #region Grouping + + [Fact] + public void Grouping_NormalizesKeysOrdersGroupsAndRestartsNumbering() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.RowNumbers(); + report.GroupBy(row => row.Department) + .Subtotal("People", report.Count()) + .Subtotal("Salaries", report.Sum(row => row.Salary), "salary"); + }); + + ReportResult result = TestReport.Run(report); + + Assert.Equal([ReportPipeline.BlankKeyLabel, "apc", "VME"], result.Groups.Select(group => group.Label)); + ReportGroupResult vme = result.Groups[2]; + Assert.Equal(["Ada", "Cy", "Di"], vme.Rows.Select(row => row.Values["name"])); + Assert.Equal([1, 2, 3], vme.Rows.Select(row => row.Number)); + Assert.Equal( + [new ReportTotal("People", null, 3m), new ReportTotal("Salaries", "salary", 270_000m)], + vme.Subtotals); + } + + [Fact] + public void PerGroupCharts_SkipSmallGroups() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.GroupBy(row => row.Department); + report.Chart("Ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) + .PerGroup(minimumRows: 2) + .CategoryOrder("Under 60", "60+"); + }); + + ReportResult result = TestReport.Run(report); + + Assert.Empty(result.Charts); + Assert.Empty(result.Groups[0].Charts); + ReportChartResult vmeChart = Assert.Single(result.Groups[2].Charts); + Assert.Equal( + [new ReportChartPoint("Under 60", 1m), new ReportChartPoint("60+", 2m)], + vmeChart.Points); + } + + [Fact] + public void Charts_CountOnlyTheRowsTheyInclude() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.GroupBy(row => row.Department); + report.Chart("Ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) + .Where(row => row.Age < 60); + report.Chart("Department ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) + .PerGroup(minimumRows: 2) + .Where(row => row.Age < 60); + }); + + ReportResult result = TestReport.Run(report); + + // Ben, Cy and Ed are under 60; Ada and Di are left out of the chart but stay in the table. + Assert.Equal([new ReportChartPoint("Under 60", 3m)], Assert.Single(result.Charts).Points); + Assert.Equal(5, result.RowCount); + // VME has three rows but only Cy is charted, which is under the per-group minimum of two. + Assert.All(result.Groups, group => Assert.Empty(group.Charts)); + } + + #endregion + + #region Pivots and charts + + [Fact] + public void Pivot_ComputesCellsRowTotalsColumnTotalsAndGrandTotal() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.Pivot( + "Age band by department", + row => row.Age >= 60 ? "60+" : "Under 60", + row => row.Department, + report.Count()); + }); + + ReportPivotResult pivot = Assert.Single(TestReport.Run(report).Pivots); + + Assert.Equal("Age band by department", pivot.Title); + Assert.Equal([ReportPipeline.BlankKeyLabel, "apc", "VME"], pivot.ColumnKeys); + Assert.Equal(["60+", "Under 60"], pivot.Rows.Select(row => row.Key)); + Assert.Equal([0m, 0m, 2m], pivot.Rows[0].Values); + Assert.Equal([1m, 1m, 1m], pivot.Rows[1].Values); + Assert.Equal([2m, 3m], pivot.Rows.Select(row => row.Total)); + Assert.Equal([1m, 1m, 3m], pivot.ColumnTotals); + Assert.Equal(5m, pivot.GrandTotal); + } + + [Fact] + public void PivotEach_CountsEverySelection() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.PivotEach("Selections", row => row.Ethnicities ?? [], row => row.Department, report.Count()); + report.PivotEach("People", row => row.Ethnicities ?? [], row => row.Department, report.CountDistinct(row => row.Name)); + }); + + IReadOnlyList pivots = TestReport.Run(report).Pivots; + + ReportPivotRow white = pivots[0].Rows.Single(row => row.Key == "White"); + Assert.Equal([1m, 1m, 1m], white.Values); + Assert.Equal(5m, pivots[0].GrandTotal); + Assert.Equal(4m, pivots[1].GrandTotal); + } + + [Fact] + public void Chart_OrdersPreferredCategoriesFirst() + { + var report = new TestReport(report => + { + BasicColumns(report); + report.Chart("Departments", ReportChartKind.Pie, row => row.Department, report.Count()) + .CategoryOrder("VME", "Missing"); + }); + + ReportChartResult chart = Assert.Single(TestReport.Run(report).Charts); + + Assert.Equal("Departments", chart.Title); + Assert.Equal(ReportChartKind.Pie, chart.Kind); + Assert.Equal(["VME", ReportPipeline.BlankKeyLabel, "apc"], chart.Points.Select(point => point.Category)); + Assert.Equal(3m, chart.Points[0].Value); + } + + #endregion + + #region Helpers and guards + + [Theory] + [InlineData(null, ReportPipeline.BlankKeyLabel)] + [InlineData(" ", ReportPipeline.BlankKeyLabel)] + [InlineData(" VME ", "VME")] + public void NormalizeKey_TrimsAndLabelsBlanks(string? key, string expected) + { + Assert.Equal(expected, ReportPipeline.NormalizeKey(key)); + } + + [Fact] + public void OrderCategories_PreferredThenAlphabetical() + { + Assert.Equal( + ["c", "a", "B", "d"], + ReportPipeline.OrderCategories(["d", "B", "a", "c"], ["c", "x"])); + } + + [Fact] + public void CreateResult_NullArguments_Throw() + { + var report = new TestReport(BasicColumns); + + Assert.Throws( + () => report.CreateResult(null!, TestReport.ContextWith(), TestReport.GeneratedAt)); + Assert.Throws( + () => report.CreateResult(TestReport.Rows(), null!, TestReport.GeneratedAt)); + } + + #endregion +} diff --git a/test/Reports/ReportRegistryTests.cs b/test/Reports/ReportRegistryTests.cs new file mode 100644 index 000000000..a5214df55 --- /dev/null +++ b/test/Reports/ReportRegistryTests.cs @@ -0,0 +1,156 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportRegistryTests +{ + [Fact] + public void All_OrdersByAreaThenTitle() + { + var registry = new ReportRegistry( + [ + new TestReport(key: "personnel.zeta", title: "Zeta", area: "Personnel"), + new TestReport(key: "effort.beta", title: "beta", area: "effort"), + new TestReport(key: "personnel.alpha", title: "Alpha", area: "Personnel"), + ]); + + Assert.Equal(["effort.beta", "personnel.alpha", "personnel.zeta"], registry.All.Select(report => report.Key)); + } + + [Fact] + public void Find_IsCaseInsensitive() + { + var report = new TestReport(key: "personnel.alpha"); + var registry = new ReportRegistry([report]); + + Assert.Same(report, registry.Find("Personnel.Alpha")); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("personnel.missing")] + public void Find_BlankOrUnknownKey_ReturnsNull(string? key) + { + var registry = new ReportRegistry([new TestReport(key: "personnel.alpha")]); + + Assert.Null(registry.Find(key)); + } + + [Fact] + public void Constructor_NullDefinitions_Throws() + { + Assert.Throws(() => new ReportRegistry(null!)); + } + + [Fact] + public void Constructor_DuplicateKey_Throws() + { + Assert.Throws(() => new ReportRegistry( + [ + new TestReport(key: "personnel.alpha"), + new TestReport(key: "PERSONNEL.ALPHA".ToLowerInvariant()), + ])); + } + + [Fact] + public void Constructor_InvalidKey_Throws() + { + Assert.Throws(() => new ReportRegistry([new TestReport(key: "Personnel Alpha")])); + } + + [Theory] + [InlineData(" ", "Area", "Description")] + [InlineData("Title", " ", "Description")] + [InlineData("Title", "Area", " ")] + public void Constructor_MissingIdentityText_Throws(string title, string area, string description) + { + var report = new TestReport(title: title, area: area, description: description); + + Assert.Throws(() => new ReportRegistry([report])); + } + + [Fact] + public void Constructor_NoPermissions_Throws() + { + Assert.Throws(() => new ReportRegistry([new TestReport(permissions: [])])); + } + + [Fact] + public void Constructor_BlankPermission_Throws() + { + Assert.Throws( + () => new ReportRegistry([new TestReport(permissions: ["SVMSecure.Test", " "])])); + } + + [Fact] + public void Planned_WithoutSources_IsEmpty() + { + Assert.Empty(new ReportRegistry([new TestReport()]).Planned); + } + + [Fact] + public void Planned_CombinesSourcesInAreaThenTitleOrder() + { + var extra = new StubPlannedSource { PlannedReports = [Plan("effort.zeta", "Zeta", "Effort")] }; + + var registry = new ReportRegistry([new TestReport()], [new TestPlannedReports(), extra]); + + Assert.Equal( + ["effort.zeta", "students.restricted", "test.planned"], + registry.Planned.Select(report => report.Key)); + } + + [Fact] + public void Find_NeverReturnsAPlannedReport() + { + var registry = new ReportRegistry([new TestReport()], [new TestPlannedReports()]); + + Assert.Null(registry.Find(TestPlannedReports.Visible.Key)); + } + + [Fact] + public void Constructor_PlannedKeyUsedByADefinition_Throws() + { + var planned = new StubPlannedSource { PlannedReports = [Plan("test.sample", "Sample", "Test")] }; + + InvalidOperationException error = Assert.Throws( + () => new ReportRegistry([new TestReport()], [planned])); + Assert.Contains("test.sample", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Constructor_DuplicatePlannedKey_Throws() + { + var first = new StubPlannedSource { PlannedReports = [Plan("test.planned-twice", "One", "Test")] }; + var second = new StubPlannedSource { PlannedReports = [Plan("test.planned-twice", "Two", "Test")] }; + + Assert.Throws(() => new ReportRegistry([], [first, second])); + } + + [Theory] + [InlineData("Test Planned", "Title", "SVMSecure.Test")] + [InlineData("test.planned", " ", "SVMSecure.Test")] + [InlineData("test.planned", "Title", " ")] + public void Constructor_InvalidPlannedReport_Throws(string key, string title, string permission) + { + var planned = new StubPlannedSource { PlannedReports = [new PlannedReport(key, title, "Test", "Description", [permission])] }; + + Assert.Throws(() => new ReportRegistry([], [planned])); + } + + private static PlannedReport Plan(string key, string title, string area) + { + return new PlannedReport(key, title, area, "Description", ["SVMSecure.Test"]); + } + + /// + /// Has a parameterless constructor because the registration tests scan this assembly and + /// build every planned report source they find. + /// + private sealed class StubPlannedSource : IPlannedReportSource + { + public IReadOnlyList PlannedReports { get; init; } = []; + } +} diff --git a/test/Reports/ReportRunTests.cs b/test/Reports/ReportRunTests.cs new file mode 100644 index 000000000..36f7f5d74 --- /dev/null +++ b/test/Reports/ReportRunTests.cs @@ -0,0 +1,45 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportRunTests +{ + [Fact] + public async Task RunAsync_FetchesWithParametersAndContextThenShapesRows() + { + var parameters = new SampleParams { FacultyType = "F" }; + var report = new TestReport(fetch: p => [.. TestReport.Rows().Where(row => p.FacultyType == "F" && row.Age > 60)]); + ReportContext context = TestReport.ContextWith(TestReport.RunPermission); + + ReportResult result = await report.RunAsync(parameters, context, TestReport.GeneratedAt, TestContext.Current.CancellationToken); + + Assert.Same(parameters, report.FetchedWith); + Assert.Same(context, report.FetchedFor); + Assert.Equal(2, result.RowCount); + Assert.Equal(TestReport.GeneratedAt, result.GeneratedAt); + } + + [Fact] + public async Task RunAsync_WrongParameterType_Throws() + { + var report = new TestReport(); + + await Assert.ThrowsAsync(() => report.RunAsync( + "parameters", TestReport.ContextWith(), TestReport.GeneratedAt, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task RunAsync_NullContext_Throws() + { + var report = new TestReport(); + + await Assert.ThrowsAsync(() => report.RunAsync( + new SampleParams(), null!, TestReport.GeneratedAt, TestContext.Current.CancellationToken)); + } + + [Fact] + public void ParametersType_IsTheDeclaredParameterClass() + { + Assert.Equal(typeof(SampleParams), new TestReport().ParametersType); + } +} diff --git a/test/Reports/ReportServiceTests.cs b/test/Reports/ReportServiceTests.cs new file mode 100644 index 000000000..3e710c231 --- /dev/null +++ b/test/Reports/ReportServiceTests.cs @@ -0,0 +1,283 @@ +using System.Text.Json; +using Microsoft.Extensions.Logging; +using System.Text; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Exporters; +using Viper.Areas.Reports.Services; + +namespace Viper.test.Reports; + +public sealed class ReportServiceTests +{ + private static readonly DateTimeOffset Now = new(2026, 9, 29, 15, 0, 0, TimeSpan.Zero); + + private readonly TestReport _sample = new(); + private readonly ListLogger _logger = new(); + + private ReportService CreateService(params string[] permissions) + { + var registry = new ReportRegistry( + [ + _sample, + new TestReport(key: "effort.other", title: "Other", area: "Effort", permissions: ["SVMSecure.Effort"]), + ], + [new TestPlannedReports()]); + return new ReportService( + registry, + new StubReportUserService(TestReport.ContextWith(permissions)), + [new ReportCsvExporter()], + new FixedTimeProvider(Now), + _logger); + } + + private static JsonElement Json(string json) + { + using JsonDocument document = JsonDocument.Parse(json); + return document.RootElement.Clone(); + } + + #region Catalog and definitions + + [Fact] + public void GetCatalog_ListsBuiltAndPlannedReportsTheUserMayRunInTitleOrder() + { + ReportService service = CreateService(TestReport.RunPermission); + + IReadOnlyList catalog = service.GetCatalog(null); + + Assert.Equal( + [ + new ReportCatalogItem("test.planned", "Planned report", "Test", "A report not built yet.", Available: false), + new ReportCatalogItem("test.sample", "Sample report", "Test", "A report used by tests.", Available: true), + ], + catalog); + } + + [Fact] + public void GetCatalog_OrdersByAreaBeforeTitle() + { + ReportService service = CreateService(TestReport.RunPermission, "SVMSecure.Effort", "SVMSecure.Students"); + + IReadOnlyList catalog = service.GetCatalog(null); + + Assert.Equal( + ["effort.other", "students.restricted", "test.planned", "test.sample"], + catalog.Select(item => item.Key)); + } + + [Theory] + [InlineData(" effort ", 1)] + [InlineData("Test", 2)] + [InlineData("Students", 0)] + [InlineData("", 3)] + public void GetCatalog_FiltersByArea(string area, int expectedCount) + { + ReportService service = CreateService(TestReport.RunPermission, "SVMSecure.Effort"); + + Assert.Equal(expectedCount, service.GetCatalog(area).Count); + } + + [Fact] + public void GetDefinition_PlannedReport_IsNotFound() + { + ReportService service = CreateService(TestReport.RunPermission); + + Assert.Equal(ReportOutcomeStatus.NotFound, service.GetDefinition(TestPlannedReports.Visible.Key).Status); + } + + [Fact] + public void GetDefinition_UnknownKey_IsNotFound() + { + ReportService service = CreateService(TestReport.RunPermission); + + Assert.Equal(ReportOutcomeStatus.NotFound, service.GetDefinition("test.missing").Status); + } + + [Fact] + public void GetDefinition_WithoutPermission_IsForbidden() + { + ReportService service = CreateService(); + + Assert.Equal(ReportOutcomeStatus.Forbidden, service.GetDefinition("test.sample").Status); + } + + [Fact] + public void GetDefinition_WithPermission_ReturnsMetadata() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = service.GetDefinition("TEST.SAMPLE"); + + Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); + Assert.NotNull(outcome.Value); + Assert.Equal("test.sample", outcome.Value.Key); + } + + #endregion + + #region Running + + [Fact] + public async Task RunAsync_UnknownKey_IsNotFound() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = await service.RunAsync("test.missing", null, TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.NotFound, outcome.Status); + } + + [Fact] + public async Task RunAsync_PlannedReport_IsNotFound() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = + await service.RunAsync(TestPlannedReports.Visible.Key, null, TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.NotFound, outcome.Status); + } + + [Fact] + public async Task RunAsync_WithoutPermission_IsForbiddenBeforeReadingParameters() + { + ReportService service = CreateService(); + + ReportOutcome outcome = + await service.RunAsync("test.sample", Json("[\"not an object\"]"), TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Forbidden, outcome.Status); + Assert.Null(_sample.FetchedWith); + } + + [Fact] + public async Task RunAsync_UnreadableParameters_IsInvalid() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = + await service.RunAsync("test.sample", Json("""{ "minimumAge": "old" }"""), TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); + Assert.Equal("minimumAge", Assert.Single(outcome.Errors).Parameter); + Assert.Null(_sample.FetchedWith); + } + + [Fact] + public async Task RunAsync_InvalidParameters_IsInvalid() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = + await service.RunAsync("test.sample", Json("""{ "facultyType": "X" }"""), TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); + Assert.Equal("facultyType", Assert.Single(outcome.Errors).Parameter); + Assert.Null(_sample.FetchedWith); + } + + [Fact] + public async Task RunAsync_ValidParameters_RunsWithDefaultsAndAudits() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = await service.RunAsync( + "test.sample", Json("""{ "search": "a\nb" }"""), TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); + Assert.NotNull(outcome.Value); + Assert.Equal(5, outcome.Value.RowCount); + Assert.Equal(Now, outcome.Value.GeneratedAt); + Assert.Equal("S", _sample.FetchedWith?.FacultyType); + Assert.Equal("tester", _sample.FetchedFor?.LoginId); + + (LogLevel level, string message) = Assert.Single(_logger.Entries); + Assert.Equal(LogLevel.Information, level); + Assert.Contains("test.sample", message, StringComparison.Ordinal); + Assert.Contains("5 rows", message, StringComparison.Ordinal); + Assert.DoesNotContain("\n", message, StringComparison.Ordinal); + } + + [Fact] + public async Task RunAsync_InformationLoggingOff_SkipsAuditEntry() + { + ReportService service = CreateService(TestReport.RunPermission); + _logger.Enabled = false; + + ReportOutcome outcome = await service.RunAsync("test.sample", null, TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); + Assert.Empty(_logger.Entries); + } + + #endregion + + #region Exporting + + [Fact] + public async Task ExportAsync_UnknownKey_IsNotFound() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = + await service.ExportAsync("test.missing", "csv", null, TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.NotFound, outcome.Status); + } + + [Fact] + public async Task ExportAsync_WithoutPermission_IsForbiddenBeforeCheckingFormat() + { + ReportService service = CreateService(); + + ReportOutcome outcome = + await service.ExportAsync("test.sample", "docx", null, TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Forbidden, outcome.Status); + } + + [Fact] + public async Task ExportAsync_UnknownFormat_IsInvalidWithoutRunning() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = + await service.ExportAsync("test.sample", "docx", null, TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); + Assert.Equal( + [new ReportValidationError(ReportService.FormatParameter, "Choose an export format: csv.")], + outcome.Errors); + Assert.Null(_sample.FetchedWith); + } + + [Fact] + public async Task ExportAsync_InvalidParameters_IsInvalid() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = await service.ExportAsync( + "test.sample", "csv", Json("""{ "facultyType": "X" }"""), TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); + Assert.Equal("facultyType", Assert.Single(outcome.Errors).Parameter); + } + + [Fact] + public async Task ExportAsync_ValidRequest_ReturnsFileAndAudits() + { + ReportService service = CreateService(TestReport.RunPermission); + + ReportOutcome outcome = + await service.ExportAsync("test.sample", "CSV", null, TestContext.Current.CancellationToken); + + Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); + Assert.NotNull(outcome.Value); + Assert.Equal("Sample report.csv", outcome.Value.FileName); + Assert.Equal("text/csv", outcome.Value.ContentType); + Assert.StartsWith("\uFEFFName,Department", Encoding.UTF8.GetString(outcome.Value.Content), StringComparison.Ordinal); + Assert.Contains("export:csv", Assert.Single(_logger.Entries).Message, StringComparison.Ordinal); + } + + #endregion +} diff --git a/test/Reports/ReportTestDoubles.cs b/test/Reports/ReportTestDoubles.cs new file mode 100644 index 000000000..99247ea46 --- /dev/null +++ b/test/Reports/ReportTestDoubles.cs @@ -0,0 +1,105 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Microsoft.Extensions.Logging; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Services; + +namespace Viper.test.Reports; + +/// +/// A clock pinned to one instant, reported in UTC. +/// +internal sealed class FixedTimeProvider : TimeProvider +{ + private readonly DateTimeOffset _now; + + public FixedTimeProvider(DateTimeOffset now) + { + _now = now; + } + + public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; + + public override DateTimeOffset GetUtcNow() + { + return _now.ToUniversalTime(); + } +} + +/// +/// Captures formatted log messages so tests can check what was audited. +/// +internal sealed class ListLogger : ILogger +{ + public List<(LogLevel Level, string Message)> Entries { get; } = []; + + public bool Enabled { get; set; } = true; + + public IDisposable? BeginScope(TState state) where TState : notnull + { + return null; + } + + public bool IsEnabled(LogLevel logLevel) + { + return Enabled; + } + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + Entries.Add((logLevel, formatter(state, exception))); + } +} + +/// +/// Always serves the same context, standing in for the signed-in user. +/// +internal sealed class StubReportUserService : IReportUserService +{ + private readonly ReportContext _context; + + public StubReportUserService(ReportContext context) + { + _context = context; + } + + public ReportContext GetCurrentContext() + { + return _context; + } +} + +/// +/// Two planned reports: one the standard test user may see, one that needs another permission. +/// +internal sealed class TestPlannedReports : IPlannedReportSource +{ + public static readonly PlannedReport Visible = + new("test.planned", "Planned report", "Test", "A report not built yet.", [TestReport.RunPermission]); + + public static readonly PlannedReport Restricted = + new("students.restricted", "Restricted plan", "Students", "Needs another permission.", ["SVMSecure.Students"]); + + public IReadOnlyList PlannedReports => [Visible, Restricted]; +} + +/// +/// A parameter type whose converter produces null, which a real parameter class never does. +/// +[JsonConverter(typeof(NullParamsConverter))] +internal sealed class NullParams; + +internal sealed class NullParamsConverter : JsonConverter +{ + public override NullParams? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + reader.Skip(); + return null; + } + + public override void Write(Utf8JsonWriter writer, NullParams value, JsonSerializerOptions options) + { + writer.WriteNullValue(); + } +} diff --git a/test/Reports/ReportTestFixtures.cs b/test/Reports/ReportTestFixtures.cs new file mode 100644 index 000000000..8f22f69da --- /dev/null +++ b/test/Reports/ReportTestFixtures.cs @@ -0,0 +1,169 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +internal sealed record SampleRow( + string Name, + string? Department, + int Age, + decimal? Salary, + DateOnly HireDate, + IReadOnlyList? Ethnicities = null); + +internal sealed record SampleParams +{ + public string? FacultyType { get; init; } + + public IReadOnlyList? Departments { get; init; } + + public DateOnly? StartDate { get; init; } + + public DateOnly? EndDate { get; init; } + + public string? Search { get; init; } + + public int? MinimumAge { get; init; } + + public bool? IncludeEmeriti { get; init; } + + public string? Computed => Search; + + public SampleInner Inner { get; init; } = new(); +} + +internal sealed record SampleInner +{ + public string? Value { get; init; } +} + +/// +/// A configurable report for engine tests. declares one parameter of +/// every type and one column of every format. +/// +internal sealed class TestReport : ReportDefinition +{ + public const string RunPermission = "SVMSecure.Test.Run"; + public const string SalaryPermission = "SVMSecure.Test.Salary"; + + public static readonly DateOnly DefaultStart = new(2026, 7, 1); + + public static readonly IReadOnlyList FacultyTypes = + [ + new("S", "Senate"), + new("F", "Federation"), + new("B", "Both"), + ]; + + public static readonly IReadOnlyList DepartmentOptions = + [ + new("APC", "Anatomy, Physiology and Cell Biology"), + new("VME", "Medicine and Epidemiology"), + ]; + + private readonly Action> _configure; + private readonly string _key; + private readonly string _title; + private readonly string _area; + private readonly string _description; + private readonly IReadOnlyList _permissions; + private readonly Func> _fetch; + + public TestReport( + Action>? configure = null, + string key = "test.sample", + string title = "Sample report", + string area = "Test", + string description = "A report used by tests.", + IReadOnlyList? permissions = null, + Func>? fetch = null) + { + _configure = configure ?? Standard; + _key = key; + _title = title; + _area = area; + _description = description; + _permissions = permissions ?? [RunPermission]; + _fetch = fetch ?? (_ => Rows()); + } + + public int ConfigureCalls { get; private set; } + + public SampleParams? FetchedWith { get; private set; } + + public ReportContext? FetchedFor { get; private set; } + + public override string Key => _key; + + public override string Title => _title; + + public override string Area => _area; + + public override string Description => _description; + + public override IReadOnlyList Permissions => _permissions; + + public static void Standard(ReportBuilder report) + { + report.Choice(p => p.FacultyType, "Faculty type", FacultyTypes).Required().Default(() => "S"); + report.MultiChoice(p => p.Departments, "Departments", DepartmentOptions); + report.Date(p => p.StartDate, "Start date").Required().Default(() => DefaultStart); + report.Date(p => p.EndDate, "End date"); + report.Text(p => p.Search, "Search"); + report.Number(p => p.MinimumAge, "Minimum age"); + report.Boolean(p => p.IncludeEmeriti, "Include emeriti"); + report.Validate( + p => p.EndDate is null || p.EndDate >= p.StartDate, + "End date must be on or after the start date.", + "endDate"); + + report.Column(r => r.Name, "Name"); + report.Column(r => r.Department, "Department"); + report.Column(r => r.Age, "Age").AsNumber(); + report.Column(r => r.Salary, "Salary").AsCurrency() + .VisibleWhen(context => context.HasPermission(SalaryPermission)); + report.Column(r => r.HireDate, "Hire date").AsDate(); + } + + public static ReportContext ContextWith(params string[] permissions) + { + var granted = new HashSet(permissions, StringComparer.Ordinal); + return new ReportContext("tester", granted.Contains); + } + + public static readonly DateTimeOffset GeneratedAt = new(2026, 9, 29, 8, 0, 0, TimeSpan.FromHours(-7)); + + /// + /// Five people: three in VME (one key padded with a space), one in "apc", and one with a + /// blank department. + /// + public static IReadOnlyList Rows() + { + return + [ + new("Ada", "VME", 61, 120_000m, new DateOnly(1995, 7, 1), ["Asian", "White"]), + new("Ben", "apc", 45, 90_000m, new DateOnly(2010, 1, 15), ["White"]), + new("Cy", "VME ", 38, null, new DateOnly(2018, 9, 1), ["Hispanic"]), + new("Di", "VME", 66, 150_000m, new DateOnly(1990, 3, 1), []), + new("Ed", " ", 29, 70_000m, new DateOnly(2022, 8, 15), ["White"]), + ]; + } + + public static ReportResult Run(TestReport report, ReportContext? context = null) + { + return report.CreateResult(Rows(), context ?? ContextWith(RunPermission, SalaryPermission), GeneratedAt); + } + + protected override void Configure(ReportBuilder report) + { + ConfigureCalls++; + _configure(report); + } + + protected override Task> FetchAsync( + SampleParams parameters, ReportContext context, CancellationToken ct) + { + FetchedWith = parameters; + FetchedFor = context; + return Task.FromResult(_fetch(parameters)); + } +} diff --git a/test/Reports/ReportUserServiceTests.cs b/test/Reports/ReportUserServiceTests.cs new file mode 100644 index 000000000..e16252f79 --- /dev/null +++ b/test/Reports/ReportUserServiceTests.cs @@ -0,0 +1,41 @@ +using NSubstitute; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Services; +using Viper.Classes.SQLContext; +using Viper.Models.AAUD; + +namespace Viper.test.Reports; + +public sealed class ReportUserServiceTests +{ + private readonly RAPSContext _rapsContext = Substitute.For(); + private readonly IUserHelper _userHelper = Substitute.For(); + + [Fact] + public void GetCurrentContext_NoUser_HasNoPermissions() + { + _userHelper.GetCurrentUser().Returns((AaudUser?)null); + var service = new ReportUserService(_rapsContext, _userHelper); + + ReportContext context = service.GetCurrentContext(); + + Assert.Null(context.LoginId); + Assert.False(context.HasPermission("SVMSecure")); + _userHelper.DidNotReceive().HasPermission(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public void GetCurrentContext_SignedInUser_ChecksPermissionsThroughRaps() + { + var user = new AaudUser { MothraId = "01234567", LoginId = "jdoe" }; + _userHelper.GetCurrentUser().Returns(user); + _userHelper.HasPermission(_rapsContext, user, "SVMSecure.Personnel.Sabbatic").Returns(true); + var service = new ReportUserService(_rapsContext, _userHelper); + + ReportContext context = service.GetCurrentContext(); + + Assert.Equal("jdoe", context.LoginId); + Assert.True(context.HasPermission("SVMSecure.Personnel.Sabbatic")); + Assert.False(context.HasPermission("SVMSecure.Personnel.FacultySalary")); + } +} diff --git a/test/Reports/ReportValueFormatterTests.cs b/test/Reports/ReportValueFormatterTests.cs new file mode 100644 index 000000000..92b55e767 --- /dev/null +++ b/test/Reports/ReportValueFormatterTests.cs @@ -0,0 +1,113 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.test.Reports; + +public sealed class ReportValueFormatterTests +{ + private static ReportColumnMetadata Column(ReportColumnFormat format, int? decimals = null) + { + return new ReportColumnMetadata("value", "Value", format, ReportAlignment.Left, decimals); + } + + [Fact] + public void Format_NonNumericValues() + { + ReportColumnMetadata text = Column(ReportColumnFormat.Text); + + Assert.Equal(string.Empty, ReportValueFormatter.Format(null, text)); + Assert.Equal("Ada", ReportValueFormatter.Format("Ada", text)); + Assert.Equal("07/01/2026", ReportValueFormatter.Format(new DateOnly(2026, 7, 1), text)); + Assert.Equal("07/01/2026", ReportValueFormatter.Format(new DateTime(2026, 7, 1, 13, 30, 0, DateTimeKind.Local), text)); + Assert.Equal("APC, VME", ReportValueFormatter.Format(new[] { "APC", "VME" }, Column(ReportColumnFormat.List))); + Assert.Equal("True", ReportValueFormatter.Format(true, text)); + } + + [Fact] + public void Format_NumbersInTextColumnsKeepTheirDigits() + { + Assert.Equal("1234567", ReportValueFormatter.Format(1_234_567, Column(ReportColumnFormat.Text))); + } + + [Theory] + [InlineData(ReportColumnFormat.Number, 0, "1,235")] + [InlineData(ReportColumnFormat.Number, 1, "1,234.6")] + [InlineData(ReportColumnFormat.Currency, 2, "$1,234.56")] + public void Format_NumericColumns(ReportColumnFormat format, int decimals, string expected) + { + Assert.Equal(expected, ReportValueFormatter.Format(1234.56m, Column(format, decimals))); + } + + [Fact] + public void Format_PercentColumnTreatsValuesAsFractions() + { + string formatted = ReportValueFormatter.Format(0.25m, Column(ReportColumnFormat.Percent)); + + Assert.StartsWith("25", formatted, StringComparison.Ordinal); + Assert.EndsWith("%", formatted, StringComparison.Ordinal); + } + + [Fact] + public void Format_NumericColumnWithoutDecimals_UsesWholeNumbers() + { + Assert.Equal("61", ReportValueFormatter.Format(61, Column(ReportColumnFormat.Number))); + } + + [Fact] + public void Format_NonNumberInNumericColumn_FallsBackToText() + { + Assert.Equal("n/a", ReportValueFormatter.Format("n/a", Column(ReportColumnFormat.Number))); + Assert.Equal("True", ReportValueFormatter.Format(true, Column(ReportColumnFormat.Number))); + } + + [Fact] + public void Format_NullColumn_Throws() + { + Assert.Throws(() => ReportValueFormatter.Format("x", null!)); + } + + [Theory] + [InlineData(ReportColumnFormat.Number, true)] + [InlineData(ReportColumnFormat.Currency, true)] + [InlineData(ReportColumnFormat.Percent, true)] + [InlineData(ReportColumnFormat.Text, false)] + [InlineData(ReportColumnFormat.Date, false)] + [InlineData(ReportColumnFormat.List, false)] + public void IsNumeric_OnlyNumberCurrencyAndPercent(ReportColumnFormat format, bool expected) + { + Assert.Equal(expected, ReportValueFormatter.IsNumeric(format)); + } + + [Fact] + public void TryGetDecimal_AcceptsNumericTypes() + { + Assert.True(ReportValueFormatter.TryGetDecimal(1.5m, out decimal fromDecimal)); + Assert.True(ReportValueFormatter.TryGetDecimal(7, out decimal fromInt)); + Assert.True(ReportValueFormatter.TryGetDecimal(8L, out decimal fromLong)); + Assert.True(ReportValueFormatter.TryGetDecimal(2.5d, out decimal fromDouble)); + + Assert.Equal([1.5m, 7m, 8m, 2.5m], new[] { fromDecimal, fromInt, fromLong, fromDouble }); + } + + [Fact] + public void TryGetDecimal_RejectsNonNumbersAndOutOfRangeDoubles() + { + Assert.False(ReportValueFormatter.TryGetDecimal(null, out _)); + Assert.False(ReportValueFormatter.TryGetDecimal("12", out _)); + Assert.False(ReportValueFormatter.TryGetDecimal(double.NaN, out _)); + Assert.False(ReportValueFormatter.TryGetDecimal(1e30, out _)); + } + + [Fact] + public void FlagText_JoinsDistinctLabels() + { + var row = new ReportRowResult(1, new Dictionary(), + [ + new ReportFlag(ReportFlagKind.Highlight, ReportTone.Warning, "60+", null), + new ReportFlag(ReportFlagKind.Badge, ReportTone.Muted, "Emeritus", "status"), + new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "60+", "age"), + ]); + + Assert.Equal("60+; Emeritus", ReportValueFormatter.FlagText(row)); + Assert.Throws(() => ReportValueFormatter.FlagText(null!)); + } +} diff --git a/test/Reports/ReportsControllerTests.cs b/test/Reports/ReportsControllerTests.cs new file mode 100644 index 000000000..9f5318fb2 --- /dev/null +++ b/test/Reports/ReportsControllerTests.cs @@ -0,0 +1,195 @@ +using System.Reflection; +using System.Text.Json; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Viper.Areas.Reports.Controllers; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Services; +using Viper.Classes; +using Web.Authorization; + +namespace Viper.test.Reports; + +public sealed class ReportsControllerTests +{ + private readonly StubReportService _service = new(); + private readonly ReportsController _controller; + + public ReportsControllerTests() + { + _controller = new ReportsController(_service); + } + + [Fact] + public void Controller_RequiresSignInAndUsesApiConventions() + { + PermissionAttribute? permission = typeof(ReportsController).GetCustomAttribute(); + RouteAttribute? route = typeof(ReportsController).GetCustomAttribute(); + + Assert.Equal("SVMSecure", permission?.Allow); + Assert.Equal("/api/reports", route?.Template); + Assert.True(typeof(ApiController).IsAssignableFrom(typeof(ReportsController))); + } + + [Fact] + public void GetCatalog_ReturnsServiceCatalog() + { + IReadOnlyList catalog = [new("test.sample", "Sample", "Test", "Description", Available: true)]; + _service.Catalog = catalog; + + ActionResult> result = _controller.GetCatalog("Test"); + + OkObjectResult ok = Assert.IsType(result.Result); + Assert.Same(catalog, ok.Value); + Assert.Equal("Test", _service.LastArea); + } + + [Fact] + public void GetDefinition_Ok_ReturnsMetadata() + { + var metadata = new ReportDefinitionMetadata("test.sample", "Sample", "Test", "Description", [], []); + _service.Definition = ReportOutcome.Ok(metadata); + + ActionResult result = _controller.GetDefinition("test.sample"); + + Assert.Same(metadata, Assert.IsType(result.Result).Value); + } + + [Fact] + public void GetDefinition_NotFound_Returns404() + { + _service.Definition = ReportOutcome.NotFound(); + + ActionResult result = _controller.GetDefinition("test.missing"); + + Assert.IsType(result.Result); + } + + [Fact] + public void GetDefinition_Forbidden_Returns403() + { + _service.Definition = ReportOutcome.Forbidden(); + + ActionResult result = _controller.GetDefinition("test.sample"); + + ObjectResult forbidden = Assert.IsType(result.Result); + Assert.Equal(StatusCodes.Status403Forbidden, forbidden.StatusCode); + } + + [Fact] + public async Task Run_Invalid_Returns400WithErrorsByParameter() + { + ReportValidationError[] errors = + [ + new("startDate", "Start date is required."), + new(null, "Enter a search or a minimum age."), + ]; + _service.Run = ReportOutcome.Invalid(errors); + + ActionResult result = await _controller.Run("test.sample", null, TestContext.Current.CancellationToken); + + BadRequestObjectResult badRequest = Assert.IsType(result.Result); + ValidationProblemDetails problem = Assert.IsType(badRequest.Value); + Assert.Equal(["Start date is required."], problem.Errors["startDate"]); + Assert.Equal(["Enter a search or a minimum age."], problem.Errors[string.Empty]); + } + + [Fact] + public async Task Run_Ok_ReturnsResult() + { + var report = new ReportResult("test.sample", "Sample", DateTimeOffset.UnixEpoch, 0, false, [], [], [], [], [], []); + _service.Run = ReportOutcome.Ok(report); + + ActionResult result = await _controller.Run("test.sample", null, TestContext.Current.CancellationToken); + + Assert.Same(report, Assert.IsType(result.Result).Value); + Assert.Equal("test.sample", _service.LastKey); + } + + [Fact] + public async Task Export_Ok_ReturnsUncachedDownload() + { + var file = new ReportFile([1, 2, 3], "text/csv", "Sample.csv"); + _service.Export = ReportOutcome.Ok(file); + _controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; + + ActionResult result = await _controller.Export("test.sample", "csv", null, TestContext.Current.CancellationToken); + + FileContentResult download = Assert.IsType(result); + Assert.Equal("text/csv", download.ContentType); + Assert.Equal("Sample.csv", download.FileDownloadName); + Assert.Equal([1, 2, 3], download.FileContents); + Assert.Equal("private, no-store, max-age=0", _controller.Response.Headers.CacheControl.ToString()); + Assert.Equal("csv", _service.LastFormat); + } + + [Fact] + public async Task Export_Invalid_Returns400() + { + _service.Export = ReportOutcome.Invalid([new("format", "Choose an export format: csv.")]); + + ActionResult result = await _controller.Export("test.sample", "docx", null, TestContext.Current.CancellationToken); + + ValidationProblemDetails problem = Assert.IsType(Assert.IsType(result).Value); + Assert.Equal(["Choose an export format: csv."], problem.Errors["format"]); + } + + [Fact] + public void ToProblemDetails_CombinesMessagesForTheSameParameter() + { + ValidationProblemDetails problem = ReportsController.ToProblemDetails( + [ + new("endDate", "First."), + new("endDate", "Second."), + ]); + + Assert.Equal(["First.", "Second."], problem.Errors["endDate"]); + Assert.Equal("The report parameters are not valid.", problem.Title); + } + + /// + /// Returns canned outcomes and records what the controller asked for. + /// + private sealed class StubReportService : IReportService + { + public IReadOnlyList Catalog { get; set; } = []; + + public ReportOutcome Definition { get; set; } = ReportOutcome.NotFound(); + + public ReportOutcome Run { get; set; } = ReportOutcome.NotFound(); + + public ReportOutcome Export { get; set; } = ReportOutcome.NotFound(); + + public string? LastFormat { get; private set; } + + public string? LastArea { get; private set; } + + public string? LastKey { get; private set; } + + public IReadOnlyList GetCatalog(string? area) + { + LastArea = area; + return Catalog; + } + + public ReportOutcome GetDefinition(string? key) + { + LastKey = key; + return Definition; + } + + public Task> RunAsync(string? key, JsonElement? parameters, CancellationToken ct) + { + LastKey = key; + return Task.FromResult(Run); + } + + public Task> ExportAsync( + string? key, string? format, JsonElement? parameters, CancellationToken ct) + { + LastKey = key; + LastFormat = format; + return Task.FromResult(Export); + } + } +} diff --git a/test/Reports/ReportsRegistrationTests.cs b/test/Reports/ReportsRegistrationTests.cs new file mode 100644 index 000000000..79c56e8d9 --- /dev/null +++ b/test/Reports/ReportsRegistrationTests.cs @@ -0,0 +1,61 @@ +using Microsoft.Extensions.DependencyInjection; +using Viper.Areas.Reports; +using Viper.Areas.Reports.Data; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Exporters; + +namespace Viper.test.Reports; + +public sealed class ReportsRegistrationTests +{ + [Fact] + public void AddReports_RegistersDefinitionsPlannedReportsRegistryAndClock() + { + var services = new ServiceCollection(); + services.AddReports(typeof(ReportsRegistrationTests).Assembly); + + using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true); + using IServiceScope scope = provider.CreateScope(); + + IReportRegistry registry = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(registry.Find("test.sample")); + Assert.Contains(TestPlannedReports.Visible, registry.Planned); + Assert.Same(TimeProvider.System, provider.GetRequiredService()); + Assert.Equal(["csv", "xlsx", "pdf"], provider.GetServices().Select(exporter => exporter.Format)); + } + + [Fact] + public void AddReports_RegistersTheStoredProcedureRunner() + { + var services = new ServiceCollection(); + + services.AddReports(typeof(ReportsRegistrationTests).Assembly); + + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IStoredProcedureRunner) + && descriptor.ImplementationType == typeof(StoredProcedureRunner) + && descriptor.Lifetime == ServiceLifetime.Singleton); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDbConnectionFactory) + && descriptor.ImplementationType == typeof(SqlConnectionFactory) + && descriptor.Lifetime == ServiceLifetime.Singleton); + } + + [Fact] + public void AddReports_KeepsAnExistingClock() + { + var clock = new FixedTimeProvider(DateTimeOffset.UnixEpoch); + var services = new ServiceCollection(); + services.AddSingleton(clock); + + services.AddReports(typeof(ReportsRegistrationTests).Assembly); + + using ServiceProvider provider = services.BuildServiceProvider(); + Assert.Same(clock, provider.GetRequiredService()); + } + + [Fact] + public void AddReports_NullArguments_Throw() + { + Assert.Throws(() => ReportsServiceCollectionExtensions.AddReports(null!, typeof(ReportsRegistrationTests).Assembly)); + Assert.Throws(() => new ServiceCollection().AddReports(null!)); + } +} diff --git a/web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs b/web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs new file mode 100644 index 000000000..fccb115e1 --- /dev/null +++ b/web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs @@ -0,0 +1,12 @@ +namespace Viper.Areas.Personnel.Models; + +/// +/// One leave of absence from usp_get_peopleOnLeave, carrying only the columns the report shows. +/// +public sealed record EmployeeOnLeaveRow( + string Name, + string? HomeDepartment, + DateOnly? LeaveStart, + DateOnly? ReturnDate, + string? Description, + string? PayStatus); diff --git a/web/Areas/Personnel/Models/FacultyAppointmentRow.cs b/web/Areas/Personnel/Models/FacultyAppointmentRow.cs new file mode 100644 index 000000000..0f089e1cf --- /dev/null +++ b/web/Areas/Personnel/Models/FacultyAppointmentRow.cs @@ -0,0 +1,13 @@ +namespace Viper.Areas.Personnel.Models; + +/// +/// One paid appointment of a faculty member, from usp_get_facultyList with every +/// employee's details. Age is computed by the procedure, as in the legacy report. +/// +public sealed record FacultyAppointmentRow( + string EmployeeId, + string Name, + int? Age, + DateOnly? HireDate, + string? Department, + string? Title); diff --git a/web/Areas/Personnel/Models/FlsaEmployeeRow.cs b/web/Areas/Personnel/Models/FlsaEmployeeRow.cs new file mode 100644 index 000000000..18387a55e --- /dev/null +++ b/web/Areas/Personnel/Models/FlsaEmployeeRow.cs @@ -0,0 +1,13 @@ +namespace Viper.Areas.Personnel.Models; + +/// +/// One appointment from usp_get_flsa. isn't shown; it counts +/// people once when they hold several appointments. +/// +public sealed record FlsaEmployeeRow( + string? EmployeeId, + string Name, + string? Department, + string? Title, + string? Flsa, + string? Email); diff --git a/web/Areas/Personnel/PersonnelDatabases.cs b/web/Areas/Personnel/PersonnelDatabases.cs new file mode 100644 index 000000000..7573376da --- /dev/null +++ b/web/Areas/Personnel/PersonnelDatabases.cs @@ -0,0 +1,12 @@ +namespace Viper.Areas.Personnel; + +/// +/// Connection string names for the Personnel data sources that have no EF context. +/// +public static class PersonnelDatabases +{ + /// + /// The UCPath/PPS warehouse (legacy DSN PPS-Prod / PPS-dev). + /// + public const string Pps = "PPS"; +} 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/Personnel/Reports/EmployeesOnLeaveReport.cs b/web/Areas/Personnel/Reports/EmployeesOnLeaveReport.cs new file mode 100644 index 000000000..c399f2ca6 --- /dev/null +++ b/web/Areas/Personnel/Reports/EmployeesOnLeaveReport.cs @@ -0,0 +1,77 @@ +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Services; +using Viper.Areas.Reports.Engine; + +namespace Viper.Areas.Personnel.Reports; + +public sealed record EmployeesOnLeaveParameters +{ + public string? EmployeeType { get; init; } + + public DateOnly? StartDate { get; init; } + + public DateOnly? EndDate { get; init; } +} + +/// +/// Faculty and staff with a leave of absence in a date range, which defaults to the current +/// fiscal year. Ports the legacy "Employee on Leave" page (leaveDetective). +/// +public sealed class EmployeesOnLeaveReport : ReportDefinition +{ + private readonly IPersonnelReportDataService _data; + + // The clock is injected so tests can pin the fiscal-year defaults. + private readonly TimeProvider _clock; + + public EmployeesOnLeaveReport(IPersonnelReportDataService data, TimeProvider clock) + { + _data = data; + _clock = clock; + } + + public override string Key => "personnel.employees-on-leave"; + + public override string Title => "Employees on Leave"; + + public override string Area => PersonnelReports.Area; + + public override string Description => "Faculty and staff on leave during a date range."; + + public override IReadOnlyList Permissions => [PersonnelPermissions.Sabbatic]; + + protected override void Configure(ReportBuilder report) + { + report.Choice(p => p.EmployeeType, "Employee type", PersonnelOptions.FacultyStaffBoth) + .Required() + .Default(() => PersonnelOptions.Faculty); + report.Date(p => p.StartDate, "Start date").Required().Default(() => FiscalYear.StartOf(Today())); + report.Date(p => p.EndDate, "End date").Required().Default(() => FiscalYear.EndOf(Today())); + report.Validate(p => p.EndDate >= p.StartDate, "End date must be on or after the start date.", "endDate"); + report.Sensitive(); + + report.Column(r => r.Name, "Name"); + report.Column(r => r.HomeDepartment, "Home department"); + report.Column(r => r.LeaveStart, "Leave start").AsDate(); + report.Column(r => r.ReturnDate, "Return date").AsDate(); + report.Column(r => r.Description, "Description"); + report.Column(r => r.PayStatus, "Pay status"); + } + + protected override Task> FetchAsync( + EmployeesOnLeaveParameters parameters, ReportContext context, CancellationToken ct) + { + // The engine has applied defaults and required checks, so all three values are set. + if (parameters is not { EmployeeType: { } type, StartDate: { } start, EndDate: { } end }) + { + throw new InvalidOperationException("Employees on Leave ran without its required parameters."); + } + + return _data.GetPeopleOnLeaveAsync(type, start, end, ct); + } + + private DateOnly Today() + { + return DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + } +} diff --git a/web/Areas/Personnel/Reports/ExemptStatusReport.cs b/web/Areas/Personnel/Reports/ExemptStatusReport.cs new file mode 100644 index 000000000..240a07cf7 --- /dev/null +++ b/web/Areas/Personnel/Reports/ExemptStatusReport.cs @@ -0,0 +1,82 @@ +using Viper.Areas.Personnel.Models; +using Viper.Areas.Personnel.Services; +using Viper.Areas.Reports.Engine; + +namespace Viper.Areas.Personnel.Reports; + +public sealed record ExemptStatusParameters +{ + public string? StatusType { get; init; } +} + +/// +/// Employees by department and FLSA exemption status, with exempt and non-exempt head counts +/// per department and for the school. Ports the legacy "Exempt/Non-Exempt" page (flsa). +/// +public sealed class ExemptStatusReport : ReportDefinition +{ + public const string Exempt = "EXEMPT"; + public const string NonExempt = "NON-EXEMPT"; + + private static readonly IReadOnlyList StatusTypes = + [ + new("E", "Exempt"), + new("N", "Non-exempt"), + new("B", "Both"), + ]; + + private readonly IPersonnelReportDataService _data; + + public ExemptStatusReport(IPersonnelReportDataService data) + { + _data = data; + } + + public override string Key => "personnel.exempt-non-exempt"; + + public override string Title => "Exempt/Non-Exempt"; + + public override string Area => PersonnelReports.Area; + + public override string Description => "Employees by department and FLSA exemption status."; + + // The legacy nav checked SVMSecure.EIS but the page ServiceCreditAdmin; decided: ServiceCreditAdmin. + public override IReadOnlyList Permissions => [PersonnelPermissions.ServiceCreditAdmin]; + + protected override void Configure(ReportBuilder report) + { + report.Choice(p => p.StatusType, "FLSA status", StatusTypes).Required().Default(() => "B"); + + report.RowNumbers(); + report.Column(r => r.Name, "Name"); + report.Column(r => r.Department, "Department"); + report.Column(r => r.Title, "Title"); + report.Column(r => r.Flsa, "FLSA"); + report.Column(r => r.Email, "Email"); + + // Head counts are of people, not appointments, as in the legacy page. + ReportMeasure exempt = report.CountDistinct(r => r.Flsa == Exempt ? r.EmployeeId : null); + ReportMeasure nonExempt = report.CountDistinct(r => r.Flsa == NonExempt ? r.EmployeeId : null); + report.Summary("Exempt employees", exempt); + report.Summary("Non-exempt employees", nonExempt); + report.GroupBy(r => r.Department) + .Subtotal("Exempt employees", exempt) + .Subtotal("Non-exempt employees", nonExempt); + } + + protected override async Task> FetchAsync( + ExemptStatusParameters parameters, ReportContext context, CancellationToken ct) + { + if (parameters.StatusType is not { } statusType) + { + throw new InvalidOperationException("Exempt/Non-Exempt ran without its required parameter."); + } + + IReadOnlyList rows = await _data.GetFlsaAsync(statusType, ct); + + // Non-exempt staff first within each department, as the legacy page listed them. + return [.. rows + .OrderByDescending(row => row.Flsa, StringComparer.Ordinal) + .ThenBy(row => row.Name, StringComparer.OrdinalIgnoreCase)]; + } +} diff --git a/web/Areas/Personnel/Reports/FacultyProfileReport.cs b/web/Areas/Personnel/Reports/FacultyProfileReport.cs new file mode 100644 index 000000000..663364dee --- /dev/null +++ b/web/Areas/Personnel/Reports/FacultyProfileReport.cs @@ -0,0 +1,92 @@ +using Viper.Areas.Personnel.Services; +using Viper.Areas.Reports.Engine; + +namespace Viper.Areas.Personnel.Reports; + +public sealed record FacultyProfileParameters +{ + public string? FacultyType { get; init; } +} + +/// +/// Faculty with a paid appointment in the school, by department, with head counts, emeriti and +/// recall counts, and the age profile of active faculty. Ports the legacy "Faculty Profile" page +/// (facultyProfile), which made one query per department and one per person; this makes one. +/// +public sealed class FacultyProfileReport : ReportDefinition +{ + private const string AgeProfileTitle = "Age profile of active faculty (excluding emeriti and recalled faculty)"; + + // The legacy report drew a department's age chart only when it had at least five faculty. + private const int DepartmentChartMinimum = 5; + + private readonly IPersonnelReportDataService _data; + + public FacultyProfileReport(IPersonnelReportDataService data) + { + _data = data; + } + + public override string Key => "personnel.faculty-profile"; + + public override string Title => "Faculty Profile"; + + public override string Area => PersonnelReports.Area; + + public override string Description => + "Faculty with a paid appointment in the school, by department, with age distribution and emeriti and recall counts."; + + public override IReadOnlyList Permissions => [PersonnelPermissions.FacultySalary]; + + protected override void Configure(ReportBuilder report) + { + report.Choice(p => p.FacultyType, "Faculty type", PersonnelOptions.SenateFederationBoth) + .Required() + .Default(() => PersonnelOptions.Both); + report.Sensitive(); + + report.Column(r => r.Name, "Name"); + report.Column(r => r.Age, "Age").AsNumber(); + report.Column(r => r.HireDate, "Hire date").AsDate(); + report.Column(r => r.AppointmentDepartment, "Department"); + report.Column(r => r.Title, "Title"); + + // Declared first so the age highlight, declared after it, wins on the age cell. + report.Highlight(r => r.IsRetired, ReportTone.Muted, "Emeritus or recalled"); + report.Highlight( + r => r.Age >= FacultyProfileRows.HighlightAge, + ReportTone.Warning, + $"{FacultyProfileRows.HighlightAge} or older", + "age"); + + ReportMeasure faculty = report.CountDistinct(r => r.EmployeeId); + ReportMeasure emeriti = report.CountDistinct(r => r.IsEmeritus ? r.EmployeeId : null); + ReportMeasure recalled = report.CountDistinct(r => r.IsRecalled ? r.EmployeeId : null); + ReportMeasure active = report.CountDistinct(r => r.IsRetired ? null : r.EmployeeId); + + report.Summary("Faculty", faculty); + report.Summary("Emeriti", emeriti); + report.Summary("Recalled", recalled); + report.GroupBy(r => r.Department) + .Subtotal("Faculty", faculty) + .Subtotal("Emeriti", emeriti) + .Subtotal("Recalled", recalled); + + report.Chart(AgeProfileTitle, ReportChartKind.Bar, r => r.AgeGroup, active) + .Where(r => !r.IsRetired); + report.Chart(AgeProfileTitle, ReportChartKind.Bar, r => r.AgeGroup, active) + .Where(r => !r.IsRetired) + .PerGroup(DepartmentChartMinimum); + } + + protected override async Task> FetchAsync( + FacultyProfileParameters parameters, ReportContext context, CancellationToken ct) + { + if (parameters.FacultyType is not { } facultyType) + { + throw new InvalidOperationException("Faculty Profile ran without its required parameter."); + } + + return FacultyProfileRows.Expand(await _data.GetFacultyAppointmentsAsync(facultyType, ct)); + } +} diff --git a/web/Areas/Personnel/Reports/FacultyProfileRows.cs b/web/Areas/Personnel/Reports/FacultyProfileRows.cs new file mode 100644 index 000000000..fdfcbadbe --- /dev/null +++ b/web/Areas/Personnel/Reports/FacultyProfileRows.cs @@ -0,0 +1,94 @@ +using Viper.Areas.Personnel.Models; + +namespace Viper.Areas.Personnel.Reports; + +/// +/// One line of the Faculty Profile: an appointment, listed under a department where the person +/// holds an appointment. is the grouping; +/// is this appointment's own department. +/// +public sealed record FacultyProfileRow( + string Department, + string EmployeeId, + string Name, + int? Age, + DateOnly? HireDate, + string? AppointmentDepartment, + string? Title) +{ + public string? AgeGroup => FacultyProfileRows.AgeGroup(Age); + + public bool IsEmeritus => FacultyProfileRows.IsEmeritusTitle(Title); + + public bool IsRecalled => FacultyProfileRows.IsRecalledTitle(Title); + + public bool IsRetired => IsEmeritus || IsRecalled; +} + +/// +/// The Faculty Profile's rules, kept apart from the report so each can be tested directly. +/// +public static class FacultyProfileRows +{ + /// + /// Ages at or above this are highlighted, as in the legacy report. + /// + public const int HighlightAge = 60; + + private const int GroupWidth = 5; + private const int YoungestGroup = 20; + private const int OldestAge = 99; + + /// + /// Five-year brackets from "20-24" to "95-99", matching usp_get_profile_facultyAge. + /// Ages outside that range have no bracket. + /// + public static string? AgeGroup(int? age) + { + if (age is not { } years || years < YoungestGroup || years > OldestAge) + { + return null; + } + + int start = years - (years % GroupWidth); + return $"{start}-{start + GroupWidth - 1}"; + } + + public static bool IsEmeritusTitle(string? title) + { + return title?.Contains("EMERI", StringComparison.OrdinalIgnoreCase) == true; + } + + public static bool IsRecalledTitle(string? title) + { + return title?.Contains("RECAL", StringComparison.OrdinalIgnoreCase) == true; + } + + /// + /// Lists each person under every department where they hold an appointment, with all of their + /// appointments each time, oldest people first, as the legacy report did with one query per + /// department and one per person. This does it from a single query. + /// + public static IReadOnlyList Expand(IReadOnlyList appointments) + { + ArgumentNullException.ThrowIfNull(appointments); + ILookup byPerson = + appointments.ToLookup(appointment => appointment.EmployeeId, StringComparer.Ordinal); + + return [.. appointments + .Select(appointment => (Department: (appointment.Department ?? string.Empty).Trim(), appointment.EmployeeId)) + .Distinct() + .SelectMany(member => byPerson[member.EmployeeId].Select(appointment => new FacultyProfileRow( + member.Department, + appointment.EmployeeId, + appointment.Name, + appointment.Age, + appointment.HireDate, + appointment.Department, + appointment.Title))) + .OrderByDescending(row => row.Age) + .ThenBy(row => row.Name, StringComparer.OrdinalIgnoreCase) + .ThenBy(row => row.EmployeeId, StringComparer.Ordinal) + .ThenBy(row => row.Title, StringComparer.OrdinalIgnoreCase)]; + } +} diff --git a/web/Areas/Personnel/Reports/FiscalYear.cs b/web/Areas/Personnel/Reports/FiscalYear.cs new file mode 100644 index 000000000..27c6b48d6 --- /dev/null +++ b/web/Areas/Personnel/Reports/FiscalYear.cs @@ -0,0 +1,20 @@ +namespace Viper.Areas.Personnel.Reports; + +/// +/// The university fiscal year, July 1 through June 30. +/// +public static class FiscalYear +{ + private const int FirstMonth = 7; + + public static DateOnly StartOf(DateOnly date) + { + int year = date.Month >= FirstMonth ? date.Year : date.Year - 1; + return new DateOnly(year, FirstMonth, 1); + } + + public static DateOnly EndOf(DateOnly date) + { + return StartOf(date).AddYears(1).AddDays(-1); + } +} diff --git a/web/Areas/Personnel/Reports/PersonnelOptions.cs b/web/Areas/Personnel/Reports/PersonnelOptions.cs new file mode 100644 index 000000000..1bbf0a715 --- /dev/null +++ b/web/Areas/Personnel/Reports/PersonnelOptions.cs @@ -0,0 +1,29 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.Areas.Personnel.Reports; + +/// +/// Choice lists shared by several Personnel reports, using the codes the PPS procedures expect. +/// +public static class PersonnelOptions +{ + public const string Faculty = "F"; + public const string Staff = "S"; + public const string Both = "B"; + public const string Senate = "S"; + public const string Federation = "F"; + + public static readonly IReadOnlyList FacultyStaffBoth = + [ + new(Faculty, "Faculty"), + new(Staff, "Staff"), + new(Both, "Both"), + ]; + + public static readonly IReadOnlyList SenateFederationBoth = + [ + new(Senate, "Senate"), + new(Federation, "Federation"), + new(Both, "Both"), + ]; +} diff --git a/web/Areas/Personnel/Reports/PersonnelReports.cs b/web/Areas/Personnel/Reports/PersonnelReports.cs new file mode 100644 index 000000000..b6d6e5180 --- /dev/null +++ b/web/Areas/Personnel/Reports/PersonnelReports.cs @@ -0,0 +1,12 @@ +namespace Viper.Areas.Personnel.Reports; + +/// +/// Shared settings for the Personnel reports. +/// +public static class PersonnelReports +{ + /// + /// The catalog area the Personnel reports are listed under. + /// + public const string Area = "Personnel"; +} diff --git a/web/Areas/Personnel/Services/PersonnelReportDataService.cs b/web/Areas/Personnel/Services/PersonnelReportDataService.cs new file mode 100644 index 000000000..78c57eedc --- /dev/null +++ b/web/Areas/Personnel/Services/PersonnelReportDataService.cs @@ -0,0 +1,124 @@ +using System.Data; +using Viper.Areas.Personnel.Models; +using Viper.Areas.Reports.Data; + +namespace Viper.Areas.Personnel.Services; + +/// +/// Reads the data behind the Personnel reports from the PPS warehouse. +/// +public interface IPersonnelReportDataService +{ + /// + /// Leaves of absence overlapping the date range, for faculty ("F"), staff ("S") or both ("B"). + /// + Task> GetPeopleOnLeaveAsync( + string employeeType, DateOnly startDate, DateOnly endDate, CancellationToken ct); + + /// + /// Employees by FLSA status: exempt ("E"), non-exempt ("N") or both ("B"). + /// + Task> GetFlsaAsync(string statusType, CancellationToken ct); + + /// + /// Every paid appointment of Senate ("S"), Federation ("F") or both ("B") faculty in the school. + /// + Task> GetFacultyAppointmentsAsync(string facultyType, CancellationToken ct); +} + +/// +/// Calls the legacy PPS stored procedures, so results match the ColdFusion reports while they +/// run side by side. Each method only calls and maps; report rules live in the report definitions. +/// +public class PersonnelReportDataService : IPersonnelReportDataService +{ + private const string PeopleOnLeaveProcedure = "usp_get_peopleOnLeave"; + private const string FlsaProcedure = "usp_get_flsa"; + private const string FacultyListProcedure = "usp_get_facultyList"; + + // usp_get_facultyList returns every employee's appointments when @employeeID is "All". + private const string AllEmployees = "All"; + private const string LegacyDateFormat = "MM/dd/yyyy"; + + private readonly IStoredProcedureRunner _runner; + + public PersonnelReportDataService(IStoredProcedureRunner runner) + { + _runner = runner; + } + + public Task> GetPeopleOnLeaveAsync( + string employeeType, DateOnly startDate, DateOnly endDate, CancellationToken ct) + { + // @fYear is the procedure's older fiscal-year filter; the date range replaces it. + return _runner.QueryAsync( + PersonnelDatabases.Pps, + PeopleOnLeaveProcedure, + [ + StoredProcedureParameter.Text("fYear", null, 4), + StoredProcedureParameter.Text("employeeType", employeeType, 1), + StoredProcedureParameter.Date("startDate", startDate), + StoredProcedureParameter.Date("endDate", endDate), + ], + MapEmployeeOnLeave, + ct); + } + + public Task> GetFlsaAsync(string statusType, CancellationToken ct) + { + return _runner.QueryAsync( + PersonnelDatabases.Pps, + FlsaProcedure, + [StoredProcedureParameter.Text("statusType", statusType, 1)], + MapFlsaEmployee, + ct); + } + + public Task> GetFacultyAppointmentsAsync(string facultyType, CancellationToken ct) + { + return _runner.QueryAsync( + PersonnelDatabases.Pps, + FacultyListProcedure, + [ + StoredProcedureParameter.Text("facultyType", facultyType, 1), + StoredProcedureParameter.Text("deptCode", string.Empty, 6), + StoredProcedureParameter.Text("employeeID", AllEmployees, 11), + ], + MapFacultyAppointment, + ct); + } + + // Stored procedure rows are mapped by hand: Mapperly maps between types, not from IDataRecord. + internal static EmployeeOnLeaveRow MapEmployeeOnLeave(IDataRecord record) + { + return new EmployeeOnLeaveRow( + record.GetTrimmedString("Name") ?? string.Empty, + record.GetTrimmedString("homeDept"), + record.GetDateOnly("loa_begin_date"), + record.GetDateOnly("loa_return_date"), + record.GetTrimmedString("loa_description"), + record.GetTrimmedString("pay_status")); + } + + internal static FlsaEmployeeRow MapFlsaEmployee(IDataRecord record) + { + return new FlsaEmployeeRow( + record.GetTrimmedString("employee_id"), + record.GetTrimmedString("emp_name") ?? string.Empty, + record.GetTrimmedString("department"), + record.GetTrimmedString("title"), + record.GetTrimmedString("flsa"), + record.GetTrimmedString("email")); + } + + internal static FacultyAppointmentRow MapFacultyAppointment(IDataRecord record) + { + return new FacultyAppointmentRow( + record.GetTrimmedString("EMPLOYEE_ID") ?? string.Empty, + record.GetTrimmedString("EMP_NAME") ?? string.Empty, + record.GetNullableInt32("AGE"), + record.GetDateOnlyFromText("HIRE_DATE", LegacyDateFormat), + record.GetTrimmedString("APPT_DEPT"), + record.GetTrimmedString("TITLE")); + } +} diff --git a/web/Areas/Reports/Controllers/ReportsController.cs b/web/Areas/Reports/Controllers/ReportsController.cs new file mode 100644 index 000000000..1d4abf077 --- /dev/null +++ b/web/Areas/Reports/Controllers/ReportsController.cs @@ -0,0 +1,91 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Services; +using Viper.Classes; +using Web.Authorization; + +namespace Viper.Areas.Reports.Controllers; + +/// +/// Lists, describes, runs and exports code-defined reports. Signing in is enough to reach the controller; +/// each report's own permissions are checked by before any +/// parameters are read. +/// +[Route("/api/reports")] +[Permission(Allow = "SVMSecure")] +public class ReportsController : ApiController +{ + private readonly IReportService _reportService; + + public ReportsController(IReportService reportService) + { + _reportService = reportService; + } + + [HttpGet] + public ActionResult> GetCatalog([FromQuery] string? area = null) + { + return Ok(_reportService.GetCatalog(area)); + } + + [HttpGet("{key}")] + public ActionResult GetDefinition(string key) + { + return ToActionResult(_reportService.GetDefinition(key)); + } + + [HttpPost("{key}/run")] + public async Task> Run( + string key, + [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] JsonElement? parameters, + CancellationToken ct = default) + { + return ToActionResult(await _reportService.RunAsync(key, parameters, ct)); + } + + /// + /// Runs the report and returns it as a file download in (csv, xlsx or pdf). + /// + [HttpPost("{key}/export/{format}")] + public async Task Export( + string key, + string format, + [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] JsonElement? parameters, + CancellationToken ct = default) + { + ReportOutcome outcome = await _reportService.ExportAsync(key, format, parameters, ct); + if (outcome.Value is not { } file) + { + return ToActionResult(outcome); + } + + // Exports hold personnel 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); + } + + /// + /// Groups validation errors by parameter name; errors that span several parameters use an + /// empty key, the same convention ASP.NET uses for model-level errors. + /// + internal static ValidationProblemDetails ToProblemDetails(IReadOnlyList errors) + { + Dictionary byParameter = errors + .GroupBy(error => error.Parameter ?? string.Empty, StringComparer.Ordinal) + .ToDictionary(group => group.Key, group => group.Select(error => error.Message).ToArray(), StringComparer.Ordinal); + return new ValidationProblemDetails(byParameter) { Title = "The report parameters are not valid." }; + } + + private ActionResult ToActionResult(ReportOutcome outcome) + { + return outcome.Status switch + { + ReportOutcomeStatus.Ok => Ok(outcome.Value), + ReportOutcomeStatus.NotFound => NotFound("Report not found."), + ReportOutcomeStatus.Forbidden => ForbidApi("You do not have access to this report."), + _ => BadRequest(ToProblemDetails(outcome.Errors)), + }; + } +} diff --git a/web/Areas/Reports/Data/DataRecordExtensions.cs b/web/Areas/Reports/Data/DataRecordExtensions.cs new file mode 100644 index 000000000..68bd22cb5 --- /dev/null +++ b/web/Areas/Reports/Data/DataRecordExtensions.cs @@ -0,0 +1,49 @@ +using System.Data; +using System.Globalization; + +namespace Viper.Areas.Reports.Data; + +/// +/// Null-safe reads of stored procedure columns by name. The legacy procedures return many +/// char columns padded with spaces, so text is trimmed on the way in. +/// +public static class DataRecordExtensions +{ + public static string? GetTrimmedString(this IDataRecord record, string column) + { + ArgumentNullException.ThrowIfNull(record); + int ordinal = record.GetOrdinal(column); + return record.IsDBNull(ordinal) + ? null + : Convert.ToString(record.GetValue(ordinal), CultureInfo.InvariantCulture)?.TrimEnd(); + } + + public static DateOnly? GetDateOnly(this IDataRecord record, string column) + { + ArgumentNullException.ThrowIfNull(record); + int ordinal = record.GetOrdinal(column); + return record.IsDBNull(ordinal) ? null : DateOnly.FromDateTime(record.GetDateTime(ordinal)); + } + + /// + /// A date the procedure returns as text, such as CONVERT(VARCHAR(10), d, 101) for + /// "MM/dd/yyyy". Blank or unreadable text is null. + /// + public static DateOnly? GetDateOnlyFromText(this IDataRecord record, string column, string format) + { + string? text = record.GetTrimmedString(column); + return DateOnly.TryParseExact(text, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly date) + ? date + : null; + } + + /// + /// A whole number from any numeric column type, such as the decimal FLOOR(...) returns. + /// + public static int? GetNullableInt32(this IDataRecord record, string column) + { + ArgumentNullException.ThrowIfNull(record); + int ordinal = record.GetOrdinal(column); + return record.IsDBNull(ordinal) ? null : Convert.ToInt32(record.GetValue(ordinal), CultureInfo.InvariantCulture); + } +} diff --git a/web/Areas/Reports/Data/DbConnectionFactory.cs b/web/Areas/Reports/Data/DbConnectionFactory.cs new file mode 100644 index 000000000..3cd92234d --- /dev/null +++ b/web/Areas/Reports/Data/DbConnectionFactory.cs @@ -0,0 +1,44 @@ +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Data.SqlClient; + +namespace Viper.Areas.Reports.Data; + +/// +/// Opens connections to databases that have no EF context, such as PPS and AcademicPersonnel, +/// by connection string name. Tests substitute a fake connection. +/// +public interface IDbConnectionFactory +{ + /// + /// A new, unopened connection. Throws when the + /// connection string isn't configured. + /// + DbConnection Create(string connectionStringName); +} + +/// +/// Creates SQL Server connections from ConnectionStrings, which AWS Systems Manager fills +/// in each environment. A missing string fails the report that needs it, not application startup. +/// +[ExcludeFromCodeCoverage(Justification = "Only creates a real SqlConnection; its callers are tested with a fake connection.")] +public sealed class SqlConnectionFactory : IDbConnectionFactory +{ + private readonly IConfiguration _configuration; + + public SqlConnectionFactory(IConfiguration configuration) + { + _configuration = configuration; + } + + public DbConnection Create(string connectionStringName) + { + string? connectionString = _configuration.GetConnectionString(connectionStringName); + if (string.IsNullOrWhiteSpace(connectionString)) + { + throw new InvalidOperationException($"Connection string '{connectionStringName}' is not configured."); + } + + return new SqlConnection(connectionString); + } +} diff --git a/web/Areas/Reports/Data/StoredProcedureParameter.cs b/web/Areas/Reports/Data/StoredProcedureParameter.cs new file mode 100644 index 000000000..d1ca8a989 --- /dev/null +++ b/web/Areas/Reports/Data/StoredProcedureParameter.cs @@ -0,0 +1,60 @@ +using System.Data; +using System.Data.Common; + +namespace Viper.Areas.Reports.Data; + +/// +/// A typed stored procedure input. Values always travel as parameters, never as SQL text. +/// +public sealed record StoredProcedureParameter +{ + private StoredProcedureParameter(string name, DbType type, object? value, int? size) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + Name = name.StartsWith('@') ? name : "@" + name; + Type = type; + Value = value; + Size = size; + } + + /// + /// The parameter name including its leading @. + /// + public string Name { get; } + + public DbType Type { get; } + + public object? Value { get; } + + public int? Size { get; } + + /// + /// A varchar input; is the procedure's declared length. + /// + public static StoredProcedureParameter Text(string name, string? value, int size) + { + return new StoredProcedureParameter(name, DbType.AnsiString, value, size); + } + + /// + /// A datetime input at midnight on . + /// + public static StoredProcedureParameter Date(string name, DateOnly? value) + { + return new StoredProcedureParameter(name, DbType.DateTime, value?.ToDateTime(TimeOnly.MinValue), null); + } + + internal DbParameter ToDbParameter(DbCommand command) + { + DbParameter parameter = command.CreateParameter(); + parameter.ParameterName = Name; + parameter.DbType = Type; + parameter.Value = Value ?? DBNull.Value; + if (Size is { } size) + { + parameter.Size = size; + } + + return parameter; + } +} diff --git a/web/Areas/Reports/Data/StoredProcedureRunner.cs b/web/Areas/Reports/Data/StoredProcedureRunner.cs new file mode 100644 index 000000000..c5fd565eb --- /dev/null +++ b/web/Areas/Reports/Data/StoredProcedureRunner.cs @@ -0,0 +1,65 @@ +using System.Data; +using System.Data.Common; + +namespace Viper.Areas.Reports.Data; + +/// +/// Runs a stored procedure and maps each row of its result. +/// +public interface IStoredProcedureRunner +{ + Task> QueryAsync( + string connectionStringName, + string procedure, + IReadOnlyList parameters, + Func map, + CancellationToken ct); +} + +/// +/// Calls stored procedures on databases that have no EF context. Procedure names are constants +/// in the data services, and every value is a typed parameter, so no SQL is ever built from input. +/// +public sealed class StoredProcedureRunner : IStoredProcedureRunner +{ + /// + /// Some PPS report procedures scan the whole UCPath extract, so allow longer than the default 30 seconds. + /// + public const int CommandTimeoutSeconds = 120; + + private readonly IDbConnectionFactory _connections; + + public StoredProcedureRunner(IDbConnectionFactory connections) + { + _connections = connections; + } + + public async Task> QueryAsync( + string connectionStringName, + string procedure, + IReadOnlyList parameters, + Func map, + CancellationToken ct) + { + ArgumentException.ThrowIfNullOrWhiteSpace(procedure); + ArgumentNullException.ThrowIfNull(parameters); + ArgumentNullException.ThrowIfNull(map); + + await using DbConnection connection = _connections.Create(connectionStringName); + await connection.OpenAsync(ct); + await using DbCommand command = connection.CreateCommand(); + command.CommandType = CommandType.StoredProcedure; + command.CommandText = procedure; + command.CommandTimeout = CommandTimeoutSeconds; + command.Parameters.AddRange(parameters.Select(parameter => parameter.ToDbParameter(command)).ToArray()); + + await using DbDataReader reader = await command.ExecuteReaderAsync(ct); + var rows = new List(); + while (await reader.ReadAsync(ct)) + { + rows.Add(map(reader)); + } + + return rows; + } +} diff --git a/web/Areas/Reports/Engine/PlannedReport.cs b/web/Areas/Reports/Engine/PlannedReport.cs new file mode 100644 index 000000000..a3cb2ea35 --- /dev/null +++ b/web/Areas/Reports/Engine/PlannedReport.cs @@ -0,0 +1,38 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// What a catalog needs to list a report: its key, display text and the permissions that grant it. +/// +public interface IReportIdentity +{ + string Key { get; } + + string Title { get; } + + string Area { get; } + + string Description { get; } + + /// + /// The user needs any one of these permissions to run the report. + /// + IReadOnlyList Permissions { get; } +} + +/// +/// A report listed in its area's catalog before it is built, so the area's pages can link to it +/// ahead of time. A planned report can't be described, run or exported: the engine treats those +/// requests as it would an unknown key. When the report's definition is added, delete its planned +/// entry; the registry refuses a key used by both. +/// +public sealed record PlannedReport( + string Key, string Title, string Area, string Description, IReadOnlyList Permissions) : IReportIdentity; + +/// +/// Supplies an area's planned reports. +/// registers every implementation in the report assembly. +/// +public interface IPlannedReportSource +{ + IReadOnlyList PlannedReports { get; } +} diff --git a/web/Areas/Reports/Engine/ReportBuilder.Layout.cs b/web/Areas/Reports/Engine/ReportBuilder.Layout.cs new file mode 100644 index 000000000..b63b214b3 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportBuilder.Layout.cs @@ -0,0 +1,209 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// Layout declarations: grouping, totals, summary facts, highlights, pivots and charts, plus the +/// measure factories they use. +/// +public sealed partial class ReportBuilder +{ + private readonly List> _totals = []; + private readonly List> _summaries = []; + private readonly List> _flags = []; + private readonly List> _pivots = []; + private readonly List> _charts = []; + + internal bool ShowRowNumbers { get; private set; } + + internal bool IsSensitive { get; private set; } + + internal ReportGrouping? Grouping { get; private set; } + + internal IReadOnlyList> Totals => _totals; + + internal IReadOnlyList> Summaries => _summaries; + + internal IReadOnlyList> Flags => _flags; + + internal IReadOnlyList> Pivots => _pivots; + + internal IReadOnlyList> Charts => _charts; + + #region Measures + + public ReportMeasure Count() + { + return new ReportMeasure(rows => rows.Count); + } + + /// + /// Counts distinct non-null keys, for example people when a person can have several rows. + /// + public ReportMeasure CountDistinct(Func key) + { + ArgumentNullException.ThrowIfNull(key); + return new ReportMeasure(rows => rows.Select(key).Where(value => value is not null).Distinct().Count()); + } + + public ReportMeasure Sum(Func value) + { + return Numeric(value, ReportMath.Sum); + } + + public ReportMeasure Average(Func value) + { + return Numeric(value, ReportMath.Average); + } + + public ReportMeasure Minimum(Func value) + { + return Numeric(value, ReportMath.Minimum); + } + + public ReportMeasure Maximum(Func value) + { + return Numeric(value, ReportMath.Maximum); + } + + public ReportMeasure StandardDeviation(Func value) + { + return Numeric(value, ReportMath.StandardDeviation); + } + + #endregion + + #region Layout + + public void RowNumbers() + { + ShowRowNumbers = true; + } + + /// + /// Marks the report as containing confidential personnel data (salary, demographics, visa + /// status, birth dates). Every export of it carries a confidentiality notice. + /// + public void Sensitive() + { + IsSensitive = true; + } + + /// + /// Splits the rows into groups by , ordered alphabetically. Blank keys + /// form one group labelled "(Not specified)". A report has at most one grouping. + /// + public ReportGroupBuilder GroupBy(Func key) + { + ArgumentNullException.ThrowIfNull(key); + if (Grouping is not null) + { + throw new InvalidOperationException("A report can be grouped only once."); + } + + Grouping = new ReportGrouping(key); + return new ReportGroupBuilder(Grouping); + } + + public void Total(string label, ReportMeasure measure, string? columnKey = null) + { + _totals.Add(ReportLayoutRules.CreateTotal(label, measure, columnKey)); + } + + /// + /// Adds a headline fact shown above the rows. Give when the fact + /// reveals that column's data, so it is hidden from users who cannot see the column. + /// + public void Summary(string label, ReportMeasure measure, string? columnKey = null) + { + _summaries.Add(ReportLayoutRules.CreateTotal(label, measure, columnKey)); + } + + /// + /// Emphasizes matching rows, or only the cell when one is given. + /// + public void Highlight(Func when, ReportTone tone, string label, string? columnKey = null) + { + AddFlag(when, ReportFlagKind.Highlight, tone, label, columnKey); + } + + /// + /// Shows as a badge beside the value of matching rows. + /// + public void Badge(Func when, ReportTone tone, string label, string columnKey) + { + ArgumentException.ThrowIfNullOrWhiteSpace(columnKey); + AddFlag(when, ReportFlagKind.Badge, tone, label, columnKey); + } + + public void Pivot(string title, Func rows, Func columns, ReportMeasure measure) + { + ArgumentNullException.ThrowIfNull(rows); + AddPivot(title, row => [rows(row)], columns, measure); + } + + /// + /// A pivot whose rows come from a multi-valued field. Each row is counted under every key it + /// returns, so totals count selections rather than rows; use to count rows. + /// + public void PivotEach( + string title, Func> rows, Func columns, ReportMeasure measure) + { + ArgumentNullException.ThrowIfNull(rows); + AddPivot(title, rows, columns, measure); + } + + public ReportChartBuilder Chart( + string title, ReportChartKind kind, Func category, ReportMeasure measure) + { + ArgumentException.ThrowIfNullOrWhiteSpace(title); + ArgumentNullException.ThrowIfNull(category); + ArgumentNullException.ThrowIfNull(measure); + var chart = new ReportChartRule(title, kind, category, measure); + _charts.Add(chart); + return new ReportChartBuilder(chart); + } + + #endregion + + private void EnsureValidLayout(string reportKey) + { + HashSet columnKeys = new(_columns.Select(column => column.Key), StringComparer.Ordinal); + string? unknown = _totals + .Concat(_summaries) + .Concat(Grouping?.Subtotals ?? []) + .Select(total => total.ColumnKey) + .Concat(_flags.Select(flag => flag.ColumnKey)) + .FirstOrDefault(key => key is not null && !columnKeys.Contains(key)); + if (unknown is not null) + { + throw new InvalidOperationException($"Report '{reportKey}' refers to the unknown column '{unknown}'."); + } + + if (Grouping is null && _charts.Any(chart => chart.PerGroup)) + { + throw new InvalidOperationException($"Report '{reportKey}' has a per-group chart but no grouping."); + } + } + + private static ReportMeasure Numeric( + Func value, Func, decimal?> aggregate) + { + ArgumentNullException.ThrowIfNull(value); + return new ReportMeasure(rows => aggregate([.. rows.Select(value).OfType()])); + } + + private void AddFlag(Func when, ReportFlagKind kind, ReportTone tone, string label, string? columnKey) + { + ArgumentNullException.ThrowIfNull(when); + ArgumentException.ThrowIfNullOrWhiteSpace(label); + _flags.Add(new ReportFlagRule(when, kind, tone, label, columnKey)); + } + + private void AddPivot( + string title, Func> rows, Func columns, ReportMeasure measure) + { + ArgumentException.ThrowIfNullOrWhiteSpace(title); + ArgumentNullException.ThrowIfNull(columns); + ArgumentNullException.ThrowIfNull(measure); + _pivots.Add(new ReportPivotRule(title, rows, columns, measure)); + } +} diff --git a/web/Areas/Reports/Engine/ReportBuilder.cs b/web/Areas/Reports/Engine/ReportBuilder.cs new file mode 100644 index 000000000..0cdcf959b --- /dev/null +++ b/web/Areas/Reports/Engine/ReportBuilder.cs @@ -0,0 +1,131 @@ +using System.Linq.Expressions; + +namespace Viper.Areas.Reports.Engine; + +/// +/// Collects the parameters, validation rules and columns a report declares in +/// . +/// +public sealed partial class ReportBuilder where TParams : class +{ + private readonly List> _parameters = []; + private readonly List> _rules = []; + private readonly List> _columns = []; + + internal IReadOnlyList> Parameters => _parameters; + + internal IReadOnlyList> Rules => _rules; + + internal IReadOnlyList> Columns => _columns; + + public ReportParameterBuilder Choice( + Expression> property, string label, IReadOnlyList options) + { + ReportParameter parameter = AddParameter(property, label, ReportParameterType.Choice); + parameter.SetOptions(RequireOptions(options), value => [(string)value]); + return new ReportParameterBuilder(parameter); + } + + public ReportParameterBuilder?> MultiChoice( + Expression?>> property, string label, IReadOnlyList options) + { + ReportParameter parameter = AddParameter(property, label, ReportParameterType.MultiChoice); + parameter.SetOptions(RequireOptions(options), value => (IEnumerable)value); + return new ReportParameterBuilder?>(parameter); + } + + public ReportParameterBuilder Date(Expression> property, string label) + { + return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Date)); + } + + public ReportParameterBuilder Text(Expression> property, string label) + { + return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Text)); + } + + public ReportParameterBuilder Number(Expression> property, string label) + { + return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Number)); + } + + public ReportParameterBuilder Boolean(Expression> property, string label) + { + return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Boolean)); + } + + /// + /// Adds a rule that spans several parameters. Rules run only after every individual + /// parameter is valid, so can rely on required values being set. + /// + public void Validate(Func isValid, string message, string? parameter = null) + { + ArgumentNullException.ThrowIfNull(isValid); + ArgumentException.ThrowIfNullOrWhiteSpace(message); + _rules.Add(new ReportParameterRule(isValid, message, parameter)); + } + + /// + /// Adds a column. The key defaults to the camelCase name of the selected property; a + /// computed selector such as r => r.First + " " + r.Last needs an explicit key. + /// + public ReportColumnBuilder Column( + Expression> selector, string label, string? key = null) + { + ArgumentNullException.ThrowIfNull(selector); + ArgumentException.ThrowIfNullOrWhiteSpace(label); + if (key is not null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + } + + string columnKey = key + ?? ReportExpressions.GetPropertyKey(selector) + ?? throw new ArgumentException("A computed column needs an explicit key.", nameof(key)); + Func getValue = selector.Compile(); + var column = new ReportColumn(columnKey, label, row => getValue(row)); + _columns.Add(column); + return new ReportColumnBuilder(column); + } + + internal void EnsureValid(string reportKey) + { + if (_columns.Count == 0) + { + throw new InvalidOperationException($"Report '{reportKey}' must define at least one column."); + } + + ThrowOnDuplicate(_columns.Select(column => column.Key), "column", reportKey); + ThrowOnDuplicate(_parameters.Select(parameter => parameter.Name), "parameter", reportKey); + EnsureValidLayout(reportKey); + } + + private ReportParameter AddParameter( + Expression> property, string label, ReportParameterType type) + { + ArgumentException.ThrowIfNullOrWhiteSpace(label); + var parameter = new ReportParameter(ReportExpressions.GetSettableProperty(property), label, type); + _parameters.Add(parameter); + return parameter; + } + + private static IReadOnlyList RequireOptions(IReadOnlyList options) + { + ArgumentNullException.ThrowIfNull(options); + return options.Count > 0 + ? options + : throw new ArgumentException("A choice parameter needs at least one option.", nameof(options)); + } + + private static void ThrowOnDuplicate(IEnumerable names, string kind, string reportKey) + { + IGrouping? duplicate = names + .GroupBy(name => name, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(group => group.Count() > 1); + if (duplicate is not null) + { + throw new InvalidOperationException( + $"Report '{reportKey}' declares the {kind} '{duplicate.Key}' more than once."); + } + } +} diff --git a/web/Areas/Reports/Engine/ReportColumn.cs b/web/Areas/Reports/Engine/ReportColumn.cs new file mode 100644 index 000000000..b1f720f4e --- /dev/null +++ b/web/Areas/Reports/Engine/ReportColumn.cs @@ -0,0 +1,106 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// One column of a report, with the function that reads its value from a row. +/// +internal sealed class ReportColumn +{ + public ReportColumn(string key, string label, Func value) + { + Key = key; + Label = label; + Value = value; + } + + public string Key { get; } + + public string Label { get; } + + public Func Value { get; } + + // Defaults are the enums' first members: Text, aligned left. + public ReportColumnFormat Format { get; set; } + + public ReportAlignment Align { get; set; } + + public int? Decimals { get; set; } + + public Func? VisibleWhen { get; set; } + + public bool IsVisible(ReportContext context) + { + return VisibleWhen?.Invoke(context) ?? true; + } + + public ReportColumnMetadata ToMetadata() + { + return new ReportColumnMetadata(Key, Label, Format, Align, Decimals); + } +} + +/// +/// Fluent options for a column declared on a . +/// +public sealed class ReportColumnBuilder +{ + private const int CurrencyDecimals = 2; + + private readonly ReportColumn _column; + + internal ReportColumnBuilder(ReportColumn column) + { + _column = column; + } + + public ReportColumnBuilder AsNumber(int decimals = 0) + { + ArgumentOutOfRangeException.ThrowIfNegative(decimals); + return SetFormat(ReportColumnFormat.Number, ReportAlignment.Right, decimals); + } + + public ReportColumnBuilder AsCurrency() + { + return SetFormat(ReportColumnFormat.Currency, ReportAlignment.Right, CurrencyDecimals); + } + + public ReportColumnBuilder AsPercent(int decimals = 0) + { + ArgumentOutOfRangeException.ThrowIfNegative(decimals); + return SetFormat(ReportColumnFormat.Percent, ReportAlignment.Right, decimals); + } + + public ReportColumnBuilder AsDate() + { + return SetFormat(ReportColumnFormat.Date, ReportAlignment.Center, null); + } + + public ReportColumnBuilder AsList() + { + return SetFormat(ReportColumnFormat.List, ReportAlignment.Left, null); + } + + public ReportColumnBuilder Align(ReportAlignment align) + { + _column.Align = align; + return this; + } + + /// + /// Shows the column only to users the predicate accepts, for example columns of + /// identifiers that only some roles may see. + /// + public ReportColumnBuilder VisibleWhen(Func predicate) + { + ArgumentNullException.ThrowIfNull(predicate); + _column.VisibleWhen = predicate; + return this; + } + + private ReportColumnBuilder SetFormat(ReportColumnFormat format, ReportAlignment align, int? decimals) + { + _column.Format = format; + _column.Align = align; + _column.Decimals = decimals; + return this; + } +} diff --git a/web/Areas/Reports/Engine/ReportContext.cs b/web/Areas/Reports/Engine/ReportContext.cs new file mode 100644 index 000000000..bc8c6bdfa --- /dev/null +++ b/web/Areas/Reports/Engine/ReportContext.cs @@ -0,0 +1,30 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// The user a report runs for. Permission checks go through a delegate so the engine never +/// depends on RAPS directly, and tests can supply any permission set. +/// +public sealed class ReportContext +{ + private readonly Func _hasPermission; + + public ReportContext(string? loginId, Func hasPermission) + { + ArgumentNullException.ThrowIfNull(hasPermission); + LoginId = loginId; + _hasPermission = hasPermission; + } + + public string? LoginId { get; } + + public bool HasPermission(string permission) + { + return !string.IsNullOrWhiteSpace(permission) && _hasPermission(permission); + } + + public bool HasAnyPermission(IEnumerable permissions) + { + ArgumentNullException.ThrowIfNull(permissions); + return permissions.Any(HasPermission); + } +} diff --git a/web/Areas/Reports/Engine/ReportDefinition.cs b/web/Areas/Reports/Engine/ReportDefinition.cs new file mode 100644 index 000000000..8319472ad --- /dev/null +++ b/web/Areas/Reports/Engine/ReportDefinition.cs @@ -0,0 +1,155 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// A report the engine can list, describe and run, independent of its row and parameter types. +/// +public interface IReportDefinition : IReportIdentity +{ + /// + /// True for reports with confidential personnel data; exports carry a confidentiality notice. + /// + bool IsSensitive { get; } + + /// + /// The class the report's parameters are bound to from the request body. + /// + Type ParametersType { get; } + + bool CanRun(ReportContext context); + + ReportDefinitionMetadata GetMetadata(ReportContext context); + + /// + /// Fills empty parameters with their defaults, then validates them. Returns an empty list + /// when the parameters are ready to run. + /// + IReadOnlyList PrepareParameters(object parameters); + + /// + /// The non-empty parameters as labelled, human-readable filters for export headers. + /// + IReadOnlyList DescribeParameters(object parameters); + + /// + /// Fetches the report's rows for prepared parameters and shapes them into a result. + /// + Task RunAsync(object parameters, ReportContext context, DateTimeOffset generatedAt, CancellationToken ct); +} + +/// +/// Base class for a code-defined report. is one row of the report's +/// data, holds the user's parameter values. +/// +public abstract class ReportDefinition : IReportDefinition where TParams : class +{ + private ReportBuilder? _layout; + + public abstract string Key { get; } + + public abstract string Title { get; } + + public abstract string Area { get; } + + public abstract string Description { get; } + + public abstract IReadOnlyList Permissions { get; } + + public Type ParametersType => typeof(TParams); + + public bool IsSensitive => Layout.IsSensitive; + + /// + /// The configured parameters, rules and columns. Built on first use so a report that is + /// only listed in the catalog never pays for compiling its column selectors. + /// + internal ReportBuilder Layout => _layout ??= BuildLayout(); + + public bool CanRun(ReportContext context) + { + ArgumentNullException.ThrowIfNull(context); + return context.HasAnyPermission(Permissions); + } + + public ReportDefinitionMetadata GetMetadata(ReportContext context) + { + ArgumentNullException.ThrowIfNull(context); + ReportBuilder layout = Layout; + return new ReportDefinitionMetadata( + Key, + Title, + Area, + Description, + [.. layout.Parameters.Select(parameter => parameter.ToMetadata())], + [.. layout.Columns.Where(column => column.IsVisible(context)).Select(column => column.ToMetadata())]); + } + + public IReadOnlyList PrepareParameters(object parameters) + { + TParams typed = AsParameters(parameters); + ReportBuilder layout = Layout; + foreach (ReportParameter parameter in layout.Parameters) + { + parameter.ApplyDefault(typed); + } + + List errors = + [.. layout.Parameters.Select(parameter => parameter.Validate(typed)).OfType()]; + if (errors.Count > 0) + { + return errors; + } + + return [.. layout.Rules + .Where(rule => !rule.IsValid(typed)) + .Select(rule => new ReportValidationError(rule.Parameter, rule.Message))]; + } + + public IReadOnlyList DescribeParameters(object parameters) + { + TParams typed = AsParameters(parameters); + return [.. Layout.Parameters.Select(parameter => parameter.Describe(typed)).OfType()]; + } + + public async Task RunAsync( + object parameters, ReportContext context, DateTimeOffset generatedAt, CancellationToken ct) + { + TParams typed = AsParameters(parameters); + ArgumentNullException.ThrowIfNull(context); + IReadOnlyList rows = await FetchAsync(typed, context, ct); + return CreateResult(rows, context, generatedAt); + } + + /// + /// Shapes fetched rows into the result the client and exporters render. + /// + internal ReportResult CreateResult(IReadOnlyList rows, ReportContext context, DateTimeOffset generatedAt) + { + return ReportPipeline.Build(Key, Title, Layout, rows, context, generatedAt); + } + + /// + /// Declares the report's parameters, cross-parameter rules, columns and layout. + /// + protected abstract void Configure(ReportBuilder report); + + /// + /// Loads the report's rows. Parameters have already been defaulted and validated. + /// identifies the user, for reports scoped to the user's own units. + /// + protected abstract Task> FetchAsync(TParams parameters, ReportContext context, CancellationToken ct); + + private TParams AsParameters(object parameters) + { + return parameters as TParams + ?? throw new ArgumentException( + $"Report '{Key}' expects parameters of type {typeof(TParams).Name}.", nameof(parameters)); + } + + private ReportBuilder BuildLayout() + { + var builder = new ReportBuilder(); + Configure(builder); + builder.EnsureValid(Key); + return builder; + } +} diff --git a/web/Areas/Reports/Engine/ReportExpressions.cs b/web/Areas/Reports/Engine/ReportExpressions.cs new file mode 100644 index 000000000..31d590099 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportExpressions.cs @@ -0,0 +1,43 @@ +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json; + +namespace Viper.Areas.Reports.Engine; + +/// +/// Turns selector lambdas such as p => p.StartDate into the property they name, so report +/// parameters and columns are declared with compile-checked member access instead of strings. +/// +internal static class ReportExpressions +{ + public static PropertyInfo GetSettableProperty(Expression> expression) + { + ArgumentNullException.ThrowIfNull(expression); + return FindProperty(expression) is { SetMethod.IsPublic: true } property + ? property + : throw new ArgumentException( + "The expression must select a public settable property, for example p => p.StartDate.", + nameof(expression)); + } + + public static string? GetPropertyKey(Expression> expression) + { + ArgumentNullException.ThrowIfNull(expression); + return FindProperty(expression) is { } property ? ToKey(property.Name) : null; + } + + /// + /// Keys use the same camelCase naming as the JSON the client sends and receives. + /// + public static string ToKey(string name) + { + return JsonNamingPolicy.CamelCase.ConvertName(name); + } + + private static PropertyInfo? FindProperty(LambdaExpression expression) + { + return expression.Body is MemberExpression { Member: PropertyInfo property, Expression: ParameterExpression } + ? property + : null; + } +} diff --git a/web/Areas/Reports/Engine/ReportFilter.cs b/web/Areas/Reports/Engine/ReportFilter.cs new file mode 100644 index 000000000..db9429fd5 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportFilter.cs @@ -0,0 +1,7 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// One parameter as the user chose it, for example "Faculty type: Senate", shown in export headers +/// so a downloaded file records how it was produced. +/// +public sealed record ReportFilter(string Label, string Value); diff --git a/web/Areas/Reports/Engine/ReportKey.cs b/web/Areas/Reports/Engine/ReportKey.cs new file mode 100644 index 000000000..3b7202587 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportKey.cs @@ -0,0 +1,42 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// Report keys look like personnel.employees-on-leave: a lowercase area segment, one dot, +/// then a kebab-case name. Keys appear in URLs and export filenames, so the character set is +/// deliberately narrow. +/// +public static class ReportKey +{ + public static bool IsValid(string? key) + { + if (string.IsNullOrEmpty(key)) + { + return false; + } + + int dot = key.IndexOf('.', StringComparison.Ordinal); + return dot > 0 + && dot < key.Length - 1 + && !key.AsSpan(dot + 1).Contains('.') + && IsSegment(key.AsSpan(0, dot)) + && IsSegment(key.AsSpan(dot + 1)); + } + + private static bool IsSegment(ReadOnlySpan segment) + { + if (segment[0] == '-' || segment[^1] == '-') + { + return false; + } + + foreach (char c in segment) + { + if (!char.IsAsciiLetterLower(c) && !char.IsAsciiDigit(c) && c != '-') + { + return false; + } + } + + return true; + } +} diff --git a/web/Areas/Reports/Engine/ReportLayoutRules.cs b/web/Areas/Reports/Engine/ReportLayoutRules.cs new file mode 100644 index 000000000..66a1fe483 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportLayoutRules.cs @@ -0,0 +1,140 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// A labelled measure: a grand total, a group subtotal or a summary fact. +/// +internal sealed record ReportTotalRule(string Label, ReportMeasure Measure, string? ColumnKey); + +internal sealed record ReportFlagRule( + Func When, ReportFlagKind Kind, ReportTone Tone, string Label, string? ColumnKey); + +/// +/// A cross-tabulation. may return several keys for one row (for example +/// every ethnicity a person selected), in which case the row counts once under each key. +/// +internal sealed record ReportPivotRule( + string Title, + Func> RowKeys, + Func ColumnKey, + ReportMeasure Measure); + +internal sealed class ReportChartRule +{ + public ReportChartRule(string title, ReportChartKind kind, Func category, ReportMeasure measure) + { + Title = title; + Kind = kind; + Category = category; + Measure = measure; + } + + public string Title { get; } + + public ReportChartKind Kind { get; } + + public Func Category { get; } + + public ReportMeasure Measure { get; } + + public bool PerGroup { get; set; } + + public int MinimumRows { get; set; } + + public IReadOnlyList CategoryOrder { get; set; } = []; + + /// + /// Which rows the chart counts; by default all of them. + /// + public Func Includes { get; set; } = _ => true; +} + +internal sealed class ReportGrouping +{ + public ReportGrouping(Func key) + { + Key = key; + } + + public Func Key { get; } + + public List> Subtotals { get; } = []; +} + +/// +/// Fluent options for the grouping declared with . +/// +public sealed class ReportGroupBuilder +{ + private readonly ReportGrouping _grouping; + + internal ReportGroupBuilder(ReportGrouping grouping) + { + _grouping = grouping; + } + + /// + /// Adds a per-group total, placed under when one is given. + /// + public ReportGroupBuilder Subtotal(string label, ReportMeasure measure, string? columnKey = null) + { + _grouping.Subtotals.Add(ReportLayoutRules.CreateTotal(label, measure, columnKey)); + return this; + } +} + +/// +/// Fluent options for a chart declared with . +/// +public sealed class ReportChartBuilder +{ + private readonly ReportChartRule _chart; + + internal ReportChartBuilder(ReportChartRule chart) + { + _chart = chart; + } + + /// + /// Draws the chart once per group instead of once for the whole report, skipping groups + /// with fewer than rows. Requires a grouping. + /// + public ReportChartBuilder PerGroup(int minimumRows = 1) + { + ArgumentOutOfRangeException.ThrowIfNegative(minimumRows); + _chart.PerGroup = true; + _chart.MinimumRows = minimumRows; + return this; + } + + /// + /// Lists categories in this order (for example age brackets). Categories not in the list + /// follow alphabetically. + /// + public ReportChartBuilder CategoryOrder(params string[] categories) + { + ArgumentNullException.ThrowIfNull(categories); + _chart.CategoryOrder = categories; + return this; + } + + /// + /// Charts only the rows that match, for example leaving out retired faculty while the table + /// still lists them. A per-group chart's minimum counts matching rows. + /// + public ReportChartBuilder Where(Func includes) + { + ArgumentNullException.ThrowIfNull(includes); + _chart.Includes = includes; + return this; + } +} + +internal static class ReportLayoutRules +{ + public static ReportTotalRule CreateTotal(string label, ReportMeasure measure, string? columnKey) + { + ArgumentException.ThrowIfNullOrWhiteSpace(label); + ArgumentNullException.ThrowIfNull(measure); + return new ReportTotalRule(label, measure, columnKey); + } +} diff --git a/web/Areas/Reports/Engine/ReportMeasure.cs b/web/Areas/Reports/Engine/ReportMeasure.cs new file mode 100644 index 000000000..27e23b22f --- /dev/null +++ b/web/Areas/Reports/Engine/ReportMeasure.cs @@ -0,0 +1,64 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// A number computed from a set of rows, such as a count, sum or average. Totals, subtotals, +/// summaries, pivots and charts all use measures, so every aggregate in a report is computed +/// the same way. Create measures with the factory methods on . +/// +public sealed class ReportMeasure +{ + private readonly Func, decimal?> _compute; + + internal ReportMeasure(Func, decimal?> compute) + { + _compute = compute; + } + + internal decimal? Compute(IReadOnlyCollection rows) + { + return _compute(rows); + } +} + +/// +/// Aggregate functions over the non-null values of a measure. Empty input gives null for +/// everything except the sum, which is zero, so an empty group shows "0" rather than a blank total. +/// +internal static class ReportMath +{ + public static decimal? Sum(IReadOnlyCollection values) + { + return values.Sum(); + } + + public static decimal? Average(IReadOnlyCollection values) + { + return values.Count == 0 ? null : values.Average(); + } + + public static decimal? Minimum(IReadOnlyCollection values) + { + return values.Count == 0 ? null : values.Min(); + } + + public static decimal? Maximum(IReadOnlyCollection values) + { + return values.Count == 0 ? null : values.Max(); + } + + /// + /// Sample standard deviation (divides by n - 1), matching SQL Server's STDEV, which the + /// legacy salary reports used. Needs at least two values. + /// + public static decimal? StandardDeviation(IReadOnlyCollection values) + { + if (values.Count < 2) + { + return null; + } + + decimal mean = values.Average(); + decimal sumOfSquares = values.Sum(value => (value - mean) * (value - mean)); + return (decimal)Math.Sqrt((double)(sumOfSquares / (values.Count - 1))); + } +} diff --git a/web/Areas/Reports/Engine/ReportMetadata.cs b/web/Areas/Reports/Engine/ReportMetadata.cs new file mode 100644 index 000000000..d7356921c --- /dev/null +++ b/web/Areas/Reports/Engine/ReportMetadata.cs @@ -0,0 +1,85 @@ +using System.Text.Json.Serialization; + +namespace Viper.Areas.Reports.Engine; + +/// +/// The kind of input a report parameter renders as on the client. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportParameterType +{ + Choice, + MultiChoice, + Date, + Text, + Number, + Boolean, +} + +/// +/// How a report column's values are formatted on screen and in exports. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportColumnFormat +{ + Text, + Number, + Currency, + Percent, + Date, + List, +} + +/// +/// Horizontal alignment of a report column. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportAlignment +{ + Left, + Center, + Right, +} + +/// +/// One selectable value of a choice parameter. +/// +public sealed record ReportOption(string Value, string Label); + +/// +/// Client-facing description of a report parameter. +/// +public sealed record ReportParameterMetadata( + string Name, + string Label, + ReportParameterType Type, + bool Required, + object? DefaultValue, + IReadOnlyList Options); + +/// +/// Client-facing description of a report column. +/// +public sealed record ReportColumnMetadata( + string Key, + string Label, + ReportColumnFormat Format, + ReportAlignment Align, + int? Decimals); + +/// +/// Client-facing description of a report: what it is, what it asks for, and what it shows. +/// +public sealed record ReportDefinitionMetadata( + string Key, + string Title, + string Area, + string Description, + IReadOnlyList Parameters, + IReadOnlyList Columns); + +/// +/// A problem with the parameters supplied for a report run. is null +/// when the problem involves several parameters rather than one field. +/// +public sealed record ReportValidationError(string? Parameter, string Message); diff --git a/web/Areas/Reports/Engine/ReportParameter.cs b/web/Areas/Reports/Engine/ReportParameter.cs new file mode 100644 index 000000000..2278e04e5 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportParameter.cs @@ -0,0 +1,151 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Reflection; + +namespace Viper.Areas.Reports.Engine; + +/// +/// One input on a report's parameter form, bound to a property of the report's parameter type. +/// +internal sealed class ReportParameter where TParams : class +{ + private readonly PropertyInfo _property; + private ChoiceRule? _choices; + + public ReportParameter(PropertyInfo property, string label, ReportParameterType type) + { + _property = property; + Name = ReportExpressions.ToKey(property.Name); + Label = label; + Type = type; + } + + public string Name { get; } + + public string Label { get; } + + public ReportParameterType Type { get; } + + public bool Required { get; set; } + + public Func? DefaultFactory { get; set; } + + public IReadOnlyList Options { get; private set; } = []; + + /// + /// Restricts the parameter to . + /// turns the bound value into the option values it selects, so single and multiple choice + /// share one validation path. + /// + public void SetOptions(IReadOnlyList options, Func> selectedValues) + { + Options = options; + _choices = new ChoiceRule( + options + .DistinctBy(option => option.Value, StringComparer.Ordinal) + .ToDictionary(option => option.Value, option => option.Label, StringComparer.Ordinal), + selectedValues); + } + + public ReportParameterMetadata ToMetadata() + { + return new ReportParameterMetadata(Name, Label, Type, Required, DefaultFactory?.Invoke(), Options); + } + + public void ApplyDefault(TParams parameters) + { + if (DefaultFactory is not null && !HasValue(_property.GetValue(parameters))) + { + _property.SetValue(parameters, DefaultFactory()); + } + } + + public ReportValidationError? Validate(TParams parameters) + { + object? value = _property.GetValue(parameters); + if (!HasValue(value)) + { + return Required ? new ReportValidationError(Name, $"{Label} is required.") : null; + } + + if (_choices is not null && _choices.SelectedValues(value).Any(selected => !_choices.Labels.ContainsKey(selected))) + { + return new ReportValidationError(Name, $"{Label} contains a value that is not an allowed option."); + } + + return null; + } + + /// + /// The parameter as a human-readable filter for report headers, or null when it is empty. + /// Choice values show their option labels rather than their codes. + /// + public ReportFilter? Describe(TParams parameters) + { + object? value = _property.GetValue(parameters); + return HasValue(value) ? new ReportFilter(Label, DescribeValue(value)) : null; + } + + private string DescribeValue(object value) + { + if (_choices is not null) + { + return string.Join(", ", _choices.SelectedValues(value).Select(selected => _choices.Labels.GetValueOrDefault(selected, selected))); + } + + return value switch + { + DateOnly date => date.ToString(ReportValueFormatter.DateFormat, CultureInfo.InvariantCulture), + bool flag => flag ? "Yes" : "No", + _ => string.Format(CultureInfo.InvariantCulture, "{0}", value), + }; + } + + private static bool HasValue([NotNullWhen(true)] object? value) + { + return value switch + { + null => false, + string text => !string.IsNullOrWhiteSpace(text), + IReadOnlyCollection values => values.Count > 0, + _ => true, + }; + } + + private sealed record ChoiceRule(Dictionary Labels, Func> SelectedValues); +} + +/// +/// A validation rule that spans several parameters, such as "end date on or after start date". +/// +internal sealed record ReportParameterRule(Func IsValid, string Message, string? Parameter); + +/// +/// Fluent options for a parameter declared on a . +/// +public sealed class ReportParameterBuilder where TParams : class +{ + private readonly ReportParameter _parameter; + + internal ReportParameterBuilder(ReportParameter parameter) + { + _parameter = parameter; + } + + public ReportParameterBuilder Required() + { + _parameter.Required = true; + return this; + } + + /// + /// Supplies the value used when the caller leaves the parameter empty. The factory runs on + /// every request, so date defaults such as "start of the current fiscal year" stay current. + /// + public ReportParameterBuilder Default(Func factory) + { + ArgumentNullException.ThrowIfNull(factory); + _parameter.DefaultFactory = () => factory(); + return this; + } +} diff --git a/web/Areas/Reports/Engine/ReportParameterBinder.cs b/web/Areas/Reports/Engine/ReportParameterBinder.cs new file mode 100644 index 000000000..f1c037da1 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportParameterBinder.cs @@ -0,0 +1,77 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Viper.Areas.Reports.Engine; + +/// +/// Binds a request's JSON body to a report's parameter class. Unknown properties are rejected +/// rather than ignored, so a misspelled parameter can't silently fall back to its default. +/// +internal static class ReportParameterBinder +{ + public const string NotAnObjectMessage = "Report parameters must be a JSON object."; + public const string UnreadableMessage = "A report parameter is not recognized or has a value of the wrong type."; + + public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) + { + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + }; + + private static readonly JsonElement EmptyObject = ParseEmptyObject(); + + public static bool TryBind( + Type parametersType, + JsonElement? json, + [NotNullWhen(true)] out object? parameters, + [NotNullWhen(false)] out ReportValidationError? error) + { + ArgumentNullException.ThrowIfNull(parametersType); + parameters = null; + error = null; + + JsonElement source = json ?? EmptyObject; + if (source.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) + { + source = EmptyObject; + } + + if (source.ValueKind != JsonValueKind.Object) + { + error = new ReportValidationError(null, NotAnObjectMessage); + return false; + } + + try + { + parameters = source.Deserialize(parametersType, JsonOptions) + ?? throw new JsonException("Report parameters deserialized to null."); + return true; + } + catch (JsonException ex) + { + error = new ReportValidationError(ParameterName(ex.Path), UnreadableMessage); + return false; + } + } + + private static JsonElement ParseEmptyObject() + { + using JsonDocument document = JsonDocument.Parse("{}"); + return document.RootElement.Clone(); + } + + /// + /// Turns a JSON path such as $.departments[1] into the parameter name departments. + /// + public static string? ParameterName(string? path) + { + if (path is null || !path.StartsWith("$.", StringComparison.Ordinal)) + { + return null; + } + + string name = path[2..].Split('[', '.')[0]; + return name.Length > 0 ? name : null; + } +} diff --git a/web/Areas/Reports/Engine/ReportPipeline.cs b/web/Areas/Reports/Engine/ReportPipeline.cs new file mode 100644 index 000000000..a576acbdb --- /dev/null +++ b/web/Areas/Reports/Engine/ReportPipeline.cs @@ -0,0 +1,157 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// Turns a report's rows and layout into a . Pure: no I/O, no clock and +/// no user lookups, so every rule here is unit-testable with plain in-memory rows. +/// +internal static class ReportPipeline +{ + public const string BlankKeyLabel = "(Not specified)"; + + public static ReportResult Build( + string key, + string title, + ReportBuilder layout, + IReadOnlyList rows, + ReportContext context, + DateTimeOffset generatedAt) + where TParams : class + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentNullException.ThrowIfNull(context); + + List> columns = [.. layout.Columns.Where(column => column.IsVisible(context))]; + HashSet visibleKeys = new(columns.Select(column => column.Key), StringComparer.Ordinal); + bool IsVisible(string? columnKey) => columnKey is null || visibleKeys.Contains(columnKey); + + return new ReportResult( + key, + title, + generatedAt, + rows.Count, + layout.ShowRowNumbers, + [.. columns.Select(column => column.ToMetadata())], + ComputeTotals(layout.Summaries, rows, IsVisible), + BuildGroups(layout, rows, columns, IsVisible), + ComputeTotals(layout.Totals, rows, IsVisible), + [.. layout.Pivots.Select(pivot => BuildPivot(pivot, rows))], + [.. layout.Charts.Where(chart => !chart.PerGroup).Select(chart => BuildChart(chart, rows))]); + } + + /// + /// Trims a grouping key and gives blank keys a visible label, so blank and whitespace-only + /// values (common in the PPS data) land in one group. + /// + public static string NormalizeKey(string? key) + { + return string.IsNullOrWhiteSpace(key) ? BlankKeyLabel : key.Trim(); + } + + /// + /// Orders categories: those named in first, in that order, then + /// the rest alphabetically. Preferred categories with no data are left out. + /// + public static IReadOnlyList OrderCategories(IEnumerable categories, IReadOnlyList preferred) + { + HashSet present = new(categories, StringComparer.Ordinal); + return [.. preferred + .Where(present.Contains) + .Concat(present.Except(preferred, StringComparer.Ordinal).Order(StringComparer.OrdinalIgnoreCase))]; + } + + private static List BuildGroups( + ReportBuilder layout, + IReadOnlyList rows, + List> columns, + Func isVisible) + where TParams : class + { + if (layout.Grouping is not { } grouping) + { + return [new ReportGroupResult(null, BuildRows(layout, rows, columns, isVisible), [], [])]; + } + + return [.. rows + .GroupBy(row => NormalizeKey(grouping.Key(row)), StringComparer.Ordinal) + .OrderBy(group => group.Key, StringComparer.OrdinalIgnoreCase) + .Select(group => BuildGroup(layout, grouping, group.Key, [.. group], columns, isVisible))]; + } + + private static ReportGroupResult BuildGroup( + ReportBuilder layout, + ReportGrouping grouping, + string label, + List rows, + List> columns, + Func isVisible) + where TParams : class + { + return new ReportGroupResult( + label, + BuildRows(layout, rows, columns, isVisible), + ComputeTotals(grouping.Subtotals, rows, isVisible), + [.. layout.Charts + .Where(chart => chart.PerGroup && rows.Count(chart.Includes) >= chart.MinimumRows) + .Select(chart => BuildChart(chart, rows))]); + } + + private static List BuildRows( + ReportBuilder layout, + IReadOnlyList rows, + List> columns, + Func isVisible) + where TParams : class + { + List> flags = [.. layout.Flags.Where(flag => isVisible(flag.ColumnKey))]; + return [.. rows.Select((row, index) => new ReportRowResult( + index + 1, + columns.ToDictionary(column => column.Key, column => column.Value(row), StringComparer.Ordinal), + [.. flags + .Where(flag => flag.When(row)) + .Select(flag => new ReportFlag(flag.Kind, flag.Tone, flag.Label, flag.ColumnKey))]))]; + } + + private static List ComputeTotals( + IEnumerable> totals, IReadOnlyCollection rows, Func isVisible) + { + return [.. totals + .Where(total => isVisible(total.ColumnKey)) + .Select(total => new ReportTotal(total.Label, total.ColumnKey, total.Measure.Compute(rows)))]; + } + + private static ReportPivotResult BuildPivot(ReportPivotRule pivot, IReadOnlyList rows) + { + List<(string Row, string Column, TRow Item)> entries = + [ + .. rows.SelectMany(item => pivot.RowKeys(item) + .Select(rowKey => (NormalizeKey(rowKey), NormalizeKey(pivot.ColumnKey(item)), item))), + ]; + IReadOnlyList rowKeys = OrderCategories(entries.Select(entry => entry.Row), []); + IReadOnlyList columnKeys = OrderCategories(entries.Select(entry => entry.Column), []); + ILookup<(string, string), TRow> byCell = entries.ToLookup(entry => (entry.Row, entry.Column), entry => entry.Item); + ILookup byRow = entries.ToLookup(entry => entry.Row, entry => entry.Item, StringComparer.Ordinal); + ILookup byColumn = entries.ToLookup(entry => entry.Column, entry => entry.Item, StringComparer.Ordinal); + + return new ReportPivotResult( + pivot.Title, + columnKeys, + [.. rowKeys.Select(rowKey => new ReportPivotRow( + rowKey, + [.. columnKeys.Select(columnKey => pivot.Measure.Compute([.. byCell[(rowKey, columnKey)]]))], + pivot.Measure.Compute([.. byRow[rowKey]])))], + [.. columnKeys.Select(columnKey => pivot.Measure.Compute([.. byColumn[columnKey]]))], + pivot.Measure.Compute([.. entries.Select(entry => entry.Item)])); + } + + private static ReportChartResult BuildChart(ReportChartRule chart, IReadOnlyCollection rows) + { + ILookup byCategory = rows + .Where(chart.Includes) + .ToLookup(row => NormalizeKey(chart.Category(row)), StringComparer.Ordinal); + IReadOnlyList categories = OrderCategories(byCategory.Select(group => group.Key), chart.CategoryOrder); + return new ReportChartResult( + chart.Title, + chart.Kind, + [.. categories.Select(category => new ReportChartPoint(category, chart.Measure.Compute([.. byCategory[category]])))]); + } +} diff --git a/web/Areas/Reports/Engine/ReportRegistry.cs b/web/Areas/Reports/Engine/ReportRegistry.cs new file mode 100644 index 000000000..1891721d2 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportRegistry.cs @@ -0,0 +1,101 @@ +namespace Viper.Areas.Reports.Engine; + +/// +/// Every report registered with the application, looked up by key. +/// +public interface IReportRegistry +{ + /// + /// All reports, ordered by area and then title. + /// + IReadOnlyList All { get; } + + /// + /// Reports listed in catalogs but not built yet, ordered by area and then title. + /// + IReadOnlyList Planned { get; } + + /// + /// The built report with this key, or null. Planned reports are never returned. + /// + IReportDefinition? Find(string? key); +} + +/// +/// Validates report identities when the registry is created, so a duplicate or malformed key +/// fails on the first request instead of producing an unreachable report. +/// +public sealed class ReportRegistry : IReportRegistry +{ + private readonly Dictionary _byKey = new(StringComparer.OrdinalIgnoreCase); + + public ReportRegistry(IEnumerable definitions, IEnumerable? plannedSources = null) + { + ArgumentNullException.ThrowIfNull(definitions); + foreach (IReportDefinition definition in definitions) + { + EnsureValidIdentity(definition); + if (!_byKey.TryAdd(definition.Key, definition)) + { + throw DuplicateKey(definition.Key); + } + } + + var plannedKeys = new HashSet(StringComparer.OrdinalIgnoreCase); + List planned = [.. (plannedSources ?? []).SelectMany(source => source.PlannedReports)]; + foreach (PlannedReport report in planned) + { + EnsureValidIdentity(report); + if (_byKey.ContainsKey(report.Key) || !plannedKeys.Add(report.Key)) + { + throw DuplicateKey(report.Key); + } + } + + All = [.. InCatalogOrder(_byKey.Values)]; + Planned = [.. InCatalogOrder(planned)]; + } + + public IReadOnlyList All { get; } + + public IReadOnlyList Planned { get; } + + public IReportDefinition? Find(string? key) + { + return string.IsNullOrWhiteSpace(key) ? null : _byKey.GetValueOrDefault(key); + } + + private static IEnumerable InCatalogOrder(IEnumerable reports) where T : IReportIdentity + { + return reports + .OrderBy(report => report.Area, StringComparer.OrdinalIgnoreCase) + .ThenBy(report => report.Title, StringComparer.OrdinalIgnoreCase); + } + + private static InvalidOperationException DuplicateKey(string key) + { + return new InvalidOperationException( + $"More than one report uses the key '{key}'. Remove a planned report once its definition exists."); + } + + private static void EnsureValidIdentity(IReportIdentity report) + { + if (!ReportKey.IsValid(report.Key)) + { + throw new InvalidOperationException( + $"Report key '{report.Key}' must look like 'area.report-name' (lowercase letters, digits and hyphens)."); + } + + if (string.IsNullOrWhiteSpace(report.Title) + || string.IsNullOrWhiteSpace(report.Area) + || string.IsNullOrWhiteSpace(report.Description)) + { + throw new InvalidOperationException($"Report '{report.Key}' needs a title, an area and a description."); + } + + if (report.Permissions.Count == 0 || report.Permissions.Any(string.IsNullOrWhiteSpace)) + { + throw new InvalidOperationException($"Report '{report.Key}' needs at least one non-blank permission."); + } + } +} diff --git a/web/Areas/Reports/Engine/ReportResult.cs b/web/Areas/Reports/Engine/ReportResult.cs new file mode 100644 index 000000000..242cdb992 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportResult.cs @@ -0,0 +1,87 @@ +using System.Text.Json.Serialization; + +namespace Viper.Areas.Reports.Engine; + +/// +/// Semantic emphasis for a row or cell. The client maps tones to design-system colors and +/// always shows the flag's label as well, so meaning never depends on color alone. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportTone +{ + Neutral, + Info, + Positive, + Warning, + Negative, + Muted, +} + +/// +/// A highlight styles a row or cell; a badge adds a short label next to a cell's value. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportFlagKind +{ + Highlight, + Badge, +} + +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum ReportChartKind +{ + Bar, + Line, + Pie, +} + +/// +/// The output of a report run, shared by the on-screen view and every export format. +/// +public sealed record ReportResult( + string Key, + string Title, + DateTimeOffset GeneratedAt, + int RowCount, + bool RowNumbers, + IReadOnlyList Columns, + IReadOnlyList Summary, + IReadOnlyList Groups, + IReadOnlyList Totals, + IReadOnlyList Pivots, + IReadOnlyList Charts); + +/// +/// One group of rows. An ungrouped report has a single group whose is null. +/// +public sealed record ReportGroupResult( + string? Label, + IReadOnlyList Rows, + IReadOnlyList Subtotals, + IReadOnlyList Charts); + +/// +/// One row. is keyed by column key and holds only the columns the user can see. +/// +public sealed record ReportRowResult(int Number, IReadOnlyDictionary Values, IReadOnlyList Flags); + +public sealed record ReportFlag(ReportFlagKind Kind, ReportTone Tone, string Label, string? ColumnKey); + +/// +/// A labelled aggregate. places a total under a column; for summary +/// facts it only ties the value to that column's visibility. +/// +public sealed record ReportTotal(string Label, string? ColumnKey, decimal? Value); + +public sealed record ReportPivotResult( + string Title, + IReadOnlyList ColumnKeys, + IReadOnlyList Rows, + IReadOnlyList ColumnTotals, + decimal? GrandTotal); + +public sealed record ReportPivotRow(string Key, IReadOnlyList Values, decimal? Total); + +public sealed record ReportChartResult(string Title, ReportChartKind Kind, IReadOnlyList Points); + +public sealed record ReportChartPoint(string Category, decimal? Value); diff --git a/web/Areas/Reports/Engine/ReportValueFormatter.cs b/web/Areas/Reports/Engine/ReportValueFormatter.cs new file mode 100644 index 000000000..f4afa37e3 --- /dev/null +++ b/web/Areas/Reports/Engine/ReportValueFormatter.cs @@ -0,0 +1,79 @@ +using System.Globalization; + +namespace Viper.Areas.Reports.Engine; + +/// +/// Formats report values as text for exports that have no cell types (CSV, PDF). Numbers use +/// US English separators and dates use MM/dd/yyyy, matching the legacy reports. +/// +public static class ReportValueFormatter +{ + public const string DateFormat = "MM/dd/yyyy"; + + // Roughly decimal.MaxValue; larger doubles can't convert to decimal. + private const double DecimalLimit = 7.9e28; + + private static readonly CultureInfo UsEnglish = CultureInfo.GetCultureInfo("en-US"); + + public static string Format(object? value, ReportColumnMetadata column) + { + ArgumentNullException.ThrowIfNull(column); + return value switch + { + null => string.Empty, + string text => text, + DateOnly date => date.ToString(DateFormat, CultureInfo.InvariantCulture), + DateTime dateTime => dateTime.ToString(DateFormat, CultureInfo.InvariantCulture), + IEnumerable values => string.Join(", ", values), + _ when IsNumeric(column.Format) && TryGetDecimal(value, out decimal number) => FormatNumber(number, column), + _ => string.Format(CultureInfo.InvariantCulture, "{0}", value), + }; + } + + public static bool IsNumeric(ReportColumnFormat format) + { + return format is ReportColumnFormat.Number or ReportColumnFormat.Currency or ReportColumnFormat.Percent; + } + + public static bool TryGetDecimal(object? value, out decimal number) + { + switch (value) + { + case decimal exact: + number = exact; + return true; + case int whole: + number = whole; + return true; + case long wide: + number = wide; + return true; + case double approximate when double.IsFinite(approximate) && Math.Abs(approximate) < DecimalLimit: + number = (decimal)approximate; + return true; + default: + number = 0; + return false; + } + } + + /// + /// The labels of a row's highlights and badges, for formats that can't show color. + /// + public static string FlagText(ReportRowResult row) + { + ArgumentNullException.ThrowIfNull(row); + return string.Join("; ", row.Flags.Select(flag => flag.Label).Distinct(StringComparer.Ordinal)); + } + + private static string FormatNumber(decimal number, ReportColumnMetadata column) + { + string decimals = (column.Decimals ?? 0).ToString(CultureInfo.InvariantCulture); + return column.Format switch + { + ReportColumnFormat.Currency => number.ToString("C" + decimals, UsEnglish), + ReportColumnFormat.Percent => number.ToString("P" + decimals, UsEnglish), + _ => number.ToString("N" + decimals, UsEnglish), + }; + } +} diff --git a/web/Areas/Reports/Exporters/ReportCsvExporter.cs b/web/Areas/Reports/Exporters/ReportCsvExporter.cs new file mode 100644 index 000000000..31f9d4dc9 --- /dev/null +++ b/web/Areas/Reports/Exporters/ReportCsvExporter.cs @@ -0,0 +1,89 @@ +using System.Text; +using Viper.Areas.Reports.Engine; +using Viper.Classes.Utilities; + +namespace Viper.Areas.Reports.Exporters; + +/// +/// Exports a report's rows as CSV: one header row, then one line per row with a Group column +/// for grouped reports and a Notes column for highlights. Totals, summaries, pivots and charts +/// are left out so the file stays a clean table for further analysis. +/// +public sealed class ReportCsvExporter : IReportExporter +{ + private static readonly char[] QuotedCharacters = ['"', ',', '\r', '\n']; + + public string Format => "csv"; + + public string ContentType => "text/csv"; + + public string Extension => ".csv"; + + public byte[] Export(ReportExport request) + { + ArgumentNullException.ThrowIfNull(request); + ReportResult result = request.Result; + bool grouped = result.Groups.Any(group => group.Label is not null); + bool hasNotes = ReportExportText.HasNotes(result); + + var csv = new StringBuilder(); + List header = []; + if (grouped) + { + header.Add(Text(ReportExportText.GroupHeader)); + } + + header.AddRange(result.Columns.Select(column => Text(column.Label))); + if (hasNotes) + { + header.Add(Text(ReportExportText.NotesHeader)); + } + + AppendLine(csv, header); + + foreach (ReportGroupResult group in result.Groups) + { + IEnumerable groupCells = group.Label is { } label ? [Text(label)] : []; + foreach (ReportRowResult row in group.Rows) + { + IEnumerable cells = groupCells.Concat(result.Columns.Select(column => Cell(row, column))); + AppendLine(csv, hasNotes ? cells.Append(Text(ReportValueFormatter.FlagText(row))) : cells); + } + } + + // The byte-order mark makes Excel open the file as UTF-8 instead of the system code page. + return [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes(csv.ToString())]; + } + + /// + /// Quotes a value when it contains a comma, quote or line break (RFC 4180). + /// + internal static string Quote(string value) + { + return value.IndexOfAny(QuotedCharacters) >= 0 + ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" + : value; + } + + /// + /// Free text is sanitized against formula injection; numbers and dates the formatter + /// produced are safe and stay numeric when a spreadsheet opens the file. + /// + private static string Cell(ReportRowResult row, ReportColumnMetadata column) + { + string formatted = ReportValueFormatter.Format(row.Values.GetValueOrDefault(column.Key), column); + return ReportValueFormatter.IsNumeric(column.Format) || column.Format == ReportColumnFormat.Date + ? Quote(formatted) + : Text(formatted); + } + + private static string Text(string value) + { + return Quote(ExcelHelper.SanitizeStringCell(value)); + } + + private static void AppendLine(StringBuilder csv, IEnumerable cells) + { + csv.Append(string.Join(",", cells)).Append("\r\n"); + } +} diff --git a/web/Areas/Reports/Exporters/ReportExcelExporter.cs b/web/Areas/Reports/Exporters/ReportExcelExporter.cs new file mode 100644 index 000000000..2118b6103 --- /dev/null +++ b/web/Areas/Reports/Exporters/ReportExcelExporter.cs @@ -0,0 +1,357 @@ +using ClosedXML.Excel; +using Viper.Areas.Reports.Engine; +using Viper.Classes.Utilities; + +namespace Viper.Areas.Reports.Exporters; + +/// +/// Exports a report to an Excel workbook. The first sheet holds the header, summary facts, +/// each group as an accessible Excel table with its subtotals, and the grand totals. Pivots +/// get a sheet each, and chart data goes on a Charts sheet. Values stay typed (numbers, dates) +/// so the workbook can be sorted and summed. +/// +public sealed class ReportExcelExporter : IReportExporter +{ + private const string DateNumberFormat = "mm/dd/yyyy"; + private const string GeneralNumberFormat = "#,##0.##"; + private const string GroupFill = "#E8E8E8"; + private const int TitleFontSize = 14; + + public string Format => "xlsx"; + + public string ContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public string Extension => ".xlsx"; + + public byte[] Export(ReportExport request) + { + ArgumentNullException.ThrowIfNull(request); + ReportResult result = request.Result; + using var workbook = new XLWorkbook(); + ExcelAccessibilityHelper.SetCoreProperties(workbook, result.Title); + var sheetNames = new HashSet(StringComparer.OrdinalIgnoreCase); + + var layout = new SheetLayout(result); + IXLWorksheet sheet = workbook.Worksheets.Add(UniqueSheetName(result.Title, sheetNames)); + int row = WriteHeader(sheet, request); + row = WriteTotals(sheet, row, result.Summary, layout); + int tableNumber = 0; + foreach (ReportGroupResult group in result.Groups) + { + row = WriteGroup(sheet, row, group, layout, ++tableNumber); + } + + WriteTotals(sheet, row, result.Totals, layout); + sheet.ColumnsUsed().AdjustToContents(); + + foreach (ReportPivotResult pivot in result.Pivots) + { + WritePivot(workbook.Worksheets.Add(UniqueSheetName(pivot.Title, sheetNames)), pivot); + } + + List<(string Title, ReportChartResult Chart)> charts = + [ + .. result.Charts.Select(chart => (chart.Title, chart)), + .. result.Groups.SelectMany(group => group.Charts.Select(chart => ($"{chart.Title}: {group.Label}", chart))), + ]; + if (charts.Count > 0) + { + WriteCharts(workbook.Worksheets.Add(UniqueSheetName("Charts", sheetNames)), charts); + } + + using var stream = new MemoryStream(); + workbook.SaveAs(stream); + return stream.ToArray(); + } + + /// + /// Sanitizes into a worksheet name that isn't already used, adding + /// " (2)", " (3)" and so on while keeping within Excel's 31-character limit. + /// + internal static string UniqueSheetName(string name, HashSet used) + { + const int maxLength = 31; + string baseName = ExcelHelper.SanitizeSheetName(name); + string candidate = baseName; + int copy = 1; + while (!used.Add(candidate)) + { + copy++; + string suffix = $" ({copy})"; + candidate = baseName[..Math.Min(baseName.Length, maxLength - suffix.Length)] + suffix; + } + + return candidate; + } + + internal static string NumberFormat(ReportColumnMetadata column) + { + int decimals = column.Decimals ?? 0; + string fraction = decimals > 0 ? "." + new string('0', decimals) : string.Empty; + return column.Format switch + { + ReportColumnFormat.Currency => "$#,##0" + fraction, + ReportColumnFormat.Percent => "0" + fraction + "%", + _ => "#,##0" + fraction, + }; + } + + private static int WriteHeader(IXLWorksheet sheet, ReportExport request) + { + int row = 1; + IXLCell title = sheet.Cell(row++, 1); + title.Value = ExcelHelper.SanitizeStringCell(request.Result.Title); + title.Style.Font.Bold = true; + title.Style.Font.FontSize = TitleFontSize; + sheet.Cell(row++, 1).Value = ReportExportText.Generated(request.Result.GeneratedAt); + + if (ReportExportText.Filters(request.Filters) is { } filters) + { + sheet.Cell(row++, 1).Value = ExcelHelper.SanitizeStringCell(filters); + } + + if (request.Confidential) + { + IXLCell notice = sheet.Cell(row++, 1); + notice.Value = ReportExportText.ConfidentialNotice; + notice.Style.Font.Italic = true; + } + + return row + 1; + } + + private static int WriteGroup(IXLWorksheet sheet, int row, ReportGroupResult group, SheetLayout layout, int tableNumber) + { + if (group.Label is { } label) + { + IXLRange heading = sheet.Range(row, 1, row, layout.LastColumn); + heading.FirstCell().Value = ExcelHelper.SanitizeStringCell(label); + heading.Style.Font.Bold = true; + heading.Style.Fill.BackgroundColor = XLColor.FromHtml(GroupFill); + row++; + } + + int headerRow = row; + foreach ((string text, int column) in layout.Headers) + { + sheet.Cell(headerRow, column).Value = ExcelHelper.SanitizeStringCell(text); + } + + sheet.Row(headerRow).CellsUsed().Style.Font.Bold = true; + row++; + + foreach (ReportRowResult reportRow in group.Rows) + { + WriteRow(sheet, row++, reportRow, layout); + } + + if (group.Rows.Count > 0) + { + ExcelAccessibilityHelper.PromoteToAccessibleTable( + sheet.Range(headerRow, 1, row - 1, layout.LastColumn), $"ReportTable{tableNumber}"); + } + + return WriteTotals(sheet, row, group.Subtotals, layout); + } + + private static void WriteRow(IXLWorksheet sheet, int row, ReportRowResult reportRow, SheetLayout layout) + { + if (layout.RowNumbers) + { + sheet.Cell(row, 1).Value = reportRow.Number; + } + + foreach ((ReportColumnMetadata column, int index) in layout.Columns) + { + WriteValue(sheet.Cell(row, index), reportRow.Values.GetValueOrDefault(column.Key), column); + } + + if (layout.NotesColumn is int notesColumn) + { + sheet.Cell(row, notesColumn).Value = ExcelHelper.SanitizeStringCell(ReportValueFormatter.FlagText(reportRow)); + } + + foreach (ReportFlag flag in reportRow.Flags.Where(flag => flag.Kind == ReportFlagKind.Highlight)) + { + if (ReportExportText.ToneFill(flag.Tone) is not { } fill) + { + continue; + } + + IXLRange target = flag.ColumnKey is { } key && layout.IndexOf(key) is int column + ? sheet.Range(row, column, row, column) + : sheet.Range(row, 1, row, layout.LastColumn); + target.Style.Fill.BackgroundColor = XLColor.FromHtml(fill); + } + } + + private static void WriteValue(IXLCell cell, object? value, ReportColumnMetadata column) + { + switch (value) + { + case null: + return; + case DateOnly date: + cell.Value = date.ToDateTime(TimeOnly.MinValue); + cell.Style.NumberFormat.Format = DateNumberFormat; + return; + case DateTime dateTime: + cell.Value = dateTime; + cell.Style.NumberFormat.Format = DateNumberFormat; + return; + } + + if (ReportValueFormatter.IsNumeric(column.Format) && ReportValueFormatter.TryGetDecimal(value, out decimal number)) + { + cell.Value = (double)number; + cell.Style.NumberFormat.Format = NumberFormat(column); + return; + } + + cell.Value = ExcelHelper.SanitizeStringCell(ReportValueFormatter.Format(value, column)); + } + + /// + /// Writes one row per total: the label in the first column and the value under the total's + /// column, or beside the label when it has none. + /// + private static int WriteTotals(IXLWorksheet sheet, int row, IReadOnlyList totals, SheetLayout layout) + { + foreach (ReportTotal total in totals) + { + IXLCell label = sheet.Cell(row, 1); + label.Value = ExcelHelper.SanitizeStringCell(total.Label); + label.Style.Font.Bold = true; + + (int column, string format) = total.ColumnKey is { } key && layout.Find(key) is { } target + ? (target.Index, NumberFormat(target.Column)) + : (2, GeneralNumberFormat); + if (total.Value is decimal value) + { + IXLCell cell = sheet.Cell(row, column); + cell.Value = (double)value; + cell.Style.NumberFormat.Format = format; + cell.Style.Font.Bold = true; + } + + row++; + } + + return totals.Count > 0 ? row + 1 : row; + } + + private static void WritePivot(IXLWorksheet sheet, ReportPivotResult pivot) + { + IXLCell title = sheet.Cell(1, 1); + title.Value = ExcelHelper.SanitizeStringCell(pivot.Title); + title.Style.Font.Bold = true; + + const int headerRow = 2; + int totalColumn = pivot.ColumnKeys.Count + 2; + for (int index = 0; index < pivot.ColumnKeys.Count; index++) + { + sheet.Cell(headerRow, index + 2).Value = ExcelHelper.SanitizeStringCell(pivot.ColumnKeys[index]); + } + + sheet.Cell(headerRow, totalColumn).Value = ReportExportText.TotalLabel; + sheet.Row(headerRow).CellsUsed().Style.Font.Bold = true; + + int row = headerRow + 1; + foreach (ReportPivotRow pivotRow in pivot.Rows) + { + sheet.Cell(row, 1).Value = ExcelHelper.SanitizeStringCell(pivotRow.Key); + WriteNumbers(sheet, row, [.. pivotRow.Values, pivotRow.Total]); + row++; + } + + sheet.Cell(row, 1).Value = ReportExportText.TotalLabel; + WriteNumbers(sheet, row, [.. pivot.ColumnTotals, pivot.GrandTotal]); + sheet.Row(row).CellsUsed().Style.Font.Bold = true; + sheet.ColumnsUsed().AdjustToContents(); + } + + private static void WriteCharts(IXLWorksheet sheet, List<(string Title, ReportChartResult Chart)> charts) + { + int row = 1; + foreach ((string title, ReportChartResult chart) in charts) + { + IXLCell heading = sheet.Cell(row++, 1); + heading.Value = ExcelHelper.SanitizeStringCell(title); + heading.Style.Font.Bold = true; + foreach (ReportChartPoint point in chart.Points) + { + sheet.Cell(row, 1).Value = ExcelHelper.SanitizeStringCell(point.Category); + WriteNumbers(sheet, row, [point.Value]); + row++; + } + + row++; + } + + sheet.ColumnsUsed().AdjustToContents(); + } + + /// + /// Writes numbers into consecutive cells starting at column 2; nulls leave the cell blank. + /// + private static void WriteNumbers(IXLWorksheet sheet, int row, IReadOnlyList values) + { + for (int index = 0; index < values.Count; index++) + { + if (values[index] is decimal value) + { + IXLCell cell = sheet.Cell(row, index + 2); + cell.Value = (double)value; + cell.Style.NumberFormat.Format = GeneralNumberFormat; + } + } + } + + /// + /// Where each part of a row goes: an optional row-number column, the report's columns, and + /// an optional Notes column for highlight and badge labels. + /// + private sealed class SheetLayout + { + private readonly Dictionary _byKey; + + public SheetLayout(ReportResult result) + { + RowNumbers = result.RowNumbers; + int offset = RowNumbers ? 1 : 0; + Columns = [.. result.Columns.Select((column, index) => (column, index + 1 + offset))]; + _byKey = Columns.ToDictionary(entry => entry.Column.Key, StringComparer.Ordinal); + NotesColumn = ReportExportText.HasNotes(result) ? Columns.Count + 1 + offset : null; + LastColumn = NotesColumn ?? Math.Max(Columns.Count + offset, 1); + + List<(string, int)> headers = RowNumbers ? [(ReportExportText.RowNumberHeader, 1)] : []; + headers.AddRange(Columns.Select(entry => (entry.Column.Label, entry.Index))); + if (NotesColumn is int notes) + { + headers.Add((ReportExportText.NotesHeader, notes)); + } + + Headers = headers; + } + + public bool RowNumbers { get; } + + public List<(ReportColumnMetadata Column, int Index)> Columns { get; } + + public int? NotesColumn { get; } + + public int LastColumn { get; } + + public List<(string Text, int Column)> Headers { get; } + + public (ReportColumnMetadata Column, int Index)? Find(string key) + { + return _byKey.TryGetValue(key, out (ReportColumnMetadata Column, int Index) entry) ? entry : null; + } + + public int? IndexOf(string key) + { + return Find(key)?.Index; + } + } +} diff --git a/web/Areas/Reports/Exporters/ReportExport.cs b/web/Areas/Reports/Exporters/ReportExport.cs new file mode 100644 index 000000000..3e655dcce --- /dev/null +++ b/web/Areas/Reports/Exporters/ReportExport.cs @@ -0,0 +1,135 @@ +using System.Globalization; +using Viper.Areas.Reports.Engine; + +namespace Viper.Areas.Reports.Exporters; + +/// +/// Everything an exporter needs: the result, the filters that produced it, and whether the +/// file must carry a confidentiality notice. +/// +public sealed record ReportExport(ReportResult Result, IReadOnlyList Filters, bool Confidential); + +/// +/// Turns a report result into a downloadable file. Exporters are pure and stateless, so one +/// instance serves every request. +/// +public interface IReportExporter +{ + /// + /// The format key used in export URLs, such as "csv". + /// + string Format { get; } + + string ContentType { get; } + + /// + /// The file extension, including the leading dot. + /// + string Extension { get; } + + byte[] Export(ReportExport request); +} + +/// +/// Wording shared by every export format, so CSV, Excel and PDF files read the same. +/// +public static class ReportExportText +{ + public const string ConfidentialNotice = + "Confidential: contains personnel information. Share only with staff authorized to see it."; + + public const string GroupHeader = "Group"; + + public const string NotesHeader = "Notes"; + + public const string RowNumberHeader = "#"; + + public const string TotalLabel = "Total"; + + private static readonly CultureInfo UsEnglish = CultureInfo.GetCultureInfo("en-US"); + + // Light fills that keep black text above WCAG AA contrast. Neutral highlights add no fill. + private static readonly Dictionary ToneFills = new() + { + [ReportTone.Info] = "#DEECF9", + [ReportTone.Positive] = "#DFF6DD", + [ReportTone.Warning] = "#FFF4CE", + [ReportTone.Negative] = "#FDE7E9", + [ReportTone.Muted] = "#EDEBE9", + }; + + public static string Generated(DateTimeOffset generatedAt) + { + return "Generated " + generatedAt.ToString("MM/dd/yyyy h:mm tt", UsEnglish); + } + + /// + /// "Filters: Faculty type: Senate; Start date: 07/01/2026", or null when nothing was filtered. + /// + public static string? Filters(IReadOnlyList filters) + { + ArgumentNullException.ThrowIfNull(filters); + return filters.Count == 0 + ? null + : "Filters: " + string.Join("; ", filters.Select(filter => $"{filter.Label}: {filter.Value}")); + } + + /// + /// A total's value as text: formatted like its column when it has one, otherwise as a plain + /// number with up to two decimals. A missing value is blank. + /// + public static string FormatTotal(ReportTotal total, IReadOnlyList columns) + { + ArgumentNullException.ThrowIfNull(total); + ArgumentNullException.ThrowIfNull(columns); + if (total.Value is not decimal value) + { + return string.Empty; + } + + ReportColumnMetadata? column = columns.FirstOrDefault(candidate => candidate.Key == total.ColumnKey); + return column is not null ? ReportValueFormatter.Format(value, column) : FormatNumber(value); + } + + /// + /// A pivot, chart or total number without a column format: thousands separators and up to two decimals. + /// + public static string FormatNumber(decimal? value) + { + return value?.ToString("#,##0.##", UsEnglish) ?? string.Empty; + } + + /// + /// The background color for a highlight tone, or null for tones that add no fill. + /// + public static string? ToneFill(ReportTone tone) + { + return ToneFills.GetValueOrDefault(tone); + } + + /// + /// The fill for one cell of a row. Highlights apply in the order the report declared them, + /// so the last one covering the cell wins. A highlight covers the cell when it targets the + /// whole row, targets this column, or targets a column the export doesn't show. + /// is null for cells that belong to no column, such as row numbers. + /// + public static string? CellFill(IReadOnlyList flags, string? columnKey, IReadOnlySet columnKeys) + { + ArgumentNullException.ThrowIfNull(flags); + ArgumentNullException.ThrowIfNull(columnKeys); + return flags + .Where(flag => flag.Kind == ReportFlagKind.Highlight + && (flag.ColumnKey is null || flag.ColumnKey == columnKey || !columnKeys.Contains(flag.ColumnKey))) + .Select(flag => ToneFill(flag.Tone)) + .LastOrDefault(fill => fill is not null); + } + + /// + /// True when any row has a highlight or badge, which adds a Notes column to exports. + /// + public static bool HasNotes(ReportResult result) + { + ArgumentNullException.ThrowIfNull(result); + return result.Groups.Any(group => group.Rows.Any(row => row.Flags.Count > 0)); + } +} diff --git a/web/Areas/Reports/Exporters/ReportPdfExporter.cs b/web/Areas/Reports/Exporters/ReportPdfExporter.cs new file mode 100644 index 000000000..a44f4159b --- /dev/null +++ b/web/Areas/Reports/Exporters/ReportPdfExporter.cs @@ -0,0 +1,333 @@ +using System.Globalization; +using QuestPDF.Fluent; +using QuestPDF.Helpers; +using QuestPDF.Infrastructure; +using Viper.Areas.Reports.Engine; +using Viper.Classes.Utilities; + +namespace Viper.Areas.Reports.Exporters; + +/// +/// Exports a report to a landscape Letter PDF tagged for PDF/UA: a header with the title, +/// generated time, filters and confidentiality notice; summary facts; each group as a table +/// with its subtotals; grand totals; then pivots and chart data as tables. Highlights become +/// light cell fills and every flag label is listed in a Notes column. +/// +public sealed class ReportPdfExporter : IReportExporter +{ + private const float FontSize = 9f; + private const float TitleFontSize = 13f; + private const float FooterFontSize = 7f; + private const float SectionSpacing = 10f; + private const float CellPaddingVertical = 2f; + private const float CellPaddingHorizontal = 3f; + private const float RowNumberWidth = 28f; + private const float NotesWidth = 2f; + private const float PivotKeyWidth = 2f; + private const float RuleWidth = 0.5f; + private const string HeaderFill = "#E8E8E8"; + private const string RuleColor = "#CCCCCC"; + + public string Format => "pdf"; + + public string ContentType => "application/pdf"; + + public string Extension => ".pdf"; + + public byte[] Export(ReportExport request) + { + ArgumentNullException.ThrowIfNull(request); + ReportResult result = request.Result; + var layout = new TableLayout(result); + + return Document.Create(container => container.Page(page => + { + page.Size(PageSizes.Letter.Landscape()); + page.MarginHorizontal(0.5f, Unit.Inch); + page.MarginVertical(0.4f, Unit.Inch); + page.DefaultTextStyle(style => style.FontSize(FontSize)); + page.Header().Element(header => ComposeHeader(header, request)); + page.Content().PaddingTop(SectionSpacing).Element(content => ComposeContent(content, result, layout)); + page.Footer().Element(footer => ComposeFooter(footer, request.Confidential)); + })) + .WithAccessibility(result.Title) + .GeneratePdf(); + } + + private static void ComposeHeader(IContainer container, ReportExport request) + { + container.Column(column => + { + column.Item().SemanticHeader1().Text(request.Result.Title).SemiBold().FontSize(TitleFontSize); + column.Item().Text(ReportExportText.Generated(request.Result.GeneratedAt)); + if (ReportExportText.Filters(request.Filters) is { } filters) + { + column.Item().Text(filters); + } + + if (request.Confidential) + { + column.Item().Text(ReportExportText.ConfidentialNotice).Italic(); + } + }); + } + + private static void ComposeContent(IContainer container, ReportResult result, TableLayout layout) + { + List<(string Title, ReportChartResult Chart)> charts = + [ + .. result.Charts.Select(chart => (chart.Title, chart)), + .. result.Groups.SelectMany(group => group.Charts.Select(chart => ($"{chart.Title}: {group.Label}", chart))), + ]; + + container.Column(column => + { + column.Spacing(SectionSpacing); + ComposeTotals(column, result.Summary, result.Columns); + foreach (ReportGroupResult group in result.Groups) + { + column.Item().Element(item => ComposeGroup(item, group, layout, result.Columns)); + } + + ComposeTotals(column, result.Totals, result.Columns); + foreach (ReportPivotResult pivot in result.Pivots) + { + column.Item().Element(item => ComposePivot(item, pivot)); + } + + foreach ((string title, ReportChartResult chart) in charts) + { + column.Item().Element(item => ComposeChart(item, title, chart)); + } + }); + } + + private static void ComposeGroup( + IContainer container, ReportGroupResult group, TableLayout layout, IReadOnlyList columns) + { + container.Column(column => + { + if (group.Label is { } label) + { + column.Item().SemanticHeader2().Text(label).SemiBold(); + } + + column.Item().SemanticTable().Table(table => + { + table.ColumnsDefinition(definition => + { + if (layout.RowNumbers) + { + definition.ConstantColumn(RowNumberWidth); + } + + for (int index = 0; index < columns.Count; index++) + { + definition.RelativeColumn(); + } + + if (layout.Notes) + { + definition.RelativeColumn(NotesWidth); + } + }); + + table.Header(header => + { + foreach ((string text, ReportAlignment align) in layout.Headers) + { + HeaderCell(header.Cell(), text, align); + } + }); + + foreach (ReportRowResult row in group.Rows) + { + string? rowFill = ReportExportText.CellFill(row.Flags, null, layout.ColumnKeys); + if (layout.RowNumbers) + { + BodyCell(table.Cell(), row.Number.ToString(CultureInfo.InvariantCulture), ReportAlignment.Right, rowFill); + } + + foreach (ReportColumnMetadata reportColumn in columns) + { + BodyCell( + table.Cell(), + ReportValueFormatter.Format(row.Values.GetValueOrDefault(reportColumn.Key), reportColumn), + reportColumn.Align, + ReportExportText.CellFill(row.Flags, reportColumn.Key, layout.ColumnKeys)); + } + + if (layout.Notes) + { + BodyCell(table.Cell(), ReportValueFormatter.FlagText(row), ReportAlignment.Left, rowFill); + } + } + }); + + ComposeTotals(column, group.Subtotals, columns); + }); + } + + private static void ComposeTotals( + ColumnDescriptor column, IReadOnlyList totals, IReadOnlyList columns) + { + foreach (ReportTotal total in totals) + { + column.Item().Text(text => + { + text.Span(total.Label + ": ").SemiBold(); + text.Span(ReportExportText.FormatTotal(total, columns)); + }); + } + } + + private static void ComposePivot(IContainer container, ReportPivotResult pivot) + { + container.Column(column => + { + column.Item().SemanticHeader2().Text(pivot.Title).SemiBold(); + column.Item().SemanticTable().Table(table => + { + table.ColumnsDefinition(definition => + { + definition.RelativeColumn(PivotKeyWidth); + for (int index = 0; index <= pivot.ColumnKeys.Count; index++) + { + definition.RelativeColumn(); + } + }); + + table.Header(header => + { + HeaderCell(header.Cell(), string.Empty, ReportAlignment.Left); + foreach (string key in pivot.ColumnKeys) + { + HeaderCell(header.Cell(), key, ReportAlignment.Right); + } + + HeaderCell(header.Cell(), ReportExportText.TotalLabel, ReportAlignment.Right); + }); + + foreach (ReportPivotRow row in pivot.Rows) + { + NumberRow(table, row.Key, [.. row.Values, row.Total]); + } + + NumberRow(table, ReportExportText.TotalLabel, [.. pivot.ColumnTotals, pivot.GrandTotal]); + }); + }); + } + + private static void ComposeChart(IContainer container, string title, ReportChartResult chart) + { + container.Column(column => + { + column.Item().SemanticHeader2().Text(title).SemiBold(); + column.Item().SemanticTable().Table(table => + { + table.ColumnsDefinition(definition => + { + definition.RelativeColumn(PivotKeyWidth); + definition.RelativeColumn(); + }); + + table.Header(header => + { + HeaderCell(header.Cell(), "Category", ReportAlignment.Left); + HeaderCell(header.Cell(), "Value", ReportAlignment.Right); + }); + + foreach (ReportChartPoint point in chart.Points) + { + NumberRow(table, point.Category, [point.Value]); + } + }); + }); + } + + private static void ComposeFooter(IContainer container, bool confidential) + { + container.Column(column => + { + if (confidential) + { + column.Item().AlignCenter().Text(ReportExportText.ConfidentialNotice).FontSize(FooterFontSize).Italic(); + } + + // The page counter repeats on every page, so assistive technology skips it. + column.Item().SemanticIgnore().AlignCenter().Text(text => + { + text.Span("Page "); + text.CurrentPageNumber(); + text.Span(" of "); + text.TotalPages(); + }); + }); + } + + private static void NumberRow(TableDescriptor table, string label, IReadOnlyList values) + { + BodyCell(table.Cell(), label, ReportAlignment.Left, null); + foreach (decimal? value in values) + { + BodyCell(table.Cell(), ReportExportText.FormatNumber(value), ReportAlignment.Right, null); + } + } + + private static void HeaderCell(IContainer cell, string text, ReportAlignment align) + { + Align(cell.Background(HeaderFill).PaddingVertical(CellPaddingVertical).PaddingHorizontal(CellPaddingHorizontal), align) + .Text(text) + .SemiBold(); + } + + private static void BodyCell(IContainer cell, string text, ReportAlignment align, string? fill) + { + IContainer styled = fill is null ? cell : cell.Background(fill); + Align( + styled.BorderBottom(RuleWidth).BorderColor(RuleColor) + .PaddingVertical(CellPaddingVertical).PaddingHorizontal(CellPaddingHorizontal), + align) + .Text(text); + } + + private static IContainer Align(IContainer container, ReportAlignment align) + { + return align switch + { + ReportAlignment.Right => container.AlignRight(), + ReportAlignment.Center => container.AlignCenter(), + _ => container.AlignLeft(), + }; + } + + /// + /// Which extra columns a group table has, and the header text and alignment for each column. + /// + private sealed class TableLayout + { + public TableLayout(ReportResult result) + { + RowNumbers = result.RowNumbers; + Notes = ReportExportText.HasNotes(result); + ColumnKeys = new HashSet(result.Columns.Select(column => column.Key), StringComparer.Ordinal); + + List<(string, ReportAlignment)> headers = RowNumbers ? [(ReportExportText.RowNumberHeader, ReportAlignment.Right)] : []; + headers.AddRange(result.Columns.Select(column => (column.Label, column.Align))); + if (Notes) + { + headers.Add((ReportExportText.NotesHeader, ReportAlignment.Left)); + } + + Headers = headers; + } + + public bool RowNumbers { get; } + + public bool Notes { get; } + + public IReadOnlySet ColumnKeys { get; } + + public List<(string Text, ReportAlignment Align)> Headers { get; } + } +} diff --git a/web/Areas/Reports/ReportsServiceCollectionExtensions.cs b/web/Areas/Reports/ReportsServiceCollectionExtensions.cs new file mode 100644 index 000000000..ae2eed100 --- /dev/null +++ b/web/Areas/Reports/ReportsServiceCollectionExtensions.cs @@ -0,0 +1,41 @@ +using System.Reflection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Viper.Areas.Reports.Data; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Exporters; + +namespace Viper.Areas.Reports; + +public static class ReportsServiceCollectionExtensions +{ + /// + /// Registers every and in + /// , the registry that indexes them, and the export formats. + /// Definitions are scoped because they depend on scoped data services; planned report lists + /// are fixed data, so they are singletons. Also registers the stored procedure runner that + /// report data services use for databases without an EF context. + /// itself is registered by the Scrutor service scan. + /// + public static IServiceCollection AddReports(this IServiceCollection services, Assembly reportAssembly) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(reportAssembly); + + services.TryAddSingleton(TimeProvider.System); + services.Scan(scan => scan + .FromAssemblies(reportAssembly) + .AddClasses(classes => classes.AssignableTo(), publicOnly: false) + .As() + .WithScopedLifetime() + .AddClasses(classes => classes.AssignableTo(), publicOnly: false) + .As() + .WithSingletonLifetime()); + services.TryAddScoped(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + return services; + } +} diff --git a/web/Areas/Reports/Services/ReportOutcome.cs b/web/Areas/Reports/Services/ReportOutcome.cs new file mode 100644 index 000000000..568d70743 --- /dev/null +++ b/web/Areas/Reports/Services/ReportOutcome.cs @@ -0,0 +1,49 @@ +using Viper.Areas.Reports.Engine; + +namespace Viper.Areas.Reports.Services; + +public enum ReportOutcomeStatus +{ + Ok, + NotFound, + Forbidden, + Invalid, +} + +/// +/// The result of a report request: a value, or the reason there isn't one. Keeps HTTP concerns +/// in the controller while the service stays testable without a request pipeline. +/// +public sealed record ReportOutcome(ReportOutcomeStatus Status, T? Value, IReadOnlyList Errors); + +public static class ReportOutcome +{ + public static ReportOutcome Ok(T value) + { + return new ReportOutcome(ReportOutcomeStatus.Ok, value, []); + } + + public static ReportOutcome NotFound() + { + return new ReportOutcome(ReportOutcomeStatus.NotFound, default, []); + } + + public static ReportOutcome Forbidden() + { + return new ReportOutcome(ReportOutcomeStatus.Forbidden, default, []); + } + + /// + /// Carries a failure status and its errors over to an outcome of another value type. + /// + internal static ReportOutcome Failed(ReportOutcomeStatus status, IReadOnlyList errors) + { + return new ReportOutcome(status, default, errors); + } + + public static ReportOutcome Invalid(IReadOnlyList errors) + { + ArgumentNullException.ThrowIfNull(errors); + return new ReportOutcome(ReportOutcomeStatus.Invalid, default, errors); + } +} diff --git a/web/Areas/Reports/Services/ReportService.cs b/web/Areas/Reports/Services/ReportService.cs new file mode 100644 index 000000000..916f9df0d --- /dev/null +++ b/web/Areas/Reports/Services/ReportService.cs @@ -0,0 +1,199 @@ +using System.Text.Json; +using Viper.Areas.Reports.Engine; +using Viper.Areas.Reports.Exporters; +using Viper.Classes.Utilities; + +namespace Viper.Areas.Reports.Services; + +/// +/// A report the current user may run, as listed in a catalog. Available is +/// false for a planned report that is listed but not built yet. +/// +public sealed record ReportCatalogItem(string Key, string Title, string Area, string Description, bool Available); + +/// +/// An exported report, ready to send as a download. +/// +public sealed record ReportFile(byte[] Content, string ContentType, string FileName); + +public interface IReportService +{ + /// + /// Reports the current user may run, built and planned, optionally limited to one area and + /// ordered by area and then title. + /// + IReadOnlyList GetCatalog(string? area); + + ReportOutcome GetDefinition(string? key); + + Task> RunAsync(string? key, JsonElement? parameters, CancellationToken ct); + + Task> ExportAsync(string? key, string? format, JsonElement? parameters, CancellationToken ct); +} + +/// +/// Runs reports for the signed-in user: checks access before reading any parameters, binds and +/// validates them, runs the report, and writes an audit log entry for every run and export. +/// +public class ReportService : IReportService +{ + public const string FormatParameter = "format"; + + private readonly IReportRegistry _registry; + private readonly IReportUserService _userService; + private readonly IReadOnlyList _exporters; + private readonly TimeProvider _timeProvider; + private readonly ILogger _logger; + + public ReportService( + IReportRegistry registry, + IReportUserService userService, + IEnumerable exporters, + TimeProvider timeProvider, + ILogger logger) + { + _registry = registry; + _userService = userService; + _exporters = [.. exporters]; + _timeProvider = timeProvider; + _logger = logger; + } + + public IReadOnlyList GetCatalog(string? area) + { + ReportContext context = _userService.GetCurrentContext(); + string? areaFilter = string.IsNullOrWhiteSpace(area) ? null : area.Trim(); + bool InArea(IReportIdentity report) => + areaFilter is null || string.Equals(report.Area, areaFilter, StringComparison.OrdinalIgnoreCase); + + IEnumerable built = _registry.All + .Where(InArea) + .Where(definition => definition.CanRun(context)) + .Select(definition => ToCatalogItem(definition, available: true)); + IEnumerable planned = _registry.Planned + .Where(InArea) + .Where(report => context.HasAnyPermission(report.Permissions)) + .Select(report => ToCatalogItem(report, available: false)); + + return [.. built.Concat(planned) + .OrderBy(item => item.Area, StringComparer.OrdinalIgnoreCase) + .ThenBy(item => item.Title, StringComparer.OrdinalIgnoreCase)]; + } + + public ReportOutcome GetDefinition(string? key) + { + ReportContext context = _userService.GetCurrentContext(); + ReportOutcomeStatus access = CheckAccess(key, context, out IReportDefinition? definition); + return definition is not null + ? ReportOutcome.Ok(definition.GetMetadata(context)) + : ReportOutcome.Failed(access, []); + } + + public async Task> RunAsync(string? key, JsonElement? parameters, CancellationToken ct) + { + ReportContext context = _userService.GetCurrentContext(); + ReportOutcomeStatus access = CheckAccess(key, context, out IReportDefinition? definition); + if (definition is null) + { + return ReportOutcome.Failed(access, []); + } + + ReportOutcome run = await ExecuteAsync(definition, context, parameters, "run", ct); + return run.Value is { } completed + ? ReportOutcome.Ok(completed.Result) + : ReportOutcome.Failed(run.Status, run.Errors); + } + + public async Task> ExportAsync( + string? key, string? format, JsonElement? parameters, CancellationToken ct) + { + ReportContext context = _userService.GetCurrentContext(); + ReportOutcomeStatus access = CheckAccess(key, context, out IReportDefinition? definition); + if (definition is null) + { + return ReportOutcome.Failed(access, []); + } + + IReportExporter? exporter = _exporters.FirstOrDefault( + candidate => string.Equals(candidate.Format, format, StringComparison.OrdinalIgnoreCase)); + if (exporter is null) + { + string supported = string.Join(", ", _exporters.Select(candidate => candidate.Format)); + return ReportOutcome.Invalid( + [new ReportValidationError(FormatParameter, $"Choose an export format: {supported}.")]); + } + + ReportOutcome run = await ExecuteAsync(definition, context, parameters, "export:" + exporter.Format, ct); + if (run.Value is not { } completed) + { + return ReportOutcome.Failed(run.Status, run.Errors); + } + + var export = new ReportExport( + completed.Result, definition.DescribeParameters(completed.Parameters), definition.IsSensitive); + string fileName = ExcelHelper.BuildExportFilename( + new ExportFilenameOptions { ReportName = definition.Title, Extension = exporter.Extension }); + return ReportOutcome.Ok(new ReportFile(exporter.Export(export), exporter.ContentType, fileName)); + } + + /// + /// Finds the report and checks the user may run it. Returns + /// with the definition, or the failure status with a null definition. + /// + private ReportOutcomeStatus CheckAccess(string? key, ReportContext context, out IReportDefinition? definition) + { + definition = null; + IReportDefinition? found = _registry.Find(key); + if (found is null) + { + return ReportOutcomeStatus.NotFound; + } + + if (!found.CanRun(context)) + { + return ReportOutcomeStatus.Forbidden; + } + + definition = found; + return ReportOutcomeStatus.Ok; + } + + private static ReportCatalogItem ToCatalogItem(IReportIdentity report, bool available) + { + return new ReportCatalogItem(report.Key, report.Title, report.Area, report.Description, available); + } + + private async Task> ExecuteAsync( + IReportDefinition definition, ReportContext context, JsonElement? parameters, string action, CancellationToken ct) + { + if (!ReportParameterBinder.TryBind(definition.ParametersType, parameters, out object? bound, out ReportValidationError? bindError)) + { + return ReportOutcome.Invalid([bindError]); + } + + IReadOnlyList errors = definition.PrepareParameters(bound); + if (errors.Count > 0) + { + return ReportOutcome.Invalid(errors); + } + + ReportResult result = await definition.RunAsync(bound, context, _timeProvider.GetLocalNow(), ct); + + // Reports expose salary, demographic and visa data, so every run and export is audited. + // The guard skips serializing the parameters when information logging is off. + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation( + "Report {ReportKey} {Action} by {LoginId} returned {RowCount} rows for parameters {Parameters}", + definition.Key, + action, + LogSanitizer.SanitizeId(context.LoginId), + result.RowCount, + LogSanitizer.SanitizeString(JsonSerializer.Serialize(bound, definition.ParametersType, ReportParameterBinder.JsonOptions))); + } + + return ReportOutcome.Ok(new ReportRun(bound, result)); + } + + private sealed record ReportRun(object Parameters, ReportResult Result); +} diff --git a/web/Areas/Reports/Services/ReportUserService.cs b/web/Areas/Reports/Services/ReportUserService.cs new file mode 100644 index 000000000..c6f87c19b --- /dev/null +++ b/web/Areas/Reports/Services/ReportUserService.cs @@ -0,0 +1,37 @@ +using Viper.Areas.Reports.Engine; +using Viper.Classes.SQLContext; +using Viper.Models.AAUD; + +namespace Viper.Areas.Reports.Services; + +public interface IReportUserService +{ + /// + /// The signed-in user as a report context. A request with no resolvable user gets a context + /// with no permissions, so every report check fails closed. + /// + ReportContext GetCurrentContext(); +} + +public class ReportUserService : IReportUserService +{ + private readonly RAPSContext _rapsContext; + private readonly IUserHelper _userHelper; + + public ReportUserService(RAPSContext rapsContext, IUserHelper userHelper) + { + _rapsContext = rapsContext; + _userHelper = userHelper; + } + + public ReportContext GetCurrentContext() + { + AaudUser? user = _userHelper.GetCurrentUser(); + if (user is null) + { + return new ReportContext(null, _ => false); + } + + return new ReportContext(user.LoginId, permission => _userHelper.HasPermission(_rapsContext, user, permission)); + } +} diff --git a/web/Program.cs b/web/Program.cs index c4ff81f24..1e59ebb94 100644 --- a/web/Program.cs +++ b/web/Program.cs @@ -33,6 +33,7 @@ using Viper.Areas.Effort.Services.Harvest; using Viper.Areas.Personnel; using Viper.Areas.RAPS.Services; +using Viper.Areas.Reports; using Viper.Classes; using Viper.Classes.HealthChecks; using Viper.Classes.Scheduler; @@ -247,6 +248,9 @@ void RegisterDbContext(string connectionStringKey, Action(); + // Code-defined reports (IReportDefinition) and the registry that indexes them + builder.Services.AddReports(typeof(Program).Assembly); + // Shared HTML sanitizer for user-authored content (CMS, CTS, ...). Thread-safe singleton. builder.Services.AddSingleton(); @@ -269,6 +273,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 f415c13d6..f3134e92d 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 2c34a1523..ca450a4c3 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 6f1d41ea8..f3bbf2cc1 100644 --- a/web/appsettings.Test.json +++ b/web/appsettings.Test.json @@ -23,6 +23,7 @@ "Effort": "", "EvalHarvest": "", "PhoneLists": "", + "PPS": "", "RAPS": "", "SIS": "", "VIPER": "" From 2128931fa1fbcb5a50bd0c456eaec18b08aa32ba Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:29:23 -0800 Subject: [PATCH 02/12] Setting up report builder --- CLAUDE.md | 59 ++-- .../ReportBuilderDbContextTests.cs | 65 +++++ .../ReportSourceCatalogServiceTests.cs | 159 +++++++++++ test/ReportBuilder/ReportSqlTypesTests.cs | 39 +++ .../Models/Entities/ReportColumn.cs | 15 ++ .../Models/Entities/ReportDefinition.cs | 48 ++++ .../Entities/ReportDefinitionHistory.cs | 15 ++ .../Models/Entities/ReportParameter.cs | 32 +++ .../Models/Entities/ReportPermission.cs | 9 + .../Models/Entities/ReportRunLog.cs | 17 ++ .../Models/ReportBuilderEnums.cs | 87 ++++++ .../ReportBuilder/Models/ReportSourceDtos.cs | 58 ++++ .../ReportBuilder/ReportBuilderDbContext.cs | 104 +++++++ .../ReportBuilder/ReportBuilderPermissions.cs | 11 + .../Scripts/CreateReportBuilderSchema.cs | 255 ++++++++++++++++++ web/Areas/ReportBuilder/Scripts/Program.cs | 49 ++++ .../Scripts/ReportBuilderScripts.csproj | 27 ++ .../ReportBuilder/Scripts/RunCreateSchema.bat | 43 +++ .../Services/ReportSourceCatalogService.cs | 146 ++++++++++ .../Services/ReportSourceMetadataReader.cs | 111 ++++++++ .../ReportBuilder/Services/ReportSqlTypes.cs | 64 +++++ web/Program.cs | 8 + web/Viper.csproj | 4 + 23 files changed, 1398 insertions(+), 27 deletions(-) create mode 100644 test/ReportBuilder/ReportBuilderDbContextTests.cs create mode 100644 test/ReportBuilder/ReportSourceCatalogServiceTests.cs create mode 100644 test/ReportBuilder/ReportSqlTypesTests.cs create mode 100644 web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs create mode 100644 web/Areas/ReportBuilder/Models/Entities/ReportDefinition.cs create mode 100644 web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs create mode 100644 web/Areas/ReportBuilder/Models/Entities/ReportParameter.cs create mode 100644 web/Areas/ReportBuilder/Models/Entities/ReportPermission.cs create mode 100644 web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs create mode 100644 web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs create mode 100644 web/Areas/ReportBuilder/Models/ReportSourceDtos.cs create mode 100644 web/Areas/ReportBuilder/ReportBuilderDbContext.cs create mode 100644 web/Areas/ReportBuilder/ReportBuilderPermissions.cs create mode 100644 web/Areas/ReportBuilder/Scripts/CreateReportBuilderSchema.cs create mode 100644 web/Areas/ReportBuilder/Scripts/Program.cs create mode 100644 web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj create mode 100644 web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat create mode 100644 web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportSqlTypes.cs diff --git a/CLAUDE.md b/CLAUDE.md index c93ba1585..0bbe1aacf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,56 +1,61 @@ # CLAUDE.md -When I ask a question or make an observation, respond with an answer - do NOT jump to making code changes unless I explicitly ask for them. +When I ask a question ("why does X...", "is Y right?") or make an observation ("X looks off"), answer it and stop. Edit code only when I ask for a change ("fix", "change", "add", "do it"). ## Environment & Commands -- Run via npm scripts, never direct .NET/dotnet commands (avoids lock-file conflicts): Dev `npm run dev` | Test `npm run test` (`test:backend`, `test:frontend`; single test: `npm run test:backend -- ` / `npm run test:frontend -- `) | Lint `npm run lint ` | Build `npm run verify:build` +- Run via npm scripts, never direct `dotnet` commands (avoids lock-file conflicts): Dev `npm run dev` | Test `npm run test` (`test:backend -- `, `test:frontend -- `) | Lint `npm run lint ` | Build `npm run verify:build` - **Stale cache**: Add `-- --clear-cache` to `verify:build` or `lint` if builds fail with cached errors ## Architecture -- **DB**: SQL Server 2016 + EF Core (CTS, RAPS, AAUD schemas) | **Auth**: CAS + `[Permission]` (see API & Cross-Environment) +- **DB**: SQL Server 2016 + EF Core (CTS, RAPS, AAUD schemas) | **Auth**: CAS + `[Permission]` - **Identity:** `AaudUser.AaudUserId` = `Person.PersonId`. If mismatched, TEST DB needs refresh. -- **Design system (UI)**: All UI rules (colors, typography, components, `
` landmark, WCAG-AA contrast) live in [DESIGN.md](DESIGN.md). Read it before building or changing UI. Always use Quasar components. -- **VueUse**: Prefer VueUse composables over hand-rolled reactive logic. -- **O(n²) lookups**: Pre-build a `Map`/`Set`/`Dictionary` rather than nesting `.find()`/`.FirstOrDefault()` in a loop over a growable list. In EF this is N+1, see Correlated subqueries. -- **Plurals**: Use `inflect("word", count)` from the `inflection` package, never hand-roll ternaries for noun pluralization +- **UI**: Read [DESIGN.md](DESIGN.md) before building or changing UI. Always use Quasar components; prefer VueUse composables over hand-rolled reactive logic. +- **O(n²) lookups**: Pre-build a `Map`/`Set`/`Dictionary` instead of nesting `.find()`/`.FirstOrDefault()` in a loop over a growable list. +- **Plurals**: `inflect("word", count)` from `inflection`, never hand-rolled ternaries ## Database & EF Core - **SQL Server 2016**: no `STRING_AGG`, `TRIM`, `CONCAT_WS`, `GREATEST/LEAST` - Prefer EF entities over raw SQL. Raw SQL only for non-EF tables via `GetConnectionString()`. Never mix raw SQL + EF entities (causes auth failures). -- **Read-only queries**: Always `.AsNoTracking()` | `.Include()` before `.Select()` is unnecessary, EF resolves navigations in projections -- **Correlated subqueries**: Avoid `.Any()` on large tables inside `.Where()`/`.CountAsync()`: pre-load ID sets then use `.Contains()`, or replace with `.Join()` -- **`.Contains()` with large collections (10+)**: Wrap with `EF.Parameter()` for `OPENJSON` translation: `.Where(x => EF.Parameter(largeList).Contains(x.Id))`. Small collections (<10) are fine without it. +- **Read-only queries**: Always `.AsNoTracking()` | No `.Include()` before `.Select()`, projections resolve navigations +- **Correlated subqueries**: Avoid `.Any()` on large tables inside `.Where()`/`.CountAsync()`: pre-load ID sets then `.Contains()`, or `.Join()` +- **`.Contains()` with 10+ items**: `.Where(x => EF.Parameter(list).Contains(x.Id))` for `OPENJSON` translation - **Thread safety**: DbContext not thread-safe, no parallel EF queries ## API & Cross-Environment - **Routes**: Absolute `/api/{area}/{controller}` + `ApiController` base - **Frontend API calls**: Service layer + `useFetch()`, never raw `fetch()` (must unwrap `{ result, success }`) -- **API URL**: `${import.meta.env.VITE_API_URL}`, never hardcode `/api/` (TEST uses `/2/` prefix) -- **Subpath PathBase (`/2`)**: TEST/PROD run VIPER 2 under a `/2` PathBase (IIS sub-app), legacy VIPER 1 at `/`; with no base locally, these bugs surface only on TEST/PROD (not in unit tests). Use `~/` for app-root redirects, never bare `/` (escapes to the legacy site). Guards matching root-relative paths (`/api`, `/welcome`) must strip the base off the base-prefixed `ReturnUrl` (`/2/...`) or use `Request.PathBase`. `RedirectToAction`, `@Url.Content("~/")`, and tag-helpers include the base; raw string paths (`Redirect("/x")`, `returnUrl.StartsWith("/api")`) don't. -- **Auth**: `[Permission(Allow = "SVMSecure.{Area}")]`, or finer `"SVMSecure.{Area}.{Permission}"`. Authenticate before validating params +- **API URL**: `${import.meta.env.VITE_API_URL}`, never hardcode `/api/` +- **Subpath PathBase (`/2`)**: TEST/PROD run VIPER 2 under a `/2` PathBase, legacy VIPER 1 at `/`; locally there is no base, so these bugs only surface on TEST/PROD. Use `~/` for app-root redirects, never bare `/`. Guards matching root-relative paths (`/api`, `/welcome`) must strip the base off `ReturnUrl` (`/2/...`) or use `Request.PathBase`. `RedirectToAction`, `@Url.Content("~/")`, and tag-helpers include the base; raw strings (`Redirect("/x")`, `returnUrl.StartsWith("/api")`) don't. +- **Auth**: `[Permission(Allow = "SVMSecure.{Area}")]` or `"SVMSecure.{Area}.{Permission}"`. Authenticate before validating params ## C# Standards -- **Exceptions**: Catch specific types (`DbUpdateException`, `SqlException`, `InvalidOperationException`). Never generic `catch (Exception ex)`. +- **Exceptions**: Catch specific types (`DbUpdateException`, `SqlException`, `InvalidOperationException`), never `catch (Exception ex)` - **Paths**: `Path.Join()` not `Path.Combine()` (`Combine` silently discards everything before a rooted segment) | **DateTime**: prefer `DateTimeKind.Local` -- **Mapperly**: Prefer over manual property mapping. Static partial mapper class per area with `[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.None)]`. Use `[MapperIgnoreTarget]` for computed properties, manual wrappers for transforms. Align entity/DTO names: use EF `HasColumnName()` to decouple from DB columns. -- **Scrutor**: Convention-based DI auto-registers `*Service`/`*Validator` from configured namespaces, prefer over manual `AddScoped`. Follow `IFooService`/`FooService` naming. Explicit `AddScoped` before Scrutor takes precedence (`RegistrationStrategy.Skip`). -- **`required` on bound models**: never on a server-generated primary key. A create body has no id yet, so System.Text.Json 400s it before the action runs. Use `int?` (a client sending `0` only masks it). +- **Mapperly** over manual property mapping, one static partial mapper per area (follow existing ones). Align entity/DTO names via EF `HasColumnName()`. +- **DI**: Scrutor auto-registers `*Service`/`*Validator` (`IFooService`/`FooService`); add explicit `AddScoped` only to override. +- **`required` on bound models**: never on a server-generated primary key (a create body has no id, so System.Text.Json 400s it). Use `int?`. - **Bug fixes**: Check for duplicate/parallel implementations of the affected logic and fix consistently, or DRY into a shared method. -- **Log injection**: Sanitize user input before logging via `LogSanitizer` (`SanitizeId()`, `SanitizeString()`, `SanitizeYear()`). Skip hard-coded strings, enums, DB values. +- **Log injection**: Sanitize user input via `LogSanitizer` before logging. Skip hard-coded strings, enums, DB values. ## Testing & Git -- **UI**: Test UI changes with Playwright MCP (modals, forms, keyboard nav) -- **API**: Use Playwright MCP to visit endpoints, APIs require browser auth, `curl` fails -- **Frontend mocks**: Vitest clears mock call history before every test (`clearMocks` default), so `vi.clearAllMocks()` in a `beforeEach` is redundant. Clear a mock explicitly only mid-test, when an assertion must ignore calls made earlier in the same test. -- **Frontend test realm**: tests run on the `vmThreads` pool (one happy-dom per worker, ~4x faster than one per file). Values built outside the test realm (`FormData.getAll()`, a component prop) carry a foreign `Array` prototype, so `toStrictEqual` fails with "values have no visual difference". Spread first: `expect([...fd.getAll("x")]).toStrictEqual([...])`. -- **Branch & merge flow**: Branch off `main`, named `feature/`|`fix/`|etc. plus the JIRA ticket if applicable (e.g. `feature/VPR-104-clinical-scheduler`). After code review, merge into `Development` and push, which deploys to TEST. After the PR is approved on TEST, merge into `main`. Every change goes through `Development` first. -- **Never branch off `Development`**: it is a merge/deploy target, never a base. A branch being "behind `Development`" is expected and not a concern (you never sync or rebase from it). Its history is messy by design and never rewritten. -- **Squash during review**: If a branch is still unmerged and worked by a single developer, squash code-review fixes into the relevant existing commit for cleaner history rather than stacking "address review" commits. -- **Plan/smoketest notes**: `PLAN-*.md` and `SMOKETEST-*.md` at the repo root are local working notes, gitignored by design. -- **Commit messages**: Conventional Commits `type(scope): subject` (`feat`|`fix`|`refactor`|`docs`|`test`|`chore`; prefer `feat` for new behavior), ticket ID from branch as prefix (e.g. `VPR-104 fix(a11y): ...`). Subject: imperative, max 72 chars, no trailing period, intent not implementation. Body only when the subject is insufficient: `-` bullets that each earn their place (skip plumbing/helpers/test scaffolding), wrapped at 72. +- **No VMACS production calls**: Unit tests, local environments, and test environments must NEVER send requests to the VMACS production server. All external HTTP requests (e.g., VMACS, Instinct, IAM API) must be mocked using in-memory databases and mock HTTP clients/factories to prevent production spam. +- **Playwright MCP**: Test UI changes (modals, forms, keyboard nav) and hit API endpoints with it; APIs need browser auth, `curl` fails +- **Frontend mocks**: Vitest `clearMocks` is on, so `vi.clearAllMocks()` in `beforeEach` is redundant +- **Frontend test realm**: `vmThreads` pool means values built outside the test realm (`FormData.getAll()`, component props) have a foreign `Array` prototype and `toStrictEqual` fails with "no visual difference". Spread first: `expect([...fd.getAll("x")]).toStrictEqual([...])`. +- **Branch & merge flow**: Branch off `main` as `feature/`|`fix/`|etc. plus JIRA ticket (e.g. `feature/VPR-104-clinical-scheduler`). After code review, merge into `Development` and push (deploys to TEST); after approval on TEST, merge the PR into `main`. `Development` is a messy merge target only: never branch off, rebase from, or rewrite it, and being behind it is fine. +- **Squash during review**: On an unmerged single-developer branch, squash review fixes into the relevant commit instead of stacking "address review" commits. +- **Plan/smoketest notes**: `PLAN-*.md` and `SMOKETEST-*.md` at the repo root are gitignored local notes. +- **Code-review self-check**: If `PLAN-code-review-lessons.md` exists at the repo root (a personal, gitignored note — may not exist on every machine or for every developer; skip silently if absent), read it and run its pre-flight checklist before saying a change is ready to build, test, or commit. +- **Commit messages**: Conventional Commits `type(scope): subject` (`feat`|`fix`|`refactor`|`docs`|`test`|`chore`; prefer `feat` for new behavior), branch ticket ID as prefix (e.g. `VPR-104 fix(a11y): ...`). Subject: imperative, max 72 chars, no trailing period, intent not implementation. Body only when needed: `-` bullets that each earn their place (skip plumbing/helpers/test scaffolding), wrapped at 72. +- **Line Endings (CRLF)**: Windows checkout and Husky validation strictly require CRLF (`\r\n`) line endings. Always ensure newly created or modified files are saved with CRLF line endings. Running tools/scripts that default to LF (`\n`) will cause pre-commit linter failures. +- **ReSharper Inspection & EF Core Scaffoldings**: + - Keep scaffolded `partial void OnModelCreatingPartial(...)` method signatures in DB context files. Deleting them violates compiler rule `CS0759` (no defining declaration). + - To silence ReSharper warnings on single-part partial types/methods, add global rules `/Default/CodeInspection/Highlighting/InspectionSeverities/=/@EntryIndexedValue=DO_NOT_SHOW` inside `Viper.sln.DotSettings` instead of deleting scaffolded code. + - Avoid redundant null-coalescing operations (`?? ""`) on non-nullable scaffolded entity properties. +- **Staged Conflict Markers (Error CS8300)**: During branch merges, do not stage conflict markers in the git index. Husky builds staged files on commit, and any residual `<<<<<<<` markers will trigger compilation error `CS8300`. Clean up all conflict zones before running `git add`. \ No newline at end of file diff --git a/test/ReportBuilder/ReportBuilderDbContextTests.cs b/test/ReportBuilder/ReportBuilderDbContextTests.cs new file mode 100644 index 000000000..eb7ede2a7 --- /dev/null +++ b/test/ReportBuilder/ReportBuilderDbContextTests.cs @@ -0,0 +1,65 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using Viper.Areas.ReportBuilder; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.test.ReportBuilder; + +/// +/// The builder's tables map to the [reportbuilder] schema the create-schema script makes, never +/// to [reports], and enums are stored by name. Building the model needs no database. +/// +public sealed class ReportBuilderDbContextTests +{ + private static IModel Model() + { + DbContextOptions options = new DbContextOptionsBuilder() + .UseSqlServer("Server=model-only;Database=VIPER") + .Options; + using var context = new ReportBuilderDbContext(options); + return context.Model; + } + + [Theory] + [InlineData(typeof(ReportDefinition), "ReportDefinition")] + [InlineData(typeof(ReportPermission), "ReportPermission")] + [InlineData(typeof(ReportColumn), "ReportColumn")] + [InlineData(typeof(ReportParameter), "ReportParameter")] + [InlineData(typeof(ReportDefinitionHistory), "ReportDefinitionHistory")] + [InlineData(typeof(ReportRunLog), "ReportRunLog")] + public void EveryTable_IsInTheReportBuilderSchema(Type entity, string table) + { + IEntityType type = Assert.IsAssignableFrom(Model().FindEntityType(entity)); + + Assert.Equal("reportbuilder", type.GetSchema()); + Assert.Equal(table, type.GetTableName()); + } + + [Fact] + public void Enums_AreStoredByName() + { + IEntityType parameter = Assert.IsAssignableFrom(Model().FindEntityType(typeof(ReportParameter))); + + Assert.Equal(typeof(string), parameter.FindProperty(nameof(ReportParameter.Binding))?.GetProviderClrType()); + Assert.Equal(typeof(string), parameter.FindProperty(nameof(ReportParameter.Operator))?.GetProviderClrType()); + } + + [Fact] + public void Slugs_AreUnique() + { + IEntityType definition = Assert.IsAssignableFrom(Model().FindEntityType(typeof(ReportDefinition))); + + Assert.Contains(definition.GetIndexes(), index => + index.IsUnique && index.Properties.Single().Name == nameof(ReportDefinition.Slug)); + } + + [Fact] + public void Permissions_AreKeyedByReportAndName() + { + IEntityType permission = Assert.IsAssignableFrom(Model().FindEntityType(typeof(ReportPermission))); + + Assert.Equal( + [nameof(ReportPermission.ReportDefinitionId), nameof(ReportPermission.Permission)], + permission.FindPrimaryKey()!.Properties.Select(p => p.Name)); + } +} diff --git a/test/ReportBuilder/ReportSourceCatalogServiceTests.cs b/test/ReportBuilder/ReportSourceCatalogServiceTests.cs new file mode 100644 index 000000000..ed24e1bf7 --- /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 [reports] 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/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/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs b/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs new file mode 100644 index 000000000..c6c4fd84b --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs @@ -0,0 +1,15 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// One column of a report: which source column it shows, its label, order and format. +public class ReportColumn +{ + public int Id { get; set; } + public int ReportDefinitionId { get; set; } + public string SourceColumn { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + public int DisplayOrder { get; set; } + public bool Visible { get; set; } = true; + public ReportColumnFormat Format { get; set; } + public bool Sortable { get; set; } = true; + public ReportDefinition? ReportDefinition { 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..5ca137056 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportDefinition.cs @@ -0,0 +1,48 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// +/// One admin-defined report: which [reports] view or procedure it reads, who may view it, and +/// how it is laid out. Its is the report's URL. +/// +public class ReportDefinition +{ + public int Id { get; set; } + public string Slug { get; set; } = string.Empty; + 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. The schema is always [reports]. + public string SourceName { get; set; } = string.Empty; + + public ReportSourceKind SourceKind { get; set; } + public bool Paginate { get; set; } = true; + public int PageSize { get; set; } = 25; + public bool AllowSearch { get; set; } + public bool AllowExcel { get; set; } + public bool AllowPdf { get; set; } + public bool PdfLandscape { get; set; } + public string? DefaultSortColumn { get; set; } + public bool DefaultSortDescending { get; set; } + + /// Shown above the table and in exports when the data is confidential. + public string? SensitiveNotice { get; set; } + + public bool IsActive { get; set; } = true; + + /// Set when soft-deleted; the report can be restored until then. + public DateTime? DeletedOn { get; set; } + + public string CreatedBy { get; set; } = string.Empty; + public DateTime CreatedOn { get; set; } + public string ModifiedBy { get; set; } = string.Empty; + + /// Sent back by the editor to detect a conflicting save, as CMS content does. + public DateTime ModifiedOn { 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..57532b5e0 --- /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 definition, taken on every change. +public class ReportDefinitionHistory +{ + public int Id { get; set; } + public int ReportDefinitionId { get; set; } + public ReportHistoryAction Action { get; set; } + + /// The whole definition, with its columns, parameters and permissions, as JSON. + public string Snapshot { get; set; } = string.Empty; + + public string ChangedBy { get; set; } = string.Empty; + public DateTime ChangedOn { 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..d6d96d6f1 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportParameter.cs @@ -0,0 +1,32 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// +/// One 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 ReportDefinitionId { get; set; } + + /// The view column to filter, or the procedure parameter name without the @. + public string Name { get; set; } = string.Empty; + + public string Label { get; set; } = string.Empty; + 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 [reports] 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? ReportDefinition { 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..dadd713af --- /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. Holding any one is enough. +public class ReportPermission +{ + public int ReportDefinitionId { get; set; } + public string Permission { get; set; } = string.Empty; + public ReportDefinition? ReportDefinition { 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..1e7b79f46 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs @@ -0,0 +1,17 @@ +namespace Viper.Areas.ReportBuilder.Models.Entities; + +/// One run or export of a report: who, when, with which parameters, and how many rows. +public class ReportRunLog +{ + public long Id { get; set; } + public int ReportDefinitionId { get; set; } + public ReportRunAction Action { get; set; } + public string LoginId { get; set; } = string.Empty; + public DateTime RanOn { get; set; } + + /// The parameter values as JSON. + public string? Parameters { get; set; } + + public int RowsReturned { get; set; } + public int DurationMs { get; set; } +} diff --git a/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs b/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs new file mode 100644 index 000000000..2ac526e01 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs @@ -0,0 +1,87 @@ +namespace Viper.Areas.ReportBuilder.Models; + +/// What kind of object in the [reports] schema a report reads. +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. +/// +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. +public enum ReportColumnFormat +{ + Text, + Number, + Currency, + Percent, + Date, + DateTime, + YesNo, +} + +/// The input a report parameter takes. +public enum ReportParameterType +{ + Text, + Number, + Date, + Boolean, + Choice, + MultiChoice, +} + +/// How a parameter filters a view's column. Procedure parameters have no operator. +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. +/// +public enum ReportParameterBinding +{ + UserInput, + CurrentUserLoginId, + CurrentUserMothraId, +} + +/// What a user did with a report, for the run log. +public enum ReportRunAction +{ + Run, + ExportExcel, + ExportPdf, +} + +/// What happened to a report definition, for its history. +public enum ReportHistoryAction +{ + Created, + Updated, + Deleted, + Restored, +} diff --git a/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs b/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs new file mode 100644 index 000000000..b70e828ef --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs @@ -0,0 +1,58 @@ +namespace Viper.Areas.ReportBuilder.Models; + +/// A view or procedure in the [reports] 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/ReportBuilderDbContext.cs b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs new file mode 100644 index 000000000..b2ac53e05 --- /dev/null +++ b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs @@ -0,0 +1,104 @@ +using Microsoft.EntityFrameworkCore; +using Viper.Areas.ReportBuilder.Models.Entities; + +namespace Viper.Areas.ReportBuilder; + +/// +/// The Report Builder's own tables, in the VIPER database's [reportbuilder] schema. Report data +/// itself comes from the [reports] schema and is never mapped here. +/// +public class ReportBuilderDbContext : DbContext +{ + internal const string Schema = "reportbuilder"; + + /// The allow-listed schema report views and procedures live in. + internal const string SourceSchema = "reports"; + + private const int EnumLength = 30; + private const int NameLength = 128; + private const int LabelLength = 200; + private const int UserLength = 50; + private const int AreaLength = 50; + + public ReportBuilderDbContext(DbContextOptions options) : base(options) + { + } + + public virtual DbSet ReportDefinitions { get; set; } + public virtual DbSet ReportPermissions { get; set; } + public virtual DbSet ReportColumns { get; set; } + public virtual DbSet ReportParameters { get; set; } + public virtual DbSet ReportDefinitionHistory { get; set; } + public virtual DbSet ReportRunLog { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.ToTable("ReportDefinition", Schema); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Slug).IsUnique(); + entity.Property(e => e.Slug).HasMaxLength(100); + entity.Property(e => e.Title).HasMaxLength(LabelLength); + entity.Property(e => e.Description).HasMaxLength(2000); + entity.Property(e => e.Area).HasMaxLength(AreaLength); + entity.Property(e => e.SourceName).HasMaxLength(NameLength); + entity.Property(e => e.SourceKind).HasConversion().HasMaxLength(EnumLength); + entity.Property(e => e.DefaultSortColumn).HasMaxLength(NameLength); + entity.Property(e => e.SensitiveNotice).HasMaxLength(1000); + entity.Property(e => e.CreatedBy).HasMaxLength(UserLength); + entity.Property(e => e.ModifiedBy).HasMaxLength(UserLength); + entity.HasMany(e => e.Permissions).WithOne(e => e.ReportDefinition).HasForeignKey(e => e.ReportDefinitionId); + entity.HasMany(e => e.Columns).WithOne(e => e.ReportDefinition).HasForeignKey(e => e.ReportDefinitionId); + entity.HasMany(e => e.Parameters).WithOne(e => e.ReportDefinition).HasForeignKey(e => e.ReportDefinitionId); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ReportPermission", Schema); + entity.HasKey(e => new { e.ReportDefinitionId, e.Permission }); + entity.Property(e => e.Permission).HasMaxLength(100); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ReportColumn", Schema); + entity.HasKey(e => e.Id); + entity.HasIndex(e => new { e.ReportDefinitionId, e.SourceColumn }).IsUnique(); + entity.Property(e => e.SourceColumn).HasMaxLength(NameLength); + entity.Property(e => e.Label).HasMaxLength(LabelLength); + entity.Property(e => e.Format).HasConversion().HasMaxLength(EnumLength); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ReportParameter", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Name).HasMaxLength(NameLength); + entity.Property(e => e.Label).HasMaxLength(LabelLength); + entity.Property(e => e.Type).HasConversion().HasMaxLength(EnumLength); + entity.Property(e => e.Operator).HasConversion().HasMaxLength(EnumLength); + entity.Property(e => e.DefaultValue).HasMaxLength(500); + entity.Property(e => e.ChoicesSource).HasMaxLength(NameLength); + entity.Property(e => e.Binding).HasConversion().HasMaxLength(EnumLength); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ReportDefinitionHistory", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Action).HasConversion().HasMaxLength(EnumLength); + entity.Property(e => e.ChangedBy).HasMaxLength(UserLength); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ReportRunLog", Schema); + entity.HasKey(e => e.Id); + entity.Property(e => e.Action).HasConversion().HasMaxLength(EnumLength); + entity.Property(e => e.LoginId).HasMaxLength(UserLength); + }); + } +} 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/Scripts/CreateReportBuilderSchema.cs b/web/Areas/ReportBuilder/Scripts/CreateReportBuilderSchema.cs new file mode 100644 index 000000000..e09d6fb48 --- /dev/null +++ b/web/Areas/ReportBuilder/Scripts/CreateReportBuilderSchema.cs @@ -0,0 +1,255 @@ +// Description: Create the Report Builder's [reportbuilder] tables and the empty [reports] schema +// Usage: dotnet run -- create-schema [--apply] +// Without --apply the changes run in a transaction that is rolled back, so the script can be +// checked against an environment first. Every step is skipped if it already exists, so running +// it again is safe. +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using Amazon; +using Amazon.Extensions.NETCore.Setup; +using Microsoft.Data.SqlClient; +using Microsoft.Extensions.Configuration; + +namespace Viper.Areas.ReportBuilder.Scripts +{ + public static class CreateReportBuilderSchema + { + /// The builder's own tables. Kept out of [reports] so they are never reportable. + private const string BuilderSchema = "reportbuilder"; + + /// The allow-list: report views and procedures go here, written as reviewed scripts. + private const string SourceSchema = "reports"; + + private static readonly (string Name, string Sql)[] Tables = + [ + ("ReportDefinition", """ + CREATE TABLE [reportbuilder].[ReportDefinition] ( + [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportDefinition] PRIMARY KEY, + [Slug] nvarchar(100) NOT NULL, + [Title] nvarchar(200) NOT NULL, + [Description] nvarchar(2000) NULL, + [Area] nvarchar(50) NULL, + [SourceName] nvarchar(128) NOT NULL, + [SourceKind] nvarchar(30) NOT NULL, + [Paginate] bit NOT NULL CONSTRAINT [DF_ReportDefinition_Paginate] DEFAULT (1), + [PageSize] int NOT NULL CONSTRAINT [DF_ReportDefinition_PageSize] DEFAULT (25), + [AllowSearch] bit NOT NULL CONSTRAINT [DF_ReportDefinition_AllowSearch] DEFAULT (0), + [AllowExcel] bit NOT NULL CONSTRAINT [DF_ReportDefinition_AllowExcel] DEFAULT (0), + [AllowPdf] bit NOT NULL CONSTRAINT [DF_ReportDefinition_AllowPdf] DEFAULT (0), + [PdfLandscape] bit NOT NULL CONSTRAINT [DF_ReportDefinition_PdfLandscape] DEFAULT (0), + [DefaultSortColumn] nvarchar(128) NULL, + [DefaultSortDescending] bit NOT NULL CONSTRAINT [DF_ReportDefinition_DefaultSortDescending] DEFAULT (0), + [SensitiveNotice] nvarchar(1000) NULL, + [IsActive] bit NOT NULL CONSTRAINT [DF_ReportDefinition_IsActive] DEFAULT (1), + [DeletedOn] datetime2 NULL, + [CreatedBy] nvarchar(50) NOT NULL, + [CreatedOn] datetime2 NOT NULL, + [ModifiedBy] nvarchar(50) NOT NULL, + [ModifiedOn] datetime2 NOT NULL, + CONSTRAINT [UQ_ReportDefinition_Slug] UNIQUE ([Slug]) + ) + """), + ("ReportPermission", """ + CREATE TABLE [reportbuilder].[ReportPermission] ( + [ReportDefinitionId] int NOT NULL, + [Permission] nvarchar(100) NOT NULL, + CONSTRAINT [PK_ReportPermission] PRIMARY KEY ([ReportDefinitionId], [Permission]), + CONSTRAINT [FK_ReportPermission_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) + REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE + ) + """), + ("ReportColumn", """ + CREATE TABLE [reportbuilder].[ReportColumn] ( + [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportColumn] PRIMARY KEY, + [ReportDefinitionId] int NOT NULL, + [SourceColumn] nvarchar(128) NOT NULL, + [Label] nvarchar(200) NOT NULL, + [DisplayOrder] int NOT NULL, + [Visible] bit NOT NULL CONSTRAINT [DF_ReportColumn_Visible] DEFAULT (1), + [Format] nvarchar(30) NOT NULL, + [Sortable] bit NOT NULL CONSTRAINT [DF_ReportColumn_Sortable] DEFAULT (1), + CONSTRAINT [FK_ReportColumn_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) + REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE, + CONSTRAINT [UQ_ReportColumn_Source] UNIQUE ([ReportDefinitionId], [SourceColumn]) + ) + """), + ("ReportParameter", """ + CREATE TABLE [reportbuilder].[ReportParameter] ( + [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportParameter] PRIMARY KEY, + [ReportDefinitionId] int NOT NULL, + [Name] nvarchar(128) NOT NULL, + [Label] nvarchar(200) NOT NULL, + [DisplayOrder] int NOT NULL, + [Type] nvarchar(30) NOT NULL, + [Operator] nvarchar(30) NULL, + [Required] bit NOT NULL CONSTRAINT [DF_ReportParameter_Required] DEFAULT (0), + [DefaultValue] nvarchar(500) NULL, + [ChoicesSource] nvarchar(128) NULL, + [ChoicesList] nvarchar(max) NULL, + [Binding] nvarchar(30) NOT NULL, + CONSTRAINT [FK_ReportParameter_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) + REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE + ) + """), + ("ReportDefinitionHistory", """ + CREATE TABLE [reportbuilder].[ReportDefinitionHistory] ( + [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportDefinitionHistory] PRIMARY KEY, + [ReportDefinitionId] int NOT NULL, + [Action] nvarchar(30) NOT NULL, + [Snapshot] nvarchar(max) NOT NULL, + [ChangedBy] nvarchar(50) NOT NULL, + [ChangedOn] datetime2 NOT NULL, + CONSTRAINT [FK_ReportDefinitionHistory_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) + REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE + ) + """), + ("ReportRunLog", """ + CREATE TABLE [reportbuilder].[ReportRunLog] ( + [Id] bigint IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportRunLog] PRIMARY KEY, + [ReportDefinitionId] int NOT NULL, + [Action] nvarchar(30) NOT NULL, + [LoginId] nvarchar(50) NOT NULL, + [RanOn] datetime2 NOT NULL, + [Parameters] nvarchar(max) NULL, + [RowsReturned] int NOT NULL, + [DurationMs] int NOT NULL, + CONSTRAINT [FK_ReportRunLog_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) + REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE + ) + """), + ]; + + private static readonly (string Table, string Name, string Sql)[] Indexes = + [ + ("ReportRunLog", "IX_ReportRunLog_Report_RanOn", + "CREATE INDEX [IX_ReportRunLog_Report_RanOn] ON [reportbuilder].[ReportRunLog] ([ReportDefinitionId], [RanOn])"), + ("ReportDefinitionHistory", "IX_ReportDefinitionHistory_Report", + "CREATE INDEX [IX_ReportDefinitionHistory_Report] ON [reportbuilder].[ReportDefinitionHistory] ([ReportDefinitionId], [ChangedOn])"), + ]; + + public static int Run(string[] args) + { + bool apply = args.Any(a => a.Equals("--apply", StringComparison.OrdinalIgnoreCase)); + IConfiguration configuration = LoadConfiguration(); + string? connectionString = configuration.GetConnectionString("VIPER"); + if (string.IsNullOrEmpty(connectionString)) + { + Console.WriteLine("ERROR: the VIPER connection string is not configured."); + return 1; + } + + var target = new SqlConnectionStringBuilder(connectionString); + Console.WriteLine($"Target: {target.DataSource}/{target.InitialCatalog}"); + Console.WriteLine(apply ? "Mode: APPLY" : "Mode: dry run (rolled back)"); + Console.WriteLine(); + + using var connection = new SqlConnection(connectionString); + connection.Open(); + using SqlTransaction transaction = connection.BeginTransaction(); + try + { + EnsureSchema(connection, transaction, BuilderSchema); + EnsureSchema(connection, transaction, SourceSchema); + foreach ((string name, string sql) in Tables) + { + EnsureObject(connection, transaction, $"table [{BuilderSchema}].[{name}]", + $"SELECT COUNT(*) FROM sys.tables WHERE schema_id = SCHEMA_ID('{BuilderSchema}') AND name = '{name}'", sql); + } + + foreach ((string table, string name, string sql) in Indexes) + { + EnsureObject(connection, transaction, $"index {name}", + $"SELECT COUNT(*) FROM sys.indexes WHERE object_id = OBJECT_ID('[{BuilderSchema}].[{table}]') AND name = '{name}'", sql); + } + + if (apply) + { + transaction.Commit(); + Console.WriteLine(); + Console.WriteLine("Committed."); + } + else + { + transaction.Rollback(); + Console.WriteLine(); + Console.WriteLine("Dry run complete; rolled back. Run with --apply to keep the changes."); + } + + return 0; + } + catch (SqlException ex) + { + transaction.Rollback(); + Console.WriteLine($"ERROR: {ex.Message}"); + Console.WriteLine("Rolled back; nothing was changed."); + return 1; + } + } + + private static void EnsureSchema(SqlConnection connection, SqlTransaction transaction, string schema) + { + // CREATE SCHEMA must be alone in its batch, so it runs through EXEC. + EnsureObject(connection, transaction, $"schema [{schema}]", + $"SELECT COUNT(*) FROM sys.schemas WHERE name = '{schema}'", + $"EXEC('CREATE SCHEMA [{schema}]')"); + } + + private static void EnsureObject(SqlConnection connection, SqlTransaction transaction, string label, string existsSql, string createSql) + { + using var check = new SqlCommand(existsSql, connection, transaction); + if (Convert.ToInt32(check.ExecuteScalar(), CultureInfo.InvariantCulture) > 0) + { + Console.WriteLine($" exists {label}"); + return; + } + + using var create = new SqlCommand(createSql, connection, transaction); + create.ExecuteNonQuery(); + Console.WriteLine($" created {label}"); + } + + /// appsettings files plus AWS Parameter Store, as the other area scripts load them. + private static IConfiguration LoadConfiguration() + { + string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"; + string appRoot = GetApplicationRoot(); + Console.WriteLine($"Environment: {environment}"); + + IConfigurationBuilder builder = new ConfigurationBuilder() + .SetBasePath(appRoot) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) + .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: false) + .AddEnvironmentVariables(); + + try + { + AWSOptions awsOptions = new() { Region = RegionEndpoint.USWest1 }; + builder.AddSystemsManager("/" + environment, awsOptions) + .AddSystemsManager("/Shared", awsOptions); + } + catch (Amazon.Runtime.AmazonServiceException ex) + { + Console.WriteLine($"Warning: could not reach AWS Parameter Store: {ex.Message}"); + } + catch (Amazon.Runtime.AmazonClientException ex) + { + Console.WriteLine($"Warning: could not reach AWS Parameter Store: {ex.Message}"); + } + + return builder.Build(); + } + + private static string GetApplicationRoot() + { + string currentDir = Directory.GetCurrentDirectory(); + if (currentDir.Contains("Scripts")) + { + currentDir = Path.GetFullPath(Path.Join(currentDir, "..", "..", "..")); + } + + return currentDir; + } + } +} diff --git a/web/Areas/ReportBuilder/Scripts/Program.cs b/web/Areas/ReportBuilder/Scripts/Program.cs new file mode 100644 index 000000000..de5f3908e --- /dev/null +++ b/web/Areas/ReportBuilder/Scripts/Program.cs @@ -0,0 +1,49 @@ +using System; +using System.Linq; + +namespace Viper.Areas.ReportBuilder.Scripts +{ + /// + /// Entry point for the Report Builder database scripts. + /// - create-schema: create the [reportbuilder] tables and the empty [reports] schema + /// + public class Program + { + public static int Main(string[] args) + { + if (args.Length == 0) + { + ShowUsage(); + return 1; + } + + var command = args[0].ToLowerInvariant(); + var commandArgs = args.Skip(1).ToArray(); + + switch (command) + { + case "create-schema": + return CreateReportBuilderSchema.Run(commandArgs); + + default: + Console.WriteLine($"Unknown command: {command}"); + ShowUsage(); + return 1; + } + } + + private static void ShowUsage() + { + Console.WriteLine("Report Builder Scripts"); + Console.WriteLine(); + Console.WriteLine("Usage: dotnet run -- [options]"); + Console.WriteLine(); + Console.WriteLine("Commands:"); + Console.WriteLine(" create-schema Create the [reportbuilder] tables and the [reports] schema"); + Console.WriteLine(); + Console.WriteLine("Examples:"); + Console.WriteLine(" dotnet run -- create-schema (dry run, rolls back)"); + Console.WriteLine(" dotnet run -- create-schema --apply (writes permanently)"); + } + } +} diff --git a/web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj b/web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj new file mode 100644 index 000000000..3aaa32d9b --- /dev/null +++ b/web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj @@ -0,0 +1,27 @@ + + + + Exe + net10.0 + enable + ReportBuilderScripts + Viper.Areas.ReportBuilder.Scripts + + + + + + + + + + + + + + + + + + + diff --git a/web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat b/web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat new file mode 100644 index 000000000..29f841f10 --- /dev/null +++ b/web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat @@ -0,0 +1,43 @@ +@echo off +REM ================================================================ +REM Report Builder - Schema Creation Runner +REM ================================================================ +REM Usage: RunCreateSchema.bat [environment] [--apply] +REM +REM Examples: +REM RunCreateSchema.bat (dry run, Development config) +REM RunCreateSchema.bat --apply (apply, Development config) +REM RunCreateSchema.bat Test --apply (apply, Test config) +REM RunCreateSchema.bat Production --apply (apply, Production config) +REM ================================================================ + +setlocal + +REM --apply is a flag; anything else names the environment. +set ASPNETCORE_ENVIRONMENT=Development +set SCRIPT_ARGS= + +:parse +if "%~1"=="" goto parsed +if /i "%~1"=="--apply" (set SCRIPT_ARGS= --apply) else (set ASPNETCORE_ENVIRONMENT=%~1) +shift +goto parse +:parsed + +echo. +echo ================================================================ +echo REPORT BUILDER SCHEMA +echo ================================================================ +echo. +echo Environment: %ASPNETCORE_ENVIRONMENT% +if "%SCRIPT_ARGS%"=="" (echo Mode: dry run - changes are rolled back) else (echo Mode: APPLY - changes are permanent) +echo. + +REM Run from this folder (the script reads appsettings from three levels up) and name the +REM project explicitly, so it works from any starting directory. +pushd "%~dp0" +dotnet run --project "%~dp0ReportBuilderScripts.csproj" -- create-schema%SCRIPT_ARGS% +set EXIT_CODE=%ERRORLEVEL% +popd + +endlocal & exit /b %EXIT_CODE% diff --git a/web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs b/web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs new file mode 100644 index 000000000..55402cb04 --- /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 [reports] schema, with the +/// columns they return and the parameters they take. +/// +public interface IReportSourceCatalogService +{ + /// Every view and procedure in [reports], by name. + Task> GetSourcesAsync(CancellationToken ct); + + /// One source's columns and parameters, or null when [reports] 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..495584496 --- /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 [reports] 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 [reports] 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.SourceSchema}) 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); + } + + /// [reports].[name], with any ] in the name doubled, for OBJECT_ID. + private static string Qualify(string name) + { + return $"[{ReportBuilderDbContext.SourceSchema}].[{name.Replace("]", "]]", StringComparison.Ordinal)}]"; + } +} 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/Program.cs b/web/Program.cs index e7521af04..f665dedcc 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.Areas.Reports; using Viper.Classes; using Viper.Classes.HealthChecks; @@ -313,6 +315,8 @@ void RegisterDbContext(string connectionStringKey, Action("VIPER"); // Phone tables are in the VIPER database's [phones] schema. RegisterDbContext("VIPER"); + // Report Builder definitions are in the VIPER database's [reportbuilder] schema. + RegisterDbContext("VIPER"); RegisterDbContext("EvalHarvest"); // Register UserHelper service (must be before Scrutor to take precedence) @@ -321,6 +325,9 @@ void RegisterDbContext(string connectionStringKey, Action(); + // Shared HTML sanitizer for user-authored content (CMS, CTS, ...). Thread-safe singleton. builder.Services.AddSingleton(); @@ -343,6 +350,7 @@ void RegisterDbContext(string connectionStringKey, Action + + + + From 02fb42d0dccadef6b10991e76614dc08ebd409b5 Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:03:55 -0800 Subject: [PATCH 03/12] Implements basic reportbuilder functions --- .../ReportBuilderDbContextTests.cs | 80 +- test/ReportBuilder/ReportBuilderFakes.cs | 72 ++ test/ReportBuilder/ReportChoiceListTests.cs | 48 ++ .../ReportBuilder/ReportChoiceServiceTests.cs | 121 +++ .../ReportParameterBinderTests.cs | 251 ++++++ test/ReportBuilder/ReportRunServiceTests.cs | 727 ++++++++++++++++++ .../ReportSourceCatalogServiceTests.cs | 2 +- test/ReportBuilder/ReportSqlBuilderTests.cs | 187 +++++ test/ReportBuilder/ReportUserServiceTests.cs | 51 ++ .../Models/Entities/ReportColumn.cs | 22 +- .../Models/Entities/ReportDefinition.cs | 46 +- .../Entities/ReportDefinitionHistory.cs | 14 +- .../Models/Entities/ReportParameter.cs | 21 +- .../Models/Entities/ReportPermission.cs | 6 +- .../Models/Entities/ReportRunLog.cs | 21 +- .../Models/ReportBuilderEnums.cs | 2 +- .../ReportBuilder/Models/ReportRunDtos.cs | 97 +++ .../ReportBuilder/Models/ReportSourceDtos.cs | 2 +- .../ReportBuilder/ReportBuilderDbContext.cs | 138 ++-- .../Scripts/CreateReportBuilderSchema.cs | 255 ------ web/Areas/ReportBuilder/Scripts/Program.cs | 49 -- .../Scripts/ReportBuilderScripts.csproj | 27 - .../ReportBuilder/Scripts/RunCreateSchema.bat | 43 -- .../Services/ReportChoiceList.cs | 80 ++ .../Services/ReportChoiceService.cs | 98 +++ .../ReportBuilder/Services/ReportLimits.cs | 26 + .../Services/ReportParameterBinder.cs | 213 +++++ .../Services/ReportQueryExecutor.cs | 111 +++ .../Services/ReportRunService.cs | 559 ++++++++++++++ .../Services/ReportSourceCatalogService.cs | 6 +- .../Services/ReportSourceMetadataReader.cs | 10 +- .../Services/ReportSqlBuilder.cs | 261 +++++++ .../Services/ReportUserService.cs | 38 + web/Program.cs | 6 +- web/Viper.csproj | 4 - 35 files changed, 3179 insertions(+), 515 deletions(-) create mode 100644 test/ReportBuilder/ReportBuilderFakes.cs create mode 100644 test/ReportBuilder/ReportChoiceListTests.cs create mode 100644 test/ReportBuilder/ReportChoiceServiceTests.cs create mode 100644 test/ReportBuilder/ReportParameterBinderTests.cs create mode 100644 test/ReportBuilder/ReportRunServiceTests.cs create mode 100644 test/ReportBuilder/ReportSqlBuilderTests.cs create mode 100644 test/ReportBuilder/ReportUserServiceTests.cs create mode 100644 web/Areas/ReportBuilder/Models/ReportRunDtos.cs delete mode 100644 web/Areas/ReportBuilder/Scripts/CreateReportBuilderSchema.cs delete mode 100644 web/Areas/ReportBuilder/Scripts/Program.cs delete mode 100644 web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj delete mode 100644 web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat create mode 100644 web/Areas/ReportBuilder/Services/ReportChoiceList.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportChoiceService.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportLimits.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportParameterBinder.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportRunService.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportUserService.cs diff --git a/test/ReportBuilder/ReportBuilderDbContextTests.cs b/test/ReportBuilder/ReportBuilderDbContextTests.cs index eb7ede2a7..0b5a0d5db 100644 --- a/test/ReportBuilder/ReportBuilderDbContextTests.cs +++ b/test/ReportBuilder/ReportBuilderDbContextTests.cs @@ -6,12 +6,14 @@ namespace Viper.test.ReportBuilder; /// -/// The builder's tables map to the [reportbuilder] schema the create-schema script makes, never -/// to [reports], and enums are stored by name. Building the model needs no database. +/// 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 IModel Model() + private static readonly IModel Model = BuildModel(); + + private static IModel BuildModel() { DbContextOptions options = new DbContextOptionsBuilder() .UseSqlServer("Server=model-only;Database=VIPER") @@ -20,46 +22,84 @@ private static IModel Model() 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), "ReportDefinition")] - [InlineData(typeof(ReportPermission), "ReportPermission")] - [InlineData(typeof(ReportColumn), "ReportColumn")] - [InlineData(typeof(ReportParameter), "ReportParameter")] - [InlineData(typeof(ReportDefinitionHistory), "ReportDefinitionHistory")] - [InlineData(typeof(ReportRunLog), "ReportRunLog")] - public void EveryTable_IsInTheReportBuilderSchema(Type entity, string table) + [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)); + IEntityType type = Assert.IsAssignableFrom(Model.FindEntityType(entity)); - Assert.Equal("reportbuilder", type.GetSchema()); + 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))); + } + + [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 = Assert.IsAssignableFrom(Model().FindEntityType(typeof(ReportParameter))); + 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_AreUnique() + public void Slugs_AreUniqueAndGeneratedByTheDatabase() { - IEntityType definition = Assert.IsAssignableFrom(Model().FindEntityType(typeof(ReportDefinition))); + IEntityType report = Entity(); - Assert.Contains(definition.GetIndexes(), index => + 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() { - IEntityType permission = Assert.IsAssignableFrom(Model().FindEntityType(typeof(ReportPermission))); - Assert.Equal( - [nameof(ReportPermission.ReportDefinitionId), nameof(ReportPermission.Permission)], - permission.FindPrimaryKey()!.Properties.Select(p => p.Name)); + [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..4cd330590 --- /dev/null +++ b/test/ReportBuilder/ReportBuilderFakes.cs @@ -0,0 +1,72 @@ +using Viper.Areas.ReportBuilder.Models; +using Viper.Areas.ReportBuilder.Services; + +namespace Viper.test.ReportBuilder; + +/// 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); + } +} 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/ReportParameterBinderTests.cs b/test/ReportBuilder/ReportParameterBinderTests.cs new file mode 100644 index 000000000..90f1004a2 --- /dev/null +++ b/test/ReportBuilder/ReportParameterBinderTests.cs @@ -0,0 +1,251 @@ +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 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/ReportRunServiceTests.cs b/test/ReportBuilder/ReportRunServiceTests.cs new file mode 100644 index 000000000..8e85cf6fb --- /dev/null +++ b/test/ReportBuilder/ReportRunServiceTests.cs @@ -0,0 +1,727 @@ +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; + + public ReportRunServiceTests() + { + DbContextOptions options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + _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(); + } + + 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() : base("timeout") + { + } + } + + 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); + return report; + } + + 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); + return report; + } + + 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_IsUnavailableAndNotLogged() + { + await AddRosterAsync(); + _executor.Answer = _ => throw new FakeDbException(); + + AssertFails(await RunAsync(RosterSlug), ReportRunStatus.Unavailable, "The report couldn't be run. Try again later."); + 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_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"]); + } + + // 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); + } + + [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 index ed24e1bf7..de75de31d 100644 --- a/test/ReportBuilder/ReportSourceCatalogServiceTests.cs +++ b/test/ReportBuilder/ReportSourceCatalogServiceTests.cs @@ -5,7 +5,7 @@ namespace Viper.test.ReportBuilder; /// -/// The catalog lists the [reports] views and procedures and describes one at a time, only by +/// 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 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/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/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs b/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs index c6c4fd84b..8bd5bca24 100644 --- a/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs +++ b/web/Areas/ReportBuilder/Models/Entities/ReportColumn.cs @@ -1,15 +1,21 @@ namespace Viper.Areas.ReportBuilder.Models.Entities; -/// One column of a report: which source column it shows, its label, order and format. +/// +/// 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 ReportDefinitionId { get; set; } - public string SourceColumn { get; set; } = string.Empty; - public string Label { get; set; } = string.Empty; - public int DisplayOrder { get; set; } - public bool Visible { get; set; } = true; - public ReportColumnFormat Format { 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 ReportDefinition? ReportDefinition { get; set; } + 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 index 5ca137056..d6f97a744 100644 --- a/web/Areas/ReportBuilder/Models/Entities/ReportDefinition.cs +++ b/web/Areas/ReportBuilder/Models/Entities/ReportDefinition.cs @@ -1,46 +1,52 @@ namespace Viper.Areas.ReportBuilder.Models.Entities; /// -/// One admin-defined report: which [reports] view or procedure it reads, who may view it, and -/// how it is laid out. Its is the report's URL. +/// 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; } - public string Slug { get; set; } = string.Empty; + + /// 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. The schema is always [reports]. - public string SourceName { get; set; } = string.Empty; + /// + /// 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 ReportSourceKind SourceKind { get; set; } - public bool Paginate { get; set; } = true; - public int PageSize { get; set; } = 25; - public bool AllowSearch { get; set; } - public bool AllowExcel { get; set; } + 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; } - public string? DefaultSortColumn { get; set; } - public bool DefaultSortDescending { 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 bool IsActive { get; set; } = true; + 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 CreatedBy { get; set; } = string.Empty; - public DateTime CreatedOn { get; set; } - public string ModifiedBy { get; set; } = string.Empty; - - /// Sent back by the editor to detect a conflicting save, as CMS content does. - public DateTime ModifiedOn { get; set; } + public string? DeletedBy { get; set; } public ICollection Permissions { get; set; } = []; public ICollection Columns { get; set; } = []; diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs b/web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs index 57532b5e0..1415012dc 100644 --- a/web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs +++ b/web/Areas/ReportBuilder/Models/Entities/ReportDefinitionHistory.cs @@ -1,15 +1,15 @@ namespace Viper.Areas.ReportBuilder.Models.Entities; -/// A saved copy of a report definition, taken on every change. +/// A saved copy of a report, taken on every change (report.report_history). public class ReportDefinitionHistory { public int Id { get; set; } - public int ReportDefinitionId { get; set; } - public ReportHistoryAction Action { get; set; } + public int ReportId { get; set; } + public ReportHistoryAction? Action { get; set; } - /// The whole definition, with its columns, parameters and permissions, as JSON. - public string Snapshot { get; set; } = string.Empty; + /// The whole report, with its columns, parameters and permissions, as JSON. + public string? Snapshot { get; set; } - public string ChangedBy { get; set; } = string.Empty; - public DateTime ChangedOn { 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 index d6d96d6f1..80eeddb7b 100644 --- a/web/Areas/ReportBuilder/Models/Entities/ReportParameter.cs +++ b/web/Areas/ReportBuilder/Models/Entities/ReportParameter.cs @@ -1,32 +1,33 @@ namespace Viper.Areas.ReportBuilder.Models.Entities; /// -/// One report parameter: a filter on a view column, or a value for a procedure parameter. +/// 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 ReportDefinitionId { get; set; } + public int ReportId { get; set; } /// The view column to filter, or the procedure parameter name without the @. - public string Name { get; set; } = string.Empty; + public string? Name { get; set; } - public string Label { get; set; } = string.Empty; - public int DisplayOrder { get; set; } - public ReportParameterType Type { 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 bool? Required { get; set; } public string? DefaultValue { get; set; } - /// A [reports] view returning value and label columns, for choice parameters. + /// 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? ReportDefinition { 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 index dadd713af..6b6d1d487 100644 --- a/web/Areas/ReportBuilder/Models/Entities/ReportPermission.cs +++ b/web/Areas/ReportBuilder/Models/Entities/ReportPermission.cs @@ -1,9 +1,9 @@ namespace Viper.Areas.ReportBuilder.Models.Entities; -/// A RAPS permission that lets a user view a report. Holding any one is enough. +/// A RAPS permission that lets a user view a report (report.report_permission). Holding any one is enough. public class ReportPermission { - public int ReportDefinitionId { get; set; } + public int ReportId { get; set; } public string Permission { get; set; } = string.Empty; - public ReportDefinition? ReportDefinition { get; set; } + public ReportDefinition? Report { get; set; } } diff --git a/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs b/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs index 1e7b79f46..5e6d28d20 100644 --- a/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs +++ b/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs @@ -1,17 +1,22 @@ namespace Viper.Areas.ReportBuilder.Models.Entities; -/// One run or export of a report: who, when, with which parameters, and how many rows. +/// +/// One run or export of a report (report.report_runLog): who, when, with which +/// parameters, and how many rows. +/// public class ReportRunLog { - public long Id { get; set; } - public int ReportDefinitionId { get; set; } - public ReportRunAction Action { get; set; } - public string LoginId { get; set; } = string.Empty; - public DateTime RanOn { get; set; } + 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; } - public int DurationMs { get; set; } + public int? RowsReturned { get; set; } + + /// How long the run took, in milliseconds. + public int? DurationMs { get; set; } } diff --git a/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs b/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs index 2ac526e01..aa5f8ed3d 100644 --- a/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs +++ b/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs @@ -1,6 +1,6 @@ namespace Viper.Areas.ReportBuilder.Models; -/// What kind of object in the [reports] schema a report reads. +/// What kind of object in the [report] schema a report reads. public enum ReportSourceKind { View, diff --git a/web/Areas/ReportBuilder/Models/ReportRunDtos.cs b/web/Areas/ReportBuilder/Models/ReportRunDtos.cs new file mode 100644 index 000000000..3c4313406 --- /dev/null +++ b/web/Areas/ReportBuilder/Models/ReportRunDtos.cs @@ -0,0 +1,97 @@ +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. + 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; } + + 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 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 }; + } +} + +/// 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 index b70e828ef..c96238426 100644 --- a/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs +++ b/web/Areas/ReportBuilder/Models/ReportSourceDtos.cs @@ -1,6 +1,6 @@ namespace Viper.Areas.ReportBuilder.Models; -/// A view or procedure in the [reports] schema that a report can read. +/// A view or procedure in the [report] schema that a report can read. public sealed record ReportSourceSummary { public required string Name { get; init; } diff --git a/web/Areas/ReportBuilder/ReportBuilderDbContext.cs b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs index b2ac53e05..d6c0388ce 100644 --- a/web/Areas/ReportBuilder/ReportBuilderDbContext.cs +++ b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs @@ -1,104 +1,146 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; using Viper.Areas.ReportBuilder.Models.Entities; namespace Viper.Areas.ReportBuilder; /// -/// The Report Builder's own tables, in the VIPER database's [reportbuilder] schema. Report data -/// itself comes from the [reports] schema and is never mapped here. +/// 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 = "reportbuilder"; + internal const string Schema = "report"; - /// The allow-listed schema report views and procedures live in. - internal const string SourceSchema = "reports"; - - private const int EnumLength = 30; - private const int NameLength = 128; - private const int LabelLength = 200; + private const int TextLength = 500; + private const int CodeLength = 50; private const int UserLength = 50; - private const int AreaLength = 50; + private const int PermissionLength = 100; + private const string DateTimeType = "datetime"; public ReportBuilderDbContext(DbContextOptions options) : base(options) { } - public virtual DbSet ReportDefinitions { get; set; } + 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 ReportDefinitionHistory { 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("ReportDefinition", Schema); + 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.Slug).HasMaxLength(100); - entity.Property(e => e.Title).HasMaxLength(LabelLength); - entity.Property(e => e.Description).HasMaxLength(2000); - entity.Property(e => e.Area).HasMaxLength(AreaLength); - entity.Property(e => e.SourceName).HasMaxLength(NameLength); - entity.Property(e => e.SourceKind).HasConversion().HasMaxLength(EnumLength); - entity.Property(e => e.DefaultSortColumn).HasMaxLength(NameLength); - entity.Property(e => e.SensitiveNotice).HasMaxLength(1000); - entity.Property(e => e.CreatedBy).HasMaxLength(UserLength); - entity.Property(e => e.ModifiedBy).HasMaxLength(UserLength); - entity.HasMany(e => e.Permissions).WithOne(e => e.ReportDefinition).HasForeignKey(e => e.ReportDefinitionId); - entity.HasMany(e => e.Columns).WithOne(e => e.ReportDefinition).HasForeignKey(e => e.ReportDefinitionId); - entity.HasMany(e => e.Parameters).WithOne(e => e.ReportDefinition).HasForeignKey(e => e.ReportDefinitionId); + 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()"); + 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("ReportPermission", Schema); - entity.HasKey(e => new { e.ReportDefinitionId, e.Permission }); - entity.Property(e => e.Permission).HasMaxLength(100); + 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("ReportColumn", Schema); + entity.ToTable("report_column", Schema); entity.HasKey(e => e.Id); - entity.HasIndex(e => new { e.ReportDefinitionId, e.SourceColumn }).IsUnique(); - entity.Property(e => e.SourceColumn).HasMaxLength(NameLength); - entity.Property(e => e.Label).HasMaxLength(LabelLength); - entity.Property(e => e.Format).HasConversion().HasMaxLength(EnumLength); + 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("ReportParameter", Schema); + entity.ToTable("report_parameter", Schema); entity.HasKey(e => e.Id); - entity.Property(e => e.Name).HasMaxLength(NameLength); - entity.Property(e => e.Label).HasMaxLength(LabelLength); - entity.Property(e => e.Type).HasConversion().HasMaxLength(EnumLength); - entity.Property(e => e.Operator).HasConversion().HasMaxLength(EnumLength); - entity.Property(e => e.DefaultValue).HasMaxLength(500); - entity.Property(e => e.ChoicesSource).HasMaxLength(NameLength); - entity.Property(e => e.Binding).HasConversion().HasMaxLength(EnumLength); + 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("ReportDefinitionHistory", Schema); + entity.ToTable("report_history", Schema); entity.HasKey(e => e.Id); - entity.Property(e => e.Action).HasConversion().HasMaxLength(EnumLength); - entity.Property(e => e.ChangedBy).HasMaxLength(UserLength); + 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("ReportRunLog", Schema); + entity.ToTable("report_runLog", Schema); entity.HasKey(e => e.Id); - entity.Property(e => e.Action).HasConversion().HasMaxLength(EnumLength); - entity.Property(e => e.LoginId).HasMaxLength(UserLength); + 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"); }); } + + /// 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/Scripts/CreateReportBuilderSchema.cs b/web/Areas/ReportBuilder/Scripts/CreateReportBuilderSchema.cs deleted file mode 100644 index e09d6fb48..000000000 --- a/web/Areas/ReportBuilder/Scripts/CreateReportBuilderSchema.cs +++ /dev/null @@ -1,255 +0,0 @@ -// Description: Create the Report Builder's [reportbuilder] tables and the empty [reports] schema -// Usage: dotnet run -- create-schema [--apply] -// Without --apply the changes run in a transaction that is rolled back, so the script can be -// checked against an environment first. Every step is skipped if it already exists, so running -// it again is safe. -using System; -using System.Globalization; -using System.IO; -using System.Linq; -using Amazon; -using Amazon.Extensions.NETCore.Setup; -using Microsoft.Data.SqlClient; -using Microsoft.Extensions.Configuration; - -namespace Viper.Areas.ReportBuilder.Scripts -{ - public static class CreateReportBuilderSchema - { - /// The builder's own tables. Kept out of [reports] so they are never reportable. - private const string BuilderSchema = "reportbuilder"; - - /// The allow-list: report views and procedures go here, written as reviewed scripts. - private const string SourceSchema = "reports"; - - private static readonly (string Name, string Sql)[] Tables = - [ - ("ReportDefinition", """ - CREATE TABLE [reportbuilder].[ReportDefinition] ( - [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportDefinition] PRIMARY KEY, - [Slug] nvarchar(100) NOT NULL, - [Title] nvarchar(200) NOT NULL, - [Description] nvarchar(2000) NULL, - [Area] nvarchar(50) NULL, - [SourceName] nvarchar(128) NOT NULL, - [SourceKind] nvarchar(30) NOT NULL, - [Paginate] bit NOT NULL CONSTRAINT [DF_ReportDefinition_Paginate] DEFAULT (1), - [PageSize] int NOT NULL CONSTRAINT [DF_ReportDefinition_PageSize] DEFAULT (25), - [AllowSearch] bit NOT NULL CONSTRAINT [DF_ReportDefinition_AllowSearch] DEFAULT (0), - [AllowExcel] bit NOT NULL CONSTRAINT [DF_ReportDefinition_AllowExcel] DEFAULT (0), - [AllowPdf] bit NOT NULL CONSTRAINT [DF_ReportDefinition_AllowPdf] DEFAULT (0), - [PdfLandscape] bit NOT NULL CONSTRAINT [DF_ReportDefinition_PdfLandscape] DEFAULT (0), - [DefaultSortColumn] nvarchar(128) NULL, - [DefaultSortDescending] bit NOT NULL CONSTRAINT [DF_ReportDefinition_DefaultSortDescending] DEFAULT (0), - [SensitiveNotice] nvarchar(1000) NULL, - [IsActive] bit NOT NULL CONSTRAINT [DF_ReportDefinition_IsActive] DEFAULT (1), - [DeletedOn] datetime2 NULL, - [CreatedBy] nvarchar(50) NOT NULL, - [CreatedOn] datetime2 NOT NULL, - [ModifiedBy] nvarchar(50) NOT NULL, - [ModifiedOn] datetime2 NOT NULL, - CONSTRAINT [UQ_ReportDefinition_Slug] UNIQUE ([Slug]) - ) - """), - ("ReportPermission", """ - CREATE TABLE [reportbuilder].[ReportPermission] ( - [ReportDefinitionId] int NOT NULL, - [Permission] nvarchar(100) NOT NULL, - CONSTRAINT [PK_ReportPermission] PRIMARY KEY ([ReportDefinitionId], [Permission]), - CONSTRAINT [FK_ReportPermission_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) - REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE - ) - """), - ("ReportColumn", """ - CREATE TABLE [reportbuilder].[ReportColumn] ( - [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportColumn] PRIMARY KEY, - [ReportDefinitionId] int NOT NULL, - [SourceColumn] nvarchar(128) NOT NULL, - [Label] nvarchar(200) NOT NULL, - [DisplayOrder] int NOT NULL, - [Visible] bit NOT NULL CONSTRAINT [DF_ReportColumn_Visible] DEFAULT (1), - [Format] nvarchar(30) NOT NULL, - [Sortable] bit NOT NULL CONSTRAINT [DF_ReportColumn_Sortable] DEFAULT (1), - CONSTRAINT [FK_ReportColumn_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) - REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE, - CONSTRAINT [UQ_ReportColumn_Source] UNIQUE ([ReportDefinitionId], [SourceColumn]) - ) - """), - ("ReportParameter", """ - CREATE TABLE [reportbuilder].[ReportParameter] ( - [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportParameter] PRIMARY KEY, - [ReportDefinitionId] int NOT NULL, - [Name] nvarchar(128) NOT NULL, - [Label] nvarchar(200) NOT NULL, - [DisplayOrder] int NOT NULL, - [Type] nvarchar(30) NOT NULL, - [Operator] nvarchar(30) NULL, - [Required] bit NOT NULL CONSTRAINT [DF_ReportParameter_Required] DEFAULT (0), - [DefaultValue] nvarchar(500) NULL, - [ChoicesSource] nvarchar(128) NULL, - [ChoicesList] nvarchar(max) NULL, - [Binding] nvarchar(30) NOT NULL, - CONSTRAINT [FK_ReportParameter_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) - REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE - ) - """), - ("ReportDefinitionHistory", """ - CREATE TABLE [reportbuilder].[ReportDefinitionHistory] ( - [Id] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportDefinitionHistory] PRIMARY KEY, - [ReportDefinitionId] int NOT NULL, - [Action] nvarchar(30) NOT NULL, - [Snapshot] nvarchar(max) NOT NULL, - [ChangedBy] nvarchar(50) NOT NULL, - [ChangedOn] datetime2 NOT NULL, - CONSTRAINT [FK_ReportDefinitionHistory_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) - REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE - ) - """), - ("ReportRunLog", """ - CREATE TABLE [reportbuilder].[ReportRunLog] ( - [Id] bigint IDENTITY(1,1) NOT NULL CONSTRAINT [PK_ReportRunLog] PRIMARY KEY, - [ReportDefinitionId] int NOT NULL, - [Action] nvarchar(30) NOT NULL, - [LoginId] nvarchar(50) NOT NULL, - [RanOn] datetime2 NOT NULL, - [Parameters] nvarchar(max) NULL, - [RowsReturned] int NOT NULL, - [DurationMs] int NOT NULL, - CONSTRAINT [FK_ReportRunLog_ReportDefinition] FOREIGN KEY ([ReportDefinitionId]) - REFERENCES [reportbuilder].[ReportDefinition] ([Id]) ON DELETE CASCADE - ) - """), - ]; - - private static readonly (string Table, string Name, string Sql)[] Indexes = - [ - ("ReportRunLog", "IX_ReportRunLog_Report_RanOn", - "CREATE INDEX [IX_ReportRunLog_Report_RanOn] ON [reportbuilder].[ReportRunLog] ([ReportDefinitionId], [RanOn])"), - ("ReportDefinitionHistory", "IX_ReportDefinitionHistory_Report", - "CREATE INDEX [IX_ReportDefinitionHistory_Report] ON [reportbuilder].[ReportDefinitionHistory] ([ReportDefinitionId], [ChangedOn])"), - ]; - - public static int Run(string[] args) - { - bool apply = args.Any(a => a.Equals("--apply", StringComparison.OrdinalIgnoreCase)); - IConfiguration configuration = LoadConfiguration(); - string? connectionString = configuration.GetConnectionString("VIPER"); - if (string.IsNullOrEmpty(connectionString)) - { - Console.WriteLine("ERROR: the VIPER connection string is not configured."); - return 1; - } - - var target = new SqlConnectionStringBuilder(connectionString); - Console.WriteLine($"Target: {target.DataSource}/{target.InitialCatalog}"); - Console.WriteLine(apply ? "Mode: APPLY" : "Mode: dry run (rolled back)"); - Console.WriteLine(); - - using var connection = new SqlConnection(connectionString); - connection.Open(); - using SqlTransaction transaction = connection.BeginTransaction(); - try - { - EnsureSchema(connection, transaction, BuilderSchema); - EnsureSchema(connection, transaction, SourceSchema); - foreach ((string name, string sql) in Tables) - { - EnsureObject(connection, transaction, $"table [{BuilderSchema}].[{name}]", - $"SELECT COUNT(*) FROM sys.tables WHERE schema_id = SCHEMA_ID('{BuilderSchema}') AND name = '{name}'", sql); - } - - foreach ((string table, string name, string sql) in Indexes) - { - EnsureObject(connection, transaction, $"index {name}", - $"SELECT COUNT(*) FROM sys.indexes WHERE object_id = OBJECT_ID('[{BuilderSchema}].[{table}]') AND name = '{name}'", sql); - } - - if (apply) - { - transaction.Commit(); - Console.WriteLine(); - Console.WriteLine("Committed."); - } - else - { - transaction.Rollback(); - Console.WriteLine(); - Console.WriteLine("Dry run complete; rolled back. Run with --apply to keep the changes."); - } - - return 0; - } - catch (SqlException ex) - { - transaction.Rollback(); - Console.WriteLine($"ERROR: {ex.Message}"); - Console.WriteLine("Rolled back; nothing was changed."); - return 1; - } - } - - private static void EnsureSchema(SqlConnection connection, SqlTransaction transaction, string schema) - { - // CREATE SCHEMA must be alone in its batch, so it runs through EXEC. - EnsureObject(connection, transaction, $"schema [{schema}]", - $"SELECT COUNT(*) FROM sys.schemas WHERE name = '{schema}'", - $"EXEC('CREATE SCHEMA [{schema}]')"); - } - - private static void EnsureObject(SqlConnection connection, SqlTransaction transaction, string label, string existsSql, string createSql) - { - using var check = new SqlCommand(existsSql, connection, transaction); - if (Convert.ToInt32(check.ExecuteScalar(), CultureInfo.InvariantCulture) > 0) - { - Console.WriteLine($" exists {label}"); - return; - } - - using var create = new SqlCommand(createSql, connection, transaction); - create.ExecuteNonQuery(); - Console.WriteLine($" created {label}"); - } - - /// appsettings files plus AWS Parameter Store, as the other area scripts load them. - private static IConfiguration LoadConfiguration() - { - string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"; - string appRoot = GetApplicationRoot(); - Console.WriteLine($"Environment: {environment}"); - - IConfigurationBuilder builder = new ConfigurationBuilder() - .SetBasePath(appRoot) - .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) - .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: false) - .AddEnvironmentVariables(); - - try - { - AWSOptions awsOptions = new() { Region = RegionEndpoint.USWest1 }; - builder.AddSystemsManager("/" + environment, awsOptions) - .AddSystemsManager("/Shared", awsOptions); - } - catch (Amazon.Runtime.AmazonServiceException ex) - { - Console.WriteLine($"Warning: could not reach AWS Parameter Store: {ex.Message}"); - } - catch (Amazon.Runtime.AmazonClientException ex) - { - Console.WriteLine($"Warning: could not reach AWS Parameter Store: {ex.Message}"); - } - - return builder.Build(); - } - - private static string GetApplicationRoot() - { - string currentDir = Directory.GetCurrentDirectory(); - if (currentDir.Contains("Scripts")) - { - currentDir = Path.GetFullPath(Path.Join(currentDir, "..", "..", "..")); - } - - return currentDir; - } - } -} diff --git a/web/Areas/ReportBuilder/Scripts/Program.cs b/web/Areas/ReportBuilder/Scripts/Program.cs deleted file mode 100644 index de5f3908e..000000000 --- a/web/Areas/ReportBuilder/Scripts/Program.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Linq; - -namespace Viper.Areas.ReportBuilder.Scripts -{ - /// - /// Entry point for the Report Builder database scripts. - /// - create-schema: create the [reportbuilder] tables and the empty [reports] schema - /// - public class Program - { - public static int Main(string[] args) - { - if (args.Length == 0) - { - ShowUsage(); - return 1; - } - - var command = args[0].ToLowerInvariant(); - var commandArgs = args.Skip(1).ToArray(); - - switch (command) - { - case "create-schema": - return CreateReportBuilderSchema.Run(commandArgs); - - default: - Console.WriteLine($"Unknown command: {command}"); - ShowUsage(); - return 1; - } - } - - private static void ShowUsage() - { - Console.WriteLine("Report Builder Scripts"); - Console.WriteLine(); - Console.WriteLine("Usage: dotnet run -- [options]"); - Console.WriteLine(); - Console.WriteLine("Commands:"); - Console.WriteLine(" create-schema Create the [reportbuilder] tables and the [reports] schema"); - Console.WriteLine(); - Console.WriteLine("Examples:"); - Console.WriteLine(" dotnet run -- create-schema (dry run, rolls back)"); - Console.WriteLine(" dotnet run -- create-schema --apply (writes permanently)"); - } - } -} diff --git a/web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj b/web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj deleted file mode 100644 index 3aaa32d9b..000000000 --- a/web/Areas/ReportBuilder/Scripts/ReportBuilderScripts.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - Exe - net10.0 - enable - ReportBuilderScripts - Viper.Areas.ReportBuilder.Scripts - - - - - - - - - - - - - - - - - - - diff --git a/web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat b/web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat deleted file mode 100644 index 29f841f10..000000000 --- a/web/Areas/ReportBuilder/Scripts/RunCreateSchema.bat +++ /dev/null @@ -1,43 +0,0 @@ -@echo off -REM ================================================================ -REM Report Builder - Schema Creation Runner -REM ================================================================ -REM Usage: RunCreateSchema.bat [environment] [--apply] -REM -REM Examples: -REM RunCreateSchema.bat (dry run, Development config) -REM RunCreateSchema.bat --apply (apply, Development config) -REM RunCreateSchema.bat Test --apply (apply, Test config) -REM RunCreateSchema.bat Production --apply (apply, Production config) -REM ================================================================ - -setlocal - -REM --apply is a flag; anything else names the environment. -set ASPNETCORE_ENVIRONMENT=Development -set SCRIPT_ARGS= - -:parse -if "%~1"=="" goto parsed -if /i "%~1"=="--apply" (set SCRIPT_ARGS= --apply) else (set ASPNETCORE_ENVIRONMENT=%~1) -shift -goto parse -:parsed - -echo. -echo ================================================================ -echo REPORT BUILDER SCHEMA -echo ================================================================ -echo. -echo Environment: %ASPNETCORE_ENVIRONMENT% -if "%SCRIPT_ARGS%"=="" (echo Mode: dry run - changes are rolled back) else (echo Mode: APPLY - changes are permanent) -echo. - -REM Run from this folder (the script reads appsettings from three levels up) and name the -REM project explicitly, so it works from any starting directory. -pushd "%~dp0" -dotnet run --project "%~dp0ReportBuilderScripts.csproj" -- create-schema%SCRIPT_ARGS% -set EXIT_CODE=%ERRORLEVEL% -popd - -endlocal & exit /b %EXIT_CODE% diff --git a/web/Areas/ReportBuilder/Services/ReportChoiceList.cs b/web/Areas/ReportBuilder/Services/ReportChoiceList.cs new file mode 100644 index 000000000..be341e3f2 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportChoiceList.cs @@ -0,0 +1,80 @@ +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) + { + foreach (JsonProperty property in item.EnumerateObject() + .Where(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))) + { + return property.Value.ValueKind == JsonValueKind.String ? property.Value.GetString() : property.Value.ToString(); + } + + return null; + } +} 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/ReportLimits.cs b/web/Areas/ReportBuilder/Services/ReportLimits.cs new file mode 100644 index 000000000..04f4e981f --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportLimits.cs @@ -0,0 +1,26 @@ +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; + + /// 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; +} diff --git a/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs b/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs new file mode 100644 index 000000000..49bd4d49e --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs @@ -0,0 +1,213 @@ +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>(input, StringComparer.OrdinalIgnoreCase); + var bound = new List(); + var errors = new List(); + var known = new HashSet(StringComparer.OrdinalIgnoreCase); + + 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 [string 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/ReportQueryExecutor.cs b/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs new file mode 100644 index 000000000..8eb1cd5a5 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs @@ -0,0 +1,111 @@ +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; + } + } + + return command; + } +} diff --git a/web/Areas/ReportBuilder/Services/ReportRunService.cs b/web/Areas/ReportBuilder/Services/ReportRunService.cs new file mode 100644 index 000000000..29e85514e --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportRunService.cs @@ -0,0 +1,559 @@ +using System.Data.Common; +using System.Globalization; +using System.Text.Json; +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); +} + +/// +/// 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. +/// 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 FindAsync(slug, ct); + if (report is null) + { + return ReportRunOutcome.Fail(ReportRunStatus.NotFound); + } + + if (!CanView(report) || !AllowsMode(report, mode)) + { + return ReportRunOutcome.Fail(ReportRunStatus.Forbidden); + } + + long started = _clock.GetTimestamp(); + ReportRunOutcome outcome; + IReadOnlyList parameters; + try + { + 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]); + } + + parameters = bound.Parameters; + outcome = Plan(report, source, request, mode, parameters, out RunPlan? plan); + if (plan is not null) + { + outcome = new ReportRunOutcome + { + Status = ReportRunStatus.Ok, + Result = source.Kind == ReportSourceKind.View + ? await RunViewAsync(plan, ct) + : await RunProcedureAsync(plan, ct), + }; + } + } + catch (DbException ex) + { + _logger.LogError(ex, "Report {ReportId} failed to run", report.Id); + return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, "The report couldn't be run. Try again later."); + } + + if (outcome.Result is not null) + { + await LogRunAsync(report, user, mode, parameters, outcome.Result, _clock.GetElapsedTime(started), ct); + } + + return outcome; + } + + private async Task FindAsync(string slug, CancellationToken ct) + { + 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) + .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. + private bool CanView(ReportDefinition report) + { + return _users.HasPermission(ReportBuilderPermissions.Admin) + || report.Permissions.Any(p => !string.IsNullOrWhiteSpace(p.Permission) && _users.HasPermission(p.Permission)); + } + + 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 = [.. report.Columns + .Where(c => c.Visible && !string.IsNullOrWhiteSpace(c.SourceColumn)) + .OrderBy(c => c.DisplayOrder) + .ThenBy(c => c.Id) + .Select(c => new ReportResultColumn + { + Name = known.TryGetValue(c.SourceColumn!, out ReportSourceColumn? match) ? match.Name : c.SourceColumn!, + Label = string.IsNullOrWhiteSpace(c.Label) ? c.SourceColumn! : c.Label, + Format = c.Format ?? ReportColumnFormat.Text, + Sortable = c.Sortable, + })]; + 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."); + } + + var errors = new List(); + (string? sortColumn, bool descending, bool sortMissing) = Sort(report, request, columns, known, checkColumns, 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."); + } + + bool screen = mode == ReportRunMode.Screen; + bool paginate = screen && report.Paginate != false; + int perPage = Math.Clamp(report.PageSize ?? ReportLimits.DefaultPageSize, 1, ReportLimits.MaxPageSize); + if (paginate && request.PerPage is int 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. + /// + private static (string? Column, bool Descending, bool Missing) Sort( + ReportDefinition report, + ReportRunRequest request, + IReadOnlyList columns, + Dictionary known, + bool checkColumns, + List errors) + { + if (!string.IsNullOrWhiteSpace(request.SortBy)) + { + 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) + { + bool pagesInSql = plan.Paginate && plan.Source.PagesInSql; + ReportSqlCommand command = ReportSqlBuilder.BuildProcedure( + plan.Source.Name, plan.Parameters, pagesInSql ? plan.Skip : null, pagesInSql ? plan.PerPage : null); + ReportQueryResult result = await _executor.QueryAsync( + command, pagesInSql ? plan.PerPage : ReportLimits.MaxRows, plan.Timeout, ct); + + if (pagesInSql) + { + // 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, + }; + } + + IEnumerable> rows = Project(result.Rows, plan.Columns); + if (plan.Search is not null) + { + rows = rows.Where(row => Matches(row, plan.Search)); + } + + if (plan.SortColumn is not null) + { + var comparer = new ReportValueComparer(); + rows = plan.SortDescending + ? rows.OrderByDescending(row => Value(row, plan.SortColumn), comparer) + : rows.OrderBy(row => Value(row, plan.SortColumn), comparer); + } + + 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; + } + } + + private async Task LogRunAsync( + ReportDefinition report, + ReportCurrentUser user, + ReportRunMode mode, + IReadOnlyList parameters, + ReportRunResult result, + TimeSpan duration, + CancellationToken ct) + { + _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(parameters), + RowsReturned = result.Rows.Count, + DurationMs = (int)Math.Min(int.MaxValue, Math.Round(duration.TotalMilliseconds)), + }); + + try + { + await _context.SaveChangesAsync(ct); + } + catch (DbUpdateException ex) + { + // The user still gets their report; a missing log entry isn't worth failing the run. + _logger.LogWarning(ex, "Couldn't log a run of report {ReportId}", report.Id); + } + } + + /// 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 index 55402cb04..3cd08f81c 100644 --- a/web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs +++ b/web/Areas/ReportBuilder/Services/ReportSourceCatalogService.cs @@ -3,15 +3,15 @@ namespace Viper.Areas.ReportBuilder.Services; /// -/// The allow-list of report sources: the views and procedures in the [reports] schema, with the +/// 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 [reports], by name. + /// Every view and procedure in [report], by name. Task> GetSourcesAsync(CancellationToken ct); - /// One source's columns and parameters, or null when [reports] has no such object. + /// One source's columns and parameters, or null when [report] has no such object. Task GetSourceAsync(string name, CancellationToken ct); } diff --git a/web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs b/web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs index 495584496..3f7ad5478 100644 --- a/web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs +++ b/web/Areas/ReportBuilder/Services/ReportSourceMetadataReader.cs @@ -3,7 +3,7 @@ namespace Viper.Areas.ReportBuilder.Services; -/// An object in the [reports] schema, as sys.objects lists it. +/// An object in the [report] schema, as sys.objects lists it. public sealed class ReportSourceObjectRow { public string Name { get; set; } = string.Empty; @@ -34,7 +34,7 @@ public sealed class ReportSourceParameterRow } /// -/// Reads the shape of the [reports] schema from SQL Server's catalog views. Names are always +/// 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 @@ -62,7 +62,7 @@ public async Task> GetObjectsAsync(Cancella 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.SourceSchema}) AND o.type IN ('V', 'P') + WHERE o.schema_id = SCHEMA_ID({ReportBuilderDbContext.Schema}) AND o.type IN ('V', 'P') ORDER BY o.name """).ToListAsync(ct); } @@ -103,9 +103,9 @@ ORDER BY r.column_ordinal """).ToListAsync(ct); } - /// [reports].[name], with any ] in the name doubled, for OBJECT_ID. + /// [report].[name], with any ] in the name doubled, for OBJECT_ID. private static string Qualify(string name) { - return $"[{ReportBuilderDbContext.SourceSchema}].[{name.Replace("]", "]]", StringComparison.Ordinal)}]"; + 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..1846da15c --- /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 int skip && query.Take is int 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 int skipRows && take is int 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/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/Program.cs b/web/Program.cs index f665dedcc..449e26904 100644 --- a/web/Program.cs +++ b/web/Program.cs @@ -315,7 +315,7 @@ void RegisterDbContext(string connectionStringKey, Action("VIPER"); // Phone tables are in the VIPER database's [phones] schema. RegisterDbContext("VIPER"); - // Report Builder definitions are in the VIPER database's [reportbuilder] schema. + // Report Builder tables (and the views and procedures reports read) are in the VIPER database's [report] schema. RegisterDbContext("VIPER"); RegisterDbContext("EvalHarvest"); @@ -325,8 +325,10 @@ void RegisterDbContext(string connectionStringKey, Action(); + // Report Builder: runs report queries on VIPERReports (or VIPER). Not a *Service either. + builder.Services.AddScoped(); // Shared HTML sanitizer for user-authored content (CMS, CTS, ...). Thread-safe singleton. builder.Services.AddSingleton(); diff --git a/web/Viper.csproj b/web/Viper.csproj index 76b55c87f..c0f8d1e41 100644 --- a/web/Viper.csproj +++ b/web/Viper.csproj @@ -25,10 +25,6 @@ - - - - From 4a09f5f8fce2510aca5dea45ebad56b91f895c0e Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:28:01 -0800 Subject: [PATCH 04/12] Initial report-builder implementation --- .../__tests__/personnel-home.test.ts | 31 +- .../__tests__/personnel-report.test.ts | 18 - VueApp/src/Personnel/pages/Home.vue | 5 - .../src/Personnel/pages/PersonnelReport.vue | 17 - VueApp/src/Personnel/router/routes.ts | 8 - VueApp/src/Reports/App.vue | 13 + VueApp/src/Reports/__tests__/deferred.ts | 11 + .../__tests__/report-admin-edit.test.ts | 150 ++++++ .../__tests__/report-admin-fixtures.ts | 63 +++ .../__tests__/report-admin-form.test.ts | 154 ++++++ .../__tests__/report-admin-list.test.ts | 74 +++ .../__tests__/report-admin-panels.test.ts | 192 +++++++ .../__tests__/report-admin-parameters.test.ts | 201 ++++++++ .../__tests__/report-admin-sections.test.ts | 219 ++++++++ .../__tests__/report-admin-service.test.ts | 169 +++++++ .../src/Reports/__tests__/report-page.test.ts | 54 ++ .../Reports/__tests__/report-problems.test.ts | 189 +++++++ .../Reports/__tests__/reports-home.test.ts | 79 +++ VueApp/src/Reports/__tests__/router.test.ts | 114 +++++ .../__tests__/use-report-admin-edit.test.ts | 274 ++++++++++ VueApp/src/Reports/admin/report-admin-form.ts | 215 ++++++++ .../Reports/admin/report-admin-permissions.ts | 2 + .../src/Reports/admin/report-admin-service.ts | 126 +++++ .../src/Reports/admin/report-admin-types.ts | 197 ++++++++ .../Reports/admin/use-report-admin-edit.ts | 184 +++++++ .../Reports/components/ReportAdminBasics.vue | 117 +++++ .../Reports/components/ReportAdminChoices.vue | 51 ++ .../Reports/components/ReportAdminColumns.vue | 143 ++++++ .../Reports/components/ReportAdminDisplay.vue | 116 +++++ .../Reports/components/ReportAdminHistory.vue | 100 ++++ .../components/ReportAdminParameterFields.vue | 157 ++++++ .../components/ReportAdminParameters.vue | 80 +++ .../components/ReportAdminPermissions.vue | 83 +++ .../Reports/components/ReportAdminPreview.vue | 107 ++++ .../Reports/components/ReportAdminStatus.vue | 81 +++ .../Reports/components/ReportFailedRuns.vue | 180 +++++++ .../components/ReportProblemsCheck.vue | 97 ++++ VueApp/src/Reports/index.html | 18 + VueApp/src/Reports/pages/ReportAdminEdit.vue | 169 +++++++ VueApp/src/Reports/pages/ReportAdminList.vue | 134 +++++ .../src/Reports/pages/ReportAdminProblems.vue | 15 + VueApp/src/Reports/pages/ReportPage.vue | 26 + VueApp/src/Reports/pages/ReportsHome.vue | 99 ++++ VueApp/src/Reports/reports.ts | 10 + VueApp/src/Reports/router/index.ts | 37 ++ VueApp/src/Reports/router/routes.ts | 58 +++ .../report-builder/ReportBuilderForm.vue | 108 ++++ .../report-builder/ReportBuilderResults.vue | 78 +++ .../report-builder/ReportBuilderTable.vue | 105 ++++ .../report-builder/ReportChoiceField.vue | 73 +++ .../shared/report-builder/ReportViewer.vue | 144 ++++++ .../__tests__/report-builder-catalog.test.ts | 37 ++ .../__tests__/report-builder-fixtures.ts | 66 +++ .../__tests__/report-builder-form.test.ts | 109 ++++ .../__tests__/report-builder-format.test.ts | 68 +++ .../__tests__/report-builder-query.test.ts | 72 +++ .../__tests__/report-builder-results.test.ts | 110 ++++ .../__tests__/report-builder-service.test.ts | 136 +++++ .../__tests__/report-builder-table.test.ts | 139 +++++ .../__tests__/report-choice-field.test.ts | 61 +++ .../__tests__/report-viewer.test.ts | 182 +++++++ .../__tests__/use-report-builder.test.ts | 374 ++++++++++++++ .../report-builder/report-builder-catalog.ts | 28 ++ .../report-builder/report-builder-format.ts | 93 ++++ .../report-builder/report-builder-query.ts | 77 +++ .../report-builder/report-builder-service.ts | 80 +++ .../report-builder/report-builder-types.ts | 101 ++++ .../report-builder/use-report-builder.ts | 256 ++++++++++ VueApp/src/shared/reports/ReportCatalog.vue | 96 ---- .../src/shared/reports/ReportGroupTable.vue | 65 --- .../src/shared/reports/ReportNumberTable.vue | 59 --- .../shared/reports/ReportParameterForm.vue | 123 ----- VueApp/src/shared/reports/ReportRunner.vue | 124 ----- VueApp/src/shared/reports/ReportTotals.vue | 52 -- VueApp/src/shared/reports/ReportView.vue | 86 ---- .../reports/__tests__/report-catalog.test.ts | 141 ------ .../reports/__tests__/report-columns.test.ts | 81 --- .../reports/__tests__/report-fixtures.ts | 66 --- .../reports/__tests__/report-format.test.ts | 105 ---- .../__tests__/report-number-tables.test.ts | 24 - .../__tests__/report-parameter-form.test.ts | 139 ----- .../reports/__tests__/report-query.test.ts | 121 ----- .../reports/__tests__/report-runner.test.ts | 183 ------- .../reports/__tests__/report-service.test.ts | 181 ------- .../reports/__tests__/report-tables.test.ts | 98 ---- .../reports/__tests__/report-tones.test.ts | 73 --- .../reports/__tests__/report-view.test.ts | 58 --- .../reports/__tests__/use-report.test.ts | 220 -------- VueApp/src/shared/reports/report-columns.ts | 51 -- VueApp/src/shared/reports/report-format.ts | 79 --- .../shared/reports/report-number-tables.ts | 39 -- VueApp/src/shared/reports/report-query.ts | 85 ---- VueApp/src/shared/reports/report-service.ts | 81 --- VueApp/src/shared/reports/report-tones.css | 23 - VueApp/src/shared/reports/report-tones.ts | 64 --- VueApp/src/shared/reports/report-types.ts | 153 ------ VueApp/src/shared/reports/use-report.ts | 82 --- VueApp/vite.config.ts | 1 + test/Personnel/EmployeesOnLeaveReportTests.cs | 93 ---- test/Personnel/ExemptStatusReportTests.cs | 105 ---- test/Personnel/FacultyProfileReportTests.cs | 126 ----- test/Personnel/FacultyProfileRowsTests.cs | 75 --- test/Personnel/FiscalYearTests.cs | 19 - .../PersonnelReportDataServiceTests.cs | 161 ------ test/Personnel/PersonnelTestDoubles.cs | 41 -- test/ReportBuilder/ReportAccessTests.cs | 86 ++++ test/ReportBuilder/ReportAdminServiceTests.cs | 474 ++++++++++++++++++ .../ReportBuilderAdminControllerTests.cs | 296 +++++++++++ .../ReportBuilderControllerTests.cs | 218 ++++++++ .../ReportBuilderDbContextTests.cs | 2 + test/ReportBuilder/ReportBuilderFakes.cs | 26 + test/ReportBuilder/ReportBuilderJsonTests.cs | 51 ++ .../ReportBuilder/ReportCellFormatterTests.cs | 108 ++++ .../ReportDefinitionValidatorTests.cs | 339 +++++++++++++ test/ReportBuilder/ReportExcelWriterTests.cs | 161 ++++++ .../ReportBuilder/ReportExportServiceTests.cs | 118 +++++ test/ReportBuilder/ReportExportTextTests.cs | 37 ++ test/ReportBuilder/ReportPdfWriterTests.cs | 60 +++ .../ReportPermissionLookupServiceTests.cs | 87 ++++ .../ReportProblemServiceTests.cs | 191 +++++++ test/ReportBuilder/ReportRunServiceTests.cs | 198 +++++++- .../ReportBuilder/ReportViewerServiceTests.cs | 264 ++++++++++ .../Reports/Data/DataRecordExtensionsTests.cs | 105 ---- test/Reports/Data/FakeDb.cs | 166 ------ .../Data/StoredProcedureParameterTests.cs | 43 -- .../Data/StoredProcedureRunnerTests.cs | 85 ---- test/Reports/ReportBuilderTests.cs | 248 --------- test/Reports/ReportContextTests.cs | 70 --- test/Reports/ReportCsvExporterTests.cs | 76 --- test/Reports/ReportDefinitionContractTests.cs | 87 ---- test/Reports/ReportDefinitionTests.cs | 263 ---------- test/Reports/ReportDescribeParametersTests.cs | 73 --- test/Reports/ReportExcelExporterTests.cs | 194 ------- test/Reports/ReportExportTestData.cs | 98 ---- test/Reports/ReportExportTextTests.cs | 119 ----- test/Reports/ReportKeyTests.cs | 35 -- test/Reports/ReportLayoutBuilderTests.cs | 157 ------ test/Reports/ReportMeasureTests.cs | 90 ---- test/Reports/ReportParameterBinderTests.cs | 107 ---- test/Reports/ReportPdfExporterTests.cs | 61 --- test/Reports/ReportPipelineTests.cs | 264 ---------- test/Reports/ReportRegistryTests.cs | 156 ------ test/Reports/ReportRunTests.cs | 45 -- test/Reports/ReportServiceTests.cs | 283 ----------- test/Reports/ReportTestDoubles.cs | 105 ---- test/Reports/ReportTestFixtures.cs | 169 ------- test/Reports/ReportUserServiceTests.cs | 41 -- test/Reports/ReportValueFormatterTests.cs | 113 ----- test/Reports/ReportsControllerTests.cs | 195 ------- test/Reports/ReportsRegistrationTests.cs | 61 --- .../Personnel/Models/EmployeeOnLeaveRow.cs | 12 - .../Personnel/Models/FacultyAppointmentRow.cs | 13 - web/Areas/Personnel/Models/FlsaEmployeeRow.cs | 13 - web/Areas/Personnel/PersonnelDatabases.cs | 12 - .../Reports/EmployeesOnLeaveReport.cs | 77 --- .../Personnel/Reports/ExemptStatusReport.cs | 82 --- .../Personnel/Reports/FacultyProfileReport.cs | 92 ---- .../Personnel/Reports/FacultyProfileRows.cs | 94 ---- web/Areas/Personnel/Reports/FiscalYear.cs | 20 - .../Personnel/Reports/PersonnelOptions.cs | 29 -- .../Personnel/Reports/PersonnelReports.cs | 12 - .../Services/PersonnelReportDataService.cs | 124 ----- .../ReportBuilderAdminController.cs | 165 ++++++ .../Controllers/ReportBuilderController.cs | 89 ++++ .../Exporters/ReportExcelWriter.cs | 179 +++++++ .../Exporters/ReportExportDocument.cs | 51 ++ .../Exporters/ReportPdfWriter.cs | 126 +++++ .../Models/Entities/ReportRunLog.cs | 8 +- .../ReportBuilder/Models/ReportAdminDtos.cs | 205 ++++++++ .../Models/ReportBuilderEnums.cs | 12 + .../Models/ReportBuilderMapper.cs | 27 + .../ReportBuilder/Models/ReportProblemDtos.cs | 50 ++ .../ReportBuilder/Models/ReportRunDtos.cs | 26 + .../ReportBuilder/Models/ReportViewerDtos.cs | 81 +++ .../ReportBuilder/ReportBuilderDbContext.cs | 3 + .../ReportBuilder/Services/ReportAccess.cs | 78 +++ .../Services/ReportAdminService.cs | 431 ++++++++++++++++ .../Services/ReportCellFormatter.cs | 135 +++++ .../Services/ReportChoiceList.cs | 11 +- .../Services/ReportDefinitionValidator.cs | 311 ++++++++++++ .../Services/ReportExportService.cs | 83 +++ .../ReportBuilder/Services/ReportLimits.cs | 11 + .../Services/ReportParameterBinder.cs | 2 +- .../Services/ReportPermissionLookupService.cs | 67 +++ .../Services/ReportProblemService.cs | 85 ++++ .../Services/ReportRunService.cs | 220 +++++--- .../Services/ReportSqlBuilder.cs | 4 +- .../Services/ReportViewerService.cs | 126 +++++ .../Reports/Controllers/ReportsController.cs | 91 ---- .../Reports/Data/DataRecordExtensions.cs | 49 -- web/Areas/Reports/Data/DbConnectionFactory.cs | 44 -- .../Reports/Data/StoredProcedureParameter.cs | 60 --- .../Reports/Data/StoredProcedureRunner.cs | 65 --- web/Areas/Reports/Engine/PlannedReport.cs | 38 -- .../Reports/Engine/ReportBuilder.Layout.cs | 209 -------- web/Areas/Reports/Engine/ReportBuilder.cs | 131 ----- web/Areas/Reports/Engine/ReportColumn.cs | 106 ---- web/Areas/Reports/Engine/ReportContext.cs | 30 -- web/Areas/Reports/Engine/ReportDefinition.cs | 155 ------ web/Areas/Reports/Engine/ReportExpressions.cs | 43 -- web/Areas/Reports/Engine/ReportFilter.cs | 7 - web/Areas/Reports/Engine/ReportKey.cs | 42 -- web/Areas/Reports/Engine/ReportLayoutRules.cs | 140 ------ web/Areas/Reports/Engine/ReportMeasure.cs | 64 --- web/Areas/Reports/Engine/ReportMetadata.cs | 85 ---- web/Areas/Reports/Engine/ReportParameter.cs | 151 ------ .../Reports/Engine/ReportParameterBinder.cs | 77 --- web/Areas/Reports/Engine/ReportPipeline.cs | 157 ------ web/Areas/Reports/Engine/ReportRegistry.cs | 101 ---- web/Areas/Reports/Engine/ReportResult.cs | 87 ---- .../Reports/Engine/ReportValueFormatter.cs | 79 --- .../Reports/Exporters/ReportCsvExporter.cs | 89 ---- .../Reports/Exporters/ReportExcelExporter.cs | 357 ------------- web/Areas/Reports/Exporters/ReportExport.cs | 135 ----- .../Reports/Exporters/ReportPdfExporter.cs | 333 ------------ .../ReportsServiceCollectionExtensions.cs | 41 -- web/Areas/Reports/Services/ReportOutcome.cs | 49 -- web/Areas/Reports/Services/ReportService.cs | 199 -------- .../Reports/Services/ReportUserService.cs | 37 -- web/Program.cs | 7 +- 220 files changed, 12279 insertions(+), 10877 deletions(-) delete mode 100644 VueApp/src/Personnel/__tests__/personnel-report.test.ts delete mode 100644 VueApp/src/Personnel/pages/PersonnelReport.vue create mode 100644 VueApp/src/Reports/App.vue create mode 100644 VueApp/src/Reports/__tests__/deferred.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-edit.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-fixtures.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-form.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-list.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-panels.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-parameters.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-sections.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-admin-service.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-page.test.ts create mode 100644 VueApp/src/Reports/__tests__/report-problems.test.ts create mode 100644 VueApp/src/Reports/__tests__/reports-home.test.ts create mode 100644 VueApp/src/Reports/__tests__/router.test.ts create mode 100644 VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts create mode 100644 VueApp/src/Reports/admin/report-admin-form.ts create mode 100644 VueApp/src/Reports/admin/report-admin-permissions.ts create mode 100644 VueApp/src/Reports/admin/report-admin-service.ts create mode 100644 VueApp/src/Reports/admin/report-admin-types.ts create mode 100644 VueApp/src/Reports/admin/use-report-admin-edit.ts create mode 100644 VueApp/src/Reports/components/ReportAdminBasics.vue create mode 100644 VueApp/src/Reports/components/ReportAdminChoices.vue create mode 100644 VueApp/src/Reports/components/ReportAdminColumns.vue create mode 100644 VueApp/src/Reports/components/ReportAdminDisplay.vue create mode 100644 VueApp/src/Reports/components/ReportAdminHistory.vue create mode 100644 VueApp/src/Reports/components/ReportAdminParameterFields.vue create mode 100644 VueApp/src/Reports/components/ReportAdminParameters.vue create mode 100644 VueApp/src/Reports/components/ReportAdminPermissions.vue create mode 100644 VueApp/src/Reports/components/ReportAdminPreview.vue create mode 100644 VueApp/src/Reports/components/ReportAdminStatus.vue create mode 100644 VueApp/src/Reports/components/ReportFailedRuns.vue create mode 100644 VueApp/src/Reports/components/ReportProblemsCheck.vue create mode 100644 VueApp/src/Reports/index.html create mode 100644 VueApp/src/Reports/pages/ReportAdminEdit.vue create mode 100644 VueApp/src/Reports/pages/ReportAdminList.vue create mode 100644 VueApp/src/Reports/pages/ReportAdminProblems.vue create mode 100644 VueApp/src/Reports/pages/ReportPage.vue create mode 100644 VueApp/src/Reports/pages/ReportsHome.vue create mode 100644 VueApp/src/Reports/reports.ts create mode 100644 VueApp/src/Reports/router/index.ts create mode 100644 VueApp/src/Reports/router/routes.ts create mode 100644 VueApp/src/shared/report-builder/ReportBuilderForm.vue create mode 100644 VueApp/src/shared/report-builder/ReportBuilderResults.vue create mode 100644 VueApp/src/shared/report-builder/ReportBuilderTable.vue create mode 100644 VueApp/src/shared/report-builder/ReportChoiceField.vue create mode 100644 VueApp/src/shared/report-builder/ReportViewer.vue create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-catalog.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-fixtures.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-form.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-format.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-query.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-results.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-service.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-builder-table.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/report-viewer.test.ts create mode 100644 VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts create mode 100644 VueApp/src/shared/report-builder/report-builder-catalog.ts create mode 100644 VueApp/src/shared/report-builder/report-builder-format.ts create mode 100644 VueApp/src/shared/report-builder/report-builder-query.ts create mode 100644 VueApp/src/shared/report-builder/report-builder-service.ts create mode 100644 VueApp/src/shared/report-builder/report-builder-types.ts create mode 100644 VueApp/src/shared/report-builder/use-report-builder.ts delete mode 100644 VueApp/src/shared/reports/ReportCatalog.vue delete mode 100644 VueApp/src/shared/reports/ReportGroupTable.vue delete mode 100644 VueApp/src/shared/reports/ReportNumberTable.vue delete mode 100644 VueApp/src/shared/reports/ReportParameterForm.vue delete mode 100644 VueApp/src/shared/reports/ReportRunner.vue delete mode 100644 VueApp/src/shared/reports/ReportTotals.vue delete mode 100644 VueApp/src/shared/reports/ReportView.vue delete mode 100644 VueApp/src/shared/reports/__tests__/report-catalog.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-columns.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-fixtures.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-format.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-number-tables.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-query.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-runner.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-service.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-tables.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-tones.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/report-view.test.ts delete mode 100644 VueApp/src/shared/reports/__tests__/use-report.test.ts delete mode 100644 VueApp/src/shared/reports/report-columns.ts delete mode 100644 VueApp/src/shared/reports/report-format.ts delete mode 100644 VueApp/src/shared/reports/report-number-tables.ts delete mode 100644 VueApp/src/shared/reports/report-query.ts delete mode 100644 VueApp/src/shared/reports/report-service.ts delete mode 100644 VueApp/src/shared/reports/report-tones.css delete mode 100644 VueApp/src/shared/reports/report-tones.ts delete mode 100644 VueApp/src/shared/reports/report-types.ts delete mode 100644 VueApp/src/shared/reports/use-report.ts delete mode 100644 test/Personnel/EmployeesOnLeaveReportTests.cs delete mode 100644 test/Personnel/ExemptStatusReportTests.cs delete mode 100644 test/Personnel/FacultyProfileReportTests.cs delete mode 100644 test/Personnel/FacultyProfileRowsTests.cs delete mode 100644 test/Personnel/FiscalYearTests.cs delete mode 100644 test/Personnel/PersonnelReportDataServiceTests.cs delete mode 100644 test/Personnel/PersonnelTestDoubles.cs create mode 100644 test/ReportBuilder/ReportAccessTests.cs create mode 100644 test/ReportBuilder/ReportAdminServiceTests.cs create mode 100644 test/ReportBuilder/ReportBuilderAdminControllerTests.cs create mode 100644 test/ReportBuilder/ReportBuilderControllerTests.cs create mode 100644 test/ReportBuilder/ReportBuilderJsonTests.cs create mode 100644 test/ReportBuilder/ReportCellFormatterTests.cs create mode 100644 test/ReportBuilder/ReportDefinitionValidatorTests.cs create mode 100644 test/ReportBuilder/ReportExcelWriterTests.cs create mode 100644 test/ReportBuilder/ReportExportServiceTests.cs create mode 100644 test/ReportBuilder/ReportExportTextTests.cs create mode 100644 test/ReportBuilder/ReportPdfWriterTests.cs create mode 100644 test/ReportBuilder/ReportPermissionLookupServiceTests.cs create mode 100644 test/ReportBuilder/ReportProblemServiceTests.cs create mode 100644 test/ReportBuilder/ReportViewerServiceTests.cs delete mode 100644 test/Reports/Data/DataRecordExtensionsTests.cs delete mode 100644 test/Reports/Data/FakeDb.cs delete mode 100644 test/Reports/Data/StoredProcedureParameterTests.cs delete mode 100644 test/Reports/Data/StoredProcedureRunnerTests.cs delete mode 100644 test/Reports/ReportBuilderTests.cs delete mode 100644 test/Reports/ReportContextTests.cs delete mode 100644 test/Reports/ReportCsvExporterTests.cs delete mode 100644 test/Reports/ReportDefinitionContractTests.cs delete mode 100644 test/Reports/ReportDefinitionTests.cs delete mode 100644 test/Reports/ReportDescribeParametersTests.cs delete mode 100644 test/Reports/ReportExcelExporterTests.cs delete mode 100644 test/Reports/ReportExportTestData.cs delete mode 100644 test/Reports/ReportExportTextTests.cs delete mode 100644 test/Reports/ReportKeyTests.cs delete mode 100644 test/Reports/ReportLayoutBuilderTests.cs delete mode 100644 test/Reports/ReportMeasureTests.cs delete mode 100644 test/Reports/ReportParameterBinderTests.cs delete mode 100644 test/Reports/ReportPdfExporterTests.cs delete mode 100644 test/Reports/ReportPipelineTests.cs delete mode 100644 test/Reports/ReportRegistryTests.cs delete mode 100644 test/Reports/ReportRunTests.cs delete mode 100644 test/Reports/ReportServiceTests.cs delete mode 100644 test/Reports/ReportTestDoubles.cs delete mode 100644 test/Reports/ReportTestFixtures.cs delete mode 100644 test/Reports/ReportUserServiceTests.cs delete mode 100644 test/Reports/ReportValueFormatterTests.cs delete mode 100644 test/Reports/ReportsControllerTests.cs delete mode 100644 test/Reports/ReportsRegistrationTests.cs delete mode 100644 web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs delete mode 100644 web/Areas/Personnel/Models/FacultyAppointmentRow.cs delete mode 100644 web/Areas/Personnel/Models/FlsaEmployeeRow.cs delete mode 100644 web/Areas/Personnel/PersonnelDatabases.cs delete mode 100644 web/Areas/Personnel/Reports/EmployeesOnLeaveReport.cs delete mode 100644 web/Areas/Personnel/Reports/ExemptStatusReport.cs delete mode 100644 web/Areas/Personnel/Reports/FacultyProfileReport.cs delete mode 100644 web/Areas/Personnel/Reports/FacultyProfileRows.cs delete mode 100644 web/Areas/Personnel/Reports/FiscalYear.cs delete mode 100644 web/Areas/Personnel/Reports/PersonnelOptions.cs delete mode 100644 web/Areas/Personnel/Reports/PersonnelReports.cs delete mode 100644 web/Areas/Personnel/Services/PersonnelReportDataService.cs create mode 100644 web/Areas/ReportBuilder/Controllers/ReportBuilderAdminController.cs create mode 100644 web/Areas/ReportBuilder/Controllers/ReportBuilderController.cs create mode 100644 web/Areas/ReportBuilder/Exporters/ReportExcelWriter.cs create mode 100644 web/Areas/ReportBuilder/Exporters/ReportExportDocument.cs create mode 100644 web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs create mode 100644 web/Areas/ReportBuilder/Models/ReportAdminDtos.cs create mode 100644 web/Areas/ReportBuilder/Models/ReportBuilderMapper.cs create mode 100644 web/Areas/ReportBuilder/Models/ReportProblemDtos.cs create mode 100644 web/Areas/ReportBuilder/Models/ReportViewerDtos.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportAccess.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportAdminService.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportCellFormatter.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportExportService.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportPermissionLookupService.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportProblemService.cs create mode 100644 web/Areas/ReportBuilder/Services/ReportViewerService.cs delete mode 100644 web/Areas/Reports/Controllers/ReportsController.cs delete mode 100644 web/Areas/Reports/Data/DataRecordExtensions.cs delete mode 100644 web/Areas/Reports/Data/DbConnectionFactory.cs delete mode 100644 web/Areas/Reports/Data/StoredProcedureParameter.cs delete mode 100644 web/Areas/Reports/Data/StoredProcedureRunner.cs delete mode 100644 web/Areas/Reports/Engine/PlannedReport.cs delete mode 100644 web/Areas/Reports/Engine/ReportBuilder.Layout.cs delete mode 100644 web/Areas/Reports/Engine/ReportBuilder.cs delete mode 100644 web/Areas/Reports/Engine/ReportColumn.cs delete mode 100644 web/Areas/Reports/Engine/ReportContext.cs delete mode 100644 web/Areas/Reports/Engine/ReportDefinition.cs delete mode 100644 web/Areas/Reports/Engine/ReportExpressions.cs delete mode 100644 web/Areas/Reports/Engine/ReportFilter.cs delete mode 100644 web/Areas/Reports/Engine/ReportKey.cs delete mode 100644 web/Areas/Reports/Engine/ReportLayoutRules.cs delete mode 100644 web/Areas/Reports/Engine/ReportMeasure.cs delete mode 100644 web/Areas/Reports/Engine/ReportMetadata.cs delete mode 100644 web/Areas/Reports/Engine/ReportParameter.cs delete mode 100644 web/Areas/Reports/Engine/ReportParameterBinder.cs delete mode 100644 web/Areas/Reports/Engine/ReportPipeline.cs delete mode 100644 web/Areas/Reports/Engine/ReportRegistry.cs delete mode 100644 web/Areas/Reports/Engine/ReportResult.cs delete mode 100644 web/Areas/Reports/Engine/ReportValueFormatter.cs delete mode 100644 web/Areas/Reports/Exporters/ReportCsvExporter.cs delete mode 100644 web/Areas/Reports/Exporters/ReportExcelExporter.cs delete mode 100644 web/Areas/Reports/Exporters/ReportExport.cs delete mode 100644 web/Areas/Reports/Exporters/ReportPdfExporter.cs delete mode 100644 web/Areas/Reports/ReportsServiceCollectionExtensions.cs delete mode 100644 web/Areas/Reports/Services/ReportOutcome.cs delete mode 100644 web/Areas/Reports/Services/ReportService.cs delete mode 100644 web/Areas/Reports/Services/ReportUserService.cs diff --git a/VueApp/src/Personnel/__tests__/personnel-home.test.ts b/VueApp/src/Personnel/__tests__/personnel-home.test.ts index 93dd31a8e..478c5acc6 100644 --- a/VueApp/src/Personnel/__tests__/personnel-home.test.ts +++ b/VueApp/src/Personnel/__tests__/personnel-home.test.ts @@ -1,35 +1,14 @@ import { mount } from "@vue/test-utils" -import { createMemoryHistory, createRouter } from "vue-router" import Home from "../pages/Home.vue" -import { routes } from "../router/routes" -/** - * The Personnel home page shows its CMS content and the Personnel report catalog, whose links - * go to the PersonnelReport route. - */ +/** The Personnel home page shows its CMS content; Personnel reports are in the Report Builder. */ describe("personnel home page", () => { - it("shows the CMS content and the Personnel reports", () => { - const wrapper = mount(Home, { - global: { stubs: { CmsContent: true, ReportCatalog: true } }, - }) + it("shows the CMS content", () => { + expect.hasAssertions() - expect(wrapper.findComponent({ name: "CmsContent" }).props("contentName")).toBe("personnel-home") - const catalog = wrapper.findComponent({ name: "ReportCatalog" }) - expect(catalog.props("area")).toBe("Personnel") - expect(catalog.props("reportRoute")).toBe("PersonnelReport") - }) -}) + const wrapper = mount(Home, { global: { stubs: { CmsContent: true } } }) -describe("personnel report route", () => { - it("resolves a report key to the PersonnelReport route", () => { - const router = createRouter({ history: createMemoryHistory(), routes }) - const resolved = router.resolve({ - name: "PersonnelReport", - params: { key: "personnel.faculty-profile" }, - }) - - expect(resolved.path).toBe("/Personnel/Reports/personnel.faculty-profile") - expect(resolved.meta.allowUnAuth).toBeFalsy() + expect(wrapper.findComponent({ name: "CmsContent" }).props("contentName")).toBe("personnel-home") }) }) diff --git a/VueApp/src/Personnel/__tests__/personnel-report.test.ts b/VueApp/src/Personnel/__tests__/personnel-report.test.ts deleted file mode 100644 index c2b7e90bd..000000000 --- a/VueApp/src/Personnel/__tests__/personnel-report.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { mount } from "@vue/test-utils" -import PersonnelReport from "../pages/PersonnelReport.vue" - -vi.mock("vue-router", () => ({ - useRoute: () => ({ params: { key: "personnel.visa-audit" } }), -})) - -describe("personnel report page", () => { - it("runs the report named by the route, with a breadcrumb back to Personnel", () => { - expect.hasAssertions() - const wrapper = mount(PersonnelReport, { global: { stubs: { ReportRunner: true } } }) - const runner = wrapper.findComponent({ name: "ReportRunner" }) - - expect(runner.props("reportKey")).toBe("personnel.visa-audit") - expect(runner.props("parentLabel")).toBe("Personnel") - expect(runner.props("parentTo")).toStrictEqual({ name: "PersonnelHome" }) - }) -}) diff --git a/VueApp/src/Personnel/pages/Home.vue b/VueApp/src/Personnel/pages/Home.vue index 0f8f24f61..a7254de06 100644 --- a/VueApp/src/Personnel/pages/Home.vue +++ b/VueApp/src/Personnel/pages/Home.vue @@ -1,11 +1,6 @@ diff --git a/VueApp/src/Personnel/pages/PersonnelReport.vue b/VueApp/src/Personnel/pages/PersonnelReport.vue deleted file mode 100644 index 907b9a8e0..000000000 --- a/VueApp/src/Personnel/pages/PersonnelReport.vue +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/VueApp/src/Personnel/router/routes.ts b/VueApp/src/Personnel/router/routes.ts index d40168387..9de63e03c 100644 --- a/VueApp/src/Personnel/router/routes.ts +++ b/VueApp/src/Personnel/router/routes.ts @@ -47,14 +47,6 @@ const routes = [ component: () => import("@/Personnel/pages/SVMPhonesMaintain.vue"), name: "MaintainSchoolwidePhones", }, - { - // Any Personnel report, by key. The API enforces each report's own permissions, so the - // route needs none of its own; a report the user can't run shows as not available. - path: "/Personnel/Reports/:key", - meta: { layout: ViperLayout, allowUnAuth: false }, - component: () => import("@/Personnel/pages/PersonnelReport.vue"), - name: "PersonnelReport", - }, { path: "/:catchAll(.*)*", meta: { layout: ViperLayout }, 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.test.ts b/VueApp/src/Reports/__tests__/report-admin-edit.test.ts new file mode 100644 index 000000000..c761d5b2a --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-edit.test.ts @@ -0,0 +1,150 @@ +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") + }) +}) 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..0e2439c07 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-list.test.ts @@ -0,0 +1,74 @@ +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" + +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.") + }) +}) 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..69bc55acb --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-panels.test.ts @@ -0,0 +1,192 @@ +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" + +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" }]) + }) + + 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") + }) +}) + +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() + }) +}) + +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..0950dcb5d --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts @@ -0,0 +1,201 @@ +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 adding = mountParameters([first]) + const changing = mountParameters([first]) + const removing = mountParameters([first]) + + await adding + .findAll("button") + .find((button) => button.text().includes("Add parameter")) + ?.trigger("click") + changing + .findComponent(ReportAdminParameterFields) + .vm.$emit("update:modelValue", { ...first, label: "Department" }) + await removing.get(`[aria-label="Remove Dept"]`).trigger("click") + + expect(lastParameters(adding)).toHaveLength(2) + expect(lastParameters(changing)[0]?.label).toBe("Department") + expect(lastParameters(removing)).toStrictEqual([]) + }) + + 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..7469fcc9c --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-sections.test.ts @@ -0,0 +1,219 @@ +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] = wrapper.findAllComponents({ name: "QInput" }) + + title?.vm.$emit("update:modelValue", "Roster") + await wrapper.setProps({ modelValue: lastForm(wrapper) }) + area?.vm.$emit("update:modelValue", " ") + + expect([lastForm(wrapper).title, lastForm(wrapper).area]).toStrictEqual(["Roster", null]) + }) + + 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.)") + }) +}) + +describe("report columns section", () => { + it("edits a column's heading, format and flags", async () => { + expect.hasAssertions() + const column = newColumn("Name") + const wrapper = mountColumns([column]) + + wrapper.findComponent({ name: "QInput" }).vm.$emit("update:modelValue", "Full name") + await wrapper.setProps({ modelValue: lastColumns(wrapper) }) + wrapper.findAllComponents({ name: "QCheckbox" })[0]?.vm.$emit("update:modelValue", false) + + expect(lastColumns(wrapper)).toStrictEqual([{ ...column, label: "Full name", visible: false }]) + }) + + 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("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" })[1]?.vm.$emit("update:modelValue", true) + const pdf = lastForm(wrapper).allowPdf + wrapper.findAllComponents({ name: "QInput" }).at(-1)?.vm.$emit("update:modelValue", " ") + + expect([sort, pdf, lastForm(wrapper).sensitiveNotice]).toStrictEqual([null, true, null]) + }) + + 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..cfc6edc01 --- /dev/null +++ b/VueApp/src/Reports/__tests__/report-admin-service.test.ts @@ -0,0 +1,169 @@ +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("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)) + }) +}) + +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..9ae271710 --- /dev/null +++ b/VueApp/src/Reports/__tests__/router.test.ts @@ -0,0 +1,114 @@ +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: "" }), +})) + +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..04410e4ac --- /dev/null +++ b/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts @@ -0,0 +1,274 @@ +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(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]) + }) +}) + +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", async () => { + expect.hasAssertions() + const state = await edit() + service.restore.mockResolvedValue(saved) + state.form.value = { ...state.form.value, title: "Mine" } + + await state.setDeleted(false) + + expect([state.form.value.title, state.isDirty.value]).toStrictEqual(["Mine", 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]) + }) +}) 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..b696cbd3e --- /dev/null +++ b/VueApp/src/Reports/admin/report-admin-service.ts @@ -0,0 +1,126 @@ +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 } +export type { ReportSaveOutcome } 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..49b70d51e --- /dev/null +++ b/VueApp/src/Reports/admin/use-report-admin-edit.ts @@ -0,0 +1,184 @@ +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, so the form takes the + * new version's time; unsaved edits stay as they are. + */ + 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 + } + const clean = !isDirty.value + definition.value = updated + form.value = { ...form.value, lastModifiedOn: updated.report.lastModifiedOn } + if (clean) { + 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/ReportAdminHistory.vue b/VueApp/src/Reports/components/ReportAdminHistory.vue new file mode 100644 index 000000000..4f638569c --- /dev/null +++ b/VueApp/src/Reports/components/ReportAdminHistory.vue @@ -0,0 +1,100 @@ + + + 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..70a1771a0 --- /dev/null +++ b/VueApp/src/Reports/pages/ReportAdminEdit.vue @@ -0,0 +1,169 @@ + + + diff --git a/VueApp/src/Reports/pages/ReportAdminList.vue b/VueApp/src/Reports/pages/ReportAdminList.vue new file mode 100644 index 000000000..47e48d171 --- /dev/null +++ b/VueApp/src/Reports/pages/ReportAdminList.vue @@ -0,0 +1,134 @@ + + + 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..d2718fe2a --- /dev/null +++ b/VueApp/src/Reports/router/index.ts @@ -0,0 +1,37 @@ +import { createSpaRouter } from "@/shared/create-spa-router" +import type { NavigationGuard, RouteLocationNormalized } from "vue-router" +import { routes } from "./routes" +import { useRequireLogin } from "@/composables/RequireLogin" +import { useUserStore } from "@/store/UserStore" +import { checkHasOnePermission } from "@/composables/CheckPagePermission" + +const router = createSpaRouter(routes) + +/** + * Signs the visitor in. Which reports they may see is decided by the API, report by report, so + * the only permissions loaded are the Report Builder's own (SVMSecure.Reports.*). + * 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.Reports") + return loginResult === null || loginResult +} + +// 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/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..268476cea --- /dev/null +++ b/VueApp/src/shared/report-builder/ReportViewer.vue @@ -0,0 +1,144 @@ + + + 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..ccdd02113 --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-format.test.ts @@ -0,0 +1,68 @@ +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.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..ccde8673a --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts @@ -0,0 +1,61 @@ +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"]]) + }) +}) 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..608d798e4 --- /dev/null +++ b/VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts @@ -0,0 +1,374 @@ +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("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) + }) +}) + +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..615767926 --- /dev/null +++ b/VueApp/src/shared/report-builder/report-builder-format.ts @@ -0,0 +1,93 @@ +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"}` +} + +/** + * 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: + * a text column only reformats full date-times, which only real date values arrive as. + */ +function formatIsoDate(value: string, format: ReportColumnFormat): string | null { + const parts = ISO_DATE_TIME.exec(value)?.groups + const isDateFormat = format === "Date" || format === "DateTime" + if (!parts || (!isDateFormat && parts.hour === undefined)) { + 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..2639f01eb --- /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 { ReportExportOutcome, 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/src/shared/reports/ReportCatalog.vue b/VueApp/src/shared/reports/ReportCatalog.vue deleted file mode 100644 index dad018cc5..000000000 --- a/VueApp/src/shared/reports/ReportCatalog.vue +++ /dev/null @@ -1,96 +0,0 @@ - - - diff --git a/VueApp/src/shared/reports/ReportGroupTable.vue b/VueApp/src/shared/reports/ReportGroupTable.vue deleted file mode 100644 index 5b1c456f4..000000000 --- a/VueApp/src/shared/reports/ReportGroupTable.vue +++ /dev/null @@ -1,65 +0,0 @@ - - - - - diff --git a/VueApp/src/shared/reports/ReportNumberTable.vue b/VueApp/src/shared/reports/ReportNumberTable.vue deleted file mode 100644 index 714437083..000000000 --- a/VueApp/src/shared/reports/ReportNumberTable.vue +++ /dev/null @@ -1,59 +0,0 @@ - - - diff --git a/VueApp/src/shared/reports/ReportParameterForm.vue b/VueApp/src/shared/reports/ReportParameterForm.vue deleted file mode 100644 index df4d028cc..000000000 --- a/VueApp/src/shared/reports/ReportParameterForm.vue +++ /dev/null @@ -1,123 +0,0 @@ - - - diff --git a/VueApp/src/shared/reports/ReportRunner.vue b/VueApp/src/shared/reports/ReportRunner.vue deleted file mode 100644 index ae2da367a..000000000 --- a/VueApp/src/shared/reports/ReportRunner.vue +++ /dev/null @@ -1,124 +0,0 @@ - - - diff --git a/VueApp/src/shared/reports/ReportTotals.vue b/VueApp/src/shared/reports/ReportTotals.vue deleted file mode 100644 index 0878b231d..000000000 --- a/VueApp/src/shared/reports/ReportTotals.vue +++ /dev/null @@ -1,52 +0,0 @@ - - - - - diff --git a/VueApp/src/shared/reports/ReportView.vue b/VueApp/src/shared/reports/ReportView.vue deleted file mode 100644 index 0ee0e5e73..000000000 --- a/VueApp/src/shared/reports/ReportView.vue +++ /dev/null @@ -1,86 +0,0 @@ - - - diff --git a/VueApp/src/shared/reports/__tests__/report-catalog.test.ts b/VueApp/src/shared/reports/__tests__/report-catalog.test.ts deleted file mode 100644 index d06b472cb..000000000 --- a/VueApp/src/shared/reports/__tests__/report-catalog.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { flushPromises, mount } from "@vue/test-utils" -import { Quasar } from "quasar" -import { createMemoryHistory, createRouter } from "vue-router" -import ReportCatalog from "../ReportCatalog.vue" -import { reportService } from "../report-service" -import type { ReportCatalogItem } from "../report-types" - -/** - * ReportCatalog lists an area's reports as links to the area's report route. It stays visible - * while loading and after a failed load, but disappears for a user who may run none of the - * area's reports. - */ - -vi.mock("../report-service", () => ({ - reportService: { getCatalog: vi.fn<(...args: unknown[]) => unknown>() }, -})) - -const built: ReportCatalogItem = { - key: "personnel.employees-on-leave", - title: "Employees on Leave", - area: "Personnel", - description: "Faculty and staff on leave.", - available: true, -} - -const planned: ReportCatalogItem = { - key: "personnel.visa-audit", - title: "Visa Audit", - area: "Personnel", - description: "Visa types and end dates.", - available: false, -} - -// Never resolves, to hold the component in its loading state. -function neverResolves(): Promise { - // eslint-disable-next-line avoid-new, no-empty-function -- deliberately pending forever, to simulate an in-flight fetch - return new Promise(() => {}) -} - -async function mountCatalog(props: Record = {}) { - const router = createRouter({ - history: createMemoryHistory(), - routes: [ - { path: "/", component: { template: "
" } }, - { path: "/reports/:key", component: { template: "
" }, name: "TestReport" }, - ], - }) - await router.push("/") - const wrapper = mount(ReportCatalog, { - props: { area: "Personnel", reportRoute: "TestReport", ...props }, - global: { plugins: [[Quasar, {}], router] }, - }) - await flushPromises() - return wrapper -} - -describe("ReportCatalog", () => { - it("asks for the catalog of its area", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockResolvedValue([]) - - await mountCatalog({ area: "Effort" }) - - expect(reportService.getCatalog).toHaveBeenCalledWith("Effort") - }) - - it("links each report to the area's report route", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockResolvedValue([built, planned]) - - const wrapper = await mountCatalog() - const links = wrapper.findAll("a") - - expect(links.map((link) => link.attributes("href"))).toStrictEqual([ - "/reports/personnel.employees-on-leave", - "/reports/personnel.visa-audit", - ]) - expect(links.map((link) => link.attributes("role"))).toStrictEqual(["link", "link"]) - expect(links[0]?.text()).toContain("Faculty and staff on leave.") - }) - - it("marks only planned reports as coming soon", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockResolvedValue([built, planned]) - - const wrapper = await mountCatalog() - const links = wrapper.findAll("a") - - expect(links[0]?.text()).not.toContain("Coming soon") - expect(links[1]?.text()).toContain("Coming soon") - }) - - it("labels the section with its heading", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockResolvedValue([built]) - - const wrapper = await mountCatalog({ heading: "Personnel reports" }) - const heading = wrapper.get("h2") - - expect(heading.text()).toBe("Personnel reports") - expect(wrapper.get("section").attributes("aria-labelledby")).toBe(heading.attributes("id")) - }) - - it("uses a default heading", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockResolvedValue([built]) - - const wrapper = await mountCatalog() - - expect(wrapper.get("h2").text()).toBe("Reports") - }) - - it("announces that it is loading until the catalog arrives", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockReturnValue(neverResolves()) - - const wrapper = await mountCatalog() - - expect(wrapper.get("[role='status']").text()).toBe("Loading reports") - expect(wrapper.find("a").exists()).toBeFalsy() - }) - - it("reports a failed load instead of hiding", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockResolvedValue(null) - - const wrapper = await mountCatalog() - - expect(wrapper.find("h2").exists()).toBeTruthy() - expect(wrapper.text()).toContain("The report list could not be loaded.") - }) - - it("renders nothing when the user may run none of the area's reports", async () => { - expect.hasAssertions() - vi.mocked(reportService.getCatalog).mockResolvedValue([]) - - const wrapper = await mountCatalog() - - expect(wrapper.find("section").exists()).toBeFalsy() - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-columns.test.ts b/VueApp/src/shared/reports/__tests__/report-columns.test.ts deleted file mode 100644 index 31563c7fe..000000000 --- a/VueApp/src/shared/reports/__tests__/report-columns.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { NOTES_COLUMN, ROW_NUMBER_COLUMN, hasNotes, toTableColumns } from "../report-columns" -import type { ReportResult, ReportRowResult } from "../report-types" - -const ada: ReportRowResult = { - number: 1, - values: { name: "Ada", salary: 120_000 }, - flags: [{ kind: "Highlight", tone: "Warning", label: "60+", columnKey: null }], -} -const bo: ReportRowResult = { number: 2, values: { name: "Bo" }, flags: [] } - -function resultWith(rows: ReportRowResult[], rowNumbers = false): ReportResult { - return { - key: "test.sample", - title: "Sample", - generatedAt: "2026-09-30T14:00:00-07:00", - rowCount: rows.length, - rowNumbers, - columns: [ - { key: "name", label: "Name", format: "Text", align: "Left", decimals: null }, - { key: "salary", label: "Salary", format: "Currency", align: "Right", decimals: 2 }, - ], - summary: [], - groups: [{ label: null, rows, subtotals: [], charts: [] }], - totals: [], - pivots: [], - charts: [], - } -} - -describe("toTableColumns()", () => { - it("maps each report column to a sortable table column", () => { - const [name, salary] = toTableColumns(resultWith([bo])) - - expect(name).toMatchObject({ name: "name", label: "Name", align: "left", sortable: true }) - expect(salary).toMatchObject({ name: "salary", label: "Salary", align: "right" }) - }) - - it("reads values by column key, treating missing values as empty", () => { - const [name, salary] = toTableColumns(resultWith([bo])) - const readName = name?.field as (row: ReportRowResult) => unknown - const readSalary = salary?.field as (row: ReportRowResult) => unknown - - expect(readName(ada)).toBe("Ada") - expect(readSalary(bo)).toBeNull() - }) - - it("formats values like the exports", () => { - const [, salary] = toTableColumns(resultWith([bo])) - - expect(salary?.format?.(120_000, ada)).toBe("$120,000.00") - }) - - it("adds a row number column first when the report numbers its rows", () => { - const columns = toTableColumns(resultWith([bo], true)) - const [numberColumn] = columns - const readNumber = numberColumn?.field as (row: ReportRowResult) => unknown - - expect(numberColumn).toMatchObject({ name: ROW_NUMBER_COLUMN, label: "#", align: "right" }) - expect(readNumber(bo)).toBe(2) - }) - - it("adds a Notes column last when any row has a flag", () => { - const columns = toTableColumns(resultWith([ada, bo])) - const notes = columns.at(-1) - const readNotes = notes?.field as (row: ReportRowResult) => unknown - - expect(notes).toMatchObject({ name: NOTES_COLUMN, label: "Notes" }) - expect(readNotes(ada)).toBe("60+") - }) - - it("leaves out the extra columns when they aren't needed", () => { - expect(toTableColumns(resultWith([bo])).map((column) => column.name)).toStrictEqual(["name", "salary"]) - }) -}) - -describe("hasNotes()", () => { - it("is true only when a row has a flag", () => { - expect(hasNotes(resultWith([bo, ada]))).toBeTruthy() - expect(hasNotes(resultWith([bo]))).toBeFalsy() - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-fixtures.ts b/VueApp/src/shared/reports/__tests__/report-fixtures.ts deleted file mode 100644 index 20fa2fdf0..000000000 --- a/VueApp/src/shared/reports/__tests__/report-fixtures.ts +++ /dev/null @@ -1,66 +0,0 @@ -import type { - ReportChartResult, - ReportGroupResult, - ReportPivotResult, - ReportResult, - ReportRowResult, -} from "../report-types" - -/** A small grouped result with every kind of section, shared by the component tests. */ - -const ada: ReportRowResult = { - number: 1, - values: { name: "Ada", salary: 120_000, hired: "1995-07-01" }, - flags: [ - { kind: "Highlight", tone: "Warning", label: "60+", columnKey: null }, - { kind: "Badge", tone: "Info", label: "Emeritus", columnKey: null }, - ], -} - -const bo: ReportRowResult = { - number: 2, - values: { name: "Bo", salary: 90_000, hired: null }, - flags: [{ kind: "Highlight", tone: "Negative", label: "Retirement age", columnKey: "salary" }], -} - -const vmeGroup: ReportGroupResult = { - label: "VME", - rows: [ada, bo], - subtotals: [{ label: "Salaries", columnKey: "salary", value: 210_000 }], - charts: [{ title: "Ages: VME", kind: "Bar", points: [{ category: "60+", value: 1 }] }], -} - -const samplePivot: ReportPivotResult = { - title: "Age by department", - columnKeys: ["APC", "VME"], - rows: [{ key: "60+", values: [0, 1], total: 1 }], - columnTotals: [1, 2], - grandTotal: 3, -} - -const sampleChart: ReportChartResult = { title: "Ages", kind: "Pie", points: [{ category: "Under 30", value: 2 }] } - -const cy: ReportRowResult = { number: 3, values: { name: "Cy", salary: 150_000, hired: "2010-01-15" }, flags: [] } - -function sampleResult(overrides: Partial = {}): ReportResult { - return { - key: "test.sample", - title: "Sample report", - generatedAt: "2026-09-30T14:05:00", - rowCount: 3, - rowNumbers: true, - columns: [ - { key: "name", label: "Name", format: "Text", align: "Left", decimals: null }, - { key: "salary", label: "Salary", format: "Currency", align: "Right", decimals: 2 }, - { key: "hired", label: "Hired", format: "Date", align: "Left", decimals: null }, - ], - summary: [{ label: "People", columnKey: null, value: 3 }], - groups: [vmeGroup, { label: "APC", rows: [cy], subtotals: [], charts: [] }], - totals: [{ label: "All salaries", columnKey: "salary", value: 360_000 }], - pivots: [samplePivot], - charts: [sampleChart], - ...overrides, - } -} - -export { ada, bo, cy, sampleChart, samplePivot, sampleResult, vmeGroup } diff --git a/VueApp/src/shared/reports/__tests__/report-format.test.ts b/VueApp/src/shared/reports/__tests__/report-format.test.ts deleted file mode 100644 index a5324684b..000000000 --- a/VueApp/src/shared/reports/__tests__/report-format.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { - formatGeneratedAt, - formatPlainNumber, - formatReportDate, - formatReportTotal, - formatReportValue, - isNumericFormat, -} from "../report-format" -import type { ReportColumnFormat, ReportColumnMetadata } from "../report-types" - -/** - * These cases mirror ReportValueFormatterTests and ReportExportTextTests on the server, so the - * screen shows values the same way the CSV and PDF exports do. - */ - -function column(format: ReportColumnFormat, decimals: number | null = null, key = "value"): ReportColumnMetadata { - return { key, label: "Value", format, align: "Right", decimals } -} - -describe("formatReportValue()", () => { - it.each([ - [1234.5, column("Number"), "1,235"], - [1234.5, column("Number", 2), "1,234.50"], - [120_000, column("Currency", 2), "$120,000.00"], - [0.125, column("Percent", 1), "12.5%"], - [0.5, column("Percent"), "50%"], - [61, column("Text"), "61"], - ])("formats the number %s for a %o column as %s", (value, format, expected) => { - expect(formatReportValue(value, format)).toBe(expected) - }) - - it.each([ - [null, ""], - [undefined, ""], - [["Asian", "White"], "Asian, White"], - [true, "Yes"], - [false, "No"], - ["pending", "pending"], - ])("formats %o as %o", (value, expected) => { - expect(formatReportValue(value, column("Text"))).toBe(expected) - }) - - it("formats dates only in date columns", () => { - expect(formatReportValue("2026-07-01", column("Date"))).toBe("07/01/2026") - expect(formatReportValue("2026-07-01", column("Text"))).toBe("2026-07-01") - }) -}) - -describe("formatReportDate()", () => { - it.each([ - ["2026-07-01", "07/01/2026"], - ["1995-07-01T00:00:00", "07/01/1995"], - ["not a date", "not a date"], - ])("formats %s as %s", (value, expected) => { - expect(formatReportDate(value)).toBe(expected) - }) -}) - -describe("formatReportTotal()", () => { - const columns = [column("Currency", 2, "salary"), column("Text", null, "name")] - - it("formats a total like the column it sits under", () => { - expect(formatReportTotal({ label: "Salaries", columnKey: "salary", value: 430_000 }, columns)).toBe( - "$430,000.00", - ) - expect(formatReportTotal({ label: "People", columnKey: "name", value: 5 }, columns)).toBe("5") - }) - - it("formats a total without a column as a plain number", () => { - expect(formatReportTotal({ label: "Average age", columnKey: null, value: 48.256 }, columns)).toBe("48.26") - expect(formatReportTotal({ label: "Hidden", columnKey: "ssn", value: 1234 }, columns)).toBe("1,234") - }) - - it("leaves a missing total blank", () => { - expect(formatReportTotal({ label: "Unknown", columnKey: "salary", value: null }, columns)).toBe("") - }) -}) - -describe("formatPlainNumber()", () => { - it("uses separators and up to two decimals, and blanks null", () => { - expect(formatPlainNumber(1234.5)).toBe("1,234.5") - expect(formatPlainNumber(null)).toBe("") - }) -}) - -describe("isNumericFormat()", () => { - it.each([ - ["Number", true], - ["Currency", true], - ["Percent", true], - ["Text", false], - ["Date", false], - ["List", false], - ] as const)("treats %s as numeric: %s", (format, expected) => { - expect(isNumericFormat(format)).toBe(expected) - }) -}) - -describe("formatGeneratedAt()", () => { - it("matches the export header wording", () => { - const local = new Date(2026, 8, 30, 14, 5) - - expect(formatGeneratedAt(local.toISOString())).toBe("Generated 09/30/2026 2:05 PM") - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-number-tables.test.ts b/VueApp/src/shared/reports/__tests__/report-number-tables.test.ts deleted file mode 100644 index 662191207..000000000 --- a/VueApp/src/shared/reports/__tests__/report-number-tables.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { chartTable, pivotTable } from "../report-number-tables" -import { sampleChart, samplePivot } from "./report-fixtures" - -describe("pivotTable()", () => { - it("adds a total to every row and a totals row, as the PDF export does", () => { - expect.hasAssertions() - expect(pivotTable(samplePivot)).toStrictEqual({ - headers: ["Category", "APC", "VME", "Total"], - rows: [{ label: "60+", values: [0, 1, 1] }], - total: { label: "Total", values: [1, 2, 3] }, - }) - }) -}) - -describe("chartTable()", () => { - it("lists each chart point as a category and value", () => { - expect.hasAssertions() - expect(chartTable(sampleChart)).toStrictEqual({ - headers: ["Category", "Value"], - rows: [{ label: "Under 30", values: [2] }], - total: null, - }) - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts b/VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts deleted file mode 100644 index e8f2074cc..000000000 --- a/VueApp/src/shared/reports/__tests__/report-parameter-form.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { flushPromises, mount } from "@vue/test-utils" -import { QSelect, Quasar } from "quasar" -import ReportParameterForm from "../ReportParameterForm.vue" -import type { ReportParameterMetadata, ReportParameterType, ReportParameterValues } from "../report-types" - -function parameter(name: string, type: ReportParameterType, required = false): ReportParameterMetadata { - return { - name, - label: name, - type, - required, - defaultValue: null, - options: [ - { value: "S", label: "Senate" }, - { value: "F", label: "Federation" }, - ], - } -} - -const parameters = [ - parameter("facultyType", "Choice", true), - parameter("departments", "MultiChoice"), - parameter("startDate", "Date"), - parameter("search", "Text"), - parameter("minimumAge", "Number"), - parameter("includeEmeriti", "Boolean"), -] - -const empty: ReportParameterValues = { - facultyType: null, - departments: [], - startDate: null, - search: null, - minimumAge: null, - includeEmeriti: null, -} - -function mountForm(modelValue: ReportParameterValues = empty) { - return mount(ReportParameterForm, { - props: { parameters, modelValue, running: false }, - global: { plugins: [[Quasar, {}]] }, - }) -} - -function lastModel(wrapper: ReturnType): ReportParameterValues | undefined { - return wrapper.emitted("update:modelValue")?.at(-1)?.[0] as ReportParameterValues | undefined -} - -describe("ReportParameterForm", () => { - it("renders an input for each parameter type", () => { - expect.hasAssertions() - const wrapper = mountForm() - - expect(wrapper.findAll(".q-select")).toHaveLength(2) - expect(wrapper.find("input[type='date']").exists()).toBeTruthy() - expect(wrapper.find("input[type='text']").exists()).toBeTruthy() - expect(wrapper.find("input[type='number']").exists()).toBeTruthy() - expect(wrapper.find(".q-checkbox").exists()).toBeTruthy() - }) - - it("marks required fields in their labels", () => { - expect.hasAssertions() - const wrapper = mountForm() - - expect(wrapper.text()).toContain("facultyType *") - expect(wrapper.text()).not.toContain("search *") - }) - - it("shows the current text, date and number values", () => { - expect.hasAssertions() - const wrapper = mountForm({ ...empty, startDate: "2026-07-01", search: "smith", minimumAge: 60 }) - - expect((wrapper.get("input[type='date']").element as HTMLInputElement).value).toBe("2026-07-01") - expect((wrapper.get("input[type='text']").element as HTMLInputElement).value).toBe("smith") - expect((wrapper.get("input[type='number']").element as HTMLInputElement).value).toBe("60") - }) - - it("stores numbers as numbers and cleared inputs as null", async () => { - expect.hasAssertions() - const wrapper = mountForm() - const input = wrapper.get("input[type='number']") - - await input.setValue("60") - expect(lastModel(wrapper)?.minimumAge).toBe(60) - await input.setValue("") - expect(lastModel(wrapper)?.minimumAge).toBeNull() - }) - - it("keeps text and dates as strings", async () => { - expect.hasAssertions() - const wrapper = mountForm() - - await wrapper.get("input[type='date']").setValue("2026-07-01") - expect(lastModel(wrapper)?.startDate).toBe("2026-07-01") - await wrapper.get("input[type='text']").setValue("smith") - expect(lastModel(wrapper)?.search).toBe("smith") - }) - - it("stores the chosen options of a select", () => { - expect.hasAssertions() - const wrapper = mountForm() - const [choice, multiChoice] = wrapper.findAllComponents(QSelect) - - choice?.vm.$emit("update:modelValue", "F") - expect(lastModel(wrapper)?.facultyType).toBe("F") - multiChoice?.vm.$emit("update:modelValue", ["S", "F"]) - expect(lastModel(wrapper)?.departments).toStrictEqual(["S", "F"]) - }) - - it("updates a checkbox value without losing the others", async () => { - expect.hasAssertions() - const wrapper = mountForm({ ...empty, search: "smith" }) - - await wrapper.get(".q-checkbox").trigger("click") - - expect(lastModel(wrapper)).toStrictEqual({ ...empty, search: "smith", includeEmeriti: true }) - }) - - it("blocks submitting until required fields are filled", async () => { - expect.hasAssertions() - const wrapper = mountForm() - - await wrapper.get("form").trigger("submit") - await flushPromises() - - expect(wrapper.emitted("submit")).toBeUndefined() - expect(wrapper.text()).toContain("facultyType is required.") - }) - - it("submits when the required fields are filled", async () => { - expect.hasAssertions() - const wrapper = mountForm({ ...empty, facultyType: "S" }) - - await wrapper.get("form").trigger("submit") - await flushPromises() - - expect(wrapper.emitted("submit")).toHaveLength(1) - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-query.test.ts b/VueApp/src/shared/reports/__tests__/report-query.test.ts deleted file mode 100644 index 80a206064..000000000 --- a/VueApp/src/shared/reports/__tests__/report-query.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { hasQueryParameters, initialValues, toQuery, toRequestBody } from "../report-query" -import type { ReportParameterMetadata, ReportParameterType, ReportParameterValue } from "../report-types" - -function parameter( - name: string, - type: ReportParameterType, - defaultValue: ReportParameterValue = null, -): ReportParameterMetadata { - return { name, label: name, type, required: false, defaultValue, options: [] } -} - -const parameters = [ - parameter("facultyType", "Choice", "S"), - parameter("departments", "MultiChoice"), - parameter("startDate", "Date", "2026-07-01"), - parameter("search", "Text"), - parameter("minimumAge", "Number"), - parameter("includeEmeriti", "Boolean"), -] - -describe("initialValues()", () => { - it("uses the report's defaults, or empty values, when the query is empty", () => { - expect(initialValues(parameters, {})).toStrictEqual({ - facultyType: "S", - departments: [], - startDate: "2026-07-01", - search: null, - minimumAge: null, - includeEmeriti: null, - }) - }) - - it("reads each parameter type from the query", () => { - const values = initialValues(parameters, { - facultyType: "F", - departments: ["VME", "APC"], - startDate: "2025-07-01", - search: "smith", - minimumAge: "60", - includeEmeriti: "true", - }) - - expect(values).toStrictEqual({ - facultyType: "F", - departments: ["VME", "APC"], - startDate: "2025-07-01", - search: "smith", - minimumAge: 60, - includeEmeriti: true, - }) - }) - - it("accepts a single value for a list and a list for a single value", () => { - const values = initialValues(parameters, { departments: "VME", search: ["first", "second"] }) - - expect(values.departments).toStrictEqual(["VME"]) - expect(values.search).toBe("first") - }) - - it.each([ - ["minimumAge", "old", null], - ["minimumAge", "", null], - ["minimumAge", null, null], - ["includeEmeriti", "false", false], - ["includeEmeriti", null, null], - ["facultyType", null, null], - ["startDate", null, null], - ["search", null, null], - ["departments", null, []], - ])("reads %s=%o as %o", (name, raw, expected) => { - expect(initialValues(parameters, { [name]: raw })[name]).toStrictEqual(expected) - }) -}) - -describe("toQuery()", () => { - it("writes the non-empty values, repeating the key for lists", () => { - const query = toQuery(parameters, { - facultyType: "F", - departments: ["VME", "APC"], - startDate: "2025-07-01", - search: "", - minimumAge: 60, - includeEmeriti: false, - }) - - expect(query).toStrictEqual({ - facultyType: "F", - departments: ["VME", "APC"], - startDate: "2025-07-01", - minimumAge: "60", - includeEmeriti: "false", - }) - }) - - it("round-trips through initialValues", () => { - const values = { ...initialValues(parameters, {}), minimumAge: 45, includeEmeriti: true } - - expect(initialValues(parameters, toQuery(parameters, values) as never)).toStrictEqual(values) - }) -}) - -describe("toRequestBody()", () => { - it("sends only the report's non-empty parameters", () => { - const body = toRequestBody(parameters, { - facultyType: "F", - departments: [], - search: "smith", - includeEmeriti: false, - unknown: "ignored", - }) - - expect(body).toStrictEqual({ facultyType: "F", search: "smith", includeEmeriti: false }) - }) -}) - -describe("hasQueryParameters()", () => { - it("is true when the query names one of the report's parameters", () => { - expect(hasQueryParameters(parameters, { search: "smith" })).toBeTruthy() - expect(hasQueryParameters(parameters, { tab: "2" })).toBeFalsy() - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-runner.test.ts b/VueApp/src/shared/reports/__tests__/report-runner.test.ts deleted file mode 100644 index 79454609e..000000000 --- a/VueApp/src/shared/reports/__tests__/report-runner.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { flushPromises, mount } from "@vue/test-utils" -import { Quasar } from "quasar" -import { ref } from "vue" -import ReportRunner from "../ReportRunner.vue" -import ReportParameterForm from "../ReportParameterForm.vue" -import { sampleResult } from "./report-fixtures" -import type { ReportDefinitionMetadata, ReportExportFormat, ReportResult } from "../report-types" - -/** - * ReportRunner only arranges what useReport provides, so useReport is replaced by plain refs - * the tests set directly. - */ - -const { state, keyGetter } = vi.hoisted(() => ({ - state: {} as Record, - keyGetter: { current: null as (() => string) | null }, -})) -vi.mock("../use-report", () => ({ - useReport: (key: () => string) => { - keyGetter.current = key - return state - }, -})) - -const definition: ReportDefinitionMetadata = { - key: "test.sample", - title: "Sample report", - area: "Test", - description: "A report used by tests.", - parameters: [{ name: "search", label: "Search", type: "Text", required: false, defaultValue: null, options: [] }], - columns: [], -} - -function setState(overrides: Record = {}) { - const values = { - definition: ref(definition), - values: ref({ search: null }), - result: ref(null), - errors: ref([]), - loading: ref(false), - notFound: ref(false), - running: ref(false), - exporting: ref(null), - run: vi.fn<() => Promise>(), - exportAs: vi.fn<(format: ReportExportFormat) => Promise>(), - } - Object.assign(state, values, overrides) - return values -} - -function mountRunner() { - return mount(ReportRunner, { - props: { reportKey: "test.sample", parentLabel: "Test", parentTo: "/" }, - global: { plugins: [[Quasar, {}]], stubs: { RouterLink: { template: "" } } }, - }) -} - -describe("ReportRunner - states", () => { - it("announces that the report is loading", () => { - expect.hasAssertions() - setState({ loading: ref(true) }) - - expect(mountRunner().get("[role='status']").text()).toBe("Loading report") - }) - - it("explains a report that isn't available", () => { - expect.hasAssertions() - setState({ notFound: ref(true), definition: ref(null) }) - const wrapper = mountRunner() - - expect(wrapper.get("h1").text()).toContain("Report not available") - expect(wrapper.text()).toContain("may not be built yet") - }) - - it("shows the title, description and parameter form", () => { - expect.hasAssertions() - setState() - const wrapper = mountRunner() - - expect(wrapper.get("h1").text()).toContain("Sample report") - expect(wrapper.text()).toContain("A report used by tests.") - expect(wrapper.find("form").exists()).toBeTruthy() - }) - - it("loads the report named by its key", () => { - expect.hasAssertions() - setState() - mountRunner() - - expect(keyGetter.current?.()).toBe("test.sample") - }) - - it("keeps the form's values in the report state", () => { - expect.hasAssertions() - const { values } = setState() - const wrapper = mountRunner() - - wrapper.findComponent(ReportParameterForm).vm.$emit("update:modelValue", { search: "smith" }) - - expect(values.value).toStrictEqual({ search: "smith" }) - }) - - it("leaves out the form for a report without parameters", () => { - expect.hasAssertions() - setState({ definition: ref({ ...definition, parameters: [] }) }) - - expect(mountRunner().find("form").exists()).toBeFalsy() - }) - - it("lists the server's messages", () => { - expect.hasAssertions() - setState({ errors: ref(["Start date is required.", "End date is required."]) }) - - expect( - mountRunner() - .findAll("li") - .map((item) => item.text()), - ).toStrictEqual(["Start date is required.", "End date is required."]) - }) - - it("announces a run in progress", () => { - expect.hasAssertions() - setState({ running: ref(true) }) - - expect(mountRunner().get("[role='status']").text()).toBe("Running report") - }) -}) - -describe("ReportRunner - results and exports", () => { - it("runs the report when the form is submitted", async () => { - expect.hasAssertions() - const { run } = setState() - const wrapper = mountRunner() - - await wrapper.get("form").trigger("submit") - await flushPromises() - - expect(run).toHaveBeenCalledOnce() - }) - - it("shows the result with its export buttons", () => { - expect.hasAssertions() - setState({ result: ref(sampleResult()) }) - const wrapper = mountRunner() - - expect(wrapper.find(".report-view").exists()).toBeTruthy() - expect(wrapper.find(".export-excel").exists()).toBeTruthy() - expect(wrapper.find(".export-pdf").exists()).toBeTruthy() - }) - - it.each([ - [".export-excel", "xlsx"], - [".export-pdf", "pdf"], - ])("exports from %s as %s", async (selector, format) => { - expect.hasAssertions() - const { exportAs } = setState({ result: ref(sampleResult()) }) - - await mountRunner().get(selector).trigger("click") - - expect(exportAs).toHaveBeenCalledWith(format) - }) - - it("shows which export is in progress and blocks the others", () => { - expect.hasAssertions() - setState({ result: ref(sampleResult()), exporting: ref("csv") }) - const wrapper = mountRunner() - const csv = wrapper.findAll("button").find((button) => button.text().endsWith("CSV")) - - expect(csv?.find(".q-spinner").exists()).toBeTruthy() - expect(wrapper.get(".export-excel").attributes("disabled")).toBeDefined() - }) - - it("exports CSV from its own button", async () => { - expect.hasAssertions() - const { exportAs } = setState({ result: ref(sampleResult()) }) - const wrapper = mountRunner() - const csv = wrapper.findAll("button").find((button) => button.text().endsWith("CSV")) - - await csv?.trigger("click") - - expect(exportAs).toHaveBeenCalledWith("csv") - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-service.test.ts b/VueApp/src/shared/reports/__tests__/report-service.test.ts deleted file mode 100644 index 843ab9521..000000000 --- a/VueApp/src/shared/reports/__tests__/report-service.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { reportService } from "../report-service" -import type { ReportDefinitionMetadata, ReportResult } from "../report-types" - -/** - * The service returns null or an outcome instead of throwing, so pages can tell "failed" apart - * from "empty": ReportCatalog shows an error instead of hiding, and the report page shows the - * server's validation 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 catalog = [ - { - key: "personnel.faculty-profile", - title: "Faculty Profile", - area: "Personnel", - description: "Faculty by department.", - available: false, - }, -] - -const definition: ReportDefinitionMetadata = { - key: "personnel.employees-on-leave", - title: "Employees on Leave", - area: "Personnel", - description: "Faculty and staff on leave.", - parameters: [], - columns: [], -} - -const result = { key: definition.key, title: definition.title, rowCount: 0 } as ReportResult - -describe("reportService.getCatalog()", () => { - it("returns the catalog for the area", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: true, result: catalog }) - - const catalogResult = await reportService.getCatalog("Personnel") - - expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/reports\?area=Personnel$/u)) - expect(catalogResult).toStrictEqual(catalog) - }) - - it("percent-encodes the area so it stays one query value", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: true, result: [] }) - - await reportService.getCatalog("a&b c") - - expect(mockGet).toHaveBeenCalledWith(expect.stringContaining("?area=a%26b%20c")) - }) - - it("returns an empty list when the user may run none of the area's reports", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: true, result: [] }) - - await expect(reportService.getCatalog("Personnel")).resolves.toStrictEqual([]) - }) - - it("returns null when the request fails", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: false, result: null }) - - await expect(reportService.getCatalog("Personnel")).resolves.toBeNull() - }) - - it("returns null when the response is not a list", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: true, result: { key: "personnel.faculty-profile" } }) - - await expect(reportService.getCatalog("Personnel")).resolves.toBeNull() - }) -}) - -describe("reportService.getDefinition()", () => { - it("returns the report's definition", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: true, result: definition }) - - await expect(reportService.getDefinition("personnel.employees-on-leave")).resolves.toStrictEqual(definition) - expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/reports\/personnel\.employees-on-leave$/u)) - }) - - it("percent-encodes the key so it stays one path segment", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: true, result: definition }) - - await reportService.getDefinition("a/b") - - expect(mockGet).toHaveBeenCalledWith(expect.stringMatching(/reports\/a%2Fb$/u)) - }) - - it("returns null for an unknown, planned or forbidden report", async () => { - expect.hasAssertions() - mockGet.mockResolvedValue({ success: false, result: null, errors: [""] }) - - await expect(reportService.getDefinition("personnel.visa-audit")).resolves.toBeNull() - }) -}) - -describe("reportService.run()", () => { - it("posts the parameters and returns the result", async () => { - expect.hasAssertions() - mockPost.mockResolvedValue({ success: true, result, errors: [] }) - - const outcome = await reportService.run(definition.key, { startDate: "2026-07-01" }) - - expect(mockPost).toHaveBeenCalledWith(expect.stringMatching(/employees-on-leave\/run$/u), { - startDate: "2026-07-01", - }) - expect(outcome).toStrictEqual({ result, errors: [] }) - }) - - it("returns the server's validation messages", async () => { - expect.hasAssertions() - mockPost.mockResolvedValue({ success: false, result: null, errors: ["Start date is required."] }) - - await expect(reportService.run(definition.key, {})).resolves.toStrictEqual({ - result: null, - errors: ["Start date is required."], - }) - }) - - it("falls back to a general message when the server gives none", async () => { - expect.hasAssertions() - mockPost.mockResolvedValue({ success: false, result: null, errors: [""] }) - - await expect(reportService.run(definition.key, {})).resolves.toStrictEqual({ - result: null, - errors: ["The report could not be run."], - }) - }) -}) - -describe("reportService.exportReport()", () => { - it("downloads the file under the server's filename", async () => { - expect.hasAssertions() - const blob = new Blob(["a,b"]) - mockPostForBlob.mockResolvedValue({ blob, filename: "Employees on Leave.csv" }) - - const exported = await reportService.exportReport(definition.key, "csv", { search: "smith" }) - - expect(exported).toBeTruthy() - expect(mockPostForBlob).toHaveBeenCalledWith(expect.stringMatching(/employees-on-leave\/export\/csv$/u), { - search: "smith", - }) - expect(mockDownloadBlob).toHaveBeenCalledWith(blob, "Employees on Leave.csv") - }) - - it("names the file after the report when the server sends no filename", async () => { - expect.hasAssertions() - const blob = new Blob(["%PDF"]) - mockPostForBlob.mockResolvedValue({ blob, filename: null }) - - await reportService.exportReport(definition.key, "pdf", {}) - - expect(mockDownloadBlob).toHaveBeenCalledWith(blob, "personnel.employees-on-leave.pdf") - }) - - it("returns false when the export fails", async () => { - expect.hasAssertions() - mockDownloadBlob.mockClear() - mockPostForBlob.mockRejectedValue(new Error("Bad Request")) - - await expect(reportService.exportReport(definition.key, "xlsx", {})).resolves.toBeFalsy() - expect(mockDownloadBlob).not.toHaveBeenCalled() - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-tables.test.ts b/VueApp/src/shared/reports/__tests__/report-tables.test.ts deleted file mode 100644 index 250349762..000000000 --- a/VueApp/src/shared/reports/__tests__/report-tables.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { mount } from "@vue/test-utils" -import { Quasar } from "quasar" -import ReportGroupTable from "../ReportGroupTable.vue" -import ReportNumberTable from "../ReportNumberTable.vue" -import ReportTotals from "../ReportTotals.vue" -import { ada, bo, sampleResult } from "./report-fixtures" - -/** - * The building blocks of a report on screen. Highlights must carry their label as text (the - * Notes column or a badge), never color alone. - */ - -const global = { plugins: [[Quasar, {}]] as [typeof Quasar, object][] } - -// Sortable headers carry Quasar's sort icon, whose ligature name shows up in the text. -function headerText(wrapper: ReturnType): string[] { - return wrapper.findAll("th").map((th) => th.text().replace("arrow_upward", "")) -} - -function rowCells(wrapper: ReturnType, index: number) { - return wrapper.findAll("tbody tr")[index]?.findAll("td") ?? [] -} - -describe("ReportGroupTable", () => { - it("shows row numbers, formatted values and a Notes column", () => { - expect.hasAssertions() - const wrapper = mount(ReportGroupTable, { props: { result: sampleResult(), rows: [ada, bo] }, global }) - - expect(headerText(wrapper)).toStrictEqual(["#", "Name", "Salary", "Hired", "Notes"]) - expect(rowCells(wrapper, 0).map((td) => td.text())).toStrictEqual([ - "1", - "Ada Emeritus", - "$120,000.00", - "07/01/1995", - "60+; Emeritus", - ]) - }) - - it("tints highlighted cells by tone", () => { - expect.hasAssertions() - const wrapper = mount(ReportGroupTable, { props: { result: sampleResult(), rows: [ada, bo] }, global }) - const [, name] = rowCells(wrapper, 0) - const [, boName, boSalary] = rowCells(wrapper, 1) - - expect(name?.classes()).toContain("report-tone-warning") - expect(boSalary?.classes()).toContain("report-tone-negative") - expect(boName?.classes()).not.toContain("report-tone-negative") - }) - - it("puts badges beside the first column only", () => { - expect.hasAssertions() - const wrapper = mount(ReportGroupTable, { props: { result: sampleResult(), rows: [ada] }, global }) - - expect(wrapper.findAll(".q-badge").map((badge) => badge.text())).toStrictEqual(["Emeritus"]) - }) -}) - -describe("ReportTotals", () => { - it("lists each total with its column's format", () => { - expect.hasAssertions() - const result = sampleResult() - const wrapper = mount(ReportTotals, { props: { totals: result.totals, columns: result.columns } }) - - expect(wrapper.get("dt").text()).toBe("All salaries") - expect(wrapper.get("dd").text()).toBe("$360,000.00") - }) - - it("renders nothing when there are no totals", () => { - expect.hasAssertions() - const wrapper = mount(ReportTotals, { props: { totals: [], columns: [] } }) - - expect(wrapper.find("dl").exists()).toBeFalsy() - }) -}) - -describe("ReportNumberTable", () => { - it("shows each row and a bold totals row", () => { - expect.hasAssertions() - const table = { - headers: ["Category", "APC", "Total"], - rows: [{ label: "60+", values: [1234.5, null] }], - total: { label: "Total", values: [1234.5, 7] }, - } - const wrapper = mount(ReportNumberTable, { props: { table }, global }) - - expect(headerText(wrapper)).toStrictEqual(["Category", "APC", "Total"]) - expect(rowCells(wrapper, 0).map((td) => td.text())).toStrictEqual(["60+", "1,234.5", ""]) - expect(wrapper.get("tr.text-weight-bold").text()).toBe("Total1,234.57") - }) - - it("leaves out the totals row when there is none", () => { - expect.hasAssertions() - const table = { headers: ["Category", "Value"], rows: [], total: null } - const wrapper = mount(ReportNumberTable, { props: { table }, global }) - - expect(wrapper.find("tr.text-weight-bold").exists()).toBeFalsy() - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-tones.test.ts b/VueApp/src/shared/reports/__tests__/report-tones.test.ts deleted file mode 100644 index 87fcc2ed5..000000000 --- a/VueApp/src/shared/reports/__tests__/report-tones.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { badgeColor, cellBadges, flagText, highlightClass } from "../report-tones" -import type { ReportFlag, ReportRowResult } from "../report-types" - -/** - * Highlights follow the export rules (ReportExportText.CellFill), so a row is emphasized the - * same way on screen and in Excel and PDF. - */ - -const visible = new Set(["name", "age", "salary"]) - -const rowWarning: ReportFlag = { kind: "Highlight", tone: "Warning", label: "60+", columnKey: null } -const ageNegative: ReportFlag = { kind: "Highlight", tone: "Negative", label: "Retirement age", columnKey: "age" } -const hiddenMuted: ReportFlag = { kind: "Highlight", tone: "Muted", label: "Retired", columnKey: "ssn" } -const neutral: ReportFlag = { kind: "Highlight", tone: "Neutral", label: "Reviewed", columnKey: null } -const emeritusBadge: ReportFlag = { kind: "Badge", tone: "Info", label: "Emeritus", columnKey: null } -const salaryBadge: ReportFlag = { kind: "Badge", tone: "Positive", label: "Raised", columnKey: "salary" } - -describe("highlightClass()", () => { - it("applies a whole-row highlight to every cell, including the row number", () => { - expect(highlightClass([rowWarning], "name", visible)).toBe("report-tone-warning") - expect(highlightClass([rowWarning], null, visible)).toBe("report-tone-warning") - }) - - it("applies a column highlight only to its column", () => { - expect(highlightClass([ageNegative], "age", visible)).toBe("report-tone-negative") - expect(highlightClass([ageNegative], "name", visible)).toBeNull() - }) - - it("lets the last highlight covering a cell win", () => { - expect(highlightClass([rowWarning, ageNegative], "age", visible)).toBe("report-tone-negative") - expect(highlightClass([ageNegative, rowWarning], "age", visible)).toBe("report-tone-warning") - }) - - it("spreads a highlight on a hidden column across the row", () => { - expect(highlightClass([hiddenMuted], "name", visible)).toBe("report-tone-muted") - }) - - it("adds no class for neutral highlights or badges", () => { - expect(highlightClass([rowWarning, neutral], "name", visible)).toBe("report-tone-warning") - expect(highlightClass([neutral, emeritusBadge], "name", visible)).toBeNull() - }) -}) - -describe("cellBadges()", () => { - it("puts column badges beside their column and row badges beside the first column", () => { - const flags = [rowWarning, emeritusBadge, salaryBadge] - - expect(cellBadges(flags, "name", true)).toStrictEqual([emeritusBadge]) - expect(cellBadges(flags, "salary", false)).toStrictEqual([salaryBadge]) - expect(cellBadges(flags, "age", false)).toStrictEqual([]) - }) -}) - -describe("badgeColor()", () => { - it.each([ - ["Neutral", "grey-7"], - ["Info", "info"], - ["Positive", "positive"], - ["Warning", "warning"], - ["Negative", "negative"], - ["Muted", "grey-7"], - ] as const)("uses %s -> %s", (tone, color) => { - expect(badgeColor(tone)).toBe(color) - }) -}) - -describe("flagText()", () => { - it("lists each label once, in order", () => { - const row: ReportRowResult = { number: 1, values: {}, flags: [ageNegative, rowWarning, { ...rowWarning }] } - - expect(flagText(row)).toBe("Retirement age; 60+") - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/report-view.test.ts b/VueApp/src/shared/reports/__tests__/report-view.test.ts deleted file mode 100644 index e94d28560..000000000 --- a/VueApp/src/shared/reports/__tests__/report-view.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { mount } from "@vue/test-utils" -import { Quasar } from "quasar" -import ReportView from "../ReportView.vue" -import { sampleResult, vmeGroup } from "./report-fixtures" - -function mountView(result = sampleResult()) { - return mount(ReportView, { props: { result }, global: { plugins: [[Quasar, {}]] } }) -} - -describe("ReportView", () => { - it("says when the report was generated and how many rows it has", () => { - expect.hasAssertions() - const wrapper = mountView() - - expect(wrapper.get("p").text()).toBe("Generated 09/30/2026 2:05 PM · 3 rows") - }) - - it("uses the singular for one row", () => { - expect.hasAssertions() - const wrapper = mountView(sampleResult({ rowCount: 1 })) - - expect(wrapper.get("p").text()).toContain("1 row") - }) - - it("lays out the sections in export order", () => { - expect.hasAssertions() - const wrapper = mountView() - - expect(wrapper.findAll("h2, h3").map((heading) => heading.text())).toStrictEqual([ - "VME", - "Ages: VME", - "APC", - "Age by department", - "Ages", - ]) - expect(wrapper.findAll("dt").map((term) => term.text())).toStrictEqual(["People", "Salaries", "All salaries"]) - }) - - it("gives an ungrouped report no group heading", () => { - expect.hasAssertions() - const ungrouped = sampleResult({ - groups: [{ ...vmeGroup, label: null, charts: [] }], - pivots: [], - charts: [], - }) - - expect(mountView(ungrouped).find("h2").exists()).toBeFalsy() - }) - - it("says so when no rows match, but still shows the summary", () => { - expect.hasAssertions() - const wrapper = mountView(sampleResult({ rowCount: 0, groups: [] })) - - expect(wrapper.text()).toContain("No rows match these parameters.") - expect(wrapper.get("dt").text()).toBe("People") - expect(wrapper.find("table").exists()).toBeFalsy() - }) -}) diff --git a/VueApp/src/shared/reports/__tests__/use-report.test.ts b/VueApp/src/shared/reports/__tests__/use-report.test.ts deleted file mode 100644 index 817450e79..000000000 --- a/VueApp/src/shared/reports/__tests__/use-report.test.ts +++ /dev/null @@ -1,220 +0,0 @@ -import { flushPromises } from "@vue/test-utils" -import { ref } from "vue" -import { useReport } from "../use-report" -import { reportService } from "../report-service" -import type { ReportDefinitionMetadata, ReportResult } from "../report-types" - -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-service", () => ({ - reportService: { - getDefinition: vi.fn<(...args: unknown[]) => unknown>(), - run: vi.fn<(...args: unknown[]) => unknown>(), - exportReport: vi.fn<(...args: unknown[]) => unknown>(), - }, -})) - -const onLeave: ReportDefinitionMetadata = { - key: "personnel.employees-on-leave", - title: "Employees on Leave", - area: "Personnel", - description: "Faculty and staff on leave.", - parameters: [ - { - name: "startDate", - label: "Start date", - type: "Date", - required: true, - defaultValue: "2026-07-01", - options: [], - }, - { name: "search", label: "Search", type: "Text", required: false, defaultValue: null, options: [] }, - ], - columns: [], -} -const noParameters: ReportDefinitionMetadata = { ...onLeave, key: "personnel.vmdo-birthdays", parameters: [] } -const result = { key: onLeave.key, rowCount: 3 } as ReportResult - -/** Fresh mocks and query, with the given definition coming back from the API. */ -function reset(definition: ReportDefinitionMetadata | null, query: Record = {}): void { - vi.clearAllMocks() - route.query = query - mockReplace.mockResolvedValue() - vi.mocked(reportService.getDefinition).mockResolvedValue(definition) - vi.mocked(reportService.run).mockResolvedValue({ result, errors: [] }) -} - -/** 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) } -} - -async function loadedReport() { - reset(onLeave) - const report = useReport(onLeave.key) - await flushPromises() - return report -} - -describe("useReport() - loading", () => { - it("is loading until the definition arrives", async () => { - expect.hasAssertions() - reset(onLeave) - - const report = useReport(onLeave.key) - expect(report.loading.value).toBeTruthy() - await flushPromises() - - expect(report.loading.value).toBeFalsy() - expect(reportService.getDefinition).toHaveBeenCalledWith(onLeave.key) - }) - - it("fills the form with the report's defaults and waits to be run", async () => { - expect.hasAssertions() - - const report = await loadedReport() - - expect(report.definition.value).toStrictEqual(onLeave) - expect(report.values.value).toStrictEqual({ startDate: "2026-07-01", search: null }) - expect(reportService.run).not.toHaveBeenCalled() - }) - - it("fills the form from the query and runs straight away for a bookmarked URL", async () => { - expect.hasAssertions() - reset(onLeave, { search: "smith" }) - - const report = useReport(onLeave.key) - await flushPromises() - - expect(report.values.value.search).toBe("smith") - expect(reportService.run).toHaveBeenCalledWith(onLeave.key, { startDate: "2026-07-01", search: "smith" }) - expect(report.result.value).toStrictEqual(result) - }) - - it("runs a report that has no parameters straight away", async () => { - expect.hasAssertions() - reset(noParameters) - - useReport(noParameters.key) - await flushPromises() - - expect(reportService.run).toHaveBeenCalledWith(noParameters.key, {}) - }) - - it("reports a missing report", async () => { - expect.hasAssertions() - reset(null) - - const report = useReport("personnel.visa-audit") - await flushPromises() - - expect(report.notFound.value).toBeTruthy() - expect(report.values.value).toStrictEqual({}) - }) - - it("reloads when the key changes and ignores an earlier load that finishes late", async () => { - expect.hasAssertions() - reset(noParameters) - const first = deferred() - vi.mocked(reportService.getDefinition).mockReturnValueOnce(first.promise) - const key = ref(onLeave.key) - - const report = useReport(key) - key.value = noParameters.key - await flushPromises() - first.resolve(onLeave) - await flushPromises() - - expect(reportService.getDefinition).toHaveBeenLastCalledWith(noParameters.key) - expect(report.definition.value).toStrictEqual(noParameters) - }) -}) - -describe("useReport() - running and exporting", () => { - it("writes the parameters to the query before running", async () => { - expect.hasAssertions() - const report = await loadedReport() - report.values.value = { startDate: "2025-07-01", search: "" } - - await report.run() - - expect(mockReplace).toHaveBeenCalledWith({ query: { startDate: "2025-07-01" } }) - expect(reportService.run).toHaveBeenCalledWith(onLeave.key, { startDate: "2025-07-01" }) - expect(report.running.value).toBeFalsy() - }) - - it("shows the server's messages when the run is refused", async () => { - expect.hasAssertions() - const report = await loadedReport() - vi.mocked(reportService.run).mockResolvedValue({ result: null, errors: ["Start date is required."] }) - - await report.run() - - expect(report.result.value).toBeNull() - expect(report.errors.value).toStrictEqual(["Start date is required."]) - }) - - it("marks the format being exported until the download finishes", async () => { - expect.hasAssertions() - const report = await loadedReport() - await report.run() - const download = deferred() - vi.mocked(reportService.exportReport).mockReturnValue(download.promise) - - const exported = report.exportAs("xlsx") - expect(report.exporting.value).toBe("xlsx") - download.resolve(true) - await exported - - expect(reportService.exportReport).toHaveBeenCalledWith(onLeave.key, "xlsx", { startDate: "2026-07-01" }) - expect(report.exporting.value).toBeNull() - }) - - it("exports with the parameters of the run on screen, not later form edits", async () => { - expect.hasAssertions() - const report = await loadedReport() - report.values.value = { startDate: "2025-07-01", search: "smith" } - await report.run() - report.values.value = { startDate: "2020-01-01", search: "jones" } - - await report.exportAs("csv") - - expect(reportService.exportReport).toHaveBeenCalledWith(onLeave.key, "csv", { - startDate: "2025-07-01", - search: "smith", - }) - }) - - it("does not export before the report has run", async () => { - expect.hasAssertions() - const report = await loadedReport() - - await report.exportAs("pdf") - - expect(reportService.exportReport).not.toHaveBeenCalled() - }) - - it("does nothing before a report has loaded", async () => { - expect.hasAssertions() - reset(null) - const report = useReport("personnel.visa-audit") - await flushPromises() - - await report.run() - await report.exportAs("pdf") - - expect(reportService.run).not.toHaveBeenCalled() - expect(reportService.exportReport).not.toHaveBeenCalled() - }) -}) diff --git a/VueApp/src/shared/reports/report-columns.ts b/VueApp/src/shared/reports/report-columns.ts deleted file mode 100644 index aa93e0f64..000000000 --- a/VueApp/src/shared/reports/report-columns.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { QTableColumn } from "quasar" -import { formatReportValue } from "./report-format" -import { flagText } from "./report-tones" -import type { ReportAlignment, ReportCellValue, ReportResult, ReportRowResult } from "./report-types" - -/** - * Turns a report result's columns into Quasar table columns. Report column keys are camelCase - * property names, so the two extra columns use names no report column can have. - */ - -const ROW_NUMBER_COLUMN = "#number" -const NOTES_COLUMN = "#notes" - -const ALIGNMENTS: Record = { - Left: "left", - Center: "center", - Right: "right", -} - -/** True when any row has a highlight or badge, which adds a Notes column as in the exports. */ -function hasNotes(result: ReportResult): boolean { - return result.groups.some((group) => group.rows.some((row) => row.flags.length > 0)) -} - -function toTableColumns(result: ReportResult): QTableColumn[] { - const columns: QTableColumn[] = result.columns.map((column) => ({ - name: column.key, - label: column.label, - field: (row: ReportRowResult): ReportCellValue => row.values[column.key] ?? null, - align: ALIGNMENTS[column.align], - format: (value: ReportCellValue) => formatReportValue(value, column), - sortable: true, - })) - - if (result.rowNumbers) { - columns.unshift({ - name: ROW_NUMBER_COLUMN, - label: "#", - field: (row: ReportRowResult) => row.number, - align: "right", - sortable: true, - }) - } - - if (hasNotes(result)) { - columns.push({ name: NOTES_COLUMN, label: "Notes", field: flagText, align: "left" }) - } - return columns -} - -export { NOTES_COLUMN, ROW_NUMBER_COLUMN, hasNotes, toTableColumns } diff --git a/VueApp/src/shared/reports/report-format.ts b/VueApp/src/shared/reports/report-format.ts deleted file mode 100644 index eabef6e9d..000000000 --- a/VueApp/src/shared/reports/report-format.ts +++ /dev/null @@ -1,79 +0,0 @@ -import type { ReportCellValue, ReportColumnFormat, ReportColumnMetadata, ReportTotal } from "./report-types" - -/** - * Formats report values for display the way the server formats them for CSV and PDF exports - * (ReportValueFormatter and ReportExportText), so the screen and the files agree. - */ - -const LOCALE = "en-US" -const ISO_DATE = /^(?\d{4})-(?\d{2})-(?\d{2})/u -const TOTAL_MAX_DECIMALS = 2 -const NUMERIC_FORMATS: ReadonlySet = new Set(["Number", "Currency", "Percent"]) - -const STYLE_OPTIONS: Partial> = { - Currency: { style: "currency", currency: "USD" }, - Percent: { style: "percent" }, -} - -type ColumnFormat = Pick - -function isNumericFormat(format: ReportColumnFormat): boolean { - return NUMERIC_FORMATS.has(format) -} - -/** "2026-07-01" or "2026-07-01T00:00:00" becomes "07/01/2026"; anything else is left alone. */ -function formatReportDate(value: string): string { - const parts = ISO_DATE.exec(value)?.groups - return parts ? `${parts.month}/${parts.day}/${parts.year}` : value -} - -function formatColumnNumber(value: number, column: ColumnFormat): string { - const digits = column.decimals ?? 0 - return new Intl.NumberFormat(LOCALE, { - ...STYLE_OPTIONS[column.format], - minimumFractionDigits: digits, - maximumFractionDigits: digits, - }).format(value) -} - -/** A number with no column format: thousands separators and up to two decimals. */ -function formatPlainNumber(value: number | null): string { - return value === null - ? "" - : new Intl.NumberFormat(LOCALE, { maximumFractionDigits: TOTAL_MAX_DECIMALS }).format(value) -} - -function formatReportValue(value: ReportCellValue | undefined, column: ColumnFormat): string { - if (value === null || value === undefined) { - return "" - } - if (Array.isArray(value)) { - return value.join(", ") - } - if (typeof value === "number") { - return isNumericFormat(column.format) ? formatColumnNumber(value, column) : String(value) - } - if (typeof value === "boolean") { - return value ? "Yes" : "No" - } - return column.format === "Date" ? formatReportDate(value) : value -} - -/** A total formatted like the column it sits under, or as a plain number when it has none. */ -function formatReportTotal(total: ReportTotal, columns: ReportColumnMetadata[]): string { - const column = columns.find((candidate) => candidate.key === total.columnKey) - if (total.value === null) { - return "" - } - return column ? formatReportValue(total.value, column) : formatPlainNumber(total.value) -} - -/** "Generated 09/30/2026 2:15 PM", matching the export headers. */ -function formatGeneratedAt(generatedAt: string): string { - const date = new Date(generatedAt) - const day = date.toLocaleDateString(LOCALE, { month: "2-digit", day: "2-digit", year: "numeric" }) - const time = date.toLocaleTimeString(LOCALE, { hour: "numeric", minute: "2-digit" }) - return `Generated ${day} ${time}` -} - -export { formatGeneratedAt, formatPlainNumber, formatReportDate, formatReportTotal, formatReportValue, isNumericFormat } diff --git a/VueApp/src/shared/reports/report-number-tables.ts b/VueApp/src/shared/reports/report-number-tables.ts deleted file mode 100644 index 511a44832..000000000 --- a/VueApp/src/shared/reports/report-number-tables.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { ReportChartResult, ReportPivotResult } from "./report-types" - -/** - * Pivots and chart data as simple labelled-number tables, the way the PDF export shows them. - */ - -interface NumberRow { - label: string - values: (number | null)[] -} - -interface NumberTable { - /** The label column's header, then one header per value. */ - headers: string[] - rows: NumberRow[] - total: NumberRow | null -} - -const CATEGORY_LABEL = "Category" -const TOTAL_LABEL = "Total" - -function pivotTable(pivot: ReportPivotResult): NumberTable { - return { - headers: [CATEGORY_LABEL, ...pivot.columnKeys, TOTAL_LABEL], - rows: pivot.rows.map((row) => ({ label: row.key, values: [...row.values, row.total] })), - total: { label: TOTAL_LABEL, values: [...pivot.columnTotals, pivot.grandTotal] }, - } -} - -function chartTable(chart: ReportChartResult): NumberTable { - return { - headers: [CATEGORY_LABEL, "Value"], - rows: chart.points.map((point) => ({ label: point.category, values: [point.value] })), - total: null, - } -} - -export { chartTable, pivotTable } -export type { NumberRow, NumberTable } diff --git a/VueApp/src/shared/reports/report-query.ts b/VueApp/src/shared/reports/report-query.ts deleted file mode 100644 index a2f855163..000000000 --- a/VueApp/src/shared/reports/report-query.ts +++ /dev/null @@ -1,85 +0,0 @@ -import type { LocationQuery, LocationQueryRaw } from "vue-router" -import type { - ReportParameterMetadata, - ReportParameterType, - ReportParameterValue, - ReportParameterValues, -} from "./report-types" - -/** - * Moves report parameter values between the form, the URL query and the request body, so a - * report page can be bookmarked or shared with its parameters filled in. - */ - -type QueryValue = LocationQuery[string] - -const PARSERS: Record ReportParameterValue> = { - Choice: (values) => values[0] ?? null, - MultiChoice: (values) => values, - Date: (values) => values[0] ?? null, - Text: (values) => values[0] ?? null, - Number: (values) => { - const number = Number(values[0]) - return values[0] !== undefined && values[0] !== "" && Number.isFinite(number) ? number : null - }, - Boolean: (values) => (values[0] === undefined ? null : values[0] === "true"), -} - -function queryStrings(value: QueryValue): string[] { - const list = Array.isArray(value) ? value : [value] - return list.filter((item): item is string => typeof item === "string") -} - -/** 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) -} - -function emptyValue(parameter: ReportParameterMetadata): ReportParameterValue { - return parameter.type === "MultiChoice" ? [] : null -} - -/** True when the query carries at least one of the report's parameters. */ -function hasQueryParameters(parameters: ReportParameterMetadata[], query: LocationQuery): boolean { - return parameters.some((parameter) => query[parameter.name] !== undefined) -} - -/** - * The form's starting values: from the query when it has the parameter, otherwise the report's - * default, otherwise empty. - */ -function initialValues(parameters: ReportParameterMetadata[], query: LocationQuery): ReportParameterValues { - return Object.fromEntries( - parameters.map((parameter) => { - const fromQuery = query[parameter.name] - const value = - fromQuery === undefined - ? (parameter.defaultValue ?? emptyValue(parameter)) - : PARSERS[parameter.type](queryStrings(fromQuery)) - return [parameter.name, value] - }), - ) -} - -/** The non-empty values as query parameters; lists repeat the key. */ -function toQuery(parameters: ReportParameterMetadata[], values: ReportParameterValues): LocationQueryRaw { - const entries = parameters - .map((parameter) => [parameter.name, values[parameter.name]] as const) - .filter(([, value]) => !isEmptyValue(value)) - .map(([name, value]) => [name, Array.isArray(value) ? value : String(value)]) - return Object.fromEntries(entries) -} - -/** - * The run request body. Empty values are left out, so the server applies its defaults and its - * own required checks, and names it doesn't know are never sent. - */ -function toRequestBody(parameters: ReportParameterMetadata[], values: ReportParameterValues): ReportParameterValues { - return Object.fromEntries( - parameters - .map((parameter) => [parameter.name, values[parameter.name] ?? null] as const) - .filter(([, value]) => !isEmptyValue(value)), - ) -} - -export { hasQueryParameters, initialValues, isEmptyValue, toQuery, toRequestBody } diff --git a/VueApp/src/shared/reports/report-service.ts b/VueApp/src/shared/reports/report-service.ts deleted file mode 100644 index 49b058b24..000000000 --- a/VueApp/src/shared/reports/report-service.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { downloadBlob, postForBlob, useFetch } from "@/composables/ViperFetch" -import type { - ReportCatalogItem, - ReportDefinitionMetadata, - ReportExportFormat, - ReportParameterValues, - ReportResult, -} from "./report-types" - -const { get, post } = useFetch() - -const RUN_FAILED = "The report could not be run." - -/** - * A finished run has a result and no errors; a refused or failed run has messages instead. - * Validation messages name the parameter they concern, so they read well as a list. - */ -type ReportRunOutcome = { result: ReportResult; errors: [] } | { result: null; errors: string[] } - -/** - * Client for the site-wide reports API. - */ -class ReportService { - private baseUrl = `${import.meta.env.VITE_API_URL}reports` - - /** - * The reports in one area that the signed-in user may run. The server filters by permission, - * so the list needs no checks here. Returns null when the request fails, so the caller can - * tell a failed load apart from an area with no reports for this user. - */ - async getCatalog(area: string): Promise { - const r = await get(`${this.baseUrl}?area=${encodeURIComponent(area)}`) - if (!r.success || !Array.isArray(r.result)) { - return null - } - return r.result as ReportCatalogItem[] - } - - /** - * A report's parameters and columns. Null when the report doesn't exist, is only planned, - * or the user may not run it; the API doesn't say which, and the page treats all three alike. - */ - async getDefinition(key: string): Promise { - const r = await get(this.reportUrl(key)) - if (!r.success || !r.result) { - return null - } - return r.result as ReportDefinitionMetadata - } - - async run(key: string, parameters: ReportParameterValues): Promise { - const r = await post(`${this.reportUrl(key)}/run`, parameters) - if (r.success && r.result) { - return { result: r.result as ReportResult, 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 downloads it in the chosen format. Returns false if the - * export failed; the shared error handler has already told the user why. - */ - async exportReport(key: string, format: ReportExportFormat, parameters: ReportParameterValues): Promise { - try { - const { blob, filename } = await postForBlob(`${this.reportUrl(key)}/export/${format}`, parameters) - downloadBlob(blob, filename ?? `${key}.${format}`) - return true - } catch { - return false - } - } - - private reportUrl(key: string): string { - return `${this.baseUrl}/${encodeURIComponent(key)}` - } -} - -const reportService = new ReportService() -export { reportService } -export type { ReportRunOutcome } diff --git a/VueApp/src/shared/reports/report-tones.css b/VueApp/src/shared/reports/report-tones.css deleted file mode 100644 index 974cd533a..000000000 --- a/VueApp/src/shared/reports/report-tones.css +++ /dev/null @@ -1,23 +0,0 @@ -/* Report highlight tints (report-tones.ts). Light enough that ink text clears WCAG AA, and each - highlight's label is also listed in the Notes column, so color is never the only signal. The - tints match StatusBanner's, so a warning row reads like a warning banner. */ - -.report-tone-info { - background-color: color-mix(in srgb, var(--q-info) 12%, white); -} - -.report-tone-positive { - background-color: color-mix(in srgb, var(--q-positive) 12%, white); -} - -.report-tone-warning { - background-color: color-mix(in srgb, var(--q-warning) 15%, white); -} - -.report-tone-negative { - background-color: color-mix(in srgb, var(--q-negative) 12%, white); -} - -.report-tone-muted { - background-color: var(--ucdavis-black-10); -} diff --git a/VueApp/src/shared/reports/report-tones.ts b/VueApp/src/shared/reports/report-tones.ts deleted file mode 100644 index fecd8e5c8..000000000 --- a/VueApp/src/shared/reports/report-tones.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { ReportFlag, ReportRowResult, ReportTone } from "./report-types" - -/** - * Maps report highlight and badge tones to page styling. Tones are semantic, never raw colors, - * and every flag also carries a text label, so no meaning depends on color alone. - */ - -const HIGHLIGHT_CLASSES: Record = { - Neutral: null, - Info: "report-tone-info", - Positive: "report-tone-positive", - Warning: "report-tone-warning", - Negative: "report-tone-negative", - Muted: "report-tone-muted", -} - -// Quasar palette names; StatusBadge picks a readable text color for each. -const BADGE_COLORS: Record = { - Neutral: "grey-7", - Info: "info", - Positive: "positive", - Warning: "warning", - Negative: "negative", - Muted: "grey-7", -} - -/** - * The highlight class for one cell, following the exports: highlights apply in declared order, - * so the last one covering the cell wins. A highlight covers a cell when it targets the whole - * row, this column, or a column the user can't see. Pass null for cells outside any column. - */ -function highlightClass( - flags: ReportFlag[], - columnKey: string | null, - visibleKeys: ReadonlySet, -): string | null { - const classes = flags - .filter( - (flag) => - flag.kind === "Highlight" && - (flag.columnKey === null || flag.columnKey === columnKey || !visibleKeys.has(flag.columnKey)), - ) - .map((flag) => HIGHLIGHT_CLASSES[flag.tone]) - .filter((name): name is string => name !== null) - return classes.at(-1) ?? null -} - -/** Badges shown beside one cell. Whole-row badges go beside the first column. */ -function cellBadges(flags: ReportFlag[], columnKey: string, isFirstColumn: boolean): ReportFlag[] { - return flags.filter( - (flag) => flag.kind === "Badge" && (flag.columnKey === columnKey || (isFirstColumn && flag.columnKey === null)), - ) -} - -function badgeColor(tone: ReportTone): string { - return BADGE_COLORS[tone] -} - -/** Every flag label on a row, once each, as the exports' Notes column lists them. */ -function flagText(row: ReportRowResult): string { - return [...new Set(row.flags.map((flag) => flag.label))].join("; ") -} - -export { badgeColor, cellBadges, flagText, highlightClass } diff --git a/VueApp/src/shared/reports/report-types.ts b/VueApp/src/shared/reports/report-types.ts deleted file mode 100644 index e66707a65..000000000 --- a/VueApp/src/shared/reports/report-types.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Types mirroring the reports API (web/Areas/Reports). Enum values arrive as their C# names. - */ - -type ReportParameterType = "Choice" | "MultiChoice" | "Date" | "Text" | "Number" | "Boolean" -type ReportColumnFormat = "Text" | "Number" | "Currency" | "Percent" | "Date" | "List" -type ReportAlignment = "Left" | "Center" | "Right" -type ReportTone = "Neutral" | "Info" | "Positive" | "Warning" | "Negative" | "Muted" -type ReportFlagKind = "Highlight" | "Badge" -type ReportChartKind = "Bar" | "Line" | "Pie" -type ReportExportFormat = "csv" | "xlsx" | "pdf" - -/** A parameter value as the form holds it; dates are "yyyy-MM-dd" strings. */ -type ReportParameterValue = string | string[] | number | boolean | null -type ReportParameterValues = Record - -/** A cell value as the API sends it; dates are ISO strings. */ -type ReportCellValue = string | string[] | number | boolean | null - -/** - * A report the signed-in user may run, as listed by the reports catalog. `available` is false - * for a planned report that is listed ahead of time but not built yet. - */ -interface ReportCatalogItem { - key: string - title: string - area: string - description: string - available: boolean -} - -interface ReportOption { - value: string - label: string -} - -interface ReportParameterMetadata { - name: string - label: string - type: ReportParameterType - required: boolean - defaultValue: ReportParameterValue - options: ReportOption[] -} - -interface ReportColumnMetadata { - key: string - label: string - format: ReportColumnFormat - align: ReportAlignment - decimals: number | null -} - -interface ReportDefinitionMetadata { - key: string - title: string - area: string - description: string - parameters: ReportParameterMetadata[] - columns: ReportColumnMetadata[] -} - -interface ReportFlag { - kind: ReportFlagKind - tone: ReportTone - label: string - columnKey: string | null -} - -interface ReportRowResult { - number: number - values: Record - flags: ReportFlag[] -} - -interface ReportTotal { - label: string - columnKey: string | null - value: number | null -} - -interface ReportChartPoint { - category: string - value: number | null -} - -interface ReportChartResult { - title: string - kind: ReportChartKind - points: ReportChartPoint[] -} - -interface ReportGroupResult { - label: string | null - rows: ReportRowResult[] - subtotals: ReportTotal[] - charts: ReportChartResult[] -} - -interface ReportPivotRow { - key: string - values: (number | null)[] - total: number | null -} - -interface ReportPivotResult { - title: string - columnKeys: string[] - rows: ReportPivotRow[] - columnTotals: (number | null)[] - grandTotal: number | null -} - -interface ReportResult { - key: string - title: string - generatedAt: string - rowCount: number - rowNumbers: boolean - columns: ReportColumnMetadata[] - summary: ReportTotal[] - groups: ReportGroupResult[] - totals: ReportTotal[] - pivots: ReportPivotResult[] - charts: ReportChartResult[] -} - -export type { - ReportAlignment, - ReportCatalogItem, - ReportCellValue, - ReportChartKind, - ReportChartPoint, - ReportChartResult, - ReportColumnFormat, - ReportColumnMetadata, - ReportDefinitionMetadata, - ReportExportFormat, - ReportFlag, - ReportFlagKind, - ReportGroupResult, - ReportOption, - ReportParameterMetadata, - ReportParameterType, - ReportParameterValue, - ReportParameterValues, - ReportPivotResult, - ReportPivotRow, - ReportResult, - ReportRowResult, - ReportTone, - ReportTotal, -} diff --git a/VueApp/src/shared/reports/use-report.ts b/VueApp/src/shared/reports/use-report.ts deleted file mode 100644 index 4ca138740..000000000 --- a/VueApp/src/shared/reports/use-report.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { ref, toValue, watch } from "vue" -import type { MaybeRefOrGetter } from "vue" -import { useRoute, useRouter } from "vue-router" -import { hasQueryParameters, initialValues, toQuery, toRequestBody } from "./report-query" -import { reportService } from "./report-service" -import type { ReportDefinitionMetadata, ReportExportFormat, ReportParameterValues, ReportResult } from "./report-types" - -/** - * State for a report page: loads the report's definition whenever the key changes, fills the - * form from the URL query or the report's defaults, and runs or exports the report. Running - * writes the parameters back to the query so the page can be bookmarked; opening a URL that - * carries parameters, or a report that has none, runs it straight away. - */ -export function useReport(key: MaybeRefOrGetter) { - const route = useRoute() - const router = useRouter() - - 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) - // The body of the run on screen, so an export matches what the user sees even after the - // form has been edited. - let shownBody: ReportParameterValues = {} - - // Only the latest load may update the page, if the key changes while one is in flight. - let loadId = 0 - - async function run(): Promise { - const report = definition.value - if (report === null) { - return - } - running.value = true - errors.value = [] - await router.replace({ query: toQuery(report.parameters, values.value) }) - const body = toRequestBody(report.parameters, values.value) - const outcome = await reportService.run(report.key, body) - result.value = outcome.result - shownBody = body - errors.value = outcome.errors - running.value = false - } - - /** Exports the report on screen; does nothing until a run has produced one. */ - async function exportAs(format: ReportExportFormat): Promise { - const report = definition.value - if (report === null || result.value === null) { - return - } - exporting.value = format - await reportService.exportReport(report.key, format, shownBody) - exporting.value = null - } - - async function load(reportKey: string): Promise { - loadId += 1 - const id = loadId - loading.value = true - result.value = null - errors.value = [] - const report = await reportService.getDefinition(reportKey) - if (id !== loadId) { - return - } - definition.value = report - notFound.value = report === null - values.value = report ? initialValues(report.parameters, route.query) : {} - loading.value = false - if (report && (report.parameters.length === 0 || hasQueryParameters(report.parameters, route.query))) { - await run() - } - } - - watch(() => toValue(key), load, { immediate: true }) - - return { definition, values, result, errors, loading, notFound, running, exporting, run, exportAs } -} 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/Personnel/EmployeesOnLeaveReportTests.cs b/test/Personnel/EmployeesOnLeaveReportTests.cs deleted file mode 100644 index d8ec10281..000000000 --- a/test/Personnel/EmployeesOnLeaveReportTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -using Viper.Areas.Personnel; -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Reports; -using Viper.Areas.Reports.Engine; -using Viper.test.Reports; - -namespace Viper.test.Personnel; - -public sealed class EmployeesOnLeaveReportTests -{ - // A February date, so the default range is the fiscal year that began the previous July. - private static readonly DateTimeOffset Now = new(2027, 2, 15, 9, 0, 0, TimeSpan.Zero); - - private readonly StubPersonnelReportDataService _data = new() - { - PeopleOnLeave = - [ - new EmployeeOnLeaveRow( - "Lovelace, Ada", "VME", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), "Sabbatical", "With pay"), - ], - }; - - private EmployeesOnLeaveReport Report() - { - return new EmployeesOnLeaveReport(_data, new FixedTimeProvider(Now)); - } - - private static ReportContext Context() - { - return new ReportContext("tester", permission => permission == PersonnelPermissions.Sabbatic); - } - - [Fact] - public void Identity_MatchesTheLegacyPage() - { - EmployeesOnLeaveReport report = Report(); - - Assert.Equal("personnel.employees-on-leave", report.Key); - Assert.Equal("Personnel", report.Area); - Assert.Equal([PersonnelPermissions.Sabbatic], report.Permissions); - Assert.True(report.IsSensitive); - Assert.True(report.CanRun(Context())); - } - - [Fact] - public void Metadata_DefaultsToFacultyAndTheCurrentFiscalYear() - { - ReportDefinitionMetadata metadata = Report().GetMetadata(Context()); - - Assert.Equal( - [("employeeType", (object?)"F"), ("startDate", new DateOnly(2026, 7, 1)), ("endDate", new DateOnly(2027, 6, 30))], - metadata.Parameters.Select(parameter => (parameter.Name, parameter.DefaultValue))); - Assert.All(metadata.Parameters, parameter => Assert.True(parameter.Required)); - Assert.Equal( - ["name", "homeDepartment", "leaveStart", "returnDate", "description", "payStatus"], - metadata.Columns.Select(column => column.Key)); - } - - [Fact] - public void PrepareParameters_EndBeforeStart_IsInvalid() - { - var parameters = new EmployeesOnLeaveParameters - { - StartDate = new DateOnly(2026, 7, 1), - EndDate = new DateOnly(2026, 6, 30), - }; - - ReportValidationError error = Assert.Single(Report().PrepareParameters(parameters)); - - Assert.Equal("endDate", error.Parameter); - } - - [Fact] - public async Task RunAsync_PassesThePreparedParametersToTheDataService() - { - EmployeesOnLeaveReport report = Report(); - var parameters = new EmployeesOnLeaveParameters { EmployeeType = "B", StartDate = new DateOnly(2025, 1, 1) }; - Assert.Empty(report.PrepareParameters(parameters)); - - ReportResult result = await report.RunAsync(parameters, Context(), Now, TestContext.Current.CancellationToken); - - Assert.Equal(("B", new DateOnly(2025, 1, 1), new DateOnly(2027, 6, 30)), _data.LeaveRequest); - Assert.Equal(1, result.RowCount); - Assert.Equal("Lovelace, Ada", Assert.Single(Assert.Single(result.Groups).Rows).Values["name"]); - } - - [Fact] - public async Task RunAsync_WithoutPreparedParameters_Throws() - { - await Assert.ThrowsAsync(() => Report().RunAsync( - new EmployeesOnLeaveParameters(), Context(), Now, TestContext.Current.CancellationToken)); - } -} diff --git a/test/Personnel/ExemptStatusReportTests.cs b/test/Personnel/ExemptStatusReportTests.cs deleted file mode 100644 index 48a6b186a..000000000 --- a/test/Personnel/ExemptStatusReportTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -using Viper.Areas.Personnel; -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Reports; -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Personnel; - -public sealed class ExemptStatusReportTests -{ - private static readonly DateTimeOffset Now = new(2026, 9, 30, 9, 0, 0, TimeSpan.Zero); - - // Ada holds two exempt appointments in VME, so VME counts her once. - private readonly StubPersonnelReportDataService _data = new() - { - FlsaEmployees = - [ - new FlsaEmployeeRow("1", "Lovelace, Ada", "VME", "Professor", ExemptStatusReport.Exempt, "ada@ucdavis.edu"), - new FlsaEmployeeRow("1", "Lovelace, Ada", "VME", "Chair", ExemptStatusReport.Exempt, "ada@ucdavis.edu"), - new FlsaEmployeeRow("2", "Byron, Bo", "VME", "Analyst", ExemptStatusReport.NonExempt, null), - new FlsaEmployeeRow("3", "Curie, Cy", "APC", "Assistant", ExemptStatusReport.NonExempt, null), - ], - }; - - private ExemptStatusReport Report() - { - return new ExemptStatusReport(_data); - } - - private static ReportContext Context() - { - return new ReportContext("tester", permission => permission == PersonnelPermissions.ServiceCreditAdmin); - } - - private async Task RunAsync(string statusType) - { - ExemptStatusReport report = Report(); - var parameters = new ExemptStatusParameters { StatusType = statusType }; - Assert.Empty(report.PrepareParameters(parameters)); - return await report.RunAsync(parameters, Context(), Now, TestContext.Current.CancellationToken); - } - - [Fact] - public void Identity_UsesTheDecidedPermission() - { - ExemptStatusReport report = Report(); - - Assert.Equal("personnel.exempt-non-exempt", report.Key); - Assert.Equal([PersonnelPermissions.ServiceCreditAdmin], report.Permissions); - Assert.False(report.IsSensitive); - Assert.True(report.CanRun(Context())); - } - - [Fact] - public void Metadata_DefaultsToBoth() - { - ReportDefinitionMetadata metadata = Report().GetMetadata(Context()); - - ReportParameterMetadata status = Assert.Single(metadata.Parameters); - Assert.Equal("statusType", status.Name); - Assert.Equal("B", status.DefaultValue); - Assert.Equal(["E", "N", "B"], status.Options.Select(option => option.Value)); - Assert.Equal(["name", "department", "title", "flsa", "email"], metadata.Columns.Select(column => column.Key)); - } - - [Fact] - public async Task RunAsync_AsksForTheChosenStatus() - { - await RunAsync("E"); - - Assert.Equal("E", _data.FlsaRequest); - } - - [Fact] - public async Task RunAsync_CountsPeopleForTheSchool() - { - ReportResult result = await RunAsync("B"); - - Assert.Equal( - [new ReportTotal("Exempt employees", null, 1), new ReportTotal("Non-exempt employees", null, 2)], - result.Summary); - Assert.True(result.RowNumbers); - } - - [Fact] - public async Task RunAsync_GroupsByDepartmentWithNonExemptFirst() - { - ReportResult result = await RunAsync("B"); - - Assert.Equal(["APC", "VME"], result.Groups.Select(group => group.Label)); - ReportGroupResult vme = result.Groups[1]; - Assert.Equal( - ["Byron, Bo", "Lovelace, Ada", "Lovelace, Ada"], - vme.Rows.Select(row => row.Values["name"])); - Assert.Equal( - [new ReportTotal("Exempt employees", null, 1), new ReportTotal("Non-exempt employees", null, 1)], - vme.Subtotals); - } - - [Fact] - public async Task RunAsync_WithoutPreparedParameters_Throws() - { - await Assert.ThrowsAsync(() => Report().RunAsync( - new ExemptStatusParameters(), Context(), Now, TestContext.Current.CancellationToken)); - } -} diff --git a/test/Personnel/FacultyProfileReportTests.cs b/test/Personnel/FacultyProfileReportTests.cs deleted file mode 100644 index f90717c00..000000000 --- a/test/Personnel/FacultyProfileReportTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -using Viper.Areas.Personnel; -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Reports; -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Personnel; - -public sealed class FacultyProfileReportTests -{ - private static readonly DateTimeOffset Now = new(2026, 9, 30, 9, 0, 0, TimeSpan.Zero); - - // VME: Ada (two appointments, 61), Bo (45), Cy (emeritus, 70), Di (recalled, 66), Ed (33). - // APC: Ada again, through her second appointment. - private readonly StubPersonnelReportDataService _data = new() - { - FacultyAppointments = - [ - new FacultyAppointmentRow("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "VME", "PROF-AY"), - new FacultyAppointmentRow("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "APC", "CHAIR"), - new FacultyAppointmentRow("2", "Byron, Bo", 45, new DateOnly(2010, 1, 15), "VME", "ASSOC PROF"), - new FacultyAppointmentRow("3", "Curie, Cy", 70, new DateOnly(1985, 9, 1), "VME", "PROF EMERITUS"), - new FacultyAppointmentRow("4", "Dirac, Di", 66, new DateOnly(1990, 3, 1), "VME", "PROF-RECALL"), - new FacultyAppointmentRow("5", "Euler, Ed", 33, new DateOnly(2022, 8, 15), "VME", "ASST PROF"), - ], - }; - - private FacultyProfileReport Report() - { - return new FacultyProfileReport(_data); - } - - private static ReportContext Context() - { - return new ReportContext("tester", permission => permission == PersonnelPermissions.FacultySalary); - } - - private async Task RunAsync(string facultyType = "B") - { - FacultyProfileReport report = Report(); - var parameters = new FacultyProfileParameters { FacultyType = facultyType }; - Assert.Empty(report.PrepareParameters(parameters)); - return await report.RunAsync(parameters, Context(), Now, TestContext.Current.CancellationToken); - } - - [Fact] - public void Identity_IsSensitiveAndNeedsFacultySalary() - { - FacultyProfileReport report = Report(); - - Assert.Equal("personnel.faculty-profile", report.Key); - Assert.Equal([PersonnelPermissions.FacultySalary], report.Permissions); - Assert.True(report.IsSensitive); - Assert.True(report.CanRun(Context())); - } - - [Fact] - public void Metadata_DefaultsToBothFacultyTypes() - { - ReportDefinitionMetadata metadata = Report().GetMetadata(Context()); - - ReportParameterMetadata type = Assert.Single(metadata.Parameters); - Assert.Equal("B", type.DefaultValue); - Assert.Equal(["S", "F", "B"], type.Options.Select(option => option.Value)); - Assert.Equal( - ["name", "age", "hireDate", "appointmentDepartment", "title"], - metadata.Columns.Select(column => column.Key)); - } - - [Fact] - public async Task RunAsync_AsksForTheChosenFacultyType() - { - await RunAsync("S"); - - Assert.Equal("S", _data.FacultyRequest); - } - - [Fact] - public async Task RunAsync_CountsPeopleNotAppointments() - { - ReportResult result = await RunAsync(); - - Assert.Equal( - [new ReportTotal("Faculty", null, 5), new ReportTotal("Emeriti", null, 1), new ReportTotal("Recalled", null, 1)], - result.Summary); - Assert.Equal(["APC", "VME"], result.Groups.Select(group => group.Label)); - Assert.Equal( - [new ReportTotal("Faculty", null, 5), new ReportTotal("Emeriti", null, 1), new ReportTotal("Recalled", null, 1)], - result.Groups[1].Subtotals); - } - - [Fact] - public async Task RunAsync_ChartsActiveFacultyOnly() - { - ReportResult result = await RunAsync(); - - ReportChartResult school = Assert.Single(result.Charts); - Assert.Equal( - [new ReportChartPoint("30-34", 1), new ReportChartPoint("45-49", 1), new ReportChartPoint("60-64", 1)], - school.Points); - Assert.Empty(result.Groups[0].Charts); - Assert.Empty(result.Groups[1].Charts); - } - - [Fact] - public async Task RunAsync_MutesRetiredFacultyAndHighlightsAgeSixtyAndOver() - { - ReportResult result = await RunAsync(); - IReadOnlyList vme = result.Groups[1].Rows; - - Assert.Equal( - ["Curie, Cy", "Dirac, Di", "Lovelace, Ada", "Lovelace, Ada", "Byron, Bo", "Euler, Ed"], - vme.Select(row => row.Values["name"])); - Assert.Equal( - [ReportTone.Muted, ReportTone.Warning], - vme[0].Flags.Select(flag => flag.Tone)); - Assert.Equal([ReportTone.Warning], vme[2].Flags.Select(flag => flag.Tone)); - Assert.Empty(vme[4].Flags); - } - - [Fact] - public async Task RunAsync_WithoutPreparedParameters_Throws() - { - await Assert.ThrowsAsync(() => Report().RunAsync( - new FacultyProfileParameters(), Context(), Now, TestContext.Current.CancellationToken)); - } -} diff --git a/test/Personnel/FacultyProfileRowsTests.cs b/test/Personnel/FacultyProfileRowsTests.cs deleted file mode 100644 index 9b6cc2e72..000000000 --- a/test/Personnel/FacultyProfileRowsTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Reports; - -namespace Viper.test.Personnel; - -public sealed class FacultyProfileRowsTests -{ - [Theory] - [InlineData(null, null)] - [InlineData(19, null)] - [InlineData(20, "20-24")] - [InlineData(24, "20-24")] - [InlineData(25, "25-29")] - [InlineData(60, "60-64")] - [InlineData(99, "95-99")] - [InlineData(100, null)] - public void AgeGroup_UsesTheLegacyFiveYearBrackets(int? age, string? expected) - { - Assert.Equal(expected, FacultyProfileRows.AgeGroup(age)); - } - - [Theory] - [InlineData("PROF EMERITUS", true, false)] - [InlineData("Prof-Emeri/Recall", true, true)] - [InlineData("PROF-RECALL", false, true)] - [InlineData("PROF-AY", false, false)] - [InlineData(null, false, false)] - public void Titles_IdentifyEmeritiAndRecalledFaculty(string? title, bool emeritus, bool recalled) - { - var row = new FacultyProfileRow("VME", "1", "Ada", 70, null, "VME", title); - - Assert.Equal(emeritus, FacultyProfileRows.IsEmeritusTitle(title)); - Assert.Equal(recalled, FacultyProfileRows.IsRecalledTitle(title)); - Assert.Equal(emeritus, row.IsEmeritus); - Assert.Equal(recalled, row.IsRecalled); - Assert.Equal(emeritus || recalled, row.IsRetired); - Assert.Equal("70-74", row.AgeGroup); - } - - [Fact] - public void Expand_ListsEachPersonWithAllAppointmentsUnderEveryDepartment() - { - FacultyAppointmentRow[] appointments = - [ - new("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "VME", "PROF-AY"), - new("1", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "APC ", "CHAIR"), - new("2", "Byron, Bo", 45, null, "VME", "ASSOC PROF"), - new("3", "Curie, Cy", 70, null, null, "PROF EMERITUS"), - ]; - - IReadOnlyList rows = FacultyProfileRows.Expand(appointments); - - Assert.Equal( - [ - ("", "3", "PROF EMERITUS"), - ("APC", "1", "CHAIR"), - ("APC", "1", "PROF-AY"), - ("VME", "1", "CHAIR"), - ("VME", "1", "PROF-AY"), - ("VME", "2", "ASSOC PROF"), - ], - rows.Select(row => (row.Department, row.EmployeeId, row.Title ?? string.Empty)) - .OrderBy(row => row.Department, StringComparer.Ordinal) - .ThenBy(row => row.EmployeeId, StringComparer.Ordinal) - .ThenBy(row => row.Item3, StringComparer.Ordinal)); - Assert.Equal(["3", "1", "1", "1", "1", "2"], rows.Select(row => row.EmployeeId)); - Assert.Equal("APC ", rows.First(row => row.Title == "CHAIR").AppointmentDepartment); - } - - [Fact] - public void Expand_Null_Throws() - { - Assert.Throws(() => FacultyProfileRows.Expand(null!)); - } -} diff --git a/test/Personnel/FiscalYearTests.cs b/test/Personnel/FiscalYearTests.cs deleted file mode 100644 index c39b8fe39..000000000 --- a/test/Personnel/FiscalYearTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Viper.Areas.Personnel.Reports; - -namespace Viper.test.Personnel; - -public sealed class FiscalYearTests -{ - [Theory] - [InlineData(2026, 7, 1, 2026)] - [InlineData(2026, 12, 31, 2026)] - [InlineData(2027, 1, 1, 2026)] - [InlineData(2027, 6, 30, 2026)] - public void StartOf_IsTheMostRecentJulyFirst(int year, int month, int day, int startYear) - { - var date = new DateOnly(year, month, day); - - Assert.Equal(new DateOnly(startYear, 7, 1), FiscalYear.StartOf(date)); - Assert.Equal(new DateOnly(startYear + 1, 6, 30), FiscalYear.EndOf(date)); - } -} diff --git a/test/Personnel/PersonnelReportDataServiceTests.cs b/test/Personnel/PersonnelReportDataServiceTests.cs deleted file mode 100644 index 94a4623e0..000000000 --- a/test/Personnel/PersonnelReportDataServiceTests.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System.Data; -using Viper.Areas.Personnel; -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Services; -using Viper.Areas.Reports.Data; - -namespace Viper.test.Personnel; - -public sealed class PersonnelReportDataServiceTests -{ - /// - /// Records the call and maps the rows it is given, standing in for SQL Server. - /// - private sealed class RecordingRunner(DataTable rows) : IStoredProcedureRunner - { - public string? ConnectionName { get; private set; } - - public string? Procedure { get; private set; } - - public IReadOnlyList Parameters { get; private set; } = []; - - public Task> QueryAsync( - string connectionStringName, - string procedure, - IReadOnlyList parameters, - Func map, - CancellationToken ct) - { - ConnectionName = connectionStringName; - Procedure = procedure; - Parameters = parameters; - using DataTableReader reader = rows.CreateDataReader(); - var mapped = new List(); - while (reader.Read()) - { - mapped.Add(map(reader)); - } - - return Task.FromResult>(mapped); - } - } - - private static DataTable LeaveTable() - { - var table = new DataTable(); - table.Columns.Add("Name", typeof(string)); - table.Columns.Add("homeDept", typeof(string)); - table.Columns.Add("loa_begin_date", typeof(DateTime)); - table.Columns.Add("loa_return_date", typeof(DateTime)); - table.Columns.Add("loa_description", typeof(string)); - table.Columns.Add("pay_status", typeof(string)); - table.Rows.Add( - "Lovelace, Ada ", - "VME ", - new DateTime(2026, 7, 1, 0, 0, 0, DateTimeKind.Local), - new DateTime(2027, 6, 30, 0, 0, 0, DateTimeKind.Local), - "Sabbatical ", - "With pay"); - table.Rows.Add(DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value); - return table; - } - - [Fact] - public async Task GetPeopleOnLeaveAsync_CallsTheLegacyProcedureOnPps() - { - var runner = new RecordingRunner(LeaveTable()); - var service = new PersonnelReportDataService(runner); - - await service.GetPeopleOnLeaveAsync( - "S", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), TestContext.Current.CancellationToken); - - Assert.Equal(PersonnelDatabases.Pps, runner.ConnectionName); - Assert.Equal("usp_get_peopleOnLeave", runner.Procedure); - Assert.Equal( - [ - StoredProcedureParameter.Text("fYear", null, 4), - StoredProcedureParameter.Text("employeeType", "S", 1), - StoredProcedureParameter.Date("startDate", new DateOnly(2026, 7, 1)), - StoredProcedureParameter.Date("endDate", new DateOnly(2027, 6, 30)), - ], - runner.Parameters); - } - - [Fact] - public async Task GetPeopleOnLeaveAsync_MapsAndTrimsEachRow() - { - var service = new PersonnelReportDataService(new RecordingRunner(LeaveTable())); - - IReadOnlyList rows = await service.GetPeopleOnLeaveAsync( - "F", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), TestContext.Current.CancellationToken); - - Assert.Equal( - [ - new EmployeeOnLeaveRow( - "Lovelace, Ada", "VME", new DateOnly(2026, 7, 1), new DateOnly(2027, 6, 30), "Sabbatical", "With pay"), - new EmployeeOnLeaveRow(string.Empty, null, null, null, null, null), - ], - rows); - } - - [Fact] - public async Task GetFlsaAsync_CallsTheLegacyProcedureAndTrimsEachRow() - { - var table = new DataTable(); - foreach (string column in new[] { "employee_id", "emp_name", "department", "title", "flsa", "email" }) - { - table.Columns.Add(column, typeof(string)); - } - - table.Rows.Add("000123456 ", "Lovelace, Ada ", "VME ", "Professor ", "EXEMPT ", "ada@ucdavis.edu"); - table.Rows.Add(DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value); - var runner = new RecordingRunner(table); - var service = new PersonnelReportDataService(runner); - - IReadOnlyList rows = await service.GetFlsaAsync("E", TestContext.Current.CancellationToken); - - Assert.Equal(PersonnelDatabases.Pps, runner.ConnectionName); - Assert.Equal("usp_get_flsa", runner.Procedure); - Assert.Equal([StoredProcedureParameter.Text("statusType", "E", 1)], runner.Parameters); - Assert.Equal( - [ - new FlsaEmployeeRow("000123456", "Lovelace, Ada", "VME", "Professor", "EXEMPT", "ada@ucdavis.edu"), - new FlsaEmployeeRow(null, string.Empty, null, null, null, null), - ], - rows); - } - - [Fact] - public async Task GetFacultyAppointmentsAsync_AsksForEveryEmployeeInOneCall() - { - var table = new DataTable(); - foreach (string column in new[] { "EMPLOYEE_ID", "EMP_NAME", "APPT_DEPT", "TITLE", "HIRE_DATE" }) - { - table.Columns.Add(column, typeof(string)); - } - - table.Columns.Add("AGE", typeof(decimal)); - table.Rows.Add("000123456", "Lovelace, Ada", "VME", "PROF-AY ", "07/01/1995", 61m); - table.Rows.Add(DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, string.Empty, DBNull.Value); - var runner = new RecordingRunner(table); - var service = new PersonnelReportDataService(runner); - - IReadOnlyList rows = - await service.GetFacultyAppointmentsAsync("B", TestContext.Current.CancellationToken); - - Assert.Equal("usp_get_facultyList", runner.Procedure); - Assert.Equal( - [ - StoredProcedureParameter.Text("facultyType", "B", 1), - StoredProcedureParameter.Text("deptCode", string.Empty, 6), - StoredProcedureParameter.Text("employeeID", "All", 11), - ], - runner.Parameters); - Assert.Equal( - [ - new FacultyAppointmentRow("000123456", "Lovelace, Ada", 61, new DateOnly(1995, 7, 1), "VME", "PROF-AY"), - new FacultyAppointmentRow(string.Empty, string.Empty, null, null, null, null), - ], - rows); - } -} diff --git a/test/Personnel/PersonnelTestDoubles.cs b/test/Personnel/PersonnelTestDoubles.cs deleted file mode 100644 index a1cf9067e..000000000 --- a/test/Personnel/PersonnelTestDoubles.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Services; - -namespace Viper.test.Personnel; - -/// -/// Returns canned rows and records what each report asked for. -/// -internal sealed class StubPersonnelReportDataService : IPersonnelReportDataService -{ - public IReadOnlyList PeopleOnLeave { get; init; } = []; - - public (string Type, DateOnly Start, DateOnly End)? LeaveRequest { get; private set; } - - public IReadOnlyList FlsaEmployees { get; init; } = []; - - public string? FlsaRequest { get; private set; } - - public IReadOnlyList FacultyAppointments { get; init; } = []; - - public string? FacultyRequest { get; private set; } - - public Task> GetPeopleOnLeaveAsync( - string employeeType, DateOnly startDate, DateOnly endDate, CancellationToken ct) - { - LeaveRequest = (employeeType, startDate, endDate); - return Task.FromResult(PeopleOnLeave); - } - - public Task> GetFlsaAsync(string statusType, CancellationToken ct) - { - FlsaRequest = statusType; - return Task.FromResult(FlsaEmployees); - } - - public Task> GetFacultyAppointmentsAsync(string facultyType, CancellationToken ct) - { - FacultyRequest = facultyType; - return Task.FromResult(FacultyAppointments); - } -} 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/ReportAdminServiceTests.cs b/test/ReportBuilder/ReportAdminServiceTests.cs new file mode 100644 index 000000000..795267bb9 --- /dev/null +++ b/test/ReportBuilder/ReportAdminServiceTests.cs @@ -0,0 +1,474 @@ +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 = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + _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", (ReportFilterOperator?)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(((DateTime?)null, (string?)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 index 0b5a0d5db..dc0094507 100644 --- a/test/ReportBuilder/ReportBuilderDbContextTests.cs +++ b/test/ReportBuilder/ReportBuilderDbContextTests.cs @@ -64,6 +64,8 @@ public void Properties_MapToTheTablesColumnNames() 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] diff --git a/test/ReportBuilder/ReportBuilderFakes.cs b/test/ReportBuilder/ReportBuilderFakes.cs index 4cd330590..29b9169e2 100644 --- a/test/ReportBuilder/ReportBuilderFakes.cs +++ b/test/ReportBuilder/ReportBuilderFakes.cs @@ -70,3 +70,29 @@ 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/ReportDefinitionValidatorTests.cs b/test/ReportBuilder/ReportDefinitionValidatorTests.cs new file mode 100644 index 000000000..8e16b4282 --- /dev/null +++ b/test/ReportBuilder/ReportDefinitionValidatorTests.cs @@ -0,0 +1,339 @@ +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); + } + + [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/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..7a3f5d97a --- /dev/null +++ b/test/ReportBuilder/ReportProblemServiceTests.cs @@ -0,0 +1,191 @@ +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 = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + _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 index 8e85cf6fb..017d790c1 100644 --- a/test/ReportBuilder/ReportRunServiceTests.cs +++ b/test/ReportBuilder/ReportRunServiceTests.cs @@ -26,6 +26,9 @@ public sealed class ReportRunServiceTests : IDisposable 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 = new DbContextOptionsBuilder() @@ -62,6 +65,7 @@ public ReportRunServiceTests() public void Dispose() { _context.Dispose(); + _cancel.Dispose(); } private static CancellationToken Ct => TestContext.Current.CancellationToken; @@ -94,7 +98,7 @@ private sealed class StepClock : TimeProvider private sealed class FakeDbException : DbException { - public FakeDbException() : base("timeout") + public FakeDbException(string message = "timeout") : base(message) { } } @@ -117,7 +121,7 @@ private static ReportColumn Column(string name, int order, string? label = null, return new ReportColumn { SourceColumn = name, Label = label, DisplayOrder = order, Visible = visible, Sortable = sortable, Format = format }; } - private async Task AddRosterAsync(Action? configure = null) + private async Task AddRosterAsync(Action? configure = null) { var report = new ReportDefinition { @@ -144,10 +148,9 @@ private async Task AddRosterAsync(Action? co configure?.Invoke(report); _context.Reports.Add(report); await _context.SaveChangesAsync(Ct); - return report; } - private async Task AddLeaveAsync(Action? configure = null) + private async Task AddLeaveAsync(Action? configure = null) { var report = new ReportDefinition { @@ -167,7 +170,6 @@ private async Task AddLeaveAsync(Action? con configure?.Invoke(report); _context.Reports.Add(report); await _context.SaveChangesAsync(Ct); - return report; } private Task RunAsync(Guid slug, ReportRunRequest? request = null, ReportRunMode mode = ReportRunMode.Screen) @@ -489,12 +491,67 @@ public async Task Downloads_ReadEveryRowWithTheLongerTimeout(ReportRunMode mode, } [Fact] - public async Task View_DatabaseError_IsUnavailableAndNotLogged() + public async Task View_DatabaseError_IsUnavailableAndLoggedWithSqlServersReason() { await AddRosterAsync(); - _executor.Answer = _ => throw new FakeDbException(); + _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); } @@ -641,6 +698,58 @@ await AddLeaveAsync(r => 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] @@ -685,6 +794,81 @@ await AddLeaveAsync(r => r.Parameters = 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] diff --git a/test/ReportBuilder/ReportViewerServiceTests.cs b/test/ReportBuilder/ReportViewerServiceTests.cs new file mode 100644 index 000000000..fd214de58 --- /dev/null +++ b/test/ReportBuilder/ReportViewerServiceTests.cs @@ -0,0 +1,264 @@ +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 = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + _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/test/Reports/Data/DataRecordExtensionsTests.cs b/test/Reports/Data/DataRecordExtensionsTests.cs deleted file mode 100644 index 0d6b8eac9..000000000 --- a/test/Reports/Data/DataRecordExtensionsTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Data; -using Viper.Areas.Reports.Data; - -namespace Viper.test.Reports; - -public sealed class DataRecordExtensionsTests -{ - private static DataTableReader Reader(object text, object date, object number) - { - var table = new DataTable(); - table.Columns.Add("text", typeof(string)); - table.Columns.Add("date", typeof(DateTime)); - table.Columns.Add("number", typeof(int)); - table.Rows.Add(text, date, number); - DataTableReader reader = table.CreateDataReader(); - reader.Read(); - return reader; - } - - [Fact] - public void GetTrimmedString_TrimsCharPadding() - { - using DataTableReader reader = Reader("Medicine ", DBNull.Value, 7); - - Assert.Equal("Medicine", reader.GetTrimmedString("text")); - Assert.Equal("7", reader.GetTrimmedString("number")); - } - - [Fact] - public void GetTrimmedString_Null_IsNull() - { - using DataTableReader reader = Reader(DBNull.Value, DBNull.Value, 7); - - Assert.Null(reader.GetTrimmedString("text")); - } - - [Fact] - public void GetDateOnly_DropsTheTime() - { - using DataTableReader reader = Reader("a", new DateTime(2026, 7, 1, 13, 30, 0, DateTimeKind.Local), 7); - - Assert.Equal(new DateOnly(2026, 7, 1), reader.GetDateOnly("date")); - } - - [Fact] - public void GetDateOnly_Null_IsNull() - { - using DataTableReader reader = Reader("a", DBNull.Value, 7); - - Assert.Null(reader.GetDateOnly("date")); - } - - [Theory] - [InlineData("07/01/1995 ", 1995, 7, 1)] - [InlineData("12/31/2020", 2020, 12, 31)] - public void GetDateOnlyFromText_ReadsTheFormat(string text, int year, int month, int day) - { - using DataTableReader reader = Reader(text, DBNull.Value, 7); - - Assert.Equal(new DateOnly(year, month, day), reader.GetDateOnlyFromText("text", "MM/dd/yyyy")); - } - - [Theory] - [InlineData("")] - [InlineData("not a date")] - public void GetDateOnlyFromText_BlankOrUnreadable_IsNull(string text) - { - using DataTableReader reader = Reader(text, DBNull.Value, 7); - - Assert.Null(reader.GetDateOnlyFromText("text", "MM/dd/yyyy")); - } - - [Fact] - public void GetDateOnlyFromText_Null_IsNull() - { - using DataTableReader reader = Reader(DBNull.Value, DBNull.Value, 7); - - Assert.Null(reader.GetDateOnlyFromText("text", "MM/dd/yyyy")); - } - - [Fact] - public void GetNullableInt32_ConvertsAnyNumber() - { - var table = new DataTable(); - table.Columns.Add("whole", typeof(decimal)); - table.Columns.Add("missing", typeof(decimal)); - table.Rows.Add(61m, DBNull.Value); - using DataTableReader reader = table.CreateDataReader(); - reader.Read(); - - Assert.Equal(61, reader.GetNullableInt32("whole")); - Assert.Null(reader.GetNullableInt32("missing")); - } - - [Fact] - public void NullRecord_Throws() - { - IDataRecord record = null!; - - Assert.Throws(() => record.GetTrimmedString("text")); - Assert.Throws(() => record.GetDateOnly("date")); - Assert.Throws(() => record.GetDateOnlyFromText("text", "MM/dd/yyyy")); - Assert.Throws(() => record.GetNullableInt32("number")); - } -} diff --git a/test/Reports/Data/FakeDb.cs b/test/Reports/Data/FakeDb.cs deleted file mode 100644 index 5740e0518..000000000 --- a/test/Reports/Data/FakeDb.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System.Data; -using System.Data.Common; -using System.Diagnostics.CodeAnalysis; -using Microsoft.Data.SqlClient; -using Viper.Areas.Reports.Data; - -namespace Viper.test.Reports; - -/// -/// Hands out one and records the name it was asked for. -/// -internal sealed class FakeDbConnectionFactory : IDbConnectionFactory -{ - public FakeDbConnectionFactory(DataTable result) - { - Connection = new FakeDbConnection(result); - } - - public FakeDbConnection Connection { get; } - - public string? RequestedName { get; private set; } - - public DbConnection Create(string connectionStringName) - { - RequestedName = connectionStringName; - return Connection; - } -} - -/// -/// A connection whose commands return a fixed table, so the stored procedure runner can be -/// tested without SQL Server. It records whether it was opened and disposed, and the last command. -/// -internal sealed class FakeDbConnection : DbConnection -{ - private readonly DataTable _result; - private ConnectionState _state = ConnectionState.Closed; - - public FakeDbConnection(DataTable result) - { - _result = result; - } - - public FakeDbCommand? LastCommand { get; private set; } - - public bool WasDisposed { get; private set; } - - [AllowNull] - public override string ConnectionString { get; set; } = string.Empty; - - public override string Database => "Fake"; - - public override string DataSource => "Fake"; - - public override string ServerVersion => "0"; - - public override ConnectionState State => _state; - - public override void ChangeDatabase(string databaseName) - { - throw new NotSupportedException(); - } - - public override void Close() - { - _state = ConnectionState.Closed; - } - - public override void Open() - { - _state = ConnectionState.Open; - } - - protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) - { - throw new NotSupportedException(); - } - - protected override DbCommand CreateDbCommand() - { - LastCommand = new FakeDbCommand(this, _result); - return LastCommand; - } - - protected override void Dispose(bool disposing) - { - WasDisposed = true; - base.Dispose(disposing); - } -} - -/// -/// A command that returns its table's rows. Parameters use a real SqlCommand's collection, so -/// they behave exactly as they would against SQL Server. -/// -internal sealed class FakeDbCommand : DbCommand -{ - private readonly DataTable _result; - private readonly SqlCommand _parameters = new(); - - public FakeDbCommand(DbConnection connection, DataTable result) - { - DbConnection = connection; - _result = result; - } - - public bool WasDisposed { get; private set; } - - [AllowNull] - public override string CommandText { get; set; } = string.Empty; - - public override int CommandTimeout { get; set; } - - public override CommandType CommandType { get; set; } - - public override bool DesignTimeVisible { get; set; } - - public override UpdateRowSource UpdatedRowSource { get; set; } - - protected override DbConnection? DbConnection { get; set; } - - protected override DbParameterCollection DbParameterCollection => _parameters.Parameters; - - protected override DbTransaction? DbTransaction { get; set; } - - public override void Cancel() - { - throw new NotSupportedException(); - } - - public override int ExecuteNonQuery() - { - throw new NotSupportedException(); - } - - public override object? ExecuteScalar() - { - throw new NotSupportedException(); - } - - public override void Prepare() - { - throw new NotSupportedException(); - } - - protected override DbParameter CreateDbParameter() - { - return new SqlParameter(); - } - - protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) - { - return _result.CreateDataReader(); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - _parameters.Dispose(); - } - - WasDisposed = true; - base.Dispose(disposing); - } -} diff --git a/test/Reports/Data/StoredProcedureParameterTests.cs b/test/Reports/Data/StoredProcedureParameterTests.cs deleted file mode 100644 index 1b8e74c4a..000000000 --- a/test/Reports/Data/StoredProcedureParameterTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Data; -using Viper.Areas.Reports.Data; - -namespace Viper.test.Reports; - -public sealed class StoredProcedureParameterTests -{ - [Fact] - public void Text_IsAnAnsiStringWithItsDeclaredSize() - { - StoredProcedureParameter parameter = StoredProcedureParameter.Text("employeeType", "F", 1); - - Assert.Equal("@employeeType", parameter.Name); - Assert.Equal(DbType.AnsiString, parameter.Type); - Assert.Equal("F", parameter.Value); - Assert.Equal(1, parameter.Size); - } - - [Fact] - public void Date_IsMidnightOnTheDate() - { - StoredProcedureParameter parameter = StoredProcedureParameter.Date("@startDate", new DateOnly(2026, 7, 1)); - - Assert.Equal("@startDate", parameter.Name); - Assert.Equal(DbType.DateTime, parameter.Type); - Assert.Equal(new DateTime(2026, 7, 1, 0, 0, 0, DateTimeKind.Unspecified), parameter.Value); - Assert.Null(parameter.Size); - } - - [Fact] - public void Date_Null_HasNoValue() - { - Assert.Null(StoredProcedureParameter.Date("endDate", null).Value); - } - - [Theory] - [InlineData("")] - [InlineData(" ")] - public void BlankName_Throws(string name) - { - Assert.Throws(() => StoredProcedureParameter.Text(name, "F", 1)); - } -} diff --git a/test/Reports/Data/StoredProcedureRunnerTests.cs b/test/Reports/Data/StoredProcedureRunnerTests.cs deleted file mode 100644 index 15faed833..000000000 --- a/test/Reports/Data/StoredProcedureRunnerTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Data; -using System.Data.Common; -using Viper.Areas.Reports.Data; - -namespace Viper.test.Reports; - -public sealed class StoredProcedureRunnerTests -{ - private static DataTable People() - { - var table = new DataTable(); - table.Columns.Add("Name", typeof(string)); - table.Rows.Add("Ada"); - table.Rows.Add("Bo"); - return table; - } - - [Fact] - public async Task QueryAsync_CallsTheProcedureWithTypedParameters() - { - var connections = new FakeDbConnectionFactory(People()); - var runner = new StoredProcedureRunner(connections); - - await runner.QueryAsync( - "PPS", - "usp_get_people", - [StoredProcedureParameter.Text("type", "F", 1), StoredProcedureParameter.Date("from", null)], - record => record.GetString(0), - TestContext.Current.CancellationToken); - - FakeDbCommand command = Assert.IsType(connections.Connection.LastCommand); - Assert.Equal("PPS", connections.RequestedName); - Assert.Equal(CommandType.StoredProcedure, command.CommandType); - Assert.Equal("usp_get_people", command.CommandText); - Assert.Equal(StoredProcedureRunner.CommandTimeoutSeconds, command.CommandTimeout); - - DbParameter[] parameters = [.. command.Parameters.Cast()]; - Assert.Equal(["@type", "@from"], parameters.Select(parameter => parameter.ParameterName)); - Assert.Equal("F", parameters[0].Value); - Assert.Equal(DBNull.Value, parameters[1].Value); - } - - [Fact] - public async Task QueryAsync_MapsEveryRowAndClosesUp() - { - var connections = new FakeDbConnectionFactory(People()); - var runner = new StoredProcedureRunner(connections); - - IReadOnlyList names = await runner.QueryAsync( - "PPS", "usp_get_people", [], record => record.GetString(0), TestContext.Current.CancellationToken); - - Assert.Equal(["Ada", "Bo"], names); - Assert.True(connections.Connection.WasDisposed); - Assert.True(connections.Connection.LastCommand is { WasDisposed: true }); - } - - [Fact] - public async Task QueryAsync_OpensTheConnectionFirst() - { - var connections = new FakeDbConnectionFactory(People()); - var runner = new StoredProcedureRunner(connections); - ConnectionState stateWhileReading = ConnectionState.Closed; - - await runner.QueryAsync( - "PPS", - "usp_get_people", - [], - _ => stateWhileReading = connections.Connection.State, - TestContext.Current.CancellationToken); - - Assert.Equal(ConnectionState.Open, stateWhileReading); - } - - [Fact] - public async Task QueryAsync_BadArguments_Throw() - { - var runner = new StoredProcedureRunner(new FakeDbConnectionFactory(People())); - CancellationToken ct = TestContext.Current.CancellationToken; - - await Assert.ThrowsAsync(() => runner.QueryAsync("PPS", " ", [], record => 1, ct)); - await Assert.ThrowsAsync(() => runner.QueryAsync("PPS", "usp_x", null!, record => 1, ct)); - await Assert.ThrowsAsync( - () => runner.QueryAsync("PPS", "usp_x", [], null!, ct)); - } -} diff --git a/test/Reports/ReportBuilderTests.cs b/test/Reports/ReportBuilderTests.cs deleted file mode 100644 index eccf3b6d5..000000000 --- a/test/Reports/ReportBuilderTests.cs +++ /dev/null @@ -1,248 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportBuilderTests -{ - private static readonly IReadOnlyList SingleOption = [new("X", "Option X")]; - - #region Parameters - - [Fact] - public void Parameters_UseCamelCasePropertyNamesAndDeclaredTypes() - { - var builder = new ReportBuilder(); - TestReport.Standard(builder); - - Assert.Equal( - ["facultyType", "departments", "startDate", "endDate", "search", "minimumAge", "includeEmeriti"], - builder.Parameters.Select(parameter => parameter.Name)); - Assert.Equal( - [ - ReportParameterType.Choice, - ReportParameterType.MultiChoice, - ReportParameterType.Date, - ReportParameterType.Date, - ReportParameterType.Text, - ReportParameterType.Number, - ReportParameterType.Boolean, - ], - builder.Parameters.Select(parameter => parameter.Type)); - } - - [Fact] - public void Choice_EmptyOptions_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Choice(p => p.FacultyType, "Faculty type", [])); - } - - [Fact] - public void MultiChoice_NullOptions_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.MultiChoice(p => p.Departments, "Departments", null!)); - } - - [Fact] - public void Parameter_BlankLabel_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Text(p => p.Search, " ")); - } - - [Fact] - public void Parameter_NullSelector_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Text(null!, "Search")); - } - - [Fact] - public void Parameter_ComputedExpression_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Text(p => p.Search + "x", "Search")); - } - - [Fact] - public void Parameter_NestedProperty_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Text(p => p.Inner.Value, "Inner value")); - } - - [Fact] - public void Parameter_ReadOnlyProperty_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Text(p => p.Computed, "Computed")); - } - - [Fact] - public void Default_NullFactory_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Choice(p => p.FacultyType, "Type", SingleOption).Default(null!)); - } - - [Fact] - public void Parameter_WithoutDefault_HasNullDefaultInMetadata() - { - var builder = new ReportBuilder(); - builder.Number(p => p.MinimumAge, "Minimum age"); - - ReportParameterMetadata metadata = builder.Parameters[0].ToMetadata(); - - Assert.Null(metadata.DefaultValue); - Assert.False(metadata.Required); - Assert.Empty(metadata.Options); - } - - [Fact] - public void Validate_NullRuleOrBlankMessage_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Validate(null!, "Message")); - Assert.Throws(() => builder.Validate(_ => true, " ")); - } - - #endregion - - #region Columns - - [Fact] - public void Column_DefaultsToTextLeftAlignedWithPropertyKey() - { - var builder = new ReportBuilder(); - builder.Column(r => r.Department, "Department"); - - ReportColumnMetadata metadata = builder.Columns[0].ToMetadata(); - - Assert.Equal(new ReportColumnMetadata("department", "Department", ReportColumnFormat.Text, ReportAlignment.Left, null), metadata); - } - - [Fact] - public void Column_ValueReadsFromRow() - { - var builder = new ReportBuilder(); - builder.Column(r => r.Age, "Age"); - var row = new SampleRow("Ada", "APC", 61, 100_000m, new DateOnly(2001, 9, 1)); - - Assert.Equal(61, builder.Columns[0].Value(row)); - } - - [Fact] - public void Column_ComputedSelectorWithKey_UsesKey() - { - var builder = new ReportBuilder(); - builder.Column(r => r.Name + " (" + r.Department + ")", "Name and department", "nameAndDepartment"); - var row = new SampleRow("Ada", "APC", 61, 100_000m, new DateOnly(2001, 9, 1)); - - Assert.Equal("nameAndDepartment", builder.Columns[0].Key); - Assert.Equal("Ada (APC)", builder.Columns[0].Value(row)); - } - - [Fact] - public void Column_ComputedSelectorWithoutKey_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Column(r => r.Name.Length, "Name length")); - } - - [Fact] - public void Column_FieldSelectorWithoutKey_Throws() - { - var builder = new ReportBuilder<(string Code, int Count), SampleParams>(); - - Assert.Throws(() => builder.Column(r => r.Code, "Code")); - } - - [Fact] - public void Column_InvalidArguments_Throw() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Column(null!, "Name")); - Assert.Throws(() => builder.Column(r => r.Name, " ")); - Assert.Throws(() => builder.Column(r => r.Name, "Name", " ")); - } - - [Fact] - public void ColumnFormats_SetFormatAlignmentAndDecimals() - { - var builder = new ReportBuilder(); - builder.Column(r => r.Age, "Age").AsNumber(1); - builder.Column(r => r.Salary, "Salary").AsCurrency(); - builder.Column(r => r.Age, "Share", "share").AsPercent(2); - builder.Column(r => r.HireDate, "Hire date").AsDate(); - builder.Column(r => r.Department, "Departments", "departments").AsList(); - - ReportColumnMetadata[] columns = [.. builder.Columns.Select(column => column.ToMetadata())]; - - Assert.Equal((ReportColumnFormat.Number, ReportAlignment.Right, 1), Describe(columns[0])); - Assert.Equal((ReportColumnFormat.Currency, ReportAlignment.Right, 2), Describe(columns[1])); - Assert.Equal((ReportColumnFormat.Percent, ReportAlignment.Right, 2), Describe(columns[2])); - Assert.Equal((ReportColumnFormat.Date, ReportAlignment.Center, (int?)null), Describe(columns[3])); - Assert.Equal((ReportColumnFormat.List, ReportAlignment.Left, (int?)null), Describe(columns[4])); - } - - [Fact] - public void Align_OverridesFormatAlignment() - { - var builder = new ReportBuilder(); - builder.Column(r => r.HireDate, "Hire date").AsDate().Align(ReportAlignment.Left); - - Assert.Equal(ReportAlignment.Left, builder.Columns[0].Align); - } - - [Fact] - public void NegativeDecimals_Throw() - { - var builder = new ReportBuilder(); - ReportColumnBuilder column = builder.Column(r => r.Age, "Age"); - - Assert.Throws(() => column.AsNumber(-1)); - Assert.Throws(() => column.AsPercent(-1)); - } - - [Fact] - public void VisibleWhen_ControlsVisibility() - { - var builder = new ReportBuilder(); - builder.Column(r => r.Name, "Name"); - builder.Column(r => r.Salary, "Salary").VisibleWhen(context => context.HasPermission(TestReport.SalaryPermission)); - - ReportContext withSalary = TestReport.ContextWith(TestReport.SalaryPermission); - ReportContext withoutSalary = TestReport.ContextWith(); - - Assert.True(builder.Columns[0].IsVisible(withoutSalary)); - Assert.True(builder.Columns[1].IsVisible(withSalary)); - Assert.False(builder.Columns[1].IsVisible(withoutSalary)); - } - - [Fact] - public void VisibleWhen_NullPredicate_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Column(r => r.Name, "Name").VisibleWhen(null!)); - } - - #endregion - - private static (ReportColumnFormat Format, ReportAlignment Align, int? Decimals) Describe(ReportColumnMetadata column) - { - return (column.Format, column.Align, column.Decimals); - } -} diff --git a/test/Reports/ReportContextTests.cs b/test/Reports/ReportContextTests.cs deleted file mode 100644 index 9775569f1..000000000 --- a/test/Reports/ReportContextTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportContextTests -{ - [Fact] - public void Constructor_NullPermissionCheck_Throws() - { - Assert.Throws(() => new ReportContext("user", null!)); - } - - [Fact] - public void LoginId_ReturnsSuppliedValue() - { - var context = new ReportContext("jdoe", _ => false); - - Assert.Equal("jdoe", context.LoginId); - } - - [Fact] - public void HasPermission_DelegatesToPermissionCheck() - { - ReportContext context = TestReport.ContextWith("SVMSecure.A"); - - Assert.True(context.HasPermission("SVMSecure.A")); - Assert.False(context.HasPermission("SVMSecure.B")); - } - - [Theory] - [InlineData("")] - [InlineData(" ")] - public void HasPermission_BlankPermission_ReturnsFalseWithoutCheckingUser(string permission) - { - int checks = 0; - var context = new ReportContext("jdoe", _ => - { - checks++; - return true; - }); - - Assert.False(context.HasPermission(permission)); - Assert.Equal(0, checks); - } - - [Fact] - public void HasAnyPermission_OneMatch_ReturnsTrue() - { - ReportContext context = TestReport.ContextWith("SVMSecure.B"); - - Assert.True(context.HasAnyPermission(["SVMSecure.A", "SVMSecure.B"])); - } - - [Fact] - public void HasAnyPermission_NoMatchOrEmptyList_ReturnsFalse() - { - ReportContext context = TestReport.ContextWith("SVMSecure.C"); - - Assert.False(context.HasAnyPermission(["SVMSecure.A", "SVMSecure.B"])); - Assert.False(context.HasAnyPermission([])); - } - - [Fact] - public void HasAnyPermission_NullList_Throws() - { - ReportContext context = TestReport.ContextWith(); - - Assert.Throws(() => context.HasAnyPermission(null!)); - } -} diff --git a/test/Reports/ReportCsvExporterTests.cs b/test/Reports/ReportCsvExporterTests.cs deleted file mode 100644 index 00569c1af..000000000 --- a/test/Reports/ReportCsvExporterTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Text; -using Viper.Areas.Reports.Exporters; - -namespace Viper.test.Reports; - -public sealed class ReportCsvExporterTests -{ - private readonly ReportCsvExporter _exporter = new(); - - private string[] Lines(ReportExport export) - { - byte[] bytes = _exporter.Export(export); - Assert.Equal(Encoding.UTF8.GetPreamble(), bytes[..3]); - string text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3); - Assert.EndsWith("\r\n", text, StringComparison.Ordinal); - return text[..^2].Split("\r\n"); - } - - [Fact] - public void Describes_ItsFormat() - { - Assert.Equal("csv", _exporter.Format); - Assert.Equal("text/csv", _exporter.ContentType); - Assert.Equal(".csv", _exporter.Extension); - } - - [Fact] - public void Plain_WritesHeaderAndOneLinePerRow() - { - string[] lines = Lines(ReportExportTestData.Export(ReportExportTestData.Plain())); - - Assert.Equal("Name,Department,Salary", lines[0]); - Assert.Equal("Ada,VME,\"$120,000.00\"", lines[1]); - Assert.Equal("Cy,VME ,", lines[3]); - Assert.Equal(6, lines.Length); - } - - [Fact] - public void Grouped_AddsGroupAndNotesColumns() - { - string[] lines = Lines(ReportExportTestData.Export(ReportExportTestData.Full(), confidential: true)); - - Assert.Equal("Group,Name,Age,Salary,Hire date,Ethnicities,Notes", lines[0]); - Assert.Equal("(Not specified),Ed,29,\"$70,000.00\",08/15/2022,White,Under 30", lines[1]); - Assert.Equal("VME,Ada,61,\"$120,000.00\",07/01/1995,\"Asian, White\",60+", lines[3]); - Assert.Equal("VME,Cy,38,,09/01/2018,Hispanic,No salary", lines[4]); - Assert.Equal("VME,Di,66,\"$150,000.00\",03/01/1990,,Retirement age; 60+", lines[5]); - } - - [Fact] - public void EdgeCases_SanitizeFormulasAndKeepTextInNumericColumns() - { - string[] lines = Lines(ReportExportTestData.Export(ReportExportTestData.EdgeCases())); - - Assert.Equal("Name,When,Share,Amount,Notes", lines[0]); - Assert.StartsWith("'=cmd|' /C calc'!A0,01/02/2026,", lines[1], StringComparison.Ordinal); - Assert.EndsWith(",pending,Check", lines[1], StringComparison.Ordinal); - Assert.Equal(2, lines.Length); - } - - [Theory] - [InlineData("plain", "plain")] - [InlineData("a,b", "\"a,b\"")] - [InlineData("say \"hi\"", "\"say \"\"hi\"\"\"")] - [InlineData("line\nbreak", "\"line\nbreak\"")] - public void Quote_FollowsRfc4180(string value, string expected) - { - Assert.Equal(expected, ReportCsvExporter.Quote(value)); - } - - [Fact] - public void NullExport_Throws() - { - Assert.Throws(() => _exporter.Export(null!)); - } -} diff --git a/test/Reports/ReportDefinitionContractTests.cs b/test/Reports/ReportDefinitionContractTests.cs deleted file mode 100644 index 5d9f1b2a2..000000000 --- a/test/Reports/ReportDefinitionContractTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Text.Json; -using Viper.Areas.Personnel.Reports; -using Viper.Areas.Reports.Engine; -using Viper.test.Personnel; - -namespace Viper.test.Reports; - -/// -/// Checks every report definition against the rules the engine relies on but the compiler can't -/// enforce. New reports join by being added to , so each one gets these -/// checks without writing them again. -/// -public sealed class ReportDefinitionContractTests -{ - private static readonly JsonSerializerOptions WebJson = new(JsonSerializerDefaults.Web); - - private static readonly Dictionary> Definitions = new(StringComparer.Ordinal) - { - ["test.sample"] = () => new TestReport(), - ["personnel.employees-on-leave"] = () => - new EmployeesOnLeaveReport(new StubPersonnelReportDataService(), new FixedTimeProvider(DateTimeOffset.UnixEpoch)), - ["personnel.exempt-non-exempt"] = () => new ExemptStatusReport(new StubPersonnelReportDataService()), - ["personnel.faculty-profile"] = () => new FacultyProfileReport(new StubPersonnelReportDataService()), - }; - - public static TheoryData DefinitionKeys() - { - return [.. Definitions.Keys]; - } - - private static ReportContext Everyone() - { - return new ReportContext("contract", _ => true); - } - - [Theory] - [MemberData(nameof(DefinitionKeys))] - public void Definition_HasAValidRegistryIdentity(string key) - { - IReportDefinition definition = Definitions[key](); - - var registry = new ReportRegistry([definition]); - - Assert.Same(definition, registry.Find(key)); - } - - [Theory] - [MemberData(nameof(DefinitionKeys))] - public void Metadata_SerializesToJson(string key) - { - IReportDefinition definition = Definitions[key](); - - string json = JsonSerializer.Serialize(definition.GetMetadata(Everyone()), WebJson); - - Assert.Contains($"\"key\":\"{key}\"", json, StringComparison.Ordinal); - } - - [Theory] - [MemberData(nameof(DefinitionKeys))] - public void EveryParameterName_BindsFromJson(string key) - { - IReportDefinition definition = Definitions[key](); - IEnumerable names = definition.GetMetadata(Everyone()).Parameters.Select(parameter => parameter.Name); - using JsonDocument body = JsonDocument.Parse("{" + string.Join(",", names.Select(name => $"\"{name}\":null")) + "}"); - - bool bound = ReportParameterBinder.TryBind(definition.ParametersType, body.RootElement, out _, out ReportValidationError? error); - - Assert.True(bound, error?.Message); - } - - [Theory] - [MemberData(nameof(DefinitionKeys))] - public async Task DefaultParameters_RunAndSerialize(string key) - { - IReportDefinition definition = Definitions[key](); - ReportContext context = Everyone(); - bool bound = ReportParameterBinder.TryBind(definition.ParametersType, null, out object? parameters, out _); - Assert.True(bound); - Assert.NotNull(parameters); - Assert.Empty(definition.PrepareParameters(parameters)); - - ReportResult result = await definition.RunAsync(parameters, context, DateTimeOffset.UnixEpoch, TestContext.Current.CancellationToken); - - Assert.Equal(key, result.Key); - Assert.NotEmpty(JsonSerializer.Serialize(result, WebJson)); - } -} diff --git a/test/Reports/ReportDefinitionTests.cs b/test/Reports/ReportDefinitionTests.cs deleted file mode 100644 index 2ab2d2732..000000000 --- a/test/Reports/ReportDefinitionTests.cs +++ /dev/null @@ -1,263 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportDefinitionTests -{ - #region Metadata and access - - [Fact] - public void GetMetadata_DescribesReportParametersAndColumns() - { - var report = new TestReport(); - - ReportDefinitionMetadata metadata = report.GetMetadata( - TestReport.ContextWith(TestReport.RunPermission, TestReport.SalaryPermission)); - - Assert.Equal("test.sample", metadata.Key); - Assert.Equal("Sample report", metadata.Title); - Assert.Equal("Test", metadata.Area); - Assert.Equal("A report used by tests.", metadata.Description); - Assert.Equal(7, metadata.Parameters.Count); - Assert.Equal( - new ReportParameterMetadata("facultyType", "Faculty type", ReportParameterType.Choice, true, "S", TestReport.FacultyTypes), - metadata.Parameters[0]); - Assert.Equal(TestReport.DefaultStart, metadata.Parameters[2].DefaultValue); - Assert.Equal(["name", "department", "age", "salary", "hireDate"], metadata.Columns.Select(column => column.Key)); - } - - [Fact] - public void GetMetadata_HidesColumnsTheUserCannotSee() - { - var report = new TestReport(); - - ReportDefinitionMetadata metadata = report.GetMetadata(TestReport.ContextWith(TestReport.RunPermission)); - - Assert.DoesNotContain(metadata.Columns, column => column.Key == "salary"); - } - - [Fact] - public void GetMetadata_NullContext_Throws() - { - var report = new TestReport(); - - Assert.Throws(() => report.GetMetadata(null!)); - } - - [Fact] - public void Layout_IsConfiguredOnce() - { - var report = new TestReport(); - ReportContext context = TestReport.ContextWith(); - - report.GetMetadata(context); - report.PrepareParameters(new SampleParams()); - - Assert.Equal(1, report.ConfigureCalls); - } - - [Fact] - public void CanRun_RequiresAnyReportPermission() - { - var report = new TestReport(permissions: ["SVMSecure.Test.A", "SVMSecure.Test.B"]); - - Assert.True(report.CanRun(TestReport.ContextWith("SVMSecure.Test.B"))); - Assert.False(report.CanRun(TestReport.ContextWith("SVMSecure.Test.C"))); - } - - [Fact] - public void CanRun_NullContext_Throws() - { - var report = new TestReport(); - - Assert.Throws(() => report.CanRun(null!)); - } - - #endregion - - #region Layout validation - - [Fact] - public void Layout_WithoutColumns_Throws() - { - var report = new TestReport(report => report.Text(p => p.Search, "Search")); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - [Fact] - public void Layout_DuplicateColumnKey_Throws() - { - var report = new TestReport(report => - { - report.Column(r => r.Name, "Name"); - report.Column(r => r.Department, "Also name", "NAME"); - }); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - [Fact] - public void Layout_DuplicateParameter_Throws() - { - var report = new TestReport(report => - { - report.Text(p => p.Search, "Search"); - report.Text(p => p.Search, "Search again"); - report.Column(r => r.Name, "Name"); - }); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - #endregion - - #region Parameter preparation - - [Fact] - public void PrepareParameters_FillsEmptyValuesWithDefaults() - { - var report = new TestReport(); - var parameters = new SampleParams { FacultyType = " " }; - - IReadOnlyList errors = report.PrepareParameters(parameters); - - Assert.Empty(errors); - Assert.Equal("S", parameters.FacultyType); - Assert.Equal(TestReport.DefaultStart, parameters.StartDate); - } - - [Fact] - public void PrepareParameters_KeepsSuppliedValues() - { - var report = new TestReport(); - var parameters = new SampleParams - { - FacultyType = "F", - Departments = ["APC", "VME"], - StartDate = new DateOnly(2025, 1, 1), - EndDate = new DateOnly(2025, 6, 30), - Search = "smith", - MinimumAge = 60, - IncludeEmeriti = false, - }; - - IReadOnlyList errors = report.PrepareParameters(parameters); - - Assert.Empty(errors); - Assert.Equal("F", parameters.FacultyType); - Assert.Equal(new DateOnly(2025, 1, 1), parameters.StartDate); - } - - [Theory] - [InlineData(null)] - [InlineData(" ")] - public void PrepareParameters_MissingRequiredValue_ReturnsFieldError(string? search) - { - var report = new TestReport(report => - { - report.Text(p => p.Search, "Search").Required(); - report.Column(r => r.Name, "Name"); - }); - - IReadOnlyList errors = report.PrepareParameters(new SampleParams { Search = search }); - - Assert.Equal([new ReportValidationError("search", "Search is required.")], errors); - } - - [Fact] - public void PrepareParameters_EmptyRequiredList_ReturnsFieldError() - { - var report = new TestReport(report => - { - report.MultiChoice(p => p.Departments, "Departments", TestReport.DepartmentOptions).Required(); - report.Column(r => r.Name, "Name"); - }); - - IReadOnlyList errors = report.PrepareParameters(new SampleParams { Departments = [] }); - - Assert.Equal([new ReportValidationError("departments", "Departments is required.")], errors); - } - - [Fact] - public void PrepareParameters_UnknownChoice_ReturnsFieldError() - { - var report = new TestReport(); - - IReadOnlyList errors = report.PrepareParameters(new SampleParams { FacultyType = "X" }); - - Assert.Equal( - [new ReportValidationError("facultyType", "Faculty type contains a value that is not an allowed option.")], - errors); - } - - [Fact] - public void PrepareParameters_UnknownValueInMultiChoice_ReturnsFieldError() - { - var report = new TestReport(); - - IReadOnlyList errors = - report.PrepareParameters(new SampleParams { Departments = ["APC", "XYZ"] }); - - Assert.Equal( - [new ReportValidationError("departments", "Departments contains a value that is not an allowed option.")], - errors); - } - - [Fact] - public void PrepareParameters_FailingRule_ReturnsRuleError() - { - var report = new TestReport(); - var parameters = new SampleParams { StartDate = new DateOnly(2025, 7, 1), EndDate = new DateOnly(2025, 6, 30) }; - - IReadOnlyList errors = report.PrepareParameters(parameters); - - Assert.Equal([new ReportValidationError("endDate", "End date must be on or after the start date.")], errors); - } - - [Fact] - public void PrepareParameters_RuleWithoutParameter_ReturnsFormLevelError() - { - var report = new TestReport(report => - { - report.Validate(p => p.Search is not null || p.MinimumAge is not null, "Enter a search or a minimum age."); - report.Column(r => r.Name, "Name"); - }); - - IReadOnlyList errors = report.PrepareParameters(new SampleParams()); - - Assert.Equal([new ReportValidationError(null, "Enter a search or a minimum age.")], errors); - } - - [Fact] - public void PrepareParameters_FieldErrors_SkipRules() - { - int ruleCalls = 0; - var report = new TestReport(report => - { - report.Text(p => p.Search, "Search").Required(); - report.Validate(_ => - { - ruleCalls++; - return false; - }, "Never reported."); - report.Column(r => r.Name, "Name"); - }); - - IReadOnlyList errors = report.PrepareParameters(new SampleParams()); - - Assert.Single(errors); - Assert.Equal(0, ruleCalls); - } - - [Fact] - public void PrepareParameters_WrongParameterType_Throws() - { - var report = new TestReport(); - - Assert.Throws(() => report.PrepareParameters("not parameters")); - Assert.Throws(() => report.PrepareParameters(null!)); - } - - #endregion -} diff --git a/test/Reports/ReportDescribeParametersTests.cs b/test/Reports/ReportDescribeParametersTests.cs deleted file mode 100644 index f723f718a..000000000 --- a/test/Reports/ReportDescribeParametersTests.cs +++ /dev/null @@ -1,73 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportDescribeParametersTests -{ - [Fact] - public void DescribeParameters_UsesLabelsAndReadableValues() - { - var report = new TestReport(); - var parameters = new SampleParams - { - FacultyType = "F", - Departments = ["VME", "APC"], - StartDate = new DateOnly(2025, 7, 1), - Search = "smith", - MinimumAge = 60, - IncludeEmeriti = true, - }; - - IReadOnlyList filters = report.DescribeParameters(parameters); - - Assert.Equal( - [ - new ReportFilter("Faculty type", "Federation"), - new ReportFilter("Departments", "Medicine and Epidemiology, Anatomy, Physiology and Cell Biology"), - new ReportFilter("Start date", "07/01/2025"), - new ReportFilter("Search", "smith"), - new ReportFilter("Minimum age", "60"), - new ReportFilter("Include emeriti", "Yes"), - ], - filters); - } - - [Fact] - public void DescribeParameters_SkipsEmptyValuesAndShowsNo() - { - var report = new TestReport(); - - IReadOnlyList filters = report.DescribeParameters(new SampleParams { IncludeEmeriti = false, Search = " " }); - - Assert.Equal([new ReportFilter("Include emeriti", "No")], filters); - } - - [Fact] - public void DescribeParameters_UnknownChoice_ShowsTheRawValue() - { - var report = new TestReport(); - - IReadOnlyList filters = report.DescribeParameters(new SampleParams { FacultyType = "Z" }); - - Assert.Equal([new ReportFilter("Faculty type", "Z")], filters); - } - - [Fact] - public void DescribeParameters_WrongType_Throws() - { - Assert.Throws(() => new TestReport().DescribeParameters("parameters")); - } - - [Fact] - public void IsSensitive_FollowsTheLayout() - { - var sensitive = new TestReport(report => - { - report.Sensitive(); - report.Column(row => row.Name, "Name"); - }); - - Assert.False(new TestReport().IsSensitive); - Assert.True(sensitive.IsSensitive); - } -} diff --git a/test/Reports/ReportExcelExporterTests.cs b/test/Reports/ReportExcelExporterTests.cs deleted file mode 100644 index 37674857b..000000000 --- a/test/Reports/ReportExcelExporterTests.cs +++ /dev/null @@ -1,194 +0,0 @@ -using ClosedXML.Excel; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Exporters; - -namespace Viper.test.Reports; - -public sealed class ReportExcelExporterTests -{ - private readonly ReportExcelExporter _exporter = new(); - - private MemoryStream Export(ReportExport export) - { - return new MemoryStream(_exporter.Export(export)); - } - - private static IXLCell FindCell(IXLWorksheet sheet, string text) - { - return sheet.CellsUsed().First(cell => cell.GetString() == text); - } - - private static int Argb(string html) - { - return XLColor.FromHtml(html).Color.ToArgb(); - } - - private static int FillArgb(IXLCell cell) - { - return cell.Style.Fill.BackgroundColor.Color.ToArgb(); - } - - [Fact] - public void Describes_ItsFormat() - { - Assert.Equal("xlsx", _exporter.Format); - Assert.Equal("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", _exporter.ContentType); - Assert.Equal(".xlsx", _exporter.Extension); - } - - [Fact] - public void Header_ShowsTitleGeneratedFiltersAndNotice() - { - using MemoryStream stream = Export(ReportExportTestData.Export( - ReportExportTestData.Full(), confidential: true, filters: ReportExportTestData.Filters)); - using var workbook = new XLWorkbook(stream); - IXLWorksheet sheet = workbook.Worksheet(1); - - Assert.Equal("Sample report", sheet.Name); - Assert.Equal("Sample report", sheet.Cell(1, 1).GetString()); - Assert.True(sheet.Cell(1, 1).Style.Font.Bold); - Assert.Equal(ReportExportText.Generated(TestReport.GeneratedAt), sheet.Cell(2, 1).GetString()); - Assert.Equal("Filters: Faculty type: Senate; Start date: 07/01/2026", sheet.Cell(3, 1).GetString()); - Assert.Equal(ReportExportText.ConfidentialNotice, sheet.Cell(4, 1).GetString()); - Assert.Equal("Sample report", workbook.Properties.Title); - } - - [Fact] - public void Header_WithoutFiltersOrNotice_StartsDataSooner() - { - using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Plain())); - using var workbook = new XLWorkbook(stream); - IXLWorksheet sheet = workbook.Worksheet(1); - - Assert.Equal("Name", sheet.Cell(4, 1).GetString()); - Assert.Equal("Ada", sheet.Cell(5, 1).GetString()); - Assert.Equal(120_000d, sheet.Cell(5, 3).GetDouble()); - Assert.Equal("$#,##0.00", sheet.Cell(5, 3).Style.NumberFormat.Format); - Assert.True(sheet.Cell(7, 3).IsEmpty()); - Assert.Single(sheet.Tables); - Assert.Single(workbook.Worksheets); - } - - [Fact] - public void Groups_WriteLabelsTypedRowsSubtotalsAndTotals() - { - using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Full())); - using var workbook = new XLWorkbook(stream); - IXLWorksheet sheet = workbook.Worksheet(1); - - IXLCell people = FindCell(sheet, "People"); - Assert.Equal(5d, people.CellRight().GetDouble()); - - IXLCell vme = FindCell(sheet, "VME"); - IXLCell header = vme.CellBelow(); - Assert.Equal("#", header.GetString()); - Assert.Equal("Notes", header.WorksheetRow().Cell(7).GetString()); - - IXLRow ada = header.WorksheetRow().RowBelow(); - Assert.Equal(1d, ada.Cell(1).GetDouble()); - Assert.Equal("Ada", ada.Cell(2).GetString()); - Assert.Equal(61d, ada.Cell(3).GetDouble()); - Assert.Equal(new DateTime(1995, 7, 1), ada.Cell(5).GetDateTime()); - Assert.Equal("mm/dd/yyyy", ada.Cell(5).Style.NumberFormat.Format); - Assert.Equal("Asian, White", ada.Cell(6).GetString()); - - IXLCell subtotal = sheet.CellsUsed().Last(cell => cell.GetString() == "Salaries"); - Assert.Equal(270_000d, subtotal.WorksheetRow().Cell(4).GetDouble()); - IXLCell total = FindCell(sheet, "All salaries"); - Assert.Equal(430_000d, total.WorksheetRow().Cell(4).GetDouble()); - Assert.Equal(3, sheet.Tables.Count()); - } - - [Fact] - public void Highlights_FillRowsAndCellsAndListLabelsInNotes() - { - using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Full())); - using var workbook = new XLWorkbook(stream); - IXLWorksheet sheet = workbook.Worksheet(1); - - IXLRow ada = FindCell(sheet, "Ada").WorksheetRow(); - Assert.Equal(Argb("#FFF4CE"), FillArgb(ada.Cell(3))); - Assert.Equal("60+", ada.Cell(7).GetString()); - - IXLRow di = FindCell(sheet, "Di").WorksheetRow(); - Assert.Equal(Argb("#EDEBE9"), FillArgb(di.Cell(2))); - Assert.Equal("Retirement age; 60+", di.Cell(7).GetString()); - - IXLRow ed = FindCell(sheet, "Ed").WorksheetRow(); - Assert.Equal("Under 30", ed.Cell(7).GetString()); - } - - [Fact] - public void PivotsAndCharts_GetTheirOwnSheets() - { - using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.Full())); - using var workbook = new XLWorkbook(stream); - - Assert.Equal(["Sample report", "Sample report (2)", "Charts"], workbook.Worksheets.Select(sheet => sheet.Name)); - - IXLWorksheet pivot = workbook.Worksheet(2); - Assert.Equal("Total", pivot.Cell(2, 5).GetString()); - Assert.Equal("60+", pivot.Cell(3, 1).GetString()); - Assert.Equal(2d, pivot.Cell(3, 4).GetDouble()); - Assert.Equal(5d, pivot.Cell(5, 5).GetDouble()); - - IXLWorksheet charts = workbook.Worksheet(3); - Assert.Equal("Ages", charts.Cell(1, 1).GetString()); - Assert.Equal("Department ages: VME", FindCell(charts, "Department ages: VME").GetString()); - } - - [Fact] - public void EdgeCases_AreHandledWithoutErrors() - { - using MemoryStream stream = Export(ReportExportTestData.Export(ReportExportTestData.EdgeCases())); - using var workbook = new XLWorkbook(stream); - IXLWorksheet sheet = workbook.Worksheet(1); - - // ClosedXML stores a leading apostrophe as Excel's quote prefix rather than as text, so - // find the row through its header and check the value can't run as a formula. - IXLRow row = FindCell(sheet, "Name").CellBelow().WorksheetRow(); - Assert.EndsWith("=cmd|' /C calc'!A0", row.Cell(1).GetString(), StringComparison.Ordinal); - Assert.False(row.Cell(1).HasFormula); - Assert.Equal(new DateTime(2026, 1, 2), row.Cell(2).GetDateTime()); - Assert.Equal(0.125d, row.Cell(3).GetDouble()); - Assert.Equal("0.0%", row.Cell(3).Style.NumberFormat.Format); - Assert.Equal("pending", row.Cell(4).GetString()); - Assert.Equal(Argb("#FDE7E9"), FillArgb(row.Cell(1))); - - Assert.Equal(3d, FindCell(sheet, "Unplaced").CellRight().GetDouble()); - Assert.True(FindCell(sheet, "Unknown").CellRight().IsEmpty()); - Assert.Single(sheet.Tables); - } - - [Fact] - public void NullExport_Throws() - { - Assert.Throws(() => _exporter.Export(null!)); - } - - [Fact] - public void UniqueSheetName_AddsNumberedSuffixWithinTheLengthLimit() - { - var used = new HashSet(StringComparer.OrdinalIgnoreCase); - string longName = new('x', 40); - - Assert.Equal("Report", ReportExcelExporter.UniqueSheetName("Report", used)); - Assert.Equal("Report (2)", ReportExcelExporter.UniqueSheetName("Report", used)); - Assert.Equal("Report (3)", ReportExcelExporter.UniqueSheetName("Report", used)); - Assert.Equal(new string('x', 31), ReportExcelExporter.UniqueSheetName(longName, used)); - Assert.Equal(new string('x', 27) + " (2)", ReportExcelExporter.UniqueSheetName(longName, used)); - } - - [Theory] - [InlineData(ReportColumnFormat.Number, null, "#,##0")] - [InlineData(ReportColumnFormat.Number, 2, "#,##0.00")] - [InlineData(ReportColumnFormat.Currency, 2, "$#,##0.00")] - [InlineData(ReportColumnFormat.Percent, 0, "0%")] - [InlineData(ReportColumnFormat.Percent, 1, "0.0%")] - public void NumberFormat_MatchesColumnFormat(ReportColumnFormat format, int? decimals, string expected) - { - var column = new ReportColumnMetadata("value", "Value", format, ReportAlignment.Right, decimals); - - Assert.Equal(expected, ReportExcelExporter.NumberFormat(column)); - } -} diff --git a/test/Reports/ReportExportTestData.cs b/test/Reports/ReportExportTestData.cs deleted file mode 100644 index fb54ff52c..000000000 --- a/test/Reports/ReportExportTestData.cs +++ /dev/null @@ -1,98 +0,0 @@ -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Exporters; - -namespace Viper.test.Reports; - -/// -/// Report results shaped for exporter tests, built through the real pipeline where possible. -/// -internal static class ReportExportTestData -{ - public static readonly IReadOnlyList Filters = [new("Faculty type", "Senate"), new("Start date", "07/01/2026")]; - - /// - /// Grouped by department with row numbers, subtotals, totals, a summary, flags, a pivot and - /// per-group and whole-report charts. - /// - public static ReportResult Full() - { - var report = new TestReport(report => - { - report.Sensitive(); - report.RowNumbers(); - report.Column(row => row.Name, "Name"); - report.Column(row => row.Age, "Age").AsNumber(); - report.Column(row => row.Salary, "Salary").AsCurrency(); - report.Column(row => row.HireDate, "Hire date").AsDate(); - report.Column(row => row.Ethnicities, "Ethnicities").AsList(); - report.Summary("People", report.Count()); - report.GroupBy(row => row.Department).Subtotal("Salaries", report.Sum(row => row.Salary), "salary"); - report.Total("All salaries", report.Sum(row => row.Salary), "salary"); - report.Highlight(row => row.Age >= 65, ReportTone.Muted, "Retirement age"); - report.Highlight(row => row.Age >= 60, ReportTone.Warning, "60+", "age"); - report.Highlight(row => row.Age < 30, ReportTone.Neutral, "Under 30"); - report.Badge(row => row.Salary is null, ReportTone.Info, "No salary", "salary"); - report.Pivot("Sample report", row => row.Age >= 60 ? "60+" : "Under 60", row => row.Department, report.Count()); - report.Chart("Ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()); - report.Chart("Department ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) - .PerGroup(minimumRows: 2); - }); - return TestReport.Run(report); - } - - /// - /// Ungrouped, no row numbers, no flags or totals. - /// - public static ReportResult Plain() - { - var report = new TestReport(report => - { - report.Column(row => row.Name, "Name"); - report.Column(row => row.Department, "Department"); - report.Column(row => row.Salary, "Salary").AsCurrency(); - }); - return TestReport.Run(report); - } - - /// - /// A hand-built result covering cases the pipeline never produces, so exporters handle any - /// well-formed result: unknown column keys, null totals, empty groups and text in numeric columns. - /// - public static ReportResult EdgeCases() - { - ReportColumnMetadata[] columns = - [ - new("name", "Name", ReportColumnFormat.Text, ReportAlignment.Left, null), - new("when", "When", ReportColumnFormat.Date, ReportAlignment.Center, null), - new("share", "Share", ReportColumnFormat.Percent, ReportAlignment.Right, 1), - new("amount", "Amount", ReportColumnFormat.Number, ReportAlignment.Right, null), - ]; - var row = new ReportRowResult( - 1, - new Dictionary - { - ["name"] = "=cmd|' /C calc'!A0", - ["when"] = new DateTime(2026, 1, 2, 0, 0, 0, DateTimeKind.Local), - ["share"] = 0.125m, - ["amount"] = "pending", - }, - [new ReportFlag(ReportFlagKind.Highlight, ReportTone.Negative, "Check", "missing")]); - return new ReportResult( - "test.edge", - "Edge cases", - TestReport.GeneratedAt, - 1, - false, - columns, - [], - [new ReportGroupResult(null, [row], [], []), new ReportGroupResult(null, [], [], [])], - [new ReportTotal("Unplaced", "missing", 3m), new ReportTotal("Unknown", null, null)], - [], - []); - } - - public static ReportExport Export(ReportResult result, bool confidential = false, IReadOnlyList? filters = null) - { - return new ReportExport(result, filters ?? [], confidential); - } -} diff --git a/test/Reports/ReportExportTextTests.cs b/test/Reports/ReportExportTextTests.cs deleted file mode 100644 index f7e07ff42..000000000 --- a/test/Reports/ReportExportTextTests.cs +++ /dev/null @@ -1,119 +0,0 @@ -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Exporters; - -namespace Viper.test.Reports; - -public sealed class ReportExportTextTests -{ - private static readonly HashSet Columns = new(["name", "age"], StringComparer.Ordinal); - - private static readonly ReportColumnMetadata[] SalaryColumn = - [ - new("salary", "Salary", ReportColumnFormat.Currency, ReportAlignment.Right, 2), - ]; - - private static ReportFlag Highlight(ReportTone tone, string? columnKey = null) - { - return new ReportFlag(ReportFlagKind.Highlight, tone, tone.ToString(), columnKey); - } - - [Fact] - public void Generated_UsesUsDateAndTime() - { - Assert.Equal("Generated 09/29/2026 8:00 AM", ReportExportText.Generated(TestReport.GeneratedAt)); - } - - [Fact] - public void Filters_JoinsLabelsOrReturnsNull() - { - Assert.Null(ReportExportText.Filters([])); - Assert.Equal( - "Filters: Faculty type: Senate; Start date: 07/01/2026", - ReportExportText.Filters(ReportExportTestData.Filters)); - Assert.Throws(() => ReportExportText.Filters(null!)); - } - - [Fact] - public void HasNotes_NullResult_Throws() - { - Assert.Throws(() => ReportExportText.HasNotes(null!)); - } - - [Theory] - [InlineData(ReportTone.Neutral, null)] - [InlineData(ReportTone.Warning, "#FFF4CE")] - [InlineData(ReportTone.Muted, "#EDEBE9")] - public void ToneFill_MapsTonesToLightFills(ReportTone tone, string? expected) - { - Assert.Equal(expected, ReportExportText.ToneFill(tone)); - } - - [Fact] - public void CellFill_RowHighlightCoversEveryCell() - { - ReportFlag[] flags = [Highlight(ReportTone.Muted)]; - - Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, "name", Columns)); - Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, null, Columns)); - } - - [Fact] - public void CellFill_ColumnHighlightCoversOnlyItsColumn() - { - ReportFlag[] flags = [Highlight(ReportTone.Muted), Highlight(ReportTone.Warning, "age")]; - - Assert.Equal("#FFF4CE", ReportExportText.CellFill(flags, "age", Columns)); - Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, "name", Columns)); - Assert.Equal("#EDEBE9", ReportExportText.CellFill(flags, null, Columns)); - } - - [Fact] - public void CellFill_HighlightOnUnknownColumnCoversTheRow() - { - Assert.Equal("#FDE7E9", ReportExportText.CellFill([Highlight(ReportTone.Negative, "missing")], "name", Columns)); - } - - [Fact] - public void CellFill_IgnoresBadgesAndNeutralHighlights() - { - ReportFlag[] flags = - [ - Highlight(ReportTone.Info), - new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "Badge", "name"), - Highlight(ReportTone.Neutral), - ]; - - Assert.Equal("#DEECF9", ReportExportText.CellFill(flags, "name", Columns)); - Assert.Null(ReportExportText.CellFill([], "name", Columns)); - } - - [Fact] - public void CellFill_NullArguments_Throw() - { - Assert.Throws(() => ReportExportText.CellFill(null!, "name", Columns)); - Assert.Throws(() => ReportExportText.CellFill([], "name", null!)); - } - - [Fact] - public void FormatTotal_UsesTheColumnFormatWhenThereIsOne() - { - Assert.Equal("$1,234.50", ReportExportText.FormatTotal(new ReportTotal("Salaries", "salary", 1234.5m), SalaryColumn)); - Assert.Equal("1,234.5", ReportExportText.FormatTotal(new ReportTotal("People", null, 1234.5m), SalaryColumn)); - Assert.Equal("7", ReportExportText.FormatTotal(new ReportTotal("Other", "missing", 7m), SalaryColumn)); - Assert.Equal(string.Empty, ReportExportText.FormatTotal(new ReportTotal("None", "salary", null), SalaryColumn)); - } - - [Fact] - public void FormatTotal_NullArguments_Throw() - { - Assert.Throws(() => ReportExportText.FormatTotal(null!, SalaryColumn)); - Assert.Throws(() => ReportExportText.FormatTotal(new ReportTotal("T", null, 1m), null!)); - } - - [Fact] - public void FormatNumber_BlankForNull() - { - Assert.Equal(string.Empty, ReportExportText.FormatNumber(null)); - Assert.Equal("12,345.68", ReportExportText.FormatNumber(12345.678m)); - } -} diff --git a/test/Reports/ReportKeyTests.cs b/test/Reports/ReportKeyTests.cs deleted file mode 100644 index c5323ef48..000000000 --- a/test/Reports/ReportKeyTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportKeyTests -{ - [Theory] - [InlineData("personnel.employees-on-leave")] - [InlineData("a.b")] - [InlineData("clinical-scheduler.rotation-2")] - [InlineData("a1.b2")] - public void IsValid_WellFormedKey_ReturnsTrue(string key) - { - Assert.True(ReportKey.IsValid(key)); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("nodot")] - [InlineData(".report")] - [InlineData("area.")] - [InlineData("a.b.c")] - [InlineData("-a.b")] - [InlineData("a-.b")] - [InlineData("a.-b")] - [InlineData("a.b-")] - [InlineData("Personnel.report")] - [InlineData("a.b_c")] - [InlineData("a.b c")] - public void IsValid_MalformedKey_ReturnsFalse(string? key) - { - Assert.False(ReportKey.IsValid(key)); - } -} diff --git a/test/Reports/ReportLayoutBuilderTests.cs b/test/Reports/ReportLayoutBuilderTests.cs deleted file mode 100644 index 2a6dd74bf..000000000 --- a/test/Reports/ReportLayoutBuilderTests.cs +++ /dev/null @@ -1,157 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportLayoutBuilderTests -{ - #region Argument validation - - [Fact] - public void GroupBy_Twice_Throws() - { - var builder = new ReportBuilder(); - builder.GroupBy(row => row.Department); - - Assert.Throws(() => builder.GroupBy(row => row.Name)); - } - - [Fact] - public void GroupBy_NullKey_Throws() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.GroupBy(null!)); - } - - [Fact] - public void Totals_InvalidArguments_Throw() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Total(" ", builder.Count())); - Assert.Throws(() => builder.Summary("People", null!)); - Assert.Throws(() => builder.GroupBy(row => row.Department).Subtotal("", builder.Count())); - } - - [Fact] - public void Flags_InvalidArguments_Throw() - { - var builder = new ReportBuilder(); - - Assert.Throws(() => builder.Highlight(null!, ReportTone.Warning, "Old")); - Assert.Throws(() => builder.Highlight(_ => true, ReportTone.Warning, " ")); - Assert.Throws(() => builder.Badge(_ => true, ReportTone.Info, "Emeritus", " ")); - } - - [Fact] - public void Pivots_InvalidArguments_Throw() - { - var builder = new ReportBuilder(); - ReportMeasure count = builder.Count(); - - Assert.Throws(() => builder.Pivot("Pivot", null!, row => row.Name, count)); - Assert.Throws(() => builder.PivotEach("Pivot", null!, row => row.Name, count)); - Assert.Throws(() => builder.Pivot(" ", row => row.Name, row => row.Name, count)); - Assert.Throws(() => builder.Pivot("Pivot", row => row.Name, null!, count)); - Assert.Throws(() => builder.Pivot("Pivot", row => row.Name, row => row.Name, null!)); - } - - [Fact] - public void Charts_InvalidArguments_Throw() - { - var builder = new ReportBuilder(); - ReportMeasure count = builder.Count(); - - Assert.Throws(() => builder.Chart(" ", ReportChartKind.Bar, row => row.Name, count)); - Assert.Throws(() => builder.Chart("Chart", ReportChartKind.Bar, null!, count)); - Assert.Throws(() => builder.Chart("Chart", ReportChartKind.Bar, row => row.Name, null!)); - - ReportChartBuilder chart = builder.Chart("Chart", ReportChartKind.Pie, row => row.Name, count); - Assert.Throws(() => chart.PerGroup(-1)); - Assert.Throws(() => chart.CategoryOrder(null!)); - } - - #endregion - - #region Layout validation - - [Fact] - public void UnknownTotalColumn_Throws() - { - var report = new TestReport(report => - { - report.Column(row => row.Name, "Name"); - report.Total("Total", report.Count(), "missing"); - }); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - [Fact] - public void UnknownSummaryColumn_Throws() - { - var report = new TestReport(report => - { - report.Column(row => row.Name, "Name"); - report.Summary("People", report.Count(), "missing"); - }); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - [Fact] - public void UnknownSubtotalColumn_Throws() - { - var report = new TestReport(report => - { - report.Column(row => row.Name, "Name"); - report.GroupBy(row => row.Department).Subtotal("People", report.Count(), "missing"); - }); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - [Fact] - public void UnknownFlagColumn_Throws() - { - var report = new TestReport(report => - { - report.Column(row => row.Name, "Name"); - report.Badge(_ => true, ReportTone.Info, "Badge", "missing"); - }); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - [Fact] - public void PerGroupChartWithoutGrouping_Throws() - { - var report = new TestReport(report => - { - report.Column(row => row.Name, "Name"); - report.Chart("Ages", ReportChartKind.Bar, row => row.Name, report.Count()).PerGroup(); - }); - - Assert.Throws(() => report.GetMetadata(TestReport.ContextWith())); - } - - [Fact] - public void KnownColumnsAndGroupedCharts_AreValid() - { - var report = new TestReport(report => - { - report.Column(row => row.Name, "Name"); - report.Column(row => row.Salary, "Salary"); - report.Total("Salaries", report.Sum(row => row.Salary), "salary"); - report.Highlight(row => row.Age > 60, ReportTone.Warning, "Over 60"); - report.GroupBy(row => row.Department).Subtotal("People", report.Count()); - report.Chart("Ages", ReportChartKind.Bar, row => row.Name, report.Count()).PerGroup(2); - }); - - ReportDefinitionMetadata metadata = report.GetMetadata(TestReport.ContextWith()); - - Assert.Equal(2, metadata.Columns.Count); - } - - #endregion -} diff --git a/test/Reports/ReportMeasureTests.cs b/test/Reports/ReportMeasureTests.cs deleted file mode 100644 index 4bd84cc25..000000000 --- a/test/Reports/ReportMeasureTests.cs +++ /dev/null @@ -1,90 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportMeasureTests -{ - private static readonly ReportBuilder Builder = new(); - - #region ReportMath - - [Fact] - public void Sum_EmptyIsZero() - { - Assert.Equal(0m, ReportMath.Sum([])); - Assert.Equal(6m, ReportMath.Sum([1m, 2m, 3m])); - } - - [Fact] - public void AverageMinimumMaximum_EmptyIsNull() - { - Assert.Null(ReportMath.Average([])); - Assert.Null(ReportMath.Minimum([])); - Assert.Null(ReportMath.Maximum([])); - } - - [Fact] - public void AverageMinimumMaximum_ComputeFromValues() - { - decimal[] values = [4m, 1m, 7m]; - - Assert.Equal(4m, ReportMath.Average(values)); - Assert.Equal(1m, ReportMath.Minimum(values)); - Assert.Equal(7m, ReportMath.Maximum(values)); - } - - [Fact] - public void StandardDeviation_FewerThanTwoValues_IsNull() - { - Assert.Null(ReportMath.StandardDeviation([])); - Assert.Null(ReportMath.StandardDeviation([5m])); - } - - [Fact] - public void StandardDeviation_IsSampleStandardDeviation() - { - decimal? deviation = ReportMath.StandardDeviation([1m, 2m, 3m, 4m]); - - Assert.NotNull(deviation); - Assert.Equal(1.2910m, Math.Round(deviation.Value, 4)); - } - - #endregion - - #region Measure factories - - [Fact] - public void Count_CountsRows() - { - Assert.Equal(5m, Builder.Count().Compute(TestReport.Rows())); - } - - [Fact] - public void CountDistinct_IgnoresNullKeys() - { - ReportMeasure measure = Builder.CountDistinct(row => row.Salary); - - Assert.Equal(4m, measure.Compute(TestReport.Rows())); - } - - [Fact] - public void NumericMeasures_IgnoreNullValues() - { - IReadOnlyList rows = TestReport.Rows(); - - Assert.Equal(430_000m, Builder.Sum(row => row.Salary).Compute(rows)); - Assert.Equal(107_500m, Builder.Average(row => row.Salary).Compute(rows)); - Assert.Equal(70_000m, Builder.Minimum(row => row.Salary).Compute(rows)); - Assert.Equal(150_000m, Builder.Maximum(row => row.Salary).Compute(rows)); - Assert.NotNull(Builder.StandardDeviation(row => row.Age).Compute(rows)); - } - - [Fact] - public void MeasureFactories_NullSelector_Throws() - { - Assert.Throws(() => Builder.CountDistinct(null!)); - Assert.Throws(() => Builder.Sum(null!)); - } - - #endregion -} diff --git a/test/Reports/ReportParameterBinderTests.cs b/test/Reports/ReportParameterBinderTests.cs deleted file mode 100644 index 4bf2f1613..000000000 --- a/test/Reports/ReportParameterBinderTests.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System.Text.Json; -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportParameterBinderTests -{ - private static JsonElement Json(string json) - { - using JsonDocument document = JsonDocument.Parse(json); - return document.RootElement.Clone(); - } - - [Fact] - public void TryBind_MissingBody_BindsEmptyParameters() - { - bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), null, out object? parameters, out ReportValidationError? error); - - Assert.True(bound); - Assert.Null(error); - Assert.Equal(new SampleParams(), parameters); - } - - [Fact] - public void TryBind_JsonNull_BindsEmptyParameters() - { - bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), Json("null"), out object? parameters, out _); - - Assert.True(bound); - Assert.IsType(parameters); - } - - [Fact] - public void TryBind_Object_BindsCamelCaseValues() - { - JsonElement json = Json("""{ "facultyType": "F", "departments": ["APC"], "startDate": "2025-07-01", "MinimumAge": 60 }"""); - - bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), json, out object? parameters, out _); - - Assert.True(bound); - SampleParams typed = Assert.IsType(parameters); - Assert.Equal("F", typed.FacultyType); - Assert.NotNull(typed.Departments); - Assert.Equal(["APC"], typed.Departments); - Assert.Equal(new DateOnly(2025, 7, 1), typed.StartDate); - Assert.Equal(60, typed.MinimumAge); - } - - [Fact] - public void TryBind_NonObject_ReturnsError() - { - bool bound = ReportParameterBinder.TryBind(typeof(SampleParams), Json("[1, 2]"), out object? parameters, out ReportValidationError? error); - - Assert.False(bound); - Assert.Null(parameters); - Assert.Equal(new ReportValidationError(null, ReportParameterBinder.NotAnObjectMessage), error); - } - - [Fact] - public void TryBind_WrongValueType_ReturnsErrorForThatParameter() - { - bool bound = ReportParameterBinder.TryBind( - typeof(SampleParams), Json("""{ "minimumAge": "sixty" }"""), out _, out ReportValidationError? error); - - Assert.False(bound); - Assert.Equal(new ReportValidationError("minimumAge", ReportParameterBinder.UnreadableMessage), error); - } - - [Fact] - public void TryBind_UnknownParameter_ReturnsError() - { - bool bound = ReportParameterBinder.TryBind( - typeof(SampleParams), Json("""{ "facultyTyp": "S" }"""), out _, out ReportValidationError? error); - - Assert.False(bound); - Assert.NotNull(error); - Assert.Equal(ReportParameterBinder.UnreadableMessage, error.Message); - } - - [Fact] - public void TryBind_NullResult_ReturnsError() - { - bool bound = ReportParameterBinder.TryBind(typeof(NullParams), Json("{}"), out _, out ReportValidationError? error); - - Assert.False(bound); - Assert.NotNull(error); - } - - [Fact] - public void TryBind_NullType_Throws() - { - Assert.Throws(() => ReportParameterBinder.TryBind(null!, null, out _, out _)); - } - - [Theory] - [InlineData(null, null)] - [InlineData("$", null)] - [InlineData("$.", null)] - [InlineData("$.startDate", "startDate")] - [InlineData("$.departments[1]", "departments")] - [InlineData("$.inner.value", "inner")] - [InlineData("startDate", null)] - public void ParameterName_ExtractsTopLevelName(string? path, string? expected) - { - Assert.Equal(expected, ReportParameterBinder.ParameterName(path)); - } -} diff --git a/test/Reports/ReportPdfExporterTests.cs b/test/Reports/ReportPdfExporterTests.cs deleted file mode 100644 index fa6843633..000000000 --- a/test/Reports/ReportPdfExporterTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Text; -using QuestPDF.Infrastructure; -using Viper.Areas.Reports.Exporters; - -namespace Viper.test.Reports; - -/// -/// QuestPDF output can't be read back without a PDF parser, so these tests render every layout -/// path (groups, row numbers, notes, fills, totals, pivots, charts, header variants) and check -/// that a PDF comes out. The layout decisions themselves are unit-tested in -/// . -/// -public sealed class ReportPdfExporterTests -{ - private readonly ReportPdfExporter _exporter = new(); - - public ReportPdfExporterTests() - { - // Program.cs sets this at startup; unit tests don't run Program.cs. - QuestPDF.Settings.License = LicenseType.Community; - } - - private static void AssertIsPdf(byte[] bytes) - { - Assert.True(bytes.Length > 0); - Assert.Equal("%PDF-", Encoding.ASCII.GetString(bytes, 0, 5)); - } - - [Fact] - public void Describes_ItsFormat() - { - Assert.Equal("pdf", _exporter.Format); - Assert.Equal("application/pdf", _exporter.ContentType); - Assert.Equal(".pdf", _exporter.Extension); - } - - [Fact] - public void Full_WithFiltersAndNotice_RendersPdf() - { - AssertIsPdf(_exporter.Export(ReportExportTestData.Export( - ReportExportTestData.Full(), confidential: true, filters: ReportExportTestData.Filters))); - } - - [Fact] - public void Plain_RendersPdf() - { - AssertIsPdf(_exporter.Export(ReportExportTestData.Export(ReportExportTestData.Plain()))); - } - - [Fact] - public void EdgeCases_RenderPdf() - { - AssertIsPdf(_exporter.Export(ReportExportTestData.Export(ReportExportTestData.EdgeCases()))); - } - - [Fact] - public void NullExport_Throws() - { - Assert.Throws(() => _exporter.Export(null!)); - } -} diff --git a/test/Reports/ReportPipelineTests.cs b/test/Reports/ReportPipelineTests.cs deleted file mode 100644 index 47150dcea..000000000 --- a/test/Reports/ReportPipelineTests.cs +++ /dev/null @@ -1,264 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportPipelineTests -{ - private static void BasicColumns(ReportBuilder report) - { - report.Column(row => row.Name, "Name"); - report.Column(row => row.Age, "Age").AsNumber(); - report.Column(row => row.Salary, "Salary").AsCurrency() - .VisibleWhen(context => context.HasPermission(TestReport.SalaryPermission)); - } - - #region Ungrouped reports - - [Fact] - public void Ungrouped_ReturnsOneUnlabelledGroupWithNumberedRows() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.RowNumbers(); - }); - - ReportResult result = TestReport.Run(report); - - Assert.Equal("test.sample", result.Key); - Assert.Equal("Sample report", result.Title); - Assert.Equal(TestReport.GeneratedAt, result.GeneratedAt); - Assert.Equal(5, result.RowCount); - Assert.True(result.RowNumbers); - ReportGroupResult group = Assert.Single(result.Groups); - Assert.Null(group.Label); - Assert.Equal([1, 2, 3, 4, 5], group.Rows.Select(row => row.Number)); - Assert.Equal("Ada", group.Rows[0].Values["name"]); - Assert.Equal(120_000m, group.Rows[0].Values["salary"]); - Assert.Empty(group.Subtotals); - Assert.Empty(group.Charts); - } - - [Fact] - public void RowNumbers_DefaultToOff() - { - ReportResult result = TestReport.Run(new TestReport(BasicColumns)); - - Assert.False(result.RowNumbers); - } - - [Fact] - public void HiddenColumn_RemovesItsValuesTotalsSummariesAndFlags() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.Summary("People", report.Count()); - report.Summary("Top salary", report.Maximum(row => row.Salary), "salary"); - report.Total("Ages", report.Sum(row => row.Age), "age"); - report.Total("Salaries", report.Sum(row => row.Salary), "salary"); - report.Highlight(row => row.Salary > 100_000m, ReportTone.Info, "High salary", "salary"); - }); - - ReportResult result = TestReport.Run(report, TestReport.ContextWith(TestReport.RunPermission)); - - Assert.Equal(["name", "age"], result.Columns.Select(column => column.Key)); - Assert.DoesNotContain("salary", result.Groups[0].Rows[0].Values.Keys); - Assert.Equal([new ReportTotal("People", null, 5m)], result.Summary); - Assert.Equal([new ReportTotal("Ages", "age", 239m)], result.Totals); - Assert.All(result.Groups[0].Rows, row => Assert.Empty(row.Flags)); - } - - [Fact] - public void Flags_MarkMatchingRowsAndCells() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.Highlight(row => row.Age >= 65, ReportTone.Muted, "Retirement age"); - report.Badge(row => row.Age >= 60, ReportTone.Warning, "60+", "age"); - }); - - IReadOnlyList rows = TestReport.Run(report).Groups[0].Rows; - - Assert.Equal([new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "60+", "age")], rows[0].Flags); - Assert.Empty(rows[1].Flags); - Assert.Equal( - [ - new ReportFlag(ReportFlagKind.Highlight, ReportTone.Muted, "Retirement age", null), - new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "60+", "age"), - ], - rows[3].Flags); - } - - #endregion - - #region Grouping - - [Fact] - public void Grouping_NormalizesKeysOrdersGroupsAndRestartsNumbering() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.RowNumbers(); - report.GroupBy(row => row.Department) - .Subtotal("People", report.Count()) - .Subtotal("Salaries", report.Sum(row => row.Salary), "salary"); - }); - - ReportResult result = TestReport.Run(report); - - Assert.Equal([ReportPipeline.BlankKeyLabel, "apc", "VME"], result.Groups.Select(group => group.Label)); - ReportGroupResult vme = result.Groups[2]; - Assert.Equal(["Ada", "Cy", "Di"], vme.Rows.Select(row => row.Values["name"])); - Assert.Equal([1, 2, 3], vme.Rows.Select(row => row.Number)); - Assert.Equal( - [new ReportTotal("People", null, 3m), new ReportTotal("Salaries", "salary", 270_000m)], - vme.Subtotals); - } - - [Fact] - public void PerGroupCharts_SkipSmallGroups() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.GroupBy(row => row.Department); - report.Chart("Ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) - .PerGroup(minimumRows: 2) - .CategoryOrder("Under 60", "60+"); - }); - - ReportResult result = TestReport.Run(report); - - Assert.Empty(result.Charts); - Assert.Empty(result.Groups[0].Charts); - ReportChartResult vmeChart = Assert.Single(result.Groups[2].Charts); - Assert.Equal( - [new ReportChartPoint("Under 60", 1m), new ReportChartPoint("60+", 2m)], - vmeChart.Points); - } - - [Fact] - public void Charts_CountOnlyTheRowsTheyInclude() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.GroupBy(row => row.Department); - report.Chart("Ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) - .Where(row => row.Age < 60); - report.Chart("Department ages", ReportChartKind.Bar, row => row.Age >= 60 ? "60+" : "Under 60", report.Count()) - .PerGroup(minimumRows: 2) - .Where(row => row.Age < 60); - }); - - ReportResult result = TestReport.Run(report); - - // Ben, Cy and Ed are under 60; Ada and Di are left out of the chart but stay in the table. - Assert.Equal([new ReportChartPoint("Under 60", 3m)], Assert.Single(result.Charts).Points); - Assert.Equal(5, result.RowCount); - // VME has three rows but only Cy is charted, which is under the per-group minimum of two. - Assert.All(result.Groups, group => Assert.Empty(group.Charts)); - } - - #endregion - - #region Pivots and charts - - [Fact] - public void Pivot_ComputesCellsRowTotalsColumnTotalsAndGrandTotal() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.Pivot( - "Age band by department", - row => row.Age >= 60 ? "60+" : "Under 60", - row => row.Department, - report.Count()); - }); - - ReportPivotResult pivot = Assert.Single(TestReport.Run(report).Pivots); - - Assert.Equal("Age band by department", pivot.Title); - Assert.Equal([ReportPipeline.BlankKeyLabel, "apc", "VME"], pivot.ColumnKeys); - Assert.Equal(["60+", "Under 60"], pivot.Rows.Select(row => row.Key)); - Assert.Equal([0m, 0m, 2m], pivot.Rows[0].Values); - Assert.Equal([1m, 1m, 1m], pivot.Rows[1].Values); - Assert.Equal([2m, 3m], pivot.Rows.Select(row => row.Total)); - Assert.Equal([1m, 1m, 3m], pivot.ColumnTotals); - Assert.Equal(5m, pivot.GrandTotal); - } - - [Fact] - public void PivotEach_CountsEverySelection() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.PivotEach("Selections", row => row.Ethnicities ?? [], row => row.Department, report.Count()); - report.PivotEach("People", row => row.Ethnicities ?? [], row => row.Department, report.CountDistinct(row => row.Name)); - }); - - IReadOnlyList pivots = TestReport.Run(report).Pivots; - - ReportPivotRow white = pivots[0].Rows.Single(row => row.Key == "White"); - Assert.Equal([1m, 1m, 1m], white.Values); - Assert.Equal(5m, pivots[0].GrandTotal); - Assert.Equal(4m, pivots[1].GrandTotal); - } - - [Fact] - public void Chart_OrdersPreferredCategoriesFirst() - { - var report = new TestReport(report => - { - BasicColumns(report); - report.Chart("Departments", ReportChartKind.Pie, row => row.Department, report.Count()) - .CategoryOrder("VME", "Missing"); - }); - - ReportChartResult chart = Assert.Single(TestReport.Run(report).Charts); - - Assert.Equal("Departments", chart.Title); - Assert.Equal(ReportChartKind.Pie, chart.Kind); - Assert.Equal(["VME", ReportPipeline.BlankKeyLabel, "apc"], chart.Points.Select(point => point.Category)); - Assert.Equal(3m, chart.Points[0].Value); - } - - #endregion - - #region Helpers and guards - - [Theory] - [InlineData(null, ReportPipeline.BlankKeyLabel)] - [InlineData(" ", ReportPipeline.BlankKeyLabel)] - [InlineData(" VME ", "VME")] - public void NormalizeKey_TrimsAndLabelsBlanks(string? key, string expected) - { - Assert.Equal(expected, ReportPipeline.NormalizeKey(key)); - } - - [Fact] - public void OrderCategories_PreferredThenAlphabetical() - { - Assert.Equal( - ["c", "a", "B", "d"], - ReportPipeline.OrderCategories(["d", "B", "a", "c"], ["c", "x"])); - } - - [Fact] - public void CreateResult_NullArguments_Throw() - { - var report = new TestReport(BasicColumns); - - Assert.Throws( - () => report.CreateResult(null!, TestReport.ContextWith(), TestReport.GeneratedAt)); - Assert.Throws( - () => report.CreateResult(TestReport.Rows(), null!, TestReport.GeneratedAt)); - } - - #endregion -} diff --git a/test/Reports/ReportRegistryTests.cs b/test/Reports/ReportRegistryTests.cs deleted file mode 100644 index a5214df55..000000000 --- a/test/Reports/ReportRegistryTests.cs +++ /dev/null @@ -1,156 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportRegistryTests -{ - [Fact] - public void All_OrdersByAreaThenTitle() - { - var registry = new ReportRegistry( - [ - new TestReport(key: "personnel.zeta", title: "Zeta", area: "Personnel"), - new TestReport(key: "effort.beta", title: "beta", area: "effort"), - new TestReport(key: "personnel.alpha", title: "Alpha", area: "Personnel"), - ]); - - Assert.Equal(["effort.beta", "personnel.alpha", "personnel.zeta"], registry.All.Select(report => report.Key)); - } - - [Fact] - public void Find_IsCaseInsensitive() - { - var report = new TestReport(key: "personnel.alpha"); - var registry = new ReportRegistry([report]); - - Assert.Same(report, registry.Find("Personnel.Alpha")); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - [InlineData("personnel.missing")] - public void Find_BlankOrUnknownKey_ReturnsNull(string? key) - { - var registry = new ReportRegistry([new TestReport(key: "personnel.alpha")]); - - Assert.Null(registry.Find(key)); - } - - [Fact] - public void Constructor_NullDefinitions_Throws() - { - Assert.Throws(() => new ReportRegistry(null!)); - } - - [Fact] - public void Constructor_DuplicateKey_Throws() - { - Assert.Throws(() => new ReportRegistry( - [ - new TestReport(key: "personnel.alpha"), - new TestReport(key: "PERSONNEL.ALPHA".ToLowerInvariant()), - ])); - } - - [Fact] - public void Constructor_InvalidKey_Throws() - { - Assert.Throws(() => new ReportRegistry([new TestReport(key: "Personnel Alpha")])); - } - - [Theory] - [InlineData(" ", "Area", "Description")] - [InlineData("Title", " ", "Description")] - [InlineData("Title", "Area", " ")] - public void Constructor_MissingIdentityText_Throws(string title, string area, string description) - { - var report = new TestReport(title: title, area: area, description: description); - - Assert.Throws(() => new ReportRegistry([report])); - } - - [Fact] - public void Constructor_NoPermissions_Throws() - { - Assert.Throws(() => new ReportRegistry([new TestReport(permissions: [])])); - } - - [Fact] - public void Constructor_BlankPermission_Throws() - { - Assert.Throws( - () => new ReportRegistry([new TestReport(permissions: ["SVMSecure.Test", " "])])); - } - - [Fact] - public void Planned_WithoutSources_IsEmpty() - { - Assert.Empty(new ReportRegistry([new TestReport()]).Planned); - } - - [Fact] - public void Planned_CombinesSourcesInAreaThenTitleOrder() - { - var extra = new StubPlannedSource { PlannedReports = [Plan("effort.zeta", "Zeta", "Effort")] }; - - var registry = new ReportRegistry([new TestReport()], [new TestPlannedReports(), extra]); - - Assert.Equal( - ["effort.zeta", "students.restricted", "test.planned"], - registry.Planned.Select(report => report.Key)); - } - - [Fact] - public void Find_NeverReturnsAPlannedReport() - { - var registry = new ReportRegistry([new TestReport()], [new TestPlannedReports()]); - - Assert.Null(registry.Find(TestPlannedReports.Visible.Key)); - } - - [Fact] - public void Constructor_PlannedKeyUsedByADefinition_Throws() - { - var planned = new StubPlannedSource { PlannedReports = [Plan("test.sample", "Sample", "Test")] }; - - InvalidOperationException error = Assert.Throws( - () => new ReportRegistry([new TestReport()], [planned])); - Assert.Contains("test.sample", error.Message, StringComparison.Ordinal); - } - - [Fact] - public void Constructor_DuplicatePlannedKey_Throws() - { - var first = new StubPlannedSource { PlannedReports = [Plan("test.planned-twice", "One", "Test")] }; - var second = new StubPlannedSource { PlannedReports = [Plan("test.planned-twice", "Two", "Test")] }; - - Assert.Throws(() => new ReportRegistry([], [first, second])); - } - - [Theory] - [InlineData("Test Planned", "Title", "SVMSecure.Test")] - [InlineData("test.planned", " ", "SVMSecure.Test")] - [InlineData("test.planned", "Title", " ")] - public void Constructor_InvalidPlannedReport_Throws(string key, string title, string permission) - { - var planned = new StubPlannedSource { PlannedReports = [new PlannedReport(key, title, "Test", "Description", [permission])] }; - - Assert.Throws(() => new ReportRegistry([], [planned])); - } - - private static PlannedReport Plan(string key, string title, string area) - { - return new PlannedReport(key, title, area, "Description", ["SVMSecure.Test"]); - } - - /// - /// Has a parameterless constructor because the registration tests scan this assembly and - /// build every planned report source they find. - /// - private sealed class StubPlannedSource : IPlannedReportSource - { - public IReadOnlyList PlannedReports { get; init; } = []; - } -} diff --git a/test/Reports/ReportRunTests.cs b/test/Reports/ReportRunTests.cs deleted file mode 100644 index 36f7f5d74..000000000 --- a/test/Reports/ReportRunTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportRunTests -{ - [Fact] - public async Task RunAsync_FetchesWithParametersAndContextThenShapesRows() - { - var parameters = new SampleParams { FacultyType = "F" }; - var report = new TestReport(fetch: p => [.. TestReport.Rows().Where(row => p.FacultyType == "F" && row.Age > 60)]); - ReportContext context = TestReport.ContextWith(TestReport.RunPermission); - - ReportResult result = await report.RunAsync(parameters, context, TestReport.GeneratedAt, TestContext.Current.CancellationToken); - - Assert.Same(parameters, report.FetchedWith); - Assert.Same(context, report.FetchedFor); - Assert.Equal(2, result.RowCount); - Assert.Equal(TestReport.GeneratedAt, result.GeneratedAt); - } - - [Fact] - public async Task RunAsync_WrongParameterType_Throws() - { - var report = new TestReport(); - - await Assert.ThrowsAsync(() => report.RunAsync( - "parameters", TestReport.ContextWith(), TestReport.GeneratedAt, TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task RunAsync_NullContext_Throws() - { - var report = new TestReport(); - - await Assert.ThrowsAsync(() => report.RunAsync( - new SampleParams(), null!, TestReport.GeneratedAt, TestContext.Current.CancellationToken)); - } - - [Fact] - public void ParametersType_IsTheDeclaredParameterClass() - { - Assert.Equal(typeof(SampleParams), new TestReport().ParametersType); - } -} diff --git a/test/Reports/ReportServiceTests.cs b/test/Reports/ReportServiceTests.cs deleted file mode 100644 index 3e710c231..000000000 --- a/test/Reports/ReportServiceTests.cs +++ /dev/null @@ -1,283 +0,0 @@ -using System.Text.Json; -using Microsoft.Extensions.Logging; -using System.Text; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Exporters; -using Viper.Areas.Reports.Services; - -namespace Viper.test.Reports; - -public sealed class ReportServiceTests -{ - private static readonly DateTimeOffset Now = new(2026, 9, 29, 15, 0, 0, TimeSpan.Zero); - - private readonly TestReport _sample = new(); - private readonly ListLogger _logger = new(); - - private ReportService CreateService(params string[] permissions) - { - var registry = new ReportRegistry( - [ - _sample, - new TestReport(key: "effort.other", title: "Other", area: "Effort", permissions: ["SVMSecure.Effort"]), - ], - [new TestPlannedReports()]); - return new ReportService( - registry, - new StubReportUserService(TestReport.ContextWith(permissions)), - [new ReportCsvExporter()], - new FixedTimeProvider(Now), - _logger); - } - - private static JsonElement Json(string json) - { - using JsonDocument document = JsonDocument.Parse(json); - return document.RootElement.Clone(); - } - - #region Catalog and definitions - - [Fact] - public void GetCatalog_ListsBuiltAndPlannedReportsTheUserMayRunInTitleOrder() - { - ReportService service = CreateService(TestReport.RunPermission); - - IReadOnlyList catalog = service.GetCatalog(null); - - Assert.Equal( - [ - new ReportCatalogItem("test.planned", "Planned report", "Test", "A report not built yet.", Available: false), - new ReportCatalogItem("test.sample", "Sample report", "Test", "A report used by tests.", Available: true), - ], - catalog); - } - - [Fact] - public void GetCatalog_OrdersByAreaBeforeTitle() - { - ReportService service = CreateService(TestReport.RunPermission, "SVMSecure.Effort", "SVMSecure.Students"); - - IReadOnlyList catalog = service.GetCatalog(null); - - Assert.Equal( - ["effort.other", "students.restricted", "test.planned", "test.sample"], - catalog.Select(item => item.Key)); - } - - [Theory] - [InlineData(" effort ", 1)] - [InlineData("Test", 2)] - [InlineData("Students", 0)] - [InlineData("", 3)] - public void GetCatalog_FiltersByArea(string area, int expectedCount) - { - ReportService service = CreateService(TestReport.RunPermission, "SVMSecure.Effort"); - - Assert.Equal(expectedCount, service.GetCatalog(area).Count); - } - - [Fact] - public void GetDefinition_PlannedReport_IsNotFound() - { - ReportService service = CreateService(TestReport.RunPermission); - - Assert.Equal(ReportOutcomeStatus.NotFound, service.GetDefinition(TestPlannedReports.Visible.Key).Status); - } - - [Fact] - public void GetDefinition_UnknownKey_IsNotFound() - { - ReportService service = CreateService(TestReport.RunPermission); - - Assert.Equal(ReportOutcomeStatus.NotFound, service.GetDefinition("test.missing").Status); - } - - [Fact] - public void GetDefinition_WithoutPermission_IsForbidden() - { - ReportService service = CreateService(); - - Assert.Equal(ReportOutcomeStatus.Forbidden, service.GetDefinition("test.sample").Status); - } - - [Fact] - public void GetDefinition_WithPermission_ReturnsMetadata() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = service.GetDefinition("TEST.SAMPLE"); - - Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); - Assert.NotNull(outcome.Value); - Assert.Equal("test.sample", outcome.Value.Key); - } - - #endregion - - #region Running - - [Fact] - public async Task RunAsync_UnknownKey_IsNotFound() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = await service.RunAsync("test.missing", null, TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.NotFound, outcome.Status); - } - - [Fact] - public async Task RunAsync_PlannedReport_IsNotFound() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = - await service.RunAsync(TestPlannedReports.Visible.Key, null, TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.NotFound, outcome.Status); - } - - [Fact] - public async Task RunAsync_WithoutPermission_IsForbiddenBeforeReadingParameters() - { - ReportService service = CreateService(); - - ReportOutcome outcome = - await service.RunAsync("test.sample", Json("[\"not an object\"]"), TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Forbidden, outcome.Status); - Assert.Null(_sample.FetchedWith); - } - - [Fact] - public async Task RunAsync_UnreadableParameters_IsInvalid() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = - await service.RunAsync("test.sample", Json("""{ "minimumAge": "old" }"""), TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); - Assert.Equal("minimumAge", Assert.Single(outcome.Errors).Parameter); - Assert.Null(_sample.FetchedWith); - } - - [Fact] - public async Task RunAsync_InvalidParameters_IsInvalid() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = - await service.RunAsync("test.sample", Json("""{ "facultyType": "X" }"""), TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); - Assert.Equal("facultyType", Assert.Single(outcome.Errors).Parameter); - Assert.Null(_sample.FetchedWith); - } - - [Fact] - public async Task RunAsync_ValidParameters_RunsWithDefaultsAndAudits() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = await service.RunAsync( - "test.sample", Json("""{ "search": "a\nb" }"""), TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); - Assert.NotNull(outcome.Value); - Assert.Equal(5, outcome.Value.RowCount); - Assert.Equal(Now, outcome.Value.GeneratedAt); - Assert.Equal("S", _sample.FetchedWith?.FacultyType); - Assert.Equal("tester", _sample.FetchedFor?.LoginId); - - (LogLevel level, string message) = Assert.Single(_logger.Entries); - Assert.Equal(LogLevel.Information, level); - Assert.Contains("test.sample", message, StringComparison.Ordinal); - Assert.Contains("5 rows", message, StringComparison.Ordinal); - Assert.DoesNotContain("\n", message, StringComparison.Ordinal); - } - - [Fact] - public async Task RunAsync_InformationLoggingOff_SkipsAuditEntry() - { - ReportService service = CreateService(TestReport.RunPermission); - _logger.Enabled = false; - - ReportOutcome outcome = await service.RunAsync("test.sample", null, TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); - Assert.Empty(_logger.Entries); - } - - #endregion - - #region Exporting - - [Fact] - public async Task ExportAsync_UnknownKey_IsNotFound() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = - await service.ExportAsync("test.missing", "csv", null, TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.NotFound, outcome.Status); - } - - [Fact] - public async Task ExportAsync_WithoutPermission_IsForbiddenBeforeCheckingFormat() - { - ReportService service = CreateService(); - - ReportOutcome outcome = - await service.ExportAsync("test.sample", "docx", null, TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Forbidden, outcome.Status); - } - - [Fact] - public async Task ExportAsync_UnknownFormat_IsInvalidWithoutRunning() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = - await service.ExportAsync("test.sample", "docx", null, TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); - Assert.Equal( - [new ReportValidationError(ReportService.FormatParameter, "Choose an export format: csv.")], - outcome.Errors); - Assert.Null(_sample.FetchedWith); - } - - [Fact] - public async Task ExportAsync_InvalidParameters_IsInvalid() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = await service.ExportAsync( - "test.sample", "csv", Json("""{ "facultyType": "X" }"""), TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Invalid, outcome.Status); - Assert.Equal("facultyType", Assert.Single(outcome.Errors).Parameter); - } - - [Fact] - public async Task ExportAsync_ValidRequest_ReturnsFileAndAudits() - { - ReportService service = CreateService(TestReport.RunPermission); - - ReportOutcome outcome = - await service.ExportAsync("test.sample", "CSV", null, TestContext.Current.CancellationToken); - - Assert.Equal(ReportOutcomeStatus.Ok, outcome.Status); - Assert.NotNull(outcome.Value); - Assert.Equal("Sample report.csv", outcome.Value.FileName); - Assert.Equal("text/csv", outcome.Value.ContentType); - Assert.StartsWith("\uFEFFName,Department", Encoding.UTF8.GetString(outcome.Value.Content), StringComparison.Ordinal); - Assert.Contains("export:csv", Assert.Single(_logger.Entries).Message, StringComparison.Ordinal); - } - - #endregion -} diff --git a/test/Reports/ReportTestDoubles.cs b/test/Reports/ReportTestDoubles.cs deleted file mode 100644 index 99247ea46..000000000 --- a/test/Reports/ReportTestDoubles.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Text.Json; -using System.Text.Json.Serialization; -using Microsoft.Extensions.Logging; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Services; - -namespace Viper.test.Reports; - -/// -/// A clock pinned to one instant, reported in UTC. -/// -internal sealed class FixedTimeProvider : TimeProvider -{ - private readonly DateTimeOffset _now; - - public FixedTimeProvider(DateTimeOffset now) - { - _now = now; - } - - public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; - - public override DateTimeOffset GetUtcNow() - { - return _now.ToUniversalTime(); - } -} - -/// -/// Captures formatted log messages so tests can check what was audited. -/// -internal sealed class ListLogger : ILogger -{ - public List<(LogLevel Level, string Message)> Entries { get; } = []; - - public bool Enabled { get; set; } = true; - - public IDisposable? BeginScope(TState state) where TState : notnull - { - return null; - } - - public bool IsEnabled(LogLevel logLevel) - { - return Enabled; - } - - public void Log( - LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) - { - Entries.Add((logLevel, formatter(state, exception))); - } -} - -/// -/// Always serves the same context, standing in for the signed-in user. -/// -internal sealed class StubReportUserService : IReportUserService -{ - private readonly ReportContext _context; - - public StubReportUserService(ReportContext context) - { - _context = context; - } - - public ReportContext GetCurrentContext() - { - return _context; - } -} - -/// -/// Two planned reports: one the standard test user may see, one that needs another permission. -/// -internal sealed class TestPlannedReports : IPlannedReportSource -{ - public static readonly PlannedReport Visible = - new("test.planned", "Planned report", "Test", "A report not built yet.", [TestReport.RunPermission]); - - public static readonly PlannedReport Restricted = - new("students.restricted", "Restricted plan", "Students", "Needs another permission.", ["SVMSecure.Students"]); - - public IReadOnlyList PlannedReports => [Visible, Restricted]; -} - -/// -/// A parameter type whose converter produces null, which a real parameter class never does. -/// -[JsonConverter(typeof(NullParamsConverter))] -internal sealed class NullParams; - -internal sealed class NullParamsConverter : JsonConverter -{ - public override NullParams? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - reader.Skip(); - return null; - } - - public override void Write(Utf8JsonWriter writer, NullParams value, JsonSerializerOptions options) - { - writer.WriteNullValue(); - } -} diff --git a/test/Reports/ReportTestFixtures.cs b/test/Reports/ReportTestFixtures.cs deleted file mode 100644 index 8f22f69da..000000000 --- a/test/Reports/ReportTestFixtures.cs +++ /dev/null @@ -1,169 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -internal sealed record SampleRow( - string Name, - string? Department, - int Age, - decimal? Salary, - DateOnly HireDate, - IReadOnlyList? Ethnicities = null); - -internal sealed record SampleParams -{ - public string? FacultyType { get; init; } - - public IReadOnlyList? Departments { get; init; } - - public DateOnly? StartDate { get; init; } - - public DateOnly? EndDate { get; init; } - - public string? Search { get; init; } - - public int? MinimumAge { get; init; } - - public bool? IncludeEmeriti { get; init; } - - public string? Computed => Search; - - public SampleInner Inner { get; init; } = new(); -} - -internal sealed record SampleInner -{ - public string? Value { get; init; } -} - -/// -/// A configurable report for engine tests. declares one parameter of -/// every type and one column of every format. -/// -internal sealed class TestReport : ReportDefinition -{ - public const string RunPermission = "SVMSecure.Test.Run"; - public const string SalaryPermission = "SVMSecure.Test.Salary"; - - public static readonly DateOnly DefaultStart = new(2026, 7, 1); - - public static readonly IReadOnlyList FacultyTypes = - [ - new("S", "Senate"), - new("F", "Federation"), - new("B", "Both"), - ]; - - public static readonly IReadOnlyList DepartmentOptions = - [ - new("APC", "Anatomy, Physiology and Cell Biology"), - new("VME", "Medicine and Epidemiology"), - ]; - - private readonly Action> _configure; - private readonly string _key; - private readonly string _title; - private readonly string _area; - private readonly string _description; - private readonly IReadOnlyList _permissions; - private readonly Func> _fetch; - - public TestReport( - Action>? configure = null, - string key = "test.sample", - string title = "Sample report", - string area = "Test", - string description = "A report used by tests.", - IReadOnlyList? permissions = null, - Func>? fetch = null) - { - _configure = configure ?? Standard; - _key = key; - _title = title; - _area = area; - _description = description; - _permissions = permissions ?? [RunPermission]; - _fetch = fetch ?? (_ => Rows()); - } - - public int ConfigureCalls { get; private set; } - - public SampleParams? FetchedWith { get; private set; } - - public ReportContext? FetchedFor { get; private set; } - - public override string Key => _key; - - public override string Title => _title; - - public override string Area => _area; - - public override string Description => _description; - - public override IReadOnlyList Permissions => _permissions; - - public static void Standard(ReportBuilder report) - { - report.Choice(p => p.FacultyType, "Faculty type", FacultyTypes).Required().Default(() => "S"); - report.MultiChoice(p => p.Departments, "Departments", DepartmentOptions); - report.Date(p => p.StartDate, "Start date").Required().Default(() => DefaultStart); - report.Date(p => p.EndDate, "End date"); - report.Text(p => p.Search, "Search"); - report.Number(p => p.MinimumAge, "Minimum age"); - report.Boolean(p => p.IncludeEmeriti, "Include emeriti"); - report.Validate( - p => p.EndDate is null || p.EndDate >= p.StartDate, - "End date must be on or after the start date.", - "endDate"); - - report.Column(r => r.Name, "Name"); - report.Column(r => r.Department, "Department"); - report.Column(r => r.Age, "Age").AsNumber(); - report.Column(r => r.Salary, "Salary").AsCurrency() - .VisibleWhen(context => context.HasPermission(SalaryPermission)); - report.Column(r => r.HireDate, "Hire date").AsDate(); - } - - public static ReportContext ContextWith(params string[] permissions) - { - var granted = new HashSet(permissions, StringComparer.Ordinal); - return new ReportContext("tester", granted.Contains); - } - - public static readonly DateTimeOffset GeneratedAt = new(2026, 9, 29, 8, 0, 0, TimeSpan.FromHours(-7)); - - /// - /// Five people: three in VME (one key padded with a space), one in "apc", and one with a - /// blank department. - /// - public static IReadOnlyList Rows() - { - return - [ - new("Ada", "VME", 61, 120_000m, new DateOnly(1995, 7, 1), ["Asian", "White"]), - new("Ben", "apc", 45, 90_000m, new DateOnly(2010, 1, 15), ["White"]), - new("Cy", "VME ", 38, null, new DateOnly(2018, 9, 1), ["Hispanic"]), - new("Di", "VME", 66, 150_000m, new DateOnly(1990, 3, 1), []), - new("Ed", " ", 29, 70_000m, new DateOnly(2022, 8, 15), ["White"]), - ]; - } - - public static ReportResult Run(TestReport report, ReportContext? context = null) - { - return report.CreateResult(Rows(), context ?? ContextWith(RunPermission, SalaryPermission), GeneratedAt); - } - - protected override void Configure(ReportBuilder report) - { - ConfigureCalls++; - _configure(report); - } - - protected override Task> FetchAsync( - SampleParams parameters, ReportContext context, CancellationToken ct) - { - FetchedWith = parameters; - FetchedFor = context; - return Task.FromResult(_fetch(parameters)); - } -} diff --git a/test/Reports/ReportUserServiceTests.cs b/test/Reports/ReportUserServiceTests.cs deleted file mode 100644 index e16252f79..000000000 --- a/test/Reports/ReportUserServiceTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using NSubstitute; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Services; -using Viper.Classes.SQLContext; -using Viper.Models.AAUD; - -namespace Viper.test.Reports; - -public sealed class ReportUserServiceTests -{ - private readonly RAPSContext _rapsContext = Substitute.For(); - private readonly IUserHelper _userHelper = Substitute.For(); - - [Fact] - public void GetCurrentContext_NoUser_HasNoPermissions() - { - _userHelper.GetCurrentUser().Returns((AaudUser?)null); - var service = new ReportUserService(_rapsContext, _userHelper); - - ReportContext context = service.GetCurrentContext(); - - Assert.Null(context.LoginId); - Assert.False(context.HasPermission("SVMSecure")); - _userHelper.DidNotReceive().HasPermission(Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public void GetCurrentContext_SignedInUser_ChecksPermissionsThroughRaps() - { - var user = new AaudUser { MothraId = "01234567", LoginId = "jdoe" }; - _userHelper.GetCurrentUser().Returns(user); - _userHelper.HasPermission(_rapsContext, user, "SVMSecure.Personnel.Sabbatic").Returns(true); - var service = new ReportUserService(_rapsContext, _userHelper); - - ReportContext context = service.GetCurrentContext(); - - Assert.Equal("jdoe", context.LoginId); - Assert.True(context.HasPermission("SVMSecure.Personnel.Sabbatic")); - Assert.False(context.HasPermission("SVMSecure.Personnel.FacultySalary")); - } -} diff --git a/test/Reports/ReportValueFormatterTests.cs b/test/Reports/ReportValueFormatterTests.cs deleted file mode 100644 index 92b55e767..000000000 --- a/test/Reports/ReportValueFormatterTests.cs +++ /dev/null @@ -1,113 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.test.Reports; - -public sealed class ReportValueFormatterTests -{ - private static ReportColumnMetadata Column(ReportColumnFormat format, int? decimals = null) - { - return new ReportColumnMetadata("value", "Value", format, ReportAlignment.Left, decimals); - } - - [Fact] - public void Format_NonNumericValues() - { - ReportColumnMetadata text = Column(ReportColumnFormat.Text); - - Assert.Equal(string.Empty, ReportValueFormatter.Format(null, text)); - Assert.Equal("Ada", ReportValueFormatter.Format("Ada", text)); - Assert.Equal("07/01/2026", ReportValueFormatter.Format(new DateOnly(2026, 7, 1), text)); - Assert.Equal("07/01/2026", ReportValueFormatter.Format(new DateTime(2026, 7, 1, 13, 30, 0, DateTimeKind.Local), text)); - Assert.Equal("APC, VME", ReportValueFormatter.Format(new[] { "APC", "VME" }, Column(ReportColumnFormat.List))); - Assert.Equal("True", ReportValueFormatter.Format(true, text)); - } - - [Fact] - public void Format_NumbersInTextColumnsKeepTheirDigits() - { - Assert.Equal("1234567", ReportValueFormatter.Format(1_234_567, Column(ReportColumnFormat.Text))); - } - - [Theory] - [InlineData(ReportColumnFormat.Number, 0, "1,235")] - [InlineData(ReportColumnFormat.Number, 1, "1,234.6")] - [InlineData(ReportColumnFormat.Currency, 2, "$1,234.56")] - public void Format_NumericColumns(ReportColumnFormat format, int decimals, string expected) - { - Assert.Equal(expected, ReportValueFormatter.Format(1234.56m, Column(format, decimals))); - } - - [Fact] - public void Format_PercentColumnTreatsValuesAsFractions() - { - string formatted = ReportValueFormatter.Format(0.25m, Column(ReportColumnFormat.Percent)); - - Assert.StartsWith("25", formatted, StringComparison.Ordinal); - Assert.EndsWith("%", formatted, StringComparison.Ordinal); - } - - [Fact] - public void Format_NumericColumnWithoutDecimals_UsesWholeNumbers() - { - Assert.Equal("61", ReportValueFormatter.Format(61, Column(ReportColumnFormat.Number))); - } - - [Fact] - public void Format_NonNumberInNumericColumn_FallsBackToText() - { - Assert.Equal("n/a", ReportValueFormatter.Format("n/a", Column(ReportColumnFormat.Number))); - Assert.Equal("True", ReportValueFormatter.Format(true, Column(ReportColumnFormat.Number))); - } - - [Fact] - public void Format_NullColumn_Throws() - { - Assert.Throws(() => ReportValueFormatter.Format("x", null!)); - } - - [Theory] - [InlineData(ReportColumnFormat.Number, true)] - [InlineData(ReportColumnFormat.Currency, true)] - [InlineData(ReportColumnFormat.Percent, true)] - [InlineData(ReportColumnFormat.Text, false)] - [InlineData(ReportColumnFormat.Date, false)] - [InlineData(ReportColumnFormat.List, false)] - public void IsNumeric_OnlyNumberCurrencyAndPercent(ReportColumnFormat format, bool expected) - { - Assert.Equal(expected, ReportValueFormatter.IsNumeric(format)); - } - - [Fact] - public void TryGetDecimal_AcceptsNumericTypes() - { - Assert.True(ReportValueFormatter.TryGetDecimal(1.5m, out decimal fromDecimal)); - Assert.True(ReportValueFormatter.TryGetDecimal(7, out decimal fromInt)); - Assert.True(ReportValueFormatter.TryGetDecimal(8L, out decimal fromLong)); - Assert.True(ReportValueFormatter.TryGetDecimal(2.5d, out decimal fromDouble)); - - Assert.Equal([1.5m, 7m, 8m, 2.5m], new[] { fromDecimal, fromInt, fromLong, fromDouble }); - } - - [Fact] - public void TryGetDecimal_RejectsNonNumbersAndOutOfRangeDoubles() - { - Assert.False(ReportValueFormatter.TryGetDecimal(null, out _)); - Assert.False(ReportValueFormatter.TryGetDecimal("12", out _)); - Assert.False(ReportValueFormatter.TryGetDecimal(double.NaN, out _)); - Assert.False(ReportValueFormatter.TryGetDecimal(1e30, out _)); - } - - [Fact] - public void FlagText_JoinsDistinctLabels() - { - var row = new ReportRowResult(1, new Dictionary(), - [ - new ReportFlag(ReportFlagKind.Highlight, ReportTone.Warning, "60+", null), - new ReportFlag(ReportFlagKind.Badge, ReportTone.Muted, "Emeritus", "status"), - new ReportFlag(ReportFlagKind.Badge, ReportTone.Warning, "60+", "age"), - ]); - - Assert.Equal("60+; Emeritus", ReportValueFormatter.FlagText(row)); - Assert.Throws(() => ReportValueFormatter.FlagText(null!)); - } -} diff --git a/test/Reports/ReportsControllerTests.cs b/test/Reports/ReportsControllerTests.cs deleted file mode 100644 index 9f5318fb2..000000000 --- a/test/Reports/ReportsControllerTests.cs +++ /dev/null @@ -1,195 +0,0 @@ -using System.Reflection; -using System.Text.Json; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Viper.Areas.Reports.Controllers; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Services; -using Viper.Classes; -using Web.Authorization; - -namespace Viper.test.Reports; - -public sealed class ReportsControllerTests -{ - private readonly StubReportService _service = new(); - private readonly ReportsController _controller; - - public ReportsControllerTests() - { - _controller = new ReportsController(_service); - } - - [Fact] - public void Controller_RequiresSignInAndUsesApiConventions() - { - PermissionAttribute? permission = typeof(ReportsController).GetCustomAttribute(); - RouteAttribute? route = typeof(ReportsController).GetCustomAttribute(); - - Assert.Equal("SVMSecure", permission?.Allow); - Assert.Equal("/api/reports", route?.Template); - Assert.True(typeof(ApiController).IsAssignableFrom(typeof(ReportsController))); - } - - [Fact] - public void GetCatalog_ReturnsServiceCatalog() - { - IReadOnlyList catalog = [new("test.sample", "Sample", "Test", "Description", Available: true)]; - _service.Catalog = catalog; - - ActionResult> result = _controller.GetCatalog("Test"); - - OkObjectResult ok = Assert.IsType(result.Result); - Assert.Same(catalog, ok.Value); - Assert.Equal("Test", _service.LastArea); - } - - [Fact] - public void GetDefinition_Ok_ReturnsMetadata() - { - var metadata = new ReportDefinitionMetadata("test.sample", "Sample", "Test", "Description", [], []); - _service.Definition = ReportOutcome.Ok(metadata); - - ActionResult result = _controller.GetDefinition("test.sample"); - - Assert.Same(metadata, Assert.IsType(result.Result).Value); - } - - [Fact] - public void GetDefinition_NotFound_Returns404() - { - _service.Definition = ReportOutcome.NotFound(); - - ActionResult result = _controller.GetDefinition("test.missing"); - - Assert.IsType(result.Result); - } - - [Fact] - public void GetDefinition_Forbidden_Returns403() - { - _service.Definition = ReportOutcome.Forbidden(); - - ActionResult result = _controller.GetDefinition("test.sample"); - - ObjectResult forbidden = Assert.IsType(result.Result); - Assert.Equal(StatusCodes.Status403Forbidden, forbidden.StatusCode); - } - - [Fact] - public async Task Run_Invalid_Returns400WithErrorsByParameter() - { - ReportValidationError[] errors = - [ - new("startDate", "Start date is required."), - new(null, "Enter a search or a minimum age."), - ]; - _service.Run = ReportOutcome.Invalid(errors); - - ActionResult result = await _controller.Run("test.sample", null, TestContext.Current.CancellationToken); - - BadRequestObjectResult badRequest = Assert.IsType(result.Result); - ValidationProblemDetails problem = Assert.IsType(badRequest.Value); - Assert.Equal(["Start date is required."], problem.Errors["startDate"]); - Assert.Equal(["Enter a search or a minimum age."], problem.Errors[string.Empty]); - } - - [Fact] - public async Task Run_Ok_ReturnsResult() - { - var report = new ReportResult("test.sample", "Sample", DateTimeOffset.UnixEpoch, 0, false, [], [], [], [], [], []); - _service.Run = ReportOutcome.Ok(report); - - ActionResult result = await _controller.Run("test.sample", null, TestContext.Current.CancellationToken); - - Assert.Same(report, Assert.IsType(result.Result).Value); - Assert.Equal("test.sample", _service.LastKey); - } - - [Fact] - public async Task Export_Ok_ReturnsUncachedDownload() - { - var file = new ReportFile([1, 2, 3], "text/csv", "Sample.csv"); - _service.Export = ReportOutcome.Ok(file); - _controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; - - ActionResult result = await _controller.Export("test.sample", "csv", null, TestContext.Current.CancellationToken); - - FileContentResult download = Assert.IsType(result); - Assert.Equal("text/csv", download.ContentType); - Assert.Equal("Sample.csv", download.FileDownloadName); - Assert.Equal([1, 2, 3], download.FileContents); - Assert.Equal("private, no-store, max-age=0", _controller.Response.Headers.CacheControl.ToString()); - Assert.Equal("csv", _service.LastFormat); - } - - [Fact] - public async Task Export_Invalid_Returns400() - { - _service.Export = ReportOutcome.Invalid([new("format", "Choose an export format: csv.")]); - - ActionResult result = await _controller.Export("test.sample", "docx", null, TestContext.Current.CancellationToken); - - ValidationProblemDetails problem = Assert.IsType(Assert.IsType(result).Value); - Assert.Equal(["Choose an export format: csv."], problem.Errors["format"]); - } - - [Fact] - public void ToProblemDetails_CombinesMessagesForTheSameParameter() - { - ValidationProblemDetails problem = ReportsController.ToProblemDetails( - [ - new("endDate", "First."), - new("endDate", "Second."), - ]); - - Assert.Equal(["First.", "Second."], problem.Errors["endDate"]); - Assert.Equal("The report parameters are not valid.", problem.Title); - } - - /// - /// Returns canned outcomes and records what the controller asked for. - /// - private sealed class StubReportService : IReportService - { - public IReadOnlyList Catalog { get; set; } = []; - - public ReportOutcome Definition { get; set; } = ReportOutcome.NotFound(); - - public ReportOutcome Run { get; set; } = ReportOutcome.NotFound(); - - public ReportOutcome Export { get; set; } = ReportOutcome.NotFound(); - - public string? LastFormat { get; private set; } - - public string? LastArea { get; private set; } - - public string? LastKey { get; private set; } - - public IReadOnlyList GetCatalog(string? area) - { - LastArea = area; - return Catalog; - } - - public ReportOutcome GetDefinition(string? key) - { - LastKey = key; - return Definition; - } - - public Task> RunAsync(string? key, JsonElement? parameters, CancellationToken ct) - { - LastKey = key; - return Task.FromResult(Run); - } - - public Task> ExportAsync( - string? key, string? format, JsonElement? parameters, CancellationToken ct) - { - LastKey = key; - LastFormat = format; - return Task.FromResult(Export); - } - } -} diff --git a/test/Reports/ReportsRegistrationTests.cs b/test/Reports/ReportsRegistrationTests.cs deleted file mode 100644 index 79c56e8d9..000000000 --- a/test/Reports/ReportsRegistrationTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using Viper.Areas.Reports; -using Viper.Areas.Reports.Data; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Exporters; - -namespace Viper.test.Reports; - -public sealed class ReportsRegistrationTests -{ - [Fact] - public void AddReports_RegistersDefinitionsPlannedReportsRegistryAndClock() - { - var services = new ServiceCollection(); - services.AddReports(typeof(ReportsRegistrationTests).Assembly); - - using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true); - using IServiceScope scope = provider.CreateScope(); - - IReportRegistry registry = scope.ServiceProvider.GetRequiredService(); - Assert.NotNull(registry.Find("test.sample")); - Assert.Contains(TestPlannedReports.Visible, registry.Planned); - Assert.Same(TimeProvider.System, provider.GetRequiredService()); - Assert.Equal(["csv", "xlsx", "pdf"], provider.GetServices().Select(exporter => exporter.Format)); - } - - [Fact] - public void AddReports_RegistersTheStoredProcedureRunner() - { - var services = new ServiceCollection(); - - services.AddReports(typeof(ReportsRegistrationTests).Assembly); - - Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IStoredProcedureRunner) - && descriptor.ImplementationType == typeof(StoredProcedureRunner) - && descriptor.Lifetime == ServiceLifetime.Singleton); - Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDbConnectionFactory) - && descriptor.ImplementationType == typeof(SqlConnectionFactory) - && descriptor.Lifetime == ServiceLifetime.Singleton); - } - - [Fact] - public void AddReports_KeepsAnExistingClock() - { - var clock = new FixedTimeProvider(DateTimeOffset.UnixEpoch); - var services = new ServiceCollection(); - services.AddSingleton(clock); - - services.AddReports(typeof(ReportsRegistrationTests).Assembly); - - using ServiceProvider provider = services.BuildServiceProvider(); - Assert.Same(clock, provider.GetRequiredService()); - } - - [Fact] - public void AddReports_NullArguments_Throw() - { - Assert.Throws(() => ReportsServiceCollectionExtensions.AddReports(null!, typeof(ReportsRegistrationTests).Assembly)); - Assert.Throws(() => new ServiceCollection().AddReports(null!)); - } -} diff --git a/web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs b/web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs deleted file mode 100644 index fccb115e1..000000000 --- a/web/Areas/Personnel/Models/EmployeeOnLeaveRow.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Viper.Areas.Personnel.Models; - -/// -/// One leave of absence from usp_get_peopleOnLeave, carrying only the columns the report shows. -/// -public sealed record EmployeeOnLeaveRow( - string Name, - string? HomeDepartment, - DateOnly? LeaveStart, - DateOnly? ReturnDate, - string? Description, - string? PayStatus); diff --git a/web/Areas/Personnel/Models/FacultyAppointmentRow.cs b/web/Areas/Personnel/Models/FacultyAppointmentRow.cs deleted file mode 100644 index 0f089e1cf..000000000 --- a/web/Areas/Personnel/Models/FacultyAppointmentRow.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Viper.Areas.Personnel.Models; - -/// -/// One paid appointment of a faculty member, from usp_get_facultyList with every -/// employee's details. Age is computed by the procedure, as in the legacy report. -/// -public sealed record FacultyAppointmentRow( - string EmployeeId, - string Name, - int? Age, - DateOnly? HireDate, - string? Department, - string? Title); diff --git a/web/Areas/Personnel/Models/FlsaEmployeeRow.cs b/web/Areas/Personnel/Models/FlsaEmployeeRow.cs deleted file mode 100644 index 18387a55e..000000000 --- a/web/Areas/Personnel/Models/FlsaEmployeeRow.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Viper.Areas.Personnel.Models; - -/// -/// One appointment from usp_get_flsa. isn't shown; it counts -/// people once when they hold several appointments. -/// -public sealed record FlsaEmployeeRow( - string? EmployeeId, - string Name, - string? Department, - string? Title, - string? Flsa, - string? Email); diff --git a/web/Areas/Personnel/PersonnelDatabases.cs b/web/Areas/Personnel/PersonnelDatabases.cs deleted file mode 100644 index 7573376da..000000000 --- a/web/Areas/Personnel/PersonnelDatabases.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Viper.Areas.Personnel; - -/// -/// Connection string names for the Personnel data sources that have no EF context. -/// -public static class PersonnelDatabases -{ - /// - /// The UCPath/PPS warehouse (legacy DSN PPS-Prod / PPS-dev). - /// - public const string Pps = "PPS"; -} diff --git a/web/Areas/Personnel/Reports/EmployeesOnLeaveReport.cs b/web/Areas/Personnel/Reports/EmployeesOnLeaveReport.cs deleted file mode 100644 index c399f2ca6..000000000 --- a/web/Areas/Personnel/Reports/EmployeesOnLeaveReport.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Services; -using Viper.Areas.Reports.Engine; - -namespace Viper.Areas.Personnel.Reports; - -public sealed record EmployeesOnLeaveParameters -{ - public string? EmployeeType { get; init; } - - public DateOnly? StartDate { get; init; } - - public DateOnly? EndDate { get; init; } -} - -/// -/// Faculty and staff with a leave of absence in a date range, which defaults to the current -/// fiscal year. Ports the legacy "Employee on Leave" page (leaveDetective). -/// -public sealed class EmployeesOnLeaveReport : ReportDefinition -{ - private readonly IPersonnelReportDataService _data; - - // The clock is injected so tests can pin the fiscal-year defaults. - private readonly TimeProvider _clock; - - public EmployeesOnLeaveReport(IPersonnelReportDataService data, TimeProvider clock) - { - _data = data; - _clock = clock; - } - - public override string Key => "personnel.employees-on-leave"; - - public override string Title => "Employees on Leave"; - - public override string Area => PersonnelReports.Area; - - public override string Description => "Faculty and staff on leave during a date range."; - - public override IReadOnlyList Permissions => [PersonnelPermissions.Sabbatic]; - - protected override void Configure(ReportBuilder report) - { - report.Choice(p => p.EmployeeType, "Employee type", PersonnelOptions.FacultyStaffBoth) - .Required() - .Default(() => PersonnelOptions.Faculty); - report.Date(p => p.StartDate, "Start date").Required().Default(() => FiscalYear.StartOf(Today())); - report.Date(p => p.EndDate, "End date").Required().Default(() => FiscalYear.EndOf(Today())); - report.Validate(p => p.EndDate >= p.StartDate, "End date must be on or after the start date.", "endDate"); - report.Sensitive(); - - report.Column(r => r.Name, "Name"); - report.Column(r => r.HomeDepartment, "Home department"); - report.Column(r => r.LeaveStart, "Leave start").AsDate(); - report.Column(r => r.ReturnDate, "Return date").AsDate(); - report.Column(r => r.Description, "Description"); - report.Column(r => r.PayStatus, "Pay status"); - } - - protected override Task> FetchAsync( - EmployeesOnLeaveParameters parameters, ReportContext context, CancellationToken ct) - { - // The engine has applied defaults and required checks, so all three values are set. - if (parameters is not { EmployeeType: { } type, StartDate: { } start, EndDate: { } end }) - { - throw new InvalidOperationException("Employees on Leave ran without its required parameters."); - } - - return _data.GetPeopleOnLeaveAsync(type, start, end, ct); - } - - private DateOnly Today() - { - return DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); - } -} diff --git a/web/Areas/Personnel/Reports/ExemptStatusReport.cs b/web/Areas/Personnel/Reports/ExemptStatusReport.cs deleted file mode 100644 index 240a07cf7..000000000 --- a/web/Areas/Personnel/Reports/ExemptStatusReport.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Viper.Areas.Personnel.Models; -using Viper.Areas.Personnel.Services; -using Viper.Areas.Reports.Engine; - -namespace Viper.Areas.Personnel.Reports; - -public sealed record ExemptStatusParameters -{ - public string? StatusType { get; init; } -} - -/// -/// Employees by department and FLSA exemption status, with exempt and non-exempt head counts -/// per department and for the school. Ports the legacy "Exempt/Non-Exempt" page (flsa). -/// -public sealed class ExemptStatusReport : ReportDefinition -{ - public const string Exempt = "EXEMPT"; - public const string NonExempt = "NON-EXEMPT"; - - private static readonly IReadOnlyList StatusTypes = - [ - new("E", "Exempt"), - new("N", "Non-exempt"), - new("B", "Both"), - ]; - - private readonly IPersonnelReportDataService _data; - - public ExemptStatusReport(IPersonnelReportDataService data) - { - _data = data; - } - - public override string Key => "personnel.exempt-non-exempt"; - - public override string Title => "Exempt/Non-Exempt"; - - public override string Area => PersonnelReports.Area; - - public override string Description => "Employees by department and FLSA exemption status."; - - // The legacy nav checked SVMSecure.EIS but the page ServiceCreditAdmin; decided: ServiceCreditAdmin. - public override IReadOnlyList Permissions => [PersonnelPermissions.ServiceCreditAdmin]; - - protected override void Configure(ReportBuilder report) - { - report.Choice(p => p.StatusType, "FLSA status", StatusTypes).Required().Default(() => "B"); - - report.RowNumbers(); - report.Column(r => r.Name, "Name"); - report.Column(r => r.Department, "Department"); - report.Column(r => r.Title, "Title"); - report.Column(r => r.Flsa, "FLSA"); - report.Column(r => r.Email, "Email"); - - // Head counts are of people, not appointments, as in the legacy page. - ReportMeasure exempt = report.CountDistinct(r => r.Flsa == Exempt ? r.EmployeeId : null); - ReportMeasure nonExempt = report.CountDistinct(r => r.Flsa == NonExempt ? r.EmployeeId : null); - report.Summary("Exempt employees", exempt); - report.Summary("Non-exempt employees", nonExempt); - report.GroupBy(r => r.Department) - .Subtotal("Exempt employees", exempt) - .Subtotal("Non-exempt employees", nonExempt); - } - - protected override async Task> FetchAsync( - ExemptStatusParameters parameters, ReportContext context, CancellationToken ct) - { - if (parameters.StatusType is not { } statusType) - { - throw new InvalidOperationException("Exempt/Non-Exempt ran without its required parameter."); - } - - IReadOnlyList rows = await _data.GetFlsaAsync(statusType, ct); - - // Non-exempt staff first within each department, as the legacy page listed them. - return [.. rows - .OrderByDescending(row => row.Flsa, StringComparer.Ordinal) - .ThenBy(row => row.Name, StringComparer.OrdinalIgnoreCase)]; - } -} diff --git a/web/Areas/Personnel/Reports/FacultyProfileReport.cs b/web/Areas/Personnel/Reports/FacultyProfileReport.cs deleted file mode 100644 index 663364dee..000000000 --- a/web/Areas/Personnel/Reports/FacultyProfileReport.cs +++ /dev/null @@ -1,92 +0,0 @@ -using Viper.Areas.Personnel.Services; -using Viper.Areas.Reports.Engine; - -namespace Viper.Areas.Personnel.Reports; - -public sealed record FacultyProfileParameters -{ - public string? FacultyType { get; init; } -} - -/// -/// Faculty with a paid appointment in the school, by department, with head counts, emeriti and -/// recall counts, and the age profile of active faculty. Ports the legacy "Faculty Profile" page -/// (facultyProfile), which made one query per department and one per person; this makes one. -/// -public sealed class FacultyProfileReport : ReportDefinition -{ - private const string AgeProfileTitle = "Age profile of active faculty (excluding emeriti and recalled faculty)"; - - // The legacy report drew a department's age chart only when it had at least five faculty. - private const int DepartmentChartMinimum = 5; - - private readonly IPersonnelReportDataService _data; - - public FacultyProfileReport(IPersonnelReportDataService data) - { - _data = data; - } - - public override string Key => "personnel.faculty-profile"; - - public override string Title => "Faculty Profile"; - - public override string Area => PersonnelReports.Area; - - public override string Description => - "Faculty with a paid appointment in the school, by department, with age distribution and emeriti and recall counts."; - - public override IReadOnlyList Permissions => [PersonnelPermissions.FacultySalary]; - - protected override void Configure(ReportBuilder report) - { - report.Choice(p => p.FacultyType, "Faculty type", PersonnelOptions.SenateFederationBoth) - .Required() - .Default(() => PersonnelOptions.Both); - report.Sensitive(); - - report.Column(r => r.Name, "Name"); - report.Column(r => r.Age, "Age").AsNumber(); - report.Column(r => r.HireDate, "Hire date").AsDate(); - report.Column(r => r.AppointmentDepartment, "Department"); - report.Column(r => r.Title, "Title"); - - // Declared first so the age highlight, declared after it, wins on the age cell. - report.Highlight(r => r.IsRetired, ReportTone.Muted, "Emeritus or recalled"); - report.Highlight( - r => r.Age >= FacultyProfileRows.HighlightAge, - ReportTone.Warning, - $"{FacultyProfileRows.HighlightAge} or older", - "age"); - - ReportMeasure faculty = report.CountDistinct(r => r.EmployeeId); - ReportMeasure emeriti = report.CountDistinct(r => r.IsEmeritus ? r.EmployeeId : null); - ReportMeasure recalled = report.CountDistinct(r => r.IsRecalled ? r.EmployeeId : null); - ReportMeasure active = report.CountDistinct(r => r.IsRetired ? null : r.EmployeeId); - - report.Summary("Faculty", faculty); - report.Summary("Emeriti", emeriti); - report.Summary("Recalled", recalled); - report.GroupBy(r => r.Department) - .Subtotal("Faculty", faculty) - .Subtotal("Emeriti", emeriti) - .Subtotal("Recalled", recalled); - - report.Chart(AgeProfileTitle, ReportChartKind.Bar, r => r.AgeGroup, active) - .Where(r => !r.IsRetired); - report.Chart(AgeProfileTitle, ReportChartKind.Bar, r => r.AgeGroup, active) - .Where(r => !r.IsRetired) - .PerGroup(DepartmentChartMinimum); - } - - protected override async Task> FetchAsync( - FacultyProfileParameters parameters, ReportContext context, CancellationToken ct) - { - if (parameters.FacultyType is not { } facultyType) - { - throw new InvalidOperationException("Faculty Profile ran without its required parameter."); - } - - return FacultyProfileRows.Expand(await _data.GetFacultyAppointmentsAsync(facultyType, ct)); - } -} diff --git a/web/Areas/Personnel/Reports/FacultyProfileRows.cs b/web/Areas/Personnel/Reports/FacultyProfileRows.cs deleted file mode 100644 index fdfcbadbe..000000000 --- a/web/Areas/Personnel/Reports/FacultyProfileRows.cs +++ /dev/null @@ -1,94 +0,0 @@ -using Viper.Areas.Personnel.Models; - -namespace Viper.Areas.Personnel.Reports; - -/// -/// One line of the Faculty Profile: an appointment, listed under a department where the person -/// holds an appointment. is the grouping; -/// is this appointment's own department. -/// -public sealed record FacultyProfileRow( - string Department, - string EmployeeId, - string Name, - int? Age, - DateOnly? HireDate, - string? AppointmentDepartment, - string? Title) -{ - public string? AgeGroup => FacultyProfileRows.AgeGroup(Age); - - public bool IsEmeritus => FacultyProfileRows.IsEmeritusTitle(Title); - - public bool IsRecalled => FacultyProfileRows.IsRecalledTitle(Title); - - public bool IsRetired => IsEmeritus || IsRecalled; -} - -/// -/// The Faculty Profile's rules, kept apart from the report so each can be tested directly. -/// -public static class FacultyProfileRows -{ - /// - /// Ages at or above this are highlighted, as in the legacy report. - /// - public const int HighlightAge = 60; - - private const int GroupWidth = 5; - private const int YoungestGroup = 20; - private const int OldestAge = 99; - - /// - /// Five-year brackets from "20-24" to "95-99", matching usp_get_profile_facultyAge. - /// Ages outside that range have no bracket. - /// - public static string? AgeGroup(int? age) - { - if (age is not { } years || years < YoungestGroup || years > OldestAge) - { - return null; - } - - int start = years - (years % GroupWidth); - return $"{start}-{start + GroupWidth - 1}"; - } - - public static bool IsEmeritusTitle(string? title) - { - return title?.Contains("EMERI", StringComparison.OrdinalIgnoreCase) == true; - } - - public static bool IsRecalledTitle(string? title) - { - return title?.Contains("RECAL", StringComparison.OrdinalIgnoreCase) == true; - } - - /// - /// Lists each person under every department where they hold an appointment, with all of their - /// appointments each time, oldest people first, as the legacy report did with one query per - /// department and one per person. This does it from a single query. - /// - public static IReadOnlyList Expand(IReadOnlyList appointments) - { - ArgumentNullException.ThrowIfNull(appointments); - ILookup byPerson = - appointments.ToLookup(appointment => appointment.EmployeeId, StringComparer.Ordinal); - - return [.. appointments - .Select(appointment => (Department: (appointment.Department ?? string.Empty).Trim(), appointment.EmployeeId)) - .Distinct() - .SelectMany(member => byPerson[member.EmployeeId].Select(appointment => new FacultyProfileRow( - member.Department, - appointment.EmployeeId, - appointment.Name, - appointment.Age, - appointment.HireDate, - appointment.Department, - appointment.Title))) - .OrderByDescending(row => row.Age) - .ThenBy(row => row.Name, StringComparer.OrdinalIgnoreCase) - .ThenBy(row => row.EmployeeId, StringComparer.Ordinal) - .ThenBy(row => row.Title, StringComparer.OrdinalIgnoreCase)]; - } -} diff --git a/web/Areas/Personnel/Reports/FiscalYear.cs b/web/Areas/Personnel/Reports/FiscalYear.cs deleted file mode 100644 index 27c6b48d6..000000000 --- a/web/Areas/Personnel/Reports/FiscalYear.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Viper.Areas.Personnel.Reports; - -/// -/// The university fiscal year, July 1 through June 30. -/// -public static class FiscalYear -{ - private const int FirstMonth = 7; - - public static DateOnly StartOf(DateOnly date) - { - int year = date.Month >= FirstMonth ? date.Year : date.Year - 1; - return new DateOnly(year, FirstMonth, 1); - } - - public static DateOnly EndOf(DateOnly date) - { - return StartOf(date).AddYears(1).AddDays(-1); - } -} diff --git a/web/Areas/Personnel/Reports/PersonnelOptions.cs b/web/Areas/Personnel/Reports/PersonnelOptions.cs deleted file mode 100644 index 1bbf0a715..000000000 --- a/web/Areas/Personnel/Reports/PersonnelOptions.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.Areas.Personnel.Reports; - -/// -/// Choice lists shared by several Personnel reports, using the codes the PPS procedures expect. -/// -public static class PersonnelOptions -{ - public const string Faculty = "F"; - public const string Staff = "S"; - public const string Both = "B"; - public const string Senate = "S"; - public const string Federation = "F"; - - public static readonly IReadOnlyList FacultyStaffBoth = - [ - new(Faculty, "Faculty"), - new(Staff, "Staff"), - new(Both, "Both"), - ]; - - public static readonly IReadOnlyList SenateFederationBoth = - [ - new(Senate, "Senate"), - new(Federation, "Federation"), - new(Both, "Both"), - ]; -} diff --git a/web/Areas/Personnel/Reports/PersonnelReports.cs b/web/Areas/Personnel/Reports/PersonnelReports.cs deleted file mode 100644 index b6d6e5180..000000000 --- a/web/Areas/Personnel/Reports/PersonnelReports.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Viper.Areas.Personnel.Reports; - -/// -/// Shared settings for the Personnel reports. -/// -public static class PersonnelReports -{ - /// - /// The catalog area the Personnel reports are listed under. - /// - public const string Area = "Personnel"; -} diff --git a/web/Areas/Personnel/Services/PersonnelReportDataService.cs b/web/Areas/Personnel/Services/PersonnelReportDataService.cs deleted file mode 100644 index 78c57eedc..000000000 --- a/web/Areas/Personnel/Services/PersonnelReportDataService.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System.Data; -using Viper.Areas.Personnel.Models; -using Viper.Areas.Reports.Data; - -namespace Viper.Areas.Personnel.Services; - -/// -/// Reads the data behind the Personnel reports from the PPS warehouse. -/// -public interface IPersonnelReportDataService -{ - /// - /// Leaves of absence overlapping the date range, for faculty ("F"), staff ("S") or both ("B"). - /// - Task> GetPeopleOnLeaveAsync( - string employeeType, DateOnly startDate, DateOnly endDate, CancellationToken ct); - - /// - /// Employees by FLSA status: exempt ("E"), non-exempt ("N") or both ("B"). - /// - Task> GetFlsaAsync(string statusType, CancellationToken ct); - - /// - /// Every paid appointment of Senate ("S"), Federation ("F") or both ("B") faculty in the school. - /// - Task> GetFacultyAppointmentsAsync(string facultyType, CancellationToken ct); -} - -/// -/// Calls the legacy PPS stored procedures, so results match the ColdFusion reports while they -/// run side by side. Each method only calls and maps; report rules live in the report definitions. -/// -public class PersonnelReportDataService : IPersonnelReportDataService -{ - private const string PeopleOnLeaveProcedure = "usp_get_peopleOnLeave"; - private const string FlsaProcedure = "usp_get_flsa"; - private const string FacultyListProcedure = "usp_get_facultyList"; - - // usp_get_facultyList returns every employee's appointments when @employeeID is "All". - private const string AllEmployees = "All"; - private const string LegacyDateFormat = "MM/dd/yyyy"; - - private readonly IStoredProcedureRunner _runner; - - public PersonnelReportDataService(IStoredProcedureRunner runner) - { - _runner = runner; - } - - public Task> GetPeopleOnLeaveAsync( - string employeeType, DateOnly startDate, DateOnly endDate, CancellationToken ct) - { - // @fYear is the procedure's older fiscal-year filter; the date range replaces it. - return _runner.QueryAsync( - PersonnelDatabases.Pps, - PeopleOnLeaveProcedure, - [ - StoredProcedureParameter.Text("fYear", null, 4), - StoredProcedureParameter.Text("employeeType", employeeType, 1), - StoredProcedureParameter.Date("startDate", startDate), - StoredProcedureParameter.Date("endDate", endDate), - ], - MapEmployeeOnLeave, - ct); - } - - public Task> GetFlsaAsync(string statusType, CancellationToken ct) - { - return _runner.QueryAsync( - PersonnelDatabases.Pps, - FlsaProcedure, - [StoredProcedureParameter.Text("statusType", statusType, 1)], - MapFlsaEmployee, - ct); - } - - public Task> GetFacultyAppointmentsAsync(string facultyType, CancellationToken ct) - { - return _runner.QueryAsync( - PersonnelDatabases.Pps, - FacultyListProcedure, - [ - StoredProcedureParameter.Text("facultyType", facultyType, 1), - StoredProcedureParameter.Text("deptCode", string.Empty, 6), - StoredProcedureParameter.Text("employeeID", AllEmployees, 11), - ], - MapFacultyAppointment, - ct); - } - - // Stored procedure rows are mapped by hand: Mapperly maps between types, not from IDataRecord. - internal static EmployeeOnLeaveRow MapEmployeeOnLeave(IDataRecord record) - { - return new EmployeeOnLeaveRow( - record.GetTrimmedString("Name") ?? string.Empty, - record.GetTrimmedString("homeDept"), - record.GetDateOnly("loa_begin_date"), - record.GetDateOnly("loa_return_date"), - record.GetTrimmedString("loa_description"), - record.GetTrimmedString("pay_status")); - } - - internal static FlsaEmployeeRow MapFlsaEmployee(IDataRecord record) - { - return new FlsaEmployeeRow( - record.GetTrimmedString("employee_id"), - record.GetTrimmedString("emp_name") ?? string.Empty, - record.GetTrimmedString("department"), - record.GetTrimmedString("title"), - record.GetTrimmedString("flsa"), - record.GetTrimmedString("email")); - } - - internal static FacultyAppointmentRow MapFacultyAppointment(IDataRecord record) - { - return new FacultyAppointmentRow( - record.GetTrimmedString("EMPLOYEE_ID") ?? string.Empty, - record.GetTrimmedString("EMP_NAME") ?? string.Empty, - record.GetNullableInt32("AGE"), - record.GetDateOnlyFromText("HIRE_DATE", LegacyDateFormat), - record.GetTrimmedString("APPT_DEPT"), - record.GetTrimmedString("TITLE")); - } -} 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..bd5f044aa --- /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().SemanticHeader1().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/ReportRunLog.cs b/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs index 5e6d28d20..ca7b30742 100644 --- a/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs +++ b/web/Areas/ReportBuilder/Models/Entities/ReportRunLog.cs @@ -2,7 +2,7 @@ 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. +/// parameters, and how many rows; or, for a run that failed, why. /// public class ReportRunLog { @@ -19,4 +19,10 @@ public class ReportRunLog /// 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 index aa5f8ed3d..400fe5550 100644 --- a/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs +++ b/web/Areas/ReportBuilder/Models/ReportBuilderEnums.cs @@ -1,6 +1,11 @@ +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, @@ -11,6 +16,7 @@ public enum ReportSourceKind /// 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, @@ -26,6 +32,7 @@ public enum ReportValueKind } /// How a report column's values are shown on screen and in exports. +[JsonConverter(typeof(JsonStringEnumConverter))] public enum ReportColumnFormat { Text, @@ -38,6 +45,7 @@ public enum ReportColumnFormat } /// The input a report parameter takes. +[JsonConverter(typeof(JsonStringEnumConverter))] public enum ReportParameterType { Text, @@ -49,6 +57,7 @@ public enum ReportParameterType } /// How a parameter filters a view's column. Procedure parameters have no operator. +[JsonConverter(typeof(JsonStringEnumConverter))] public enum ReportFilterOperator { Equals, @@ -62,6 +71,7 @@ public enum ReportFilterOperator /// 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, @@ -70,6 +80,7 @@ public enum ReportParameterBinding } /// What a user did with a report, for the run log. +[JsonConverter(typeof(JsonStringEnumConverter))] public enum ReportRunAction { Run, @@ -78,6 +89,7 @@ public enum ReportRunAction } /// What happened to a report definition, for its history. +[JsonConverter(typeof(JsonStringEnumConverter))] public enum ReportHistoryAction { Created, 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 index 3c4313406..d03c890e6 100644 --- a/web/Areas/ReportBuilder/Models/ReportRunDtos.cs +++ b/web/Areas/ReportBuilder/Models/ReportRunDtos.cs @@ -1,3 +1,5 @@ +using System.Text.Json.Serialization; + namespace Viper.Areas.ReportBuilder.Models; /// Why a report is being run: on screen, or for one of the downloads. @@ -19,6 +21,7 @@ public sealed record ReportRunRequest 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. @@ -27,6 +30,7 @@ public sealed record ReportRunRequest /// 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). @@ -80,6 +84,9 @@ 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; } = []; @@ -89,6 +96,25 @@ internal static ReportRunOutcome Fail(ReportRunStatus status, params string[] er } } +/// 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 { 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 index d6c0388ce..65375d847 100644 --- a/web/Areas/ReportBuilder/ReportBuilderDbContext.cs +++ b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Viper.Areas.ReportBuilder.Models.Entities; +using Viper.Areas.ReportBuilder.Services; namespace Viper.Areas.ReportBuilder; @@ -135,6 +136,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) 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); }); } diff --git a/web/Areas/ReportBuilder/Services/ReportAccess.cs b/web/Areas/ReportBuilder/Services/ReportAccess.cs new file mode 100644 index 000000000..61ff40b2e --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportAccess.cs @@ -0,0 +1,78 @@ +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) + .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..3b2ef2a5a --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportAdminService.cs @@ -0,0 +1,431 @@ +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 _context.SaveChangesAsync(ct); + + await AddHistoryAsync(report, ReportHistoryAction.Created, now, who, 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 _context.SaveChangesAsync(ct); + + await AddHistoryAsync(report, ReportHistoryAction.Updated, now, who, 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 _context.SaveChangesAsync(ct); + await AddHistoryAsync(report, deleted ? ReportHistoryAction.Deleted : ReportHistoryAction.Restored, now, who, 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 index be341e3f2..2479a7ee5 100644 --- a/web/Areas/ReportBuilder/Services/ReportChoiceList.cs +++ b/web/Areas/ReportBuilder/Services/ReportChoiceList.cs @@ -69,12 +69,9 @@ public static class ReportChoiceList private static string? Text(JsonElement item, string name) { - foreach (JsonProperty property in item.EnumerateObject() - .Where(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))) - { - return property.Value.ValueKind == JsonValueKind.String ? property.Value.GetString() : property.Value.ToString(); - } - - return null; + 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/ReportDefinitionValidator.cs b/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs new file mode 100644 index 000000000..c5d347464 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs @@ -0,0 +1,311 @@ +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."); + } + + 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 index 04f4e981f..69f4abb02 100644 --- a/web/Areas/ReportBuilder/Services/ReportLimits.cs +++ b/web/Areas/ReportBuilder/Services/ReportLimits.cs @@ -18,9 +18,20 @@ public static class ReportLimits 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 index 49bd4d49e..1208951f1 100644 --- a/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs +++ b/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs @@ -160,7 +160,7 @@ public static ReportBindResult Bind( 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 [string choice] ? choice : null; + return AllowedValues(definition, [first], choices, errors) is [{ } choice] ? choice : null; case ReportParameterType.MultiChoice: return AllowedValues(definition, raw, choices, errors); default: 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..02a493ac3 --- /dev/null +++ b/web/Areas/ReportBuilder/Services/ReportProblemService.cs @@ -0,0 +1,85 @@ +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) + .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/ReportRunService.cs b/web/Areas/ReportBuilder/Services/ReportRunService.cs index 29e85514e..4b4c7c3ce 100644 --- a/web/Areas/ReportBuilder/Services/ReportRunService.cs +++ b/web/Areas/ReportBuilder/Services/ReportRunService.cs @@ -1,6 +1,7 @@ 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; @@ -15,11 +16,18 @@ public interface IReportRunService /// 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. +/// 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. @@ -66,82 +74,122 @@ public async Task RunAsync(string slug, ReportRunRequest reque return ReportRunOutcome.Fail(ReportRunStatus.Forbidden); } - ReportDefinition? report = await FindAsync(slug, ct); + ReportDefinition? report = await ReportAccess.FindAsync(_context, slug, ct); if (report is null) { return ReportRunOutcome.Fail(ReportRunStatus.NotFound); } - if (!CanView(report) || !AllowsMode(report, mode)) + 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; - IReadOnlyList parameters; try { - 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]); - } - - parameters = bound.Parameters; - outcome = Plan(report, source, request, mode, parameters, out RunPlan? plan); - if (plan is not null) - { - outcome = new ReportRunOutcome - { - Status = ReportRunStatus.Ok, - Result = source.Kind == ReportSourceKind.View - ? await RunViewAsync(plan, ct) - : await RunProcedureAsync(plan, ct), - }; - } + outcome = await RunReportAsync(report, request, mode, user, attempt, ct); } catch (DbException ex) { _logger.LogError(ex, "Report {ReportId} failed to run", report.Id); - return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, "The report couldn't be run. Try again later."); + 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}"); } - if (outcome.Result is not null) + // 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, parameters, outcome.Result, _clock.GetElapsedTime(started), ct); + await LogRunAsync(report, user, mode, attempt, outcome, _clock.GetElapsedTime(started), ct); } return outcome; } - private async Task FindAsync(string slug, CancellationToken ct) + /// 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) { - if (!Guid.TryParse(slug, out Guid id)) + ReportSourceDetail? source = await _catalog.GetSourceAsync(report.Source, ct); + if (source is null) { - return null; + return ReportRunOutcome.Fail(ReportRunStatus.Unavailable, "This report's data source is no longer available."); } - return await _context.Reports - .AsNoTracking() - .Include(r => r.Permissions) - .Include(r => r.Columns) - .Include(r => r.Parameters) - .FirstOrDefaultAsync(r => r.Slug == id && r.DeletedOn == null, ct); - } + 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]); + } - /// Admins see every report; others need one of its permissions. A report with none is admin-only. - private bool CanView(ReportDefinition report) - { - return _users.HasPermission(ReportBuilderPermissions.Admin) - || report.Permissions.Any(p => !string.IsNullOrWhiteSpace(p.Permission) && _users.HasPermission(p.Permission)); + 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) @@ -190,17 +238,8 @@ private static ReportRunOutcome Plan( // columns are then taken on trust and a missing one shows as empty. bool checkColumns = known.Count > 0; - List columns = [.. report.Columns - .Where(c => c.Visible && !string.IsNullOrWhiteSpace(c.SourceColumn)) - .OrderBy(c => c.DisplayOrder) - .ThenBy(c => c.Id) - .Select(c => new ReportResultColumn - { - Name = known.TryGetValue(c.SourceColumn!, out ReportSourceColumn? match) ? match.Name : c.SourceColumn!, - Label = string.IsNullOrWhiteSpace(c.Label) ? c.SourceColumn! : c.Label, - Format = c.Format ?? ReportColumnFormat.Text, - Sortable = c.Sortable, - })]; + 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."); @@ -226,9 +265,9 @@ private static ReportRunOutcome Plan( } bool screen = mode == ReportRunMode.Screen; - bool paginate = screen && report.Paginate != false; - int perPage = Math.Clamp(report.PageSize ?? ReportLimits.DefaultPageSize, 1, ReportLimits.MaxPageSize); - if (paginate && request.PerPage is int asked) + bool paginate = screen && ReportAccess.Paginates(report); + int perPage = ReportAccess.PageSize(report); + if (paginate && request.PerPage is { } asked) { if (asked is < 1 or > ReportLimits.MaxPageSize) { @@ -472,15 +511,19 @@ private static bool Matches(IReadOnlyDictionary row, string sea } } + /// Logs a run: the rows it returned, or why it failed. private async Task LogRunAsync( ReportDefinition report, ReportCurrentUser user, ReportRunMode mode, - IReadOnlyList parameters, - ReportRunResult result, + 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, @@ -492,22 +535,65 @@ private async Task LogRunAsync( }, LoginId = user.LoginId, RanOn = _clock.GetLocalNow().DateTime, - Parameters = LoggedParameters(parameters), - RowsReturned = result.Rows.Count, + 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 (DbUpdateException ex) + catch (Exception ex) when (ex is DbUpdateException or DbException) { - // The user still gets their report; a missing log entry isn't worth failing the run. + // 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) { diff --git a/web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs b/web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs index 1846da15c..660d0c194 100644 --- a/web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs +++ b/web/Areas/ReportBuilder/Services/ReportSqlBuilder.cs @@ -71,7 +71,7 @@ public static ReportSqlCommand BuildView(ReportViewQuery query) ? "ORDER BY (SELECT NULL)" : $"ORDER BY {Quote(query.SortColumn)} {direction}"; - if (query.Skip is int skip && query.Take is int take) + if (query.Skip is { } skip && query.Take is { } take) { parameters[SkipParameter] = skip; parameters[TakeParameter] = take; @@ -108,7 +108,7 @@ public static ReportSqlCommand BuildProcedure( parameters[placeholder] = ScalarValue(arguments[i]); } - if (skip is int skipRows && take is int takeRows) + if (skip is { } skipRows && take is { } takeRows) { assignments.Add($"@{ReportSourceCatalogService.SkipParameter} = {SkipParameter}"); assignments.Add($"@{ReportSourceCatalogService.TakeParameter} = {TakeParameter}"); 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/Areas/Reports/Controllers/ReportsController.cs b/web/Areas/Reports/Controllers/ReportsController.cs deleted file mode 100644 index 1d4abf077..000000000 --- a/web/Areas/Reports/Controllers/ReportsController.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System.Text.Json; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Services; -using Viper.Classes; -using Web.Authorization; - -namespace Viper.Areas.Reports.Controllers; - -/// -/// Lists, describes, runs and exports code-defined reports. Signing in is enough to reach the controller; -/// each report's own permissions are checked by before any -/// parameters are read. -/// -[Route("/api/reports")] -[Permission(Allow = "SVMSecure")] -public class ReportsController : ApiController -{ - private readonly IReportService _reportService; - - public ReportsController(IReportService reportService) - { - _reportService = reportService; - } - - [HttpGet] - public ActionResult> GetCatalog([FromQuery] string? area = null) - { - return Ok(_reportService.GetCatalog(area)); - } - - [HttpGet("{key}")] - public ActionResult GetDefinition(string key) - { - return ToActionResult(_reportService.GetDefinition(key)); - } - - [HttpPost("{key}/run")] - public async Task> Run( - string key, - [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] JsonElement? parameters, - CancellationToken ct = default) - { - return ToActionResult(await _reportService.RunAsync(key, parameters, ct)); - } - - /// - /// Runs the report and returns it as a file download in (csv, xlsx or pdf). - /// - [HttpPost("{key}/export/{format}")] - public async Task Export( - string key, - string format, - [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] JsonElement? parameters, - CancellationToken ct = default) - { - ReportOutcome outcome = await _reportService.ExportAsync(key, format, parameters, ct); - if (outcome.Value is not { } file) - { - return ToActionResult(outcome); - } - - // Exports hold personnel 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); - } - - /// - /// Groups validation errors by parameter name; errors that span several parameters use an - /// empty key, the same convention ASP.NET uses for model-level errors. - /// - internal static ValidationProblemDetails ToProblemDetails(IReadOnlyList errors) - { - Dictionary byParameter = errors - .GroupBy(error => error.Parameter ?? string.Empty, StringComparer.Ordinal) - .ToDictionary(group => group.Key, group => group.Select(error => error.Message).ToArray(), StringComparer.Ordinal); - return new ValidationProblemDetails(byParameter) { Title = "The report parameters are not valid." }; - } - - private ActionResult ToActionResult(ReportOutcome outcome) - { - return outcome.Status switch - { - ReportOutcomeStatus.Ok => Ok(outcome.Value), - ReportOutcomeStatus.NotFound => NotFound("Report not found."), - ReportOutcomeStatus.Forbidden => ForbidApi("You do not have access to this report."), - _ => BadRequest(ToProblemDetails(outcome.Errors)), - }; - } -} diff --git a/web/Areas/Reports/Data/DataRecordExtensions.cs b/web/Areas/Reports/Data/DataRecordExtensions.cs deleted file mode 100644 index 68bd22cb5..000000000 --- a/web/Areas/Reports/Data/DataRecordExtensions.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Data; -using System.Globalization; - -namespace Viper.Areas.Reports.Data; - -/// -/// Null-safe reads of stored procedure columns by name. The legacy procedures return many -/// char columns padded with spaces, so text is trimmed on the way in. -/// -public static class DataRecordExtensions -{ - public static string? GetTrimmedString(this IDataRecord record, string column) - { - ArgumentNullException.ThrowIfNull(record); - int ordinal = record.GetOrdinal(column); - return record.IsDBNull(ordinal) - ? null - : Convert.ToString(record.GetValue(ordinal), CultureInfo.InvariantCulture)?.TrimEnd(); - } - - public static DateOnly? GetDateOnly(this IDataRecord record, string column) - { - ArgumentNullException.ThrowIfNull(record); - int ordinal = record.GetOrdinal(column); - return record.IsDBNull(ordinal) ? null : DateOnly.FromDateTime(record.GetDateTime(ordinal)); - } - - /// - /// A date the procedure returns as text, such as CONVERT(VARCHAR(10), d, 101) for - /// "MM/dd/yyyy". Blank or unreadable text is null. - /// - public static DateOnly? GetDateOnlyFromText(this IDataRecord record, string column, string format) - { - string? text = record.GetTrimmedString(column); - return DateOnly.TryParseExact(text, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly date) - ? date - : null; - } - - /// - /// A whole number from any numeric column type, such as the decimal FLOOR(...) returns. - /// - public static int? GetNullableInt32(this IDataRecord record, string column) - { - ArgumentNullException.ThrowIfNull(record); - int ordinal = record.GetOrdinal(column); - return record.IsDBNull(ordinal) ? null : Convert.ToInt32(record.GetValue(ordinal), CultureInfo.InvariantCulture); - } -} diff --git a/web/Areas/Reports/Data/DbConnectionFactory.cs b/web/Areas/Reports/Data/DbConnectionFactory.cs deleted file mode 100644 index 3cd92234d..000000000 --- a/web/Areas/Reports/Data/DbConnectionFactory.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Data.Common; -using System.Diagnostics.CodeAnalysis; -using Microsoft.Data.SqlClient; - -namespace Viper.Areas.Reports.Data; - -/// -/// Opens connections to databases that have no EF context, such as PPS and AcademicPersonnel, -/// by connection string name. Tests substitute a fake connection. -/// -public interface IDbConnectionFactory -{ - /// - /// A new, unopened connection. Throws when the - /// connection string isn't configured. - /// - DbConnection Create(string connectionStringName); -} - -/// -/// Creates SQL Server connections from ConnectionStrings, which AWS Systems Manager fills -/// in each environment. A missing string fails the report that needs it, not application startup. -/// -[ExcludeFromCodeCoverage(Justification = "Only creates a real SqlConnection; its callers are tested with a fake connection.")] -public sealed class SqlConnectionFactory : IDbConnectionFactory -{ - private readonly IConfiguration _configuration; - - public SqlConnectionFactory(IConfiguration configuration) - { - _configuration = configuration; - } - - public DbConnection Create(string connectionStringName) - { - string? connectionString = _configuration.GetConnectionString(connectionStringName); - if (string.IsNullOrWhiteSpace(connectionString)) - { - throw new InvalidOperationException($"Connection string '{connectionStringName}' is not configured."); - } - - return new SqlConnection(connectionString); - } -} diff --git a/web/Areas/Reports/Data/StoredProcedureParameter.cs b/web/Areas/Reports/Data/StoredProcedureParameter.cs deleted file mode 100644 index d1ca8a989..000000000 --- a/web/Areas/Reports/Data/StoredProcedureParameter.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Data; -using System.Data.Common; - -namespace Viper.Areas.Reports.Data; - -/// -/// A typed stored procedure input. Values always travel as parameters, never as SQL text. -/// -public sealed record StoredProcedureParameter -{ - private StoredProcedureParameter(string name, DbType type, object? value, int? size) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - Name = name.StartsWith('@') ? name : "@" + name; - Type = type; - Value = value; - Size = size; - } - - /// - /// The parameter name including its leading @. - /// - public string Name { get; } - - public DbType Type { get; } - - public object? Value { get; } - - public int? Size { get; } - - /// - /// A varchar input; is the procedure's declared length. - /// - public static StoredProcedureParameter Text(string name, string? value, int size) - { - return new StoredProcedureParameter(name, DbType.AnsiString, value, size); - } - - /// - /// A datetime input at midnight on . - /// - public static StoredProcedureParameter Date(string name, DateOnly? value) - { - return new StoredProcedureParameter(name, DbType.DateTime, value?.ToDateTime(TimeOnly.MinValue), null); - } - - internal DbParameter ToDbParameter(DbCommand command) - { - DbParameter parameter = command.CreateParameter(); - parameter.ParameterName = Name; - parameter.DbType = Type; - parameter.Value = Value ?? DBNull.Value; - if (Size is { } size) - { - parameter.Size = size; - } - - return parameter; - } -} diff --git a/web/Areas/Reports/Data/StoredProcedureRunner.cs b/web/Areas/Reports/Data/StoredProcedureRunner.cs deleted file mode 100644 index c5fd565eb..000000000 --- a/web/Areas/Reports/Data/StoredProcedureRunner.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Data; -using System.Data.Common; - -namespace Viper.Areas.Reports.Data; - -/// -/// Runs a stored procedure and maps each row of its result. -/// -public interface IStoredProcedureRunner -{ - Task> QueryAsync( - string connectionStringName, - string procedure, - IReadOnlyList parameters, - Func map, - CancellationToken ct); -} - -/// -/// Calls stored procedures on databases that have no EF context. Procedure names are constants -/// in the data services, and every value is a typed parameter, so no SQL is ever built from input. -/// -public sealed class StoredProcedureRunner : IStoredProcedureRunner -{ - /// - /// Some PPS report procedures scan the whole UCPath extract, so allow longer than the default 30 seconds. - /// - public const int CommandTimeoutSeconds = 120; - - private readonly IDbConnectionFactory _connections; - - public StoredProcedureRunner(IDbConnectionFactory connections) - { - _connections = connections; - } - - public async Task> QueryAsync( - string connectionStringName, - string procedure, - IReadOnlyList parameters, - Func map, - CancellationToken ct) - { - ArgumentException.ThrowIfNullOrWhiteSpace(procedure); - ArgumentNullException.ThrowIfNull(parameters); - ArgumentNullException.ThrowIfNull(map); - - await using DbConnection connection = _connections.Create(connectionStringName); - await connection.OpenAsync(ct); - await using DbCommand command = connection.CreateCommand(); - command.CommandType = CommandType.StoredProcedure; - command.CommandText = procedure; - command.CommandTimeout = CommandTimeoutSeconds; - command.Parameters.AddRange(parameters.Select(parameter => parameter.ToDbParameter(command)).ToArray()); - - await using DbDataReader reader = await command.ExecuteReaderAsync(ct); - var rows = new List(); - while (await reader.ReadAsync(ct)) - { - rows.Add(map(reader)); - } - - return rows; - } -} diff --git a/web/Areas/Reports/Engine/PlannedReport.cs b/web/Areas/Reports/Engine/PlannedReport.cs deleted file mode 100644 index a3cb2ea35..000000000 --- a/web/Areas/Reports/Engine/PlannedReport.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// What a catalog needs to list a report: its key, display text and the permissions that grant it. -/// -public interface IReportIdentity -{ - string Key { get; } - - string Title { get; } - - string Area { get; } - - string Description { get; } - - /// - /// The user needs any one of these permissions to run the report. - /// - IReadOnlyList Permissions { get; } -} - -/// -/// A report listed in its area's catalog before it is built, so the area's pages can link to it -/// ahead of time. A planned report can't be described, run or exported: the engine treats those -/// requests as it would an unknown key. When the report's definition is added, delete its planned -/// entry; the registry refuses a key used by both. -/// -public sealed record PlannedReport( - string Key, string Title, string Area, string Description, IReadOnlyList Permissions) : IReportIdentity; - -/// -/// Supplies an area's planned reports. -/// registers every implementation in the report assembly. -/// -public interface IPlannedReportSource -{ - IReadOnlyList PlannedReports { get; } -} diff --git a/web/Areas/Reports/Engine/ReportBuilder.Layout.cs b/web/Areas/Reports/Engine/ReportBuilder.Layout.cs deleted file mode 100644 index b63b214b3..000000000 --- a/web/Areas/Reports/Engine/ReportBuilder.Layout.cs +++ /dev/null @@ -1,209 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// Layout declarations: grouping, totals, summary facts, highlights, pivots and charts, plus the -/// measure factories they use. -/// -public sealed partial class ReportBuilder -{ - private readonly List> _totals = []; - private readonly List> _summaries = []; - private readonly List> _flags = []; - private readonly List> _pivots = []; - private readonly List> _charts = []; - - internal bool ShowRowNumbers { get; private set; } - - internal bool IsSensitive { get; private set; } - - internal ReportGrouping? Grouping { get; private set; } - - internal IReadOnlyList> Totals => _totals; - - internal IReadOnlyList> Summaries => _summaries; - - internal IReadOnlyList> Flags => _flags; - - internal IReadOnlyList> Pivots => _pivots; - - internal IReadOnlyList> Charts => _charts; - - #region Measures - - public ReportMeasure Count() - { - return new ReportMeasure(rows => rows.Count); - } - - /// - /// Counts distinct non-null keys, for example people when a person can have several rows. - /// - public ReportMeasure CountDistinct(Func key) - { - ArgumentNullException.ThrowIfNull(key); - return new ReportMeasure(rows => rows.Select(key).Where(value => value is not null).Distinct().Count()); - } - - public ReportMeasure Sum(Func value) - { - return Numeric(value, ReportMath.Sum); - } - - public ReportMeasure Average(Func value) - { - return Numeric(value, ReportMath.Average); - } - - public ReportMeasure Minimum(Func value) - { - return Numeric(value, ReportMath.Minimum); - } - - public ReportMeasure Maximum(Func value) - { - return Numeric(value, ReportMath.Maximum); - } - - public ReportMeasure StandardDeviation(Func value) - { - return Numeric(value, ReportMath.StandardDeviation); - } - - #endregion - - #region Layout - - public void RowNumbers() - { - ShowRowNumbers = true; - } - - /// - /// Marks the report as containing confidential personnel data (salary, demographics, visa - /// status, birth dates). Every export of it carries a confidentiality notice. - /// - public void Sensitive() - { - IsSensitive = true; - } - - /// - /// Splits the rows into groups by , ordered alphabetically. Blank keys - /// form one group labelled "(Not specified)". A report has at most one grouping. - /// - public ReportGroupBuilder GroupBy(Func key) - { - ArgumentNullException.ThrowIfNull(key); - if (Grouping is not null) - { - throw new InvalidOperationException("A report can be grouped only once."); - } - - Grouping = new ReportGrouping(key); - return new ReportGroupBuilder(Grouping); - } - - public void Total(string label, ReportMeasure measure, string? columnKey = null) - { - _totals.Add(ReportLayoutRules.CreateTotal(label, measure, columnKey)); - } - - /// - /// Adds a headline fact shown above the rows. Give when the fact - /// reveals that column's data, so it is hidden from users who cannot see the column. - /// - public void Summary(string label, ReportMeasure measure, string? columnKey = null) - { - _summaries.Add(ReportLayoutRules.CreateTotal(label, measure, columnKey)); - } - - /// - /// Emphasizes matching rows, or only the cell when one is given. - /// - public void Highlight(Func when, ReportTone tone, string label, string? columnKey = null) - { - AddFlag(when, ReportFlagKind.Highlight, tone, label, columnKey); - } - - /// - /// Shows as a badge beside the value of matching rows. - /// - public void Badge(Func when, ReportTone tone, string label, string columnKey) - { - ArgumentException.ThrowIfNullOrWhiteSpace(columnKey); - AddFlag(when, ReportFlagKind.Badge, tone, label, columnKey); - } - - public void Pivot(string title, Func rows, Func columns, ReportMeasure measure) - { - ArgumentNullException.ThrowIfNull(rows); - AddPivot(title, row => [rows(row)], columns, measure); - } - - /// - /// A pivot whose rows come from a multi-valued field. Each row is counted under every key it - /// returns, so totals count selections rather than rows; use to count rows. - /// - public void PivotEach( - string title, Func> rows, Func columns, ReportMeasure measure) - { - ArgumentNullException.ThrowIfNull(rows); - AddPivot(title, rows, columns, measure); - } - - public ReportChartBuilder Chart( - string title, ReportChartKind kind, Func category, ReportMeasure measure) - { - ArgumentException.ThrowIfNullOrWhiteSpace(title); - ArgumentNullException.ThrowIfNull(category); - ArgumentNullException.ThrowIfNull(measure); - var chart = new ReportChartRule(title, kind, category, measure); - _charts.Add(chart); - return new ReportChartBuilder(chart); - } - - #endregion - - private void EnsureValidLayout(string reportKey) - { - HashSet columnKeys = new(_columns.Select(column => column.Key), StringComparer.Ordinal); - string? unknown = _totals - .Concat(_summaries) - .Concat(Grouping?.Subtotals ?? []) - .Select(total => total.ColumnKey) - .Concat(_flags.Select(flag => flag.ColumnKey)) - .FirstOrDefault(key => key is not null && !columnKeys.Contains(key)); - if (unknown is not null) - { - throw new InvalidOperationException($"Report '{reportKey}' refers to the unknown column '{unknown}'."); - } - - if (Grouping is null && _charts.Any(chart => chart.PerGroup)) - { - throw new InvalidOperationException($"Report '{reportKey}' has a per-group chart but no grouping."); - } - } - - private static ReportMeasure Numeric( - Func value, Func, decimal?> aggregate) - { - ArgumentNullException.ThrowIfNull(value); - return new ReportMeasure(rows => aggregate([.. rows.Select(value).OfType()])); - } - - private void AddFlag(Func when, ReportFlagKind kind, ReportTone tone, string label, string? columnKey) - { - ArgumentNullException.ThrowIfNull(when); - ArgumentException.ThrowIfNullOrWhiteSpace(label); - _flags.Add(new ReportFlagRule(when, kind, tone, label, columnKey)); - } - - private void AddPivot( - string title, Func> rows, Func columns, ReportMeasure measure) - { - ArgumentException.ThrowIfNullOrWhiteSpace(title); - ArgumentNullException.ThrowIfNull(columns); - ArgumentNullException.ThrowIfNull(measure); - _pivots.Add(new ReportPivotRule(title, rows, columns, measure)); - } -} diff --git a/web/Areas/Reports/Engine/ReportBuilder.cs b/web/Areas/Reports/Engine/ReportBuilder.cs deleted file mode 100644 index 0cdcf959b..000000000 --- a/web/Areas/Reports/Engine/ReportBuilder.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Linq.Expressions; - -namespace Viper.Areas.Reports.Engine; - -/// -/// Collects the parameters, validation rules and columns a report declares in -/// . -/// -public sealed partial class ReportBuilder where TParams : class -{ - private readonly List> _parameters = []; - private readonly List> _rules = []; - private readonly List> _columns = []; - - internal IReadOnlyList> Parameters => _parameters; - - internal IReadOnlyList> Rules => _rules; - - internal IReadOnlyList> Columns => _columns; - - public ReportParameterBuilder Choice( - Expression> property, string label, IReadOnlyList options) - { - ReportParameter parameter = AddParameter(property, label, ReportParameterType.Choice); - parameter.SetOptions(RequireOptions(options), value => [(string)value]); - return new ReportParameterBuilder(parameter); - } - - public ReportParameterBuilder?> MultiChoice( - Expression?>> property, string label, IReadOnlyList options) - { - ReportParameter parameter = AddParameter(property, label, ReportParameterType.MultiChoice); - parameter.SetOptions(RequireOptions(options), value => (IEnumerable)value); - return new ReportParameterBuilder?>(parameter); - } - - public ReportParameterBuilder Date(Expression> property, string label) - { - return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Date)); - } - - public ReportParameterBuilder Text(Expression> property, string label) - { - return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Text)); - } - - public ReportParameterBuilder Number(Expression> property, string label) - { - return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Number)); - } - - public ReportParameterBuilder Boolean(Expression> property, string label) - { - return new ReportParameterBuilder(AddParameter(property, label, ReportParameterType.Boolean)); - } - - /// - /// Adds a rule that spans several parameters. Rules run only after every individual - /// parameter is valid, so can rely on required values being set. - /// - public void Validate(Func isValid, string message, string? parameter = null) - { - ArgumentNullException.ThrowIfNull(isValid); - ArgumentException.ThrowIfNullOrWhiteSpace(message); - _rules.Add(new ReportParameterRule(isValid, message, parameter)); - } - - /// - /// Adds a column. The key defaults to the camelCase name of the selected property; a - /// computed selector such as r => r.First + " " + r.Last needs an explicit key. - /// - public ReportColumnBuilder Column( - Expression> selector, string label, string? key = null) - { - ArgumentNullException.ThrowIfNull(selector); - ArgumentException.ThrowIfNullOrWhiteSpace(label); - if (key is not null) - { - ArgumentException.ThrowIfNullOrWhiteSpace(key); - } - - string columnKey = key - ?? ReportExpressions.GetPropertyKey(selector) - ?? throw new ArgumentException("A computed column needs an explicit key.", nameof(key)); - Func getValue = selector.Compile(); - var column = new ReportColumn(columnKey, label, row => getValue(row)); - _columns.Add(column); - return new ReportColumnBuilder(column); - } - - internal void EnsureValid(string reportKey) - { - if (_columns.Count == 0) - { - throw new InvalidOperationException($"Report '{reportKey}' must define at least one column."); - } - - ThrowOnDuplicate(_columns.Select(column => column.Key), "column", reportKey); - ThrowOnDuplicate(_parameters.Select(parameter => parameter.Name), "parameter", reportKey); - EnsureValidLayout(reportKey); - } - - private ReportParameter AddParameter( - Expression> property, string label, ReportParameterType type) - { - ArgumentException.ThrowIfNullOrWhiteSpace(label); - var parameter = new ReportParameter(ReportExpressions.GetSettableProperty(property), label, type); - _parameters.Add(parameter); - return parameter; - } - - private static IReadOnlyList RequireOptions(IReadOnlyList options) - { - ArgumentNullException.ThrowIfNull(options); - return options.Count > 0 - ? options - : throw new ArgumentException("A choice parameter needs at least one option.", nameof(options)); - } - - private static void ThrowOnDuplicate(IEnumerable names, string kind, string reportKey) - { - IGrouping? duplicate = names - .GroupBy(name => name, StringComparer.OrdinalIgnoreCase) - .FirstOrDefault(group => group.Count() > 1); - if (duplicate is not null) - { - throw new InvalidOperationException( - $"Report '{reportKey}' declares the {kind} '{duplicate.Key}' more than once."); - } - } -} diff --git a/web/Areas/Reports/Engine/ReportColumn.cs b/web/Areas/Reports/Engine/ReportColumn.cs deleted file mode 100644 index b1f720f4e..000000000 --- a/web/Areas/Reports/Engine/ReportColumn.cs +++ /dev/null @@ -1,106 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// One column of a report, with the function that reads its value from a row. -/// -internal sealed class ReportColumn -{ - public ReportColumn(string key, string label, Func value) - { - Key = key; - Label = label; - Value = value; - } - - public string Key { get; } - - public string Label { get; } - - public Func Value { get; } - - // Defaults are the enums' first members: Text, aligned left. - public ReportColumnFormat Format { get; set; } - - public ReportAlignment Align { get; set; } - - public int? Decimals { get; set; } - - public Func? VisibleWhen { get; set; } - - public bool IsVisible(ReportContext context) - { - return VisibleWhen?.Invoke(context) ?? true; - } - - public ReportColumnMetadata ToMetadata() - { - return new ReportColumnMetadata(Key, Label, Format, Align, Decimals); - } -} - -/// -/// Fluent options for a column declared on a . -/// -public sealed class ReportColumnBuilder -{ - private const int CurrencyDecimals = 2; - - private readonly ReportColumn _column; - - internal ReportColumnBuilder(ReportColumn column) - { - _column = column; - } - - public ReportColumnBuilder AsNumber(int decimals = 0) - { - ArgumentOutOfRangeException.ThrowIfNegative(decimals); - return SetFormat(ReportColumnFormat.Number, ReportAlignment.Right, decimals); - } - - public ReportColumnBuilder AsCurrency() - { - return SetFormat(ReportColumnFormat.Currency, ReportAlignment.Right, CurrencyDecimals); - } - - public ReportColumnBuilder AsPercent(int decimals = 0) - { - ArgumentOutOfRangeException.ThrowIfNegative(decimals); - return SetFormat(ReportColumnFormat.Percent, ReportAlignment.Right, decimals); - } - - public ReportColumnBuilder AsDate() - { - return SetFormat(ReportColumnFormat.Date, ReportAlignment.Center, null); - } - - public ReportColumnBuilder AsList() - { - return SetFormat(ReportColumnFormat.List, ReportAlignment.Left, null); - } - - public ReportColumnBuilder Align(ReportAlignment align) - { - _column.Align = align; - return this; - } - - /// - /// Shows the column only to users the predicate accepts, for example columns of - /// identifiers that only some roles may see. - /// - public ReportColumnBuilder VisibleWhen(Func predicate) - { - ArgumentNullException.ThrowIfNull(predicate); - _column.VisibleWhen = predicate; - return this; - } - - private ReportColumnBuilder SetFormat(ReportColumnFormat format, ReportAlignment align, int? decimals) - { - _column.Format = format; - _column.Align = align; - _column.Decimals = decimals; - return this; - } -} diff --git a/web/Areas/Reports/Engine/ReportContext.cs b/web/Areas/Reports/Engine/ReportContext.cs deleted file mode 100644 index bc8c6bdfa..000000000 --- a/web/Areas/Reports/Engine/ReportContext.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// The user a report runs for. Permission checks go through a delegate so the engine never -/// depends on RAPS directly, and tests can supply any permission set. -/// -public sealed class ReportContext -{ - private readonly Func _hasPermission; - - public ReportContext(string? loginId, Func hasPermission) - { - ArgumentNullException.ThrowIfNull(hasPermission); - LoginId = loginId; - _hasPermission = hasPermission; - } - - public string? LoginId { get; } - - public bool HasPermission(string permission) - { - return !string.IsNullOrWhiteSpace(permission) && _hasPermission(permission); - } - - public bool HasAnyPermission(IEnumerable permissions) - { - ArgumentNullException.ThrowIfNull(permissions); - return permissions.Any(HasPermission); - } -} diff --git a/web/Areas/Reports/Engine/ReportDefinition.cs b/web/Areas/Reports/Engine/ReportDefinition.cs deleted file mode 100644 index 8319472ad..000000000 --- a/web/Areas/Reports/Engine/ReportDefinition.cs +++ /dev/null @@ -1,155 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// A report the engine can list, describe and run, independent of its row and parameter types. -/// -public interface IReportDefinition : IReportIdentity -{ - /// - /// True for reports with confidential personnel data; exports carry a confidentiality notice. - /// - bool IsSensitive { get; } - - /// - /// The class the report's parameters are bound to from the request body. - /// - Type ParametersType { get; } - - bool CanRun(ReportContext context); - - ReportDefinitionMetadata GetMetadata(ReportContext context); - - /// - /// Fills empty parameters with their defaults, then validates them. Returns an empty list - /// when the parameters are ready to run. - /// - IReadOnlyList PrepareParameters(object parameters); - - /// - /// The non-empty parameters as labelled, human-readable filters for export headers. - /// - IReadOnlyList DescribeParameters(object parameters); - - /// - /// Fetches the report's rows for prepared parameters and shapes them into a result. - /// - Task RunAsync(object parameters, ReportContext context, DateTimeOffset generatedAt, CancellationToken ct); -} - -/// -/// Base class for a code-defined report. is one row of the report's -/// data, holds the user's parameter values. -/// -public abstract class ReportDefinition : IReportDefinition where TParams : class -{ - private ReportBuilder? _layout; - - public abstract string Key { get; } - - public abstract string Title { get; } - - public abstract string Area { get; } - - public abstract string Description { get; } - - public abstract IReadOnlyList Permissions { get; } - - public Type ParametersType => typeof(TParams); - - public bool IsSensitive => Layout.IsSensitive; - - /// - /// The configured parameters, rules and columns. Built on first use so a report that is - /// only listed in the catalog never pays for compiling its column selectors. - /// - internal ReportBuilder Layout => _layout ??= BuildLayout(); - - public bool CanRun(ReportContext context) - { - ArgumentNullException.ThrowIfNull(context); - return context.HasAnyPermission(Permissions); - } - - public ReportDefinitionMetadata GetMetadata(ReportContext context) - { - ArgumentNullException.ThrowIfNull(context); - ReportBuilder layout = Layout; - return new ReportDefinitionMetadata( - Key, - Title, - Area, - Description, - [.. layout.Parameters.Select(parameter => parameter.ToMetadata())], - [.. layout.Columns.Where(column => column.IsVisible(context)).Select(column => column.ToMetadata())]); - } - - public IReadOnlyList PrepareParameters(object parameters) - { - TParams typed = AsParameters(parameters); - ReportBuilder layout = Layout; - foreach (ReportParameter parameter in layout.Parameters) - { - parameter.ApplyDefault(typed); - } - - List errors = - [.. layout.Parameters.Select(parameter => parameter.Validate(typed)).OfType()]; - if (errors.Count > 0) - { - return errors; - } - - return [.. layout.Rules - .Where(rule => !rule.IsValid(typed)) - .Select(rule => new ReportValidationError(rule.Parameter, rule.Message))]; - } - - public IReadOnlyList DescribeParameters(object parameters) - { - TParams typed = AsParameters(parameters); - return [.. Layout.Parameters.Select(parameter => parameter.Describe(typed)).OfType()]; - } - - public async Task RunAsync( - object parameters, ReportContext context, DateTimeOffset generatedAt, CancellationToken ct) - { - TParams typed = AsParameters(parameters); - ArgumentNullException.ThrowIfNull(context); - IReadOnlyList rows = await FetchAsync(typed, context, ct); - return CreateResult(rows, context, generatedAt); - } - - /// - /// Shapes fetched rows into the result the client and exporters render. - /// - internal ReportResult CreateResult(IReadOnlyList rows, ReportContext context, DateTimeOffset generatedAt) - { - return ReportPipeline.Build(Key, Title, Layout, rows, context, generatedAt); - } - - /// - /// Declares the report's parameters, cross-parameter rules, columns and layout. - /// - protected abstract void Configure(ReportBuilder report); - - /// - /// Loads the report's rows. Parameters have already been defaulted and validated. - /// identifies the user, for reports scoped to the user's own units. - /// - protected abstract Task> FetchAsync(TParams parameters, ReportContext context, CancellationToken ct); - - private TParams AsParameters(object parameters) - { - return parameters as TParams - ?? throw new ArgumentException( - $"Report '{Key}' expects parameters of type {typeof(TParams).Name}.", nameof(parameters)); - } - - private ReportBuilder BuildLayout() - { - var builder = new ReportBuilder(); - Configure(builder); - builder.EnsureValid(Key); - return builder; - } -} diff --git a/web/Areas/Reports/Engine/ReportExpressions.cs b/web/Areas/Reports/Engine/ReportExpressions.cs deleted file mode 100644 index 31d590099..000000000 --- a/web/Areas/Reports/Engine/ReportExpressions.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Linq.Expressions; -using System.Reflection; -using System.Text.Json; - -namespace Viper.Areas.Reports.Engine; - -/// -/// Turns selector lambdas such as p => p.StartDate into the property they name, so report -/// parameters and columns are declared with compile-checked member access instead of strings. -/// -internal static class ReportExpressions -{ - public static PropertyInfo GetSettableProperty(Expression> expression) - { - ArgumentNullException.ThrowIfNull(expression); - return FindProperty(expression) is { SetMethod.IsPublic: true } property - ? property - : throw new ArgumentException( - "The expression must select a public settable property, for example p => p.StartDate.", - nameof(expression)); - } - - public static string? GetPropertyKey(Expression> expression) - { - ArgumentNullException.ThrowIfNull(expression); - return FindProperty(expression) is { } property ? ToKey(property.Name) : null; - } - - /// - /// Keys use the same camelCase naming as the JSON the client sends and receives. - /// - public static string ToKey(string name) - { - return JsonNamingPolicy.CamelCase.ConvertName(name); - } - - private static PropertyInfo? FindProperty(LambdaExpression expression) - { - return expression.Body is MemberExpression { Member: PropertyInfo property, Expression: ParameterExpression } - ? property - : null; - } -} diff --git a/web/Areas/Reports/Engine/ReportFilter.cs b/web/Areas/Reports/Engine/ReportFilter.cs deleted file mode 100644 index db9429fd5..000000000 --- a/web/Areas/Reports/Engine/ReportFilter.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// One parameter as the user chose it, for example "Faculty type: Senate", shown in export headers -/// so a downloaded file records how it was produced. -/// -public sealed record ReportFilter(string Label, string Value); diff --git a/web/Areas/Reports/Engine/ReportKey.cs b/web/Areas/Reports/Engine/ReportKey.cs deleted file mode 100644 index 3b7202587..000000000 --- a/web/Areas/Reports/Engine/ReportKey.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// Report keys look like personnel.employees-on-leave: a lowercase area segment, one dot, -/// then a kebab-case name. Keys appear in URLs and export filenames, so the character set is -/// deliberately narrow. -/// -public static class ReportKey -{ - public static bool IsValid(string? key) - { - if (string.IsNullOrEmpty(key)) - { - return false; - } - - int dot = key.IndexOf('.', StringComparison.Ordinal); - return dot > 0 - && dot < key.Length - 1 - && !key.AsSpan(dot + 1).Contains('.') - && IsSegment(key.AsSpan(0, dot)) - && IsSegment(key.AsSpan(dot + 1)); - } - - private static bool IsSegment(ReadOnlySpan segment) - { - if (segment[0] == '-' || segment[^1] == '-') - { - return false; - } - - foreach (char c in segment) - { - if (!char.IsAsciiLetterLower(c) && !char.IsAsciiDigit(c) && c != '-') - { - return false; - } - } - - return true; - } -} diff --git a/web/Areas/Reports/Engine/ReportLayoutRules.cs b/web/Areas/Reports/Engine/ReportLayoutRules.cs deleted file mode 100644 index 66a1fe483..000000000 --- a/web/Areas/Reports/Engine/ReportLayoutRules.cs +++ /dev/null @@ -1,140 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// A labelled measure: a grand total, a group subtotal or a summary fact. -/// -internal sealed record ReportTotalRule(string Label, ReportMeasure Measure, string? ColumnKey); - -internal sealed record ReportFlagRule( - Func When, ReportFlagKind Kind, ReportTone Tone, string Label, string? ColumnKey); - -/// -/// A cross-tabulation. may return several keys for one row (for example -/// every ethnicity a person selected), in which case the row counts once under each key. -/// -internal sealed record ReportPivotRule( - string Title, - Func> RowKeys, - Func ColumnKey, - ReportMeasure Measure); - -internal sealed class ReportChartRule -{ - public ReportChartRule(string title, ReportChartKind kind, Func category, ReportMeasure measure) - { - Title = title; - Kind = kind; - Category = category; - Measure = measure; - } - - public string Title { get; } - - public ReportChartKind Kind { get; } - - public Func Category { get; } - - public ReportMeasure Measure { get; } - - public bool PerGroup { get; set; } - - public int MinimumRows { get; set; } - - public IReadOnlyList CategoryOrder { get; set; } = []; - - /// - /// Which rows the chart counts; by default all of them. - /// - public Func Includes { get; set; } = _ => true; -} - -internal sealed class ReportGrouping -{ - public ReportGrouping(Func key) - { - Key = key; - } - - public Func Key { get; } - - public List> Subtotals { get; } = []; -} - -/// -/// Fluent options for the grouping declared with . -/// -public sealed class ReportGroupBuilder -{ - private readonly ReportGrouping _grouping; - - internal ReportGroupBuilder(ReportGrouping grouping) - { - _grouping = grouping; - } - - /// - /// Adds a per-group total, placed under when one is given. - /// - public ReportGroupBuilder Subtotal(string label, ReportMeasure measure, string? columnKey = null) - { - _grouping.Subtotals.Add(ReportLayoutRules.CreateTotal(label, measure, columnKey)); - return this; - } -} - -/// -/// Fluent options for a chart declared with . -/// -public sealed class ReportChartBuilder -{ - private readonly ReportChartRule _chart; - - internal ReportChartBuilder(ReportChartRule chart) - { - _chart = chart; - } - - /// - /// Draws the chart once per group instead of once for the whole report, skipping groups - /// with fewer than rows. Requires a grouping. - /// - public ReportChartBuilder PerGroup(int minimumRows = 1) - { - ArgumentOutOfRangeException.ThrowIfNegative(minimumRows); - _chart.PerGroup = true; - _chart.MinimumRows = minimumRows; - return this; - } - - /// - /// Lists categories in this order (for example age brackets). Categories not in the list - /// follow alphabetically. - /// - public ReportChartBuilder CategoryOrder(params string[] categories) - { - ArgumentNullException.ThrowIfNull(categories); - _chart.CategoryOrder = categories; - return this; - } - - /// - /// Charts only the rows that match, for example leaving out retired faculty while the table - /// still lists them. A per-group chart's minimum counts matching rows. - /// - public ReportChartBuilder Where(Func includes) - { - ArgumentNullException.ThrowIfNull(includes); - _chart.Includes = includes; - return this; - } -} - -internal static class ReportLayoutRules -{ - public static ReportTotalRule CreateTotal(string label, ReportMeasure measure, string? columnKey) - { - ArgumentException.ThrowIfNullOrWhiteSpace(label); - ArgumentNullException.ThrowIfNull(measure); - return new ReportTotalRule(label, measure, columnKey); - } -} diff --git a/web/Areas/Reports/Engine/ReportMeasure.cs b/web/Areas/Reports/Engine/ReportMeasure.cs deleted file mode 100644 index 27e23b22f..000000000 --- a/web/Areas/Reports/Engine/ReportMeasure.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// A number computed from a set of rows, such as a count, sum or average. Totals, subtotals, -/// summaries, pivots and charts all use measures, so every aggregate in a report is computed -/// the same way. Create measures with the factory methods on . -/// -public sealed class ReportMeasure -{ - private readonly Func, decimal?> _compute; - - internal ReportMeasure(Func, decimal?> compute) - { - _compute = compute; - } - - internal decimal? Compute(IReadOnlyCollection rows) - { - return _compute(rows); - } -} - -/// -/// Aggregate functions over the non-null values of a measure. Empty input gives null for -/// everything except the sum, which is zero, so an empty group shows "0" rather than a blank total. -/// -internal static class ReportMath -{ - public static decimal? Sum(IReadOnlyCollection values) - { - return values.Sum(); - } - - public static decimal? Average(IReadOnlyCollection values) - { - return values.Count == 0 ? null : values.Average(); - } - - public static decimal? Minimum(IReadOnlyCollection values) - { - return values.Count == 0 ? null : values.Min(); - } - - public static decimal? Maximum(IReadOnlyCollection values) - { - return values.Count == 0 ? null : values.Max(); - } - - /// - /// Sample standard deviation (divides by n - 1), matching SQL Server's STDEV, which the - /// legacy salary reports used. Needs at least two values. - /// - public static decimal? StandardDeviation(IReadOnlyCollection values) - { - if (values.Count < 2) - { - return null; - } - - decimal mean = values.Average(); - decimal sumOfSquares = values.Sum(value => (value - mean) * (value - mean)); - return (decimal)Math.Sqrt((double)(sumOfSquares / (values.Count - 1))); - } -} diff --git a/web/Areas/Reports/Engine/ReportMetadata.cs b/web/Areas/Reports/Engine/ReportMetadata.cs deleted file mode 100644 index d7356921c..000000000 --- a/web/Areas/Reports/Engine/ReportMetadata.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Viper.Areas.Reports.Engine; - -/// -/// The kind of input a report parameter renders as on the client. -/// -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum ReportParameterType -{ - Choice, - MultiChoice, - Date, - Text, - Number, - Boolean, -} - -/// -/// How a report column's values are formatted on screen and in exports. -/// -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum ReportColumnFormat -{ - Text, - Number, - Currency, - Percent, - Date, - List, -} - -/// -/// Horizontal alignment of a report column. -/// -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum ReportAlignment -{ - Left, - Center, - Right, -} - -/// -/// One selectable value of a choice parameter. -/// -public sealed record ReportOption(string Value, string Label); - -/// -/// Client-facing description of a report parameter. -/// -public sealed record ReportParameterMetadata( - string Name, - string Label, - ReportParameterType Type, - bool Required, - object? DefaultValue, - IReadOnlyList Options); - -/// -/// Client-facing description of a report column. -/// -public sealed record ReportColumnMetadata( - string Key, - string Label, - ReportColumnFormat Format, - ReportAlignment Align, - int? Decimals); - -/// -/// Client-facing description of a report: what it is, what it asks for, and what it shows. -/// -public sealed record ReportDefinitionMetadata( - string Key, - string Title, - string Area, - string Description, - IReadOnlyList Parameters, - IReadOnlyList Columns); - -/// -/// A problem with the parameters supplied for a report run. is null -/// when the problem involves several parameters rather than one field. -/// -public sealed record ReportValidationError(string? Parameter, string Message); diff --git a/web/Areas/Reports/Engine/ReportParameter.cs b/web/Areas/Reports/Engine/ReportParameter.cs deleted file mode 100644 index 2278e04e5..000000000 --- a/web/Areas/Reports/Engine/ReportParameter.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Reflection; - -namespace Viper.Areas.Reports.Engine; - -/// -/// One input on a report's parameter form, bound to a property of the report's parameter type. -/// -internal sealed class ReportParameter where TParams : class -{ - private readonly PropertyInfo _property; - private ChoiceRule? _choices; - - public ReportParameter(PropertyInfo property, string label, ReportParameterType type) - { - _property = property; - Name = ReportExpressions.ToKey(property.Name); - Label = label; - Type = type; - } - - public string Name { get; } - - public string Label { get; } - - public ReportParameterType Type { get; } - - public bool Required { get; set; } - - public Func? DefaultFactory { get; set; } - - public IReadOnlyList Options { get; private set; } = []; - - /// - /// Restricts the parameter to . - /// turns the bound value into the option values it selects, so single and multiple choice - /// share one validation path. - /// - public void SetOptions(IReadOnlyList options, Func> selectedValues) - { - Options = options; - _choices = new ChoiceRule( - options - .DistinctBy(option => option.Value, StringComparer.Ordinal) - .ToDictionary(option => option.Value, option => option.Label, StringComparer.Ordinal), - selectedValues); - } - - public ReportParameterMetadata ToMetadata() - { - return new ReportParameterMetadata(Name, Label, Type, Required, DefaultFactory?.Invoke(), Options); - } - - public void ApplyDefault(TParams parameters) - { - if (DefaultFactory is not null && !HasValue(_property.GetValue(parameters))) - { - _property.SetValue(parameters, DefaultFactory()); - } - } - - public ReportValidationError? Validate(TParams parameters) - { - object? value = _property.GetValue(parameters); - if (!HasValue(value)) - { - return Required ? new ReportValidationError(Name, $"{Label} is required.") : null; - } - - if (_choices is not null && _choices.SelectedValues(value).Any(selected => !_choices.Labels.ContainsKey(selected))) - { - return new ReportValidationError(Name, $"{Label} contains a value that is not an allowed option."); - } - - return null; - } - - /// - /// The parameter as a human-readable filter for report headers, or null when it is empty. - /// Choice values show their option labels rather than their codes. - /// - public ReportFilter? Describe(TParams parameters) - { - object? value = _property.GetValue(parameters); - return HasValue(value) ? new ReportFilter(Label, DescribeValue(value)) : null; - } - - private string DescribeValue(object value) - { - if (_choices is not null) - { - return string.Join(", ", _choices.SelectedValues(value).Select(selected => _choices.Labels.GetValueOrDefault(selected, selected))); - } - - return value switch - { - DateOnly date => date.ToString(ReportValueFormatter.DateFormat, CultureInfo.InvariantCulture), - bool flag => flag ? "Yes" : "No", - _ => string.Format(CultureInfo.InvariantCulture, "{0}", value), - }; - } - - private static bool HasValue([NotNullWhen(true)] object? value) - { - return value switch - { - null => false, - string text => !string.IsNullOrWhiteSpace(text), - IReadOnlyCollection values => values.Count > 0, - _ => true, - }; - } - - private sealed record ChoiceRule(Dictionary Labels, Func> SelectedValues); -} - -/// -/// A validation rule that spans several parameters, such as "end date on or after start date". -/// -internal sealed record ReportParameterRule(Func IsValid, string Message, string? Parameter); - -/// -/// Fluent options for a parameter declared on a . -/// -public sealed class ReportParameterBuilder where TParams : class -{ - private readonly ReportParameter _parameter; - - internal ReportParameterBuilder(ReportParameter parameter) - { - _parameter = parameter; - } - - public ReportParameterBuilder Required() - { - _parameter.Required = true; - return this; - } - - /// - /// Supplies the value used when the caller leaves the parameter empty. The factory runs on - /// every request, so date defaults such as "start of the current fiscal year" stay current. - /// - public ReportParameterBuilder Default(Func factory) - { - ArgumentNullException.ThrowIfNull(factory); - _parameter.DefaultFactory = () => factory(); - return this; - } -} diff --git a/web/Areas/Reports/Engine/ReportParameterBinder.cs b/web/Areas/Reports/Engine/ReportParameterBinder.cs deleted file mode 100644 index f1c037da1..000000000 --- a/web/Areas/Reports/Engine/ReportParameterBinder.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Viper.Areas.Reports.Engine; - -/// -/// Binds a request's JSON body to a report's parameter class. Unknown properties are rejected -/// rather than ignored, so a misspelled parameter can't silently fall back to its default. -/// -internal static class ReportParameterBinder -{ - public const string NotAnObjectMessage = "Report parameters must be a JSON object."; - public const string UnreadableMessage = "A report parameter is not recognized or has a value of the wrong type."; - - public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) - { - UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, - }; - - private static readonly JsonElement EmptyObject = ParseEmptyObject(); - - public static bool TryBind( - Type parametersType, - JsonElement? json, - [NotNullWhen(true)] out object? parameters, - [NotNullWhen(false)] out ReportValidationError? error) - { - ArgumentNullException.ThrowIfNull(parametersType); - parameters = null; - error = null; - - JsonElement source = json ?? EmptyObject; - if (source.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) - { - source = EmptyObject; - } - - if (source.ValueKind != JsonValueKind.Object) - { - error = new ReportValidationError(null, NotAnObjectMessage); - return false; - } - - try - { - parameters = source.Deserialize(parametersType, JsonOptions) - ?? throw new JsonException("Report parameters deserialized to null."); - return true; - } - catch (JsonException ex) - { - error = new ReportValidationError(ParameterName(ex.Path), UnreadableMessage); - return false; - } - } - - private static JsonElement ParseEmptyObject() - { - using JsonDocument document = JsonDocument.Parse("{}"); - return document.RootElement.Clone(); - } - - /// - /// Turns a JSON path such as $.departments[1] into the parameter name departments. - /// - public static string? ParameterName(string? path) - { - if (path is null || !path.StartsWith("$.", StringComparison.Ordinal)) - { - return null; - } - - string name = path[2..].Split('[', '.')[0]; - return name.Length > 0 ? name : null; - } -} diff --git a/web/Areas/Reports/Engine/ReportPipeline.cs b/web/Areas/Reports/Engine/ReportPipeline.cs deleted file mode 100644 index a576acbdb..000000000 --- a/web/Areas/Reports/Engine/ReportPipeline.cs +++ /dev/null @@ -1,157 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// Turns a report's rows and layout into a . Pure: no I/O, no clock and -/// no user lookups, so every rule here is unit-testable with plain in-memory rows. -/// -internal static class ReportPipeline -{ - public const string BlankKeyLabel = "(Not specified)"; - - public static ReportResult Build( - string key, - string title, - ReportBuilder layout, - IReadOnlyList rows, - ReportContext context, - DateTimeOffset generatedAt) - where TParams : class - { - ArgumentNullException.ThrowIfNull(rows); - ArgumentNullException.ThrowIfNull(context); - - List> columns = [.. layout.Columns.Where(column => column.IsVisible(context))]; - HashSet visibleKeys = new(columns.Select(column => column.Key), StringComparer.Ordinal); - bool IsVisible(string? columnKey) => columnKey is null || visibleKeys.Contains(columnKey); - - return new ReportResult( - key, - title, - generatedAt, - rows.Count, - layout.ShowRowNumbers, - [.. columns.Select(column => column.ToMetadata())], - ComputeTotals(layout.Summaries, rows, IsVisible), - BuildGroups(layout, rows, columns, IsVisible), - ComputeTotals(layout.Totals, rows, IsVisible), - [.. layout.Pivots.Select(pivot => BuildPivot(pivot, rows))], - [.. layout.Charts.Where(chart => !chart.PerGroup).Select(chart => BuildChart(chart, rows))]); - } - - /// - /// Trims a grouping key and gives blank keys a visible label, so blank and whitespace-only - /// values (common in the PPS data) land in one group. - /// - public static string NormalizeKey(string? key) - { - return string.IsNullOrWhiteSpace(key) ? BlankKeyLabel : key.Trim(); - } - - /// - /// Orders categories: those named in first, in that order, then - /// the rest alphabetically. Preferred categories with no data are left out. - /// - public static IReadOnlyList OrderCategories(IEnumerable categories, IReadOnlyList preferred) - { - HashSet present = new(categories, StringComparer.Ordinal); - return [.. preferred - .Where(present.Contains) - .Concat(present.Except(preferred, StringComparer.Ordinal).Order(StringComparer.OrdinalIgnoreCase))]; - } - - private static List BuildGroups( - ReportBuilder layout, - IReadOnlyList rows, - List> columns, - Func isVisible) - where TParams : class - { - if (layout.Grouping is not { } grouping) - { - return [new ReportGroupResult(null, BuildRows(layout, rows, columns, isVisible), [], [])]; - } - - return [.. rows - .GroupBy(row => NormalizeKey(grouping.Key(row)), StringComparer.Ordinal) - .OrderBy(group => group.Key, StringComparer.OrdinalIgnoreCase) - .Select(group => BuildGroup(layout, grouping, group.Key, [.. group], columns, isVisible))]; - } - - private static ReportGroupResult BuildGroup( - ReportBuilder layout, - ReportGrouping grouping, - string label, - List rows, - List> columns, - Func isVisible) - where TParams : class - { - return new ReportGroupResult( - label, - BuildRows(layout, rows, columns, isVisible), - ComputeTotals(grouping.Subtotals, rows, isVisible), - [.. layout.Charts - .Where(chart => chart.PerGroup && rows.Count(chart.Includes) >= chart.MinimumRows) - .Select(chart => BuildChart(chart, rows))]); - } - - private static List BuildRows( - ReportBuilder layout, - IReadOnlyList rows, - List> columns, - Func isVisible) - where TParams : class - { - List> flags = [.. layout.Flags.Where(flag => isVisible(flag.ColumnKey))]; - return [.. rows.Select((row, index) => new ReportRowResult( - index + 1, - columns.ToDictionary(column => column.Key, column => column.Value(row), StringComparer.Ordinal), - [.. flags - .Where(flag => flag.When(row)) - .Select(flag => new ReportFlag(flag.Kind, flag.Tone, flag.Label, flag.ColumnKey))]))]; - } - - private static List ComputeTotals( - IEnumerable> totals, IReadOnlyCollection rows, Func isVisible) - { - return [.. totals - .Where(total => isVisible(total.ColumnKey)) - .Select(total => new ReportTotal(total.Label, total.ColumnKey, total.Measure.Compute(rows)))]; - } - - private static ReportPivotResult BuildPivot(ReportPivotRule pivot, IReadOnlyList rows) - { - List<(string Row, string Column, TRow Item)> entries = - [ - .. rows.SelectMany(item => pivot.RowKeys(item) - .Select(rowKey => (NormalizeKey(rowKey), NormalizeKey(pivot.ColumnKey(item)), item))), - ]; - IReadOnlyList rowKeys = OrderCategories(entries.Select(entry => entry.Row), []); - IReadOnlyList columnKeys = OrderCategories(entries.Select(entry => entry.Column), []); - ILookup<(string, string), TRow> byCell = entries.ToLookup(entry => (entry.Row, entry.Column), entry => entry.Item); - ILookup byRow = entries.ToLookup(entry => entry.Row, entry => entry.Item, StringComparer.Ordinal); - ILookup byColumn = entries.ToLookup(entry => entry.Column, entry => entry.Item, StringComparer.Ordinal); - - return new ReportPivotResult( - pivot.Title, - columnKeys, - [.. rowKeys.Select(rowKey => new ReportPivotRow( - rowKey, - [.. columnKeys.Select(columnKey => pivot.Measure.Compute([.. byCell[(rowKey, columnKey)]]))], - pivot.Measure.Compute([.. byRow[rowKey]])))], - [.. columnKeys.Select(columnKey => pivot.Measure.Compute([.. byColumn[columnKey]]))], - pivot.Measure.Compute([.. entries.Select(entry => entry.Item)])); - } - - private static ReportChartResult BuildChart(ReportChartRule chart, IReadOnlyCollection rows) - { - ILookup byCategory = rows - .Where(chart.Includes) - .ToLookup(row => NormalizeKey(chart.Category(row)), StringComparer.Ordinal); - IReadOnlyList categories = OrderCategories(byCategory.Select(group => group.Key), chart.CategoryOrder); - return new ReportChartResult( - chart.Title, - chart.Kind, - [.. categories.Select(category => new ReportChartPoint(category, chart.Measure.Compute([.. byCategory[category]])))]); - } -} diff --git a/web/Areas/Reports/Engine/ReportRegistry.cs b/web/Areas/Reports/Engine/ReportRegistry.cs deleted file mode 100644 index 1891721d2..000000000 --- a/web/Areas/Reports/Engine/ReportRegistry.cs +++ /dev/null @@ -1,101 +0,0 @@ -namespace Viper.Areas.Reports.Engine; - -/// -/// Every report registered with the application, looked up by key. -/// -public interface IReportRegistry -{ - /// - /// All reports, ordered by area and then title. - /// - IReadOnlyList All { get; } - - /// - /// Reports listed in catalogs but not built yet, ordered by area and then title. - /// - IReadOnlyList Planned { get; } - - /// - /// The built report with this key, or null. Planned reports are never returned. - /// - IReportDefinition? Find(string? key); -} - -/// -/// Validates report identities when the registry is created, so a duplicate or malformed key -/// fails on the first request instead of producing an unreachable report. -/// -public sealed class ReportRegistry : IReportRegistry -{ - private readonly Dictionary _byKey = new(StringComparer.OrdinalIgnoreCase); - - public ReportRegistry(IEnumerable definitions, IEnumerable? plannedSources = null) - { - ArgumentNullException.ThrowIfNull(definitions); - foreach (IReportDefinition definition in definitions) - { - EnsureValidIdentity(definition); - if (!_byKey.TryAdd(definition.Key, definition)) - { - throw DuplicateKey(definition.Key); - } - } - - var plannedKeys = new HashSet(StringComparer.OrdinalIgnoreCase); - List planned = [.. (plannedSources ?? []).SelectMany(source => source.PlannedReports)]; - foreach (PlannedReport report in planned) - { - EnsureValidIdentity(report); - if (_byKey.ContainsKey(report.Key) || !plannedKeys.Add(report.Key)) - { - throw DuplicateKey(report.Key); - } - } - - All = [.. InCatalogOrder(_byKey.Values)]; - Planned = [.. InCatalogOrder(planned)]; - } - - public IReadOnlyList All { get; } - - public IReadOnlyList Planned { get; } - - public IReportDefinition? Find(string? key) - { - return string.IsNullOrWhiteSpace(key) ? null : _byKey.GetValueOrDefault(key); - } - - private static IEnumerable InCatalogOrder(IEnumerable reports) where T : IReportIdentity - { - return reports - .OrderBy(report => report.Area, StringComparer.OrdinalIgnoreCase) - .ThenBy(report => report.Title, StringComparer.OrdinalIgnoreCase); - } - - private static InvalidOperationException DuplicateKey(string key) - { - return new InvalidOperationException( - $"More than one report uses the key '{key}'. Remove a planned report once its definition exists."); - } - - private static void EnsureValidIdentity(IReportIdentity report) - { - if (!ReportKey.IsValid(report.Key)) - { - throw new InvalidOperationException( - $"Report key '{report.Key}' must look like 'area.report-name' (lowercase letters, digits and hyphens)."); - } - - if (string.IsNullOrWhiteSpace(report.Title) - || string.IsNullOrWhiteSpace(report.Area) - || string.IsNullOrWhiteSpace(report.Description)) - { - throw new InvalidOperationException($"Report '{report.Key}' needs a title, an area and a description."); - } - - if (report.Permissions.Count == 0 || report.Permissions.Any(string.IsNullOrWhiteSpace)) - { - throw new InvalidOperationException($"Report '{report.Key}' needs at least one non-blank permission."); - } - } -} diff --git a/web/Areas/Reports/Engine/ReportResult.cs b/web/Areas/Reports/Engine/ReportResult.cs deleted file mode 100644 index 242cdb992..000000000 --- a/web/Areas/Reports/Engine/ReportResult.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Viper.Areas.Reports.Engine; - -/// -/// Semantic emphasis for a row or cell. The client maps tones to design-system colors and -/// always shows the flag's label as well, so meaning never depends on color alone. -/// -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum ReportTone -{ - Neutral, - Info, - Positive, - Warning, - Negative, - Muted, -} - -/// -/// A highlight styles a row or cell; a badge adds a short label next to a cell's value. -/// -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum ReportFlagKind -{ - Highlight, - Badge, -} - -[JsonConverter(typeof(JsonStringEnumConverter))] -public enum ReportChartKind -{ - Bar, - Line, - Pie, -} - -/// -/// The output of a report run, shared by the on-screen view and every export format. -/// -public sealed record ReportResult( - string Key, - string Title, - DateTimeOffset GeneratedAt, - int RowCount, - bool RowNumbers, - IReadOnlyList Columns, - IReadOnlyList Summary, - IReadOnlyList Groups, - IReadOnlyList Totals, - IReadOnlyList Pivots, - IReadOnlyList Charts); - -/// -/// One group of rows. An ungrouped report has a single group whose is null. -/// -public sealed record ReportGroupResult( - string? Label, - IReadOnlyList Rows, - IReadOnlyList Subtotals, - IReadOnlyList Charts); - -/// -/// One row. is keyed by column key and holds only the columns the user can see. -/// -public sealed record ReportRowResult(int Number, IReadOnlyDictionary Values, IReadOnlyList Flags); - -public sealed record ReportFlag(ReportFlagKind Kind, ReportTone Tone, string Label, string? ColumnKey); - -/// -/// A labelled aggregate. places a total under a column; for summary -/// facts it only ties the value to that column's visibility. -/// -public sealed record ReportTotal(string Label, string? ColumnKey, decimal? Value); - -public sealed record ReportPivotResult( - string Title, - IReadOnlyList ColumnKeys, - IReadOnlyList Rows, - IReadOnlyList ColumnTotals, - decimal? GrandTotal); - -public sealed record ReportPivotRow(string Key, IReadOnlyList Values, decimal? Total); - -public sealed record ReportChartResult(string Title, ReportChartKind Kind, IReadOnlyList Points); - -public sealed record ReportChartPoint(string Category, decimal? Value); diff --git a/web/Areas/Reports/Engine/ReportValueFormatter.cs b/web/Areas/Reports/Engine/ReportValueFormatter.cs deleted file mode 100644 index f4afa37e3..000000000 --- a/web/Areas/Reports/Engine/ReportValueFormatter.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Globalization; - -namespace Viper.Areas.Reports.Engine; - -/// -/// Formats report values as text for exports that have no cell types (CSV, PDF). Numbers use -/// US English separators and dates use MM/dd/yyyy, matching the legacy reports. -/// -public static class ReportValueFormatter -{ - public const string DateFormat = "MM/dd/yyyy"; - - // Roughly decimal.MaxValue; larger doubles can't convert to decimal. - private const double DecimalLimit = 7.9e28; - - private static readonly CultureInfo UsEnglish = CultureInfo.GetCultureInfo("en-US"); - - public static string Format(object? value, ReportColumnMetadata column) - { - ArgumentNullException.ThrowIfNull(column); - return value switch - { - null => string.Empty, - string text => text, - DateOnly date => date.ToString(DateFormat, CultureInfo.InvariantCulture), - DateTime dateTime => dateTime.ToString(DateFormat, CultureInfo.InvariantCulture), - IEnumerable values => string.Join(", ", values), - _ when IsNumeric(column.Format) && TryGetDecimal(value, out decimal number) => FormatNumber(number, column), - _ => string.Format(CultureInfo.InvariantCulture, "{0}", value), - }; - } - - public static bool IsNumeric(ReportColumnFormat format) - { - return format is ReportColumnFormat.Number or ReportColumnFormat.Currency or ReportColumnFormat.Percent; - } - - public static bool TryGetDecimal(object? value, out decimal number) - { - switch (value) - { - case decimal exact: - number = exact; - return true; - case int whole: - number = whole; - return true; - case long wide: - number = wide; - return true; - case double approximate when double.IsFinite(approximate) && Math.Abs(approximate) < DecimalLimit: - number = (decimal)approximate; - return true; - default: - number = 0; - return false; - } - } - - /// - /// The labels of a row's highlights and badges, for formats that can't show color. - /// - public static string FlagText(ReportRowResult row) - { - ArgumentNullException.ThrowIfNull(row); - return string.Join("; ", row.Flags.Select(flag => flag.Label).Distinct(StringComparer.Ordinal)); - } - - private static string FormatNumber(decimal number, ReportColumnMetadata column) - { - string decimals = (column.Decimals ?? 0).ToString(CultureInfo.InvariantCulture); - return column.Format switch - { - ReportColumnFormat.Currency => number.ToString("C" + decimals, UsEnglish), - ReportColumnFormat.Percent => number.ToString("P" + decimals, UsEnglish), - _ => number.ToString("N" + decimals, UsEnglish), - }; - } -} diff --git a/web/Areas/Reports/Exporters/ReportCsvExporter.cs b/web/Areas/Reports/Exporters/ReportCsvExporter.cs deleted file mode 100644 index 31f9d4dc9..000000000 --- a/web/Areas/Reports/Exporters/ReportCsvExporter.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Text; -using Viper.Areas.Reports.Engine; -using Viper.Classes.Utilities; - -namespace Viper.Areas.Reports.Exporters; - -/// -/// Exports a report's rows as CSV: one header row, then one line per row with a Group column -/// for grouped reports and a Notes column for highlights. Totals, summaries, pivots and charts -/// are left out so the file stays a clean table for further analysis. -/// -public sealed class ReportCsvExporter : IReportExporter -{ - private static readonly char[] QuotedCharacters = ['"', ',', '\r', '\n']; - - public string Format => "csv"; - - public string ContentType => "text/csv"; - - public string Extension => ".csv"; - - public byte[] Export(ReportExport request) - { - ArgumentNullException.ThrowIfNull(request); - ReportResult result = request.Result; - bool grouped = result.Groups.Any(group => group.Label is not null); - bool hasNotes = ReportExportText.HasNotes(result); - - var csv = new StringBuilder(); - List header = []; - if (grouped) - { - header.Add(Text(ReportExportText.GroupHeader)); - } - - header.AddRange(result.Columns.Select(column => Text(column.Label))); - if (hasNotes) - { - header.Add(Text(ReportExportText.NotesHeader)); - } - - AppendLine(csv, header); - - foreach (ReportGroupResult group in result.Groups) - { - IEnumerable groupCells = group.Label is { } label ? [Text(label)] : []; - foreach (ReportRowResult row in group.Rows) - { - IEnumerable cells = groupCells.Concat(result.Columns.Select(column => Cell(row, column))); - AppendLine(csv, hasNotes ? cells.Append(Text(ReportValueFormatter.FlagText(row))) : cells); - } - } - - // The byte-order mark makes Excel open the file as UTF-8 instead of the system code page. - return [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes(csv.ToString())]; - } - - /// - /// Quotes a value when it contains a comma, quote or line break (RFC 4180). - /// - internal static string Quote(string value) - { - return value.IndexOfAny(QuotedCharacters) >= 0 - ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" - : value; - } - - /// - /// Free text is sanitized against formula injection; numbers and dates the formatter - /// produced are safe and stay numeric when a spreadsheet opens the file. - /// - private static string Cell(ReportRowResult row, ReportColumnMetadata column) - { - string formatted = ReportValueFormatter.Format(row.Values.GetValueOrDefault(column.Key), column); - return ReportValueFormatter.IsNumeric(column.Format) || column.Format == ReportColumnFormat.Date - ? Quote(formatted) - : Text(formatted); - } - - private static string Text(string value) - { - return Quote(ExcelHelper.SanitizeStringCell(value)); - } - - private static void AppendLine(StringBuilder csv, IEnumerable cells) - { - csv.Append(string.Join(",", cells)).Append("\r\n"); - } -} diff --git a/web/Areas/Reports/Exporters/ReportExcelExporter.cs b/web/Areas/Reports/Exporters/ReportExcelExporter.cs deleted file mode 100644 index 2118b6103..000000000 --- a/web/Areas/Reports/Exporters/ReportExcelExporter.cs +++ /dev/null @@ -1,357 +0,0 @@ -using ClosedXML.Excel; -using Viper.Areas.Reports.Engine; -using Viper.Classes.Utilities; - -namespace Viper.Areas.Reports.Exporters; - -/// -/// Exports a report to an Excel workbook. The first sheet holds the header, summary facts, -/// each group as an accessible Excel table with its subtotals, and the grand totals. Pivots -/// get a sheet each, and chart data goes on a Charts sheet. Values stay typed (numbers, dates) -/// so the workbook can be sorted and summed. -/// -public sealed class ReportExcelExporter : IReportExporter -{ - private const string DateNumberFormat = "mm/dd/yyyy"; - private const string GeneralNumberFormat = "#,##0.##"; - private const string GroupFill = "#E8E8E8"; - private const int TitleFontSize = 14; - - public string Format => "xlsx"; - - public string ContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; - - public string Extension => ".xlsx"; - - public byte[] Export(ReportExport request) - { - ArgumentNullException.ThrowIfNull(request); - ReportResult result = request.Result; - using var workbook = new XLWorkbook(); - ExcelAccessibilityHelper.SetCoreProperties(workbook, result.Title); - var sheetNames = new HashSet(StringComparer.OrdinalIgnoreCase); - - var layout = new SheetLayout(result); - IXLWorksheet sheet = workbook.Worksheets.Add(UniqueSheetName(result.Title, sheetNames)); - int row = WriteHeader(sheet, request); - row = WriteTotals(sheet, row, result.Summary, layout); - int tableNumber = 0; - foreach (ReportGroupResult group in result.Groups) - { - row = WriteGroup(sheet, row, group, layout, ++tableNumber); - } - - WriteTotals(sheet, row, result.Totals, layout); - sheet.ColumnsUsed().AdjustToContents(); - - foreach (ReportPivotResult pivot in result.Pivots) - { - WritePivot(workbook.Worksheets.Add(UniqueSheetName(pivot.Title, sheetNames)), pivot); - } - - List<(string Title, ReportChartResult Chart)> charts = - [ - .. result.Charts.Select(chart => (chart.Title, chart)), - .. result.Groups.SelectMany(group => group.Charts.Select(chart => ($"{chart.Title}: {group.Label}", chart))), - ]; - if (charts.Count > 0) - { - WriteCharts(workbook.Worksheets.Add(UniqueSheetName("Charts", sheetNames)), charts); - } - - using var stream = new MemoryStream(); - workbook.SaveAs(stream); - return stream.ToArray(); - } - - /// - /// Sanitizes into a worksheet name that isn't already used, adding - /// " (2)", " (3)" and so on while keeping within Excel's 31-character limit. - /// - internal static string UniqueSheetName(string name, HashSet used) - { - const int maxLength = 31; - string baseName = ExcelHelper.SanitizeSheetName(name); - string candidate = baseName; - int copy = 1; - while (!used.Add(candidate)) - { - copy++; - string suffix = $" ({copy})"; - candidate = baseName[..Math.Min(baseName.Length, maxLength - suffix.Length)] + suffix; - } - - return candidate; - } - - internal static string NumberFormat(ReportColumnMetadata column) - { - int decimals = column.Decimals ?? 0; - string fraction = decimals > 0 ? "." + new string('0', decimals) : string.Empty; - return column.Format switch - { - ReportColumnFormat.Currency => "$#,##0" + fraction, - ReportColumnFormat.Percent => "0" + fraction + "%", - _ => "#,##0" + fraction, - }; - } - - private static int WriteHeader(IXLWorksheet sheet, ReportExport request) - { - int row = 1; - IXLCell title = sheet.Cell(row++, 1); - title.Value = ExcelHelper.SanitizeStringCell(request.Result.Title); - title.Style.Font.Bold = true; - title.Style.Font.FontSize = TitleFontSize; - sheet.Cell(row++, 1).Value = ReportExportText.Generated(request.Result.GeneratedAt); - - if (ReportExportText.Filters(request.Filters) is { } filters) - { - sheet.Cell(row++, 1).Value = ExcelHelper.SanitizeStringCell(filters); - } - - if (request.Confidential) - { - IXLCell notice = sheet.Cell(row++, 1); - notice.Value = ReportExportText.ConfidentialNotice; - notice.Style.Font.Italic = true; - } - - return row + 1; - } - - private static int WriteGroup(IXLWorksheet sheet, int row, ReportGroupResult group, SheetLayout layout, int tableNumber) - { - if (group.Label is { } label) - { - IXLRange heading = sheet.Range(row, 1, row, layout.LastColumn); - heading.FirstCell().Value = ExcelHelper.SanitizeStringCell(label); - heading.Style.Font.Bold = true; - heading.Style.Fill.BackgroundColor = XLColor.FromHtml(GroupFill); - row++; - } - - int headerRow = row; - foreach ((string text, int column) in layout.Headers) - { - sheet.Cell(headerRow, column).Value = ExcelHelper.SanitizeStringCell(text); - } - - sheet.Row(headerRow).CellsUsed().Style.Font.Bold = true; - row++; - - foreach (ReportRowResult reportRow in group.Rows) - { - WriteRow(sheet, row++, reportRow, layout); - } - - if (group.Rows.Count > 0) - { - ExcelAccessibilityHelper.PromoteToAccessibleTable( - sheet.Range(headerRow, 1, row - 1, layout.LastColumn), $"ReportTable{tableNumber}"); - } - - return WriteTotals(sheet, row, group.Subtotals, layout); - } - - private static void WriteRow(IXLWorksheet sheet, int row, ReportRowResult reportRow, SheetLayout layout) - { - if (layout.RowNumbers) - { - sheet.Cell(row, 1).Value = reportRow.Number; - } - - foreach ((ReportColumnMetadata column, int index) in layout.Columns) - { - WriteValue(sheet.Cell(row, index), reportRow.Values.GetValueOrDefault(column.Key), column); - } - - if (layout.NotesColumn is int notesColumn) - { - sheet.Cell(row, notesColumn).Value = ExcelHelper.SanitizeStringCell(ReportValueFormatter.FlagText(reportRow)); - } - - foreach (ReportFlag flag in reportRow.Flags.Where(flag => flag.Kind == ReportFlagKind.Highlight)) - { - if (ReportExportText.ToneFill(flag.Tone) is not { } fill) - { - continue; - } - - IXLRange target = flag.ColumnKey is { } key && layout.IndexOf(key) is int column - ? sheet.Range(row, column, row, column) - : sheet.Range(row, 1, row, layout.LastColumn); - target.Style.Fill.BackgroundColor = XLColor.FromHtml(fill); - } - } - - private static void WriteValue(IXLCell cell, object? value, ReportColumnMetadata column) - { - switch (value) - { - case null: - return; - case DateOnly date: - cell.Value = date.ToDateTime(TimeOnly.MinValue); - cell.Style.NumberFormat.Format = DateNumberFormat; - return; - case DateTime dateTime: - cell.Value = dateTime; - cell.Style.NumberFormat.Format = DateNumberFormat; - return; - } - - if (ReportValueFormatter.IsNumeric(column.Format) && ReportValueFormatter.TryGetDecimal(value, out decimal number)) - { - cell.Value = (double)number; - cell.Style.NumberFormat.Format = NumberFormat(column); - return; - } - - cell.Value = ExcelHelper.SanitizeStringCell(ReportValueFormatter.Format(value, column)); - } - - /// - /// Writes one row per total: the label in the first column and the value under the total's - /// column, or beside the label when it has none. - /// - private static int WriteTotals(IXLWorksheet sheet, int row, IReadOnlyList totals, SheetLayout layout) - { - foreach (ReportTotal total in totals) - { - IXLCell label = sheet.Cell(row, 1); - label.Value = ExcelHelper.SanitizeStringCell(total.Label); - label.Style.Font.Bold = true; - - (int column, string format) = total.ColumnKey is { } key && layout.Find(key) is { } target - ? (target.Index, NumberFormat(target.Column)) - : (2, GeneralNumberFormat); - if (total.Value is decimal value) - { - IXLCell cell = sheet.Cell(row, column); - cell.Value = (double)value; - cell.Style.NumberFormat.Format = format; - cell.Style.Font.Bold = true; - } - - row++; - } - - return totals.Count > 0 ? row + 1 : row; - } - - private static void WritePivot(IXLWorksheet sheet, ReportPivotResult pivot) - { - IXLCell title = sheet.Cell(1, 1); - title.Value = ExcelHelper.SanitizeStringCell(pivot.Title); - title.Style.Font.Bold = true; - - const int headerRow = 2; - int totalColumn = pivot.ColumnKeys.Count + 2; - for (int index = 0; index < pivot.ColumnKeys.Count; index++) - { - sheet.Cell(headerRow, index + 2).Value = ExcelHelper.SanitizeStringCell(pivot.ColumnKeys[index]); - } - - sheet.Cell(headerRow, totalColumn).Value = ReportExportText.TotalLabel; - sheet.Row(headerRow).CellsUsed().Style.Font.Bold = true; - - int row = headerRow + 1; - foreach (ReportPivotRow pivotRow in pivot.Rows) - { - sheet.Cell(row, 1).Value = ExcelHelper.SanitizeStringCell(pivotRow.Key); - WriteNumbers(sheet, row, [.. pivotRow.Values, pivotRow.Total]); - row++; - } - - sheet.Cell(row, 1).Value = ReportExportText.TotalLabel; - WriteNumbers(sheet, row, [.. pivot.ColumnTotals, pivot.GrandTotal]); - sheet.Row(row).CellsUsed().Style.Font.Bold = true; - sheet.ColumnsUsed().AdjustToContents(); - } - - private static void WriteCharts(IXLWorksheet sheet, List<(string Title, ReportChartResult Chart)> charts) - { - int row = 1; - foreach ((string title, ReportChartResult chart) in charts) - { - IXLCell heading = sheet.Cell(row++, 1); - heading.Value = ExcelHelper.SanitizeStringCell(title); - heading.Style.Font.Bold = true; - foreach (ReportChartPoint point in chart.Points) - { - sheet.Cell(row, 1).Value = ExcelHelper.SanitizeStringCell(point.Category); - WriteNumbers(sheet, row, [point.Value]); - row++; - } - - row++; - } - - sheet.ColumnsUsed().AdjustToContents(); - } - - /// - /// Writes numbers into consecutive cells starting at column 2; nulls leave the cell blank. - /// - private static void WriteNumbers(IXLWorksheet sheet, int row, IReadOnlyList values) - { - for (int index = 0; index < values.Count; index++) - { - if (values[index] is decimal value) - { - IXLCell cell = sheet.Cell(row, index + 2); - cell.Value = (double)value; - cell.Style.NumberFormat.Format = GeneralNumberFormat; - } - } - } - - /// - /// Where each part of a row goes: an optional row-number column, the report's columns, and - /// an optional Notes column for highlight and badge labels. - /// - private sealed class SheetLayout - { - private readonly Dictionary _byKey; - - public SheetLayout(ReportResult result) - { - RowNumbers = result.RowNumbers; - int offset = RowNumbers ? 1 : 0; - Columns = [.. result.Columns.Select((column, index) => (column, index + 1 + offset))]; - _byKey = Columns.ToDictionary(entry => entry.Column.Key, StringComparer.Ordinal); - NotesColumn = ReportExportText.HasNotes(result) ? Columns.Count + 1 + offset : null; - LastColumn = NotesColumn ?? Math.Max(Columns.Count + offset, 1); - - List<(string, int)> headers = RowNumbers ? [(ReportExportText.RowNumberHeader, 1)] : []; - headers.AddRange(Columns.Select(entry => (entry.Column.Label, entry.Index))); - if (NotesColumn is int notes) - { - headers.Add((ReportExportText.NotesHeader, notes)); - } - - Headers = headers; - } - - public bool RowNumbers { get; } - - public List<(ReportColumnMetadata Column, int Index)> Columns { get; } - - public int? NotesColumn { get; } - - public int LastColumn { get; } - - public List<(string Text, int Column)> Headers { get; } - - public (ReportColumnMetadata Column, int Index)? Find(string key) - { - return _byKey.TryGetValue(key, out (ReportColumnMetadata Column, int Index) entry) ? entry : null; - } - - public int? IndexOf(string key) - { - return Find(key)?.Index; - } - } -} diff --git a/web/Areas/Reports/Exporters/ReportExport.cs b/web/Areas/Reports/Exporters/ReportExport.cs deleted file mode 100644 index 3e655dcce..000000000 --- a/web/Areas/Reports/Exporters/ReportExport.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System.Globalization; -using Viper.Areas.Reports.Engine; - -namespace Viper.Areas.Reports.Exporters; - -/// -/// Everything an exporter needs: the result, the filters that produced it, and whether the -/// file must carry a confidentiality notice. -/// -public sealed record ReportExport(ReportResult Result, IReadOnlyList Filters, bool Confidential); - -/// -/// Turns a report result into a downloadable file. Exporters are pure and stateless, so one -/// instance serves every request. -/// -public interface IReportExporter -{ - /// - /// The format key used in export URLs, such as "csv". - /// - string Format { get; } - - string ContentType { get; } - - /// - /// The file extension, including the leading dot. - /// - string Extension { get; } - - byte[] Export(ReportExport request); -} - -/// -/// Wording shared by every export format, so CSV, Excel and PDF files read the same. -/// -public static class ReportExportText -{ - public const string ConfidentialNotice = - "Confidential: contains personnel information. Share only with staff authorized to see it."; - - public const string GroupHeader = "Group"; - - public const string NotesHeader = "Notes"; - - public const string RowNumberHeader = "#"; - - public const string TotalLabel = "Total"; - - private static readonly CultureInfo UsEnglish = CultureInfo.GetCultureInfo("en-US"); - - // Light fills that keep black text above WCAG AA contrast. Neutral highlights add no fill. - private static readonly Dictionary ToneFills = new() - { - [ReportTone.Info] = "#DEECF9", - [ReportTone.Positive] = "#DFF6DD", - [ReportTone.Warning] = "#FFF4CE", - [ReportTone.Negative] = "#FDE7E9", - [ReportTone.Muted] = "#EDEBE9", - }; - - public static string Generated(DateTimeOffset generatedAt) - { - return "Generated " + generatedAt.ToString("MM/dd/yyyy h:mm tt", UsEnglish); - } - - /// - /// "Filters: Faculty type: Senate; Start date: 07/01/2026", or null when nothing was filtered. - /// - public static string? Filters(IReadOnlyList filters) - { - ArgumentNullException.ThrowIfNull(filters); - return filters.Count == 0 - ? null - : "Filters: " + string.Join("; ", filters.Select(filter => $"{filter.Label}: {filter.Value}")); - } - - /// - /// A total's value as text: formatted like its column when it has one, otherwise as a plain - /// number with up to two decimals. A missing value is blank. - /// - public static string FormatTotal(ReportTotal total, IReadOnlyList columns) - { - ArgumentNullException.ThrowIfNull(total); - ArgumentNullException.ThrowIfNull(columns); - if (total.Value is not decimal value) - { - return string.Empty; - } - - ReportColumnMetadata? column = columns.FirstOrDefault(candidate => candidate.Key == total.ColumnKey); - return column is not null ? ReportValueFormatter.Format(value, column) : FormatNumber(value); - } - - /// - /// A pivot, chart or total number without a column format: thousands separators and up to two decimals. - /// - public static string FormatNumber(decimal? value) - { - return value?.ToString("#,##0.##", UsEnglish) ?? string.Empty; - } - - /// - /// The background color for a highlight tone, or null for tones that add no fill. - /// - public static string? ToneFill(ReportTone tone) - { - return ToneFills.GetValueOrDefault(tone); - } - - /// - /// The fill for one cell of a row. Highlights apply in the order the report declared them, - /// so the last one covering the cell wins. A highlight covers the cell when it targets the - /// whole row, targets this column, or targets a column the export doesn't show. - /// is null for cells that belong to no column, such as row numbers. - /// - public static string? CellFill(IReadOnlyList flags, string? columnKey, IReadOnlySet columnKeys) - { - ArgumentNullException.ThrowIfNull(flags); - ArgumentNullException.ThrowIfNull(columnKeys); - return flags - .Where(flag => flag.Kind == ReportFlagKind.Highlight - && (flag.ColumnKey is null || flag.ColumnKey == columnKey || !columnKeys.Contains(flag.ColumnKey))) - .Select(flag => ToneFill(flag.Tone)) - .LastOrDefault(fill => fill is not null); - } - - /// - /// True when any row has a highlight or badge, which adds a Notes column to exports. - /// - public static bool HasNotes(ReportResult result) - { - ArgumentNullException.ThrowIfNull(result); - return result.Groups.Any(group => group.Rows.Any(row => row.Flags.Count > 0)); - } -} diff --git a/web/Areas/Reports/Exporters/ReportPdfExporter.cs b/web/Areas/Reports/Exporters/ReportPdfExporter.cs deleted file mode 100644 index a44f4159b..000000000 --- a/web/Areas/Reports/Exporters/ReportPdfExporter.cs +++ /dev/null @@ -1,333 +0,0 @@ -using System.Globalization; -using QuestPDF.Fluent; -using QuestPDF.Helpers; -using QuestPDF.Infrastructure; -using Viper.Areas.Reports.Engine; -using Viper.Classes.Utilities; - -namespace Viper.Areas.Reports.Exporters; - -/// -/// Exports a report to a landscape Letter PDF tagged for PDF/UA: a header with the title, -/// generated time, filters and confidentiality notice; summary facts; each group as a table -/// with its subtotals; grand totals; then pivots and chart data as tables. Highlights become -/// light cell fills and every flag label is listed in a Notes column. -/// -public sealed class ReportPdfExporter : IReportExporter -{ - private const float FontSize = 9f; - private const float TitleFontSize = 13f; - private const float FooterFontSize = 7f; - private const float SectionSpacing = 10f; - private const float CellPaddingVertical = 2f; - private const float CellPaddingHorizontal = 3f; - private const float RowNumberWidth = 28f; - private const float NotesWidth = 2f; - private const float PivotKeyWidth = 2f; - private const float RuleWidth = 0.5f; - private const string HeaderFill = "#E8E8E8"; - private const string RuleColor = "#CCCCCC"; - - public string Format => "pdf"; - - public string ContentType => "application/pdf"; - - public string Extension => ".pdf"; - - public byte[] Export(ReportExport request) - { - ArgumentNullException.ThrowIfNull(request); - ReportResult result = request.Result; - var layout = new TableLayout(result); - - return Document.Create(container => container.Page(page => - { - page.Size(PageSizes.Letter.Landscape()); - page.MarginHorizontal(0.5f, Unit.Inch); - page.MarginVertical(0.4f, Unit.Inch); - page.DefaultTextStyle(style => style.FontSize(FontSize)); - page.Header().Element(header => ComposeHeader(header, request)); - page.Content().PaddingTop(SectionSpacing).Element(content => ComposeContent(content, result, layout)); - page.Footer().Element(footer => ComposeFooter(footer, request.Confidential)); - })) - .WithAccessibility(result.Title) - .GeneratePdf(); - } - - private static void ComposeHeader(IContainer container, ReportExport request) - { - container.Column(column => - { - column.Item().SemanticHeader1().Text(request.Result.Title).SemiBold().FontSize(TitleFontSize); - column.Item().Text(ReportExportText.Generated(request.Result.GeneratedAt)); - if (ReportExportText.Filters(request.Filters) is { } filters) - { - column.Item().Text(filters); - } - - if (request.Confidential) - { - column.Item().Text(ReportExportText.ConfidentialNotice).Italic(); - } - }); - } - - private static void ComposeContent(IContainer container, ReportResult result, TableLayout layout) - { - List<(string Title, ReportChartResult Chart)> charts = - [ - .. result.Charts.Select(chart => (chart.Title, chart)), - .. result.Groups.SelectMany(group => group.Charts.Select(chart => ($"{chart.Title}: {group.Label}", chart))), - ]; - - container.Column(column => - { - column.Spacing(SectionSpacing); - ComposeTotals(column, result.Summary, result.Columns); - foreach (ReportGroupResult group in result.Groups) - { - column.Item().Element(item => ComposeGroup(item, group, layout, result.Columns)); - } - - ComposeTotals(column, result.Totals, result.Columns); - foreach (ReportPivotResult pivot in result.Pivots) - { - column.Item().Element(item => ComposePivot(item, pivot)); - } - - foreach ((string title, ReportChartResult chart) in charts) - { - column.Item().Element(item => ComposeChart(item, title, chart)); - } - }); - } - - private static void ComposeGroup( - IContainer container, ReportGroupResult group, TableLayout layout, IReadOnlyList columns) - { - container.Column(column => - { - if (group.Label is { } label) - { - column.Item().SemanticHeader2().Text(label).SemiBold(); - } - - column.Item().SemanticTable().Table(table => - { - table.ColumnsDefinition(definition => - { - if (layout.RowNumbers) - { - definition.ConstantColumn(RowNumberWidth); - } - - for (int index = 0; index < columns.Count; index++) - { - definition.RelativeColumn(); - } - - if (layout.Notes) - { - definition.RelativeColumn(NotesWidth); - } - }); - - table.Header(header => - { - foreach ((string text, ReportAlignment align) in layout.Headers) - { - HeaderCell(header.Cell(), text, align); - } - }); - - foreach (ReportRowResult row in group.Rows) - { - string? rowFill = ReportExportText.CellFill(row.Flags, null, layout.ColumnKeys); - if (layout.RowNumbers) - { - BodyCell(table.Cell(), row.Number.ToString(CultureInfo.InvariantCulture), ReportAlignment.Right, rowFill); - } - - foreach (ReportColumnMetadata reportColumn in columns) - { - BodyCell( - table.Cell(), - ReportValueFormatter.Format(row.Values.GetValueOrDefault(reportColumn.Key), reportColumn), - reportColumn.Align, - ReportExportText.CellFill(row.Flags, reportColumn.Key, layout.ColumnKeys)); - } - - if (layout.Notes) - { - BodyCell(table.Cell(), ReportValueFormatter.FlagText(row), ReportAlignment.Left, rowFill); - } - } - }); - - ComposeTotals(column, group.Subtotals, columns); - }); - } - - private static void ComposeTotals( - ColumnDescriptor column, IReadOnlyList totals, IReadOnlyList columns) - { - foreach (ReportTotal total in totals) - { - column.Item().Text(text => - { - text.Span(total.Label + ": ").SemiBold(); - text.Span(ReportExportText.FormatTotal(total, columns)); - }); - } - } - - private static void ComposePivot(IContainer container, ReportPivotResult pivot) - { - container.Column(column => - { - column.Item().SemanticHeader2().Text(pivot.Title).SemiBold(); - column.Item().SemanticTable().Table(table => - { - table.ColumnsDefinition(definition => - { - definition.RelativeColumn(PivotKeyWidth); - for (int index = 0; index <= pivot.ColumnKeys.Count; index++) - { - definition.RelativeColumn(); - } - }); - - table.Header(header => - { - HeaderCell(header.Cell(), string.Empty, ReportAlignment.Left); - foreach (string key in pivot.ColumnKeys) - { - HeaderCell(header.Cell(), key, ReportAlignment.Right); - } - - HeaderCell(header.Cell(), ReportExportText.TotalLabel, ReportAlignment.Right); - }); - - foreach (ReportPivotRow row in pivot.Rows) - { - NumberRow(table, row.Key, [.. row.Values, row.Total]); - } - - NumberRow(table, ReportExportText.TotalLabel, [.. pivot.ColumnTotals, pivot.GrandTotal]); - }); - }); - } - - private static void ComposeChart(IContainer container, string title, ReportChartResult chart) - { - container.Column(column => - { - column.Item().SemanticHeader2().Text(title).SemiBold(); - column.Item().SemanticTable().Table(table => - { - table.ColumnsDefinition(definition => - { - definition.RelativeColumn(PivotKeyWidth); - definition.RelativeColumn(); - }); - - table.Header(header => - { - HeaderCell(header.Cell(), "Category", ReportAlignment.Left); - HeaderCell(header.Cell(), "Value", ReportAlignment.Right); - }); - - foreach (ReportChartPoint point in chart.Points) - { - NumberRow(table, point.Category, [point.Value]); - } - }); - }); - } - - private static void ComposeFooter(IContainer container, bool confidential) - { - container.Column(column => - { - if (confidential) - { - column.Item().AlignCenter().Text(ReportExportText.ConfidentialNotice).FontSize(FooterFontSize).Italic(); - } - - // The page counter repeats on every page, so assistive technology skips it. - column.Item().SemanticIgnore().AlignCenter().Text(text => - { - text.Span("Page "); - text.CurrentPageNumber(); - text.Span(" of "); - text.TotalPages(); - }); - }); - } - - private static void NumberRow(TableDescriptor table, string label, IReadOnlyList values) - { - BodyCell(table.Cell(), label, ReportAlignment.Left, null); - foreach (decimal? value in values) - { - BodyCell(table.Cell(), ReportExportText.FormatNumber(value), ReportAlignment.Right, null); - } - } - - private static void HeaderCell(IContainer cell, string text, ReportAlignment align) - { - Align(cell.Background(HeaderFill).PaddingVertical(CellPaddingVertical).PaddingHorizontal(CellPaddingHorizontal), align) - .Text(text) - .SemiBold(); - } - - private static void BodyCell(IContainer cell, string text, ReportAlignment align, string? fill) - { - IContainer styled = fill is null ? cell : cell.Background(fill); - Align( - styled.BorderBottom(RuleWidth).BorderColor(RuleColor) - .PaddingVertical(CellPaddingVertical).PaddingHorizontal(CellPaddingHorizontal), - align) - .Text(text); - } - - private static IContainer Align(IContainer container, ReportAlignment align) - { - return align switch - { - ReportAlignment.Right => container.AlignRight(), - ReportAlignment.Center => container.AlignCenter(), - _ => container.AlignLeft(), - }; - } - - /// - /// Which extra columns a group table has, and the header text and alignment for each column. - /// - private sealed class TableLayout - { - public TableLayout(ReportResult result) - { - RowNumbers = result.RowNumbers; - Notes = ReportExportText.HasNotes(result); - ColumnKeys = new HashSet(result.Columns.Select(column => column.Key), StringComparer.Ordinal); - - List<(string, ReportAlignment)> headers = RowNumbers ? [(ReportExportText.RowNumberHeader, ReportAlignment.Right)] : []; - headers.AddRange(result.Columns.Select(column => (column.Label, column.Align))); - if (Notes) - { - headers.Add((ReportExportText.NotesHeader, ReportAlignment.Left)); - } - - Headers = headers; - } - - public bool RowNumbers { get; } - - public bool Notes { get; } - - public IReadOnlySet ColumnKeys { get; } - - public List<(string Text, ReportAlignment Align)> Headers { get; } - } -} diff --git a/web/Areas/Reports/ReportsServiceCollectionExtensions.cs b/web/Areas/Reports/ReportsServiceCollectionExtensions.cs deleted file mode 100644 index ae2eed100..000000000 --- a/web/Areas/Reports/ReportsServiceCollectionExtensions.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Reflection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Viper.Areas.Reports.Data; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Exporters; - -namespace Viper.Areas.Reports; - -public static class ReportsServiceCollectionExtensions -{ - /// - /// Registers every and in - /// , the registry that indexes them, and the export formats. - /// Definitions are scoped because they depend on scoped data services; planned report lists - /// are fixed data, so they are singletons. Also registers the stored procedure runner that - /// report data services use for databases without an EF context. - /// itself is registered by the Scrutor service scan. - /// - public static IServiceCollection AddReports(this IServiceCollection services, Assembly reportAssembly) - { - ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(reportAssembly); - - services.TryAddSingleton(TimeProvider.System); - services.Scan(scan => scan - .FromAssemblies(reportAssembly) - .AddClasses(classes => classes.AssignableTo(), publicOnly: false) - .As() - .WithScopedLifetime() - .AddClasses(classes => classes.AssignableTo(), publicOnly: false) - .As() - .WithSingletonLifetime()); - services.TryAddScoped(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddEnumerable(ServiceDescriptor.Singleton()); - services.TryAddEnumerable(ServiceDescriptor.Singleton()); - services.TryAddEnumerable(ServiceDescriptor.Singleton()); - return services; - } -} diff --git a/web/Areas/Reports/Services/ReportOutcome.cs b/web/Areas/Reports/Services/ReportOutcome.cs deleted file mode 100644 index 568d70743..000000000 --- a/web/Areas/Reports/Services/ReportOutcome.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Viper.Areas.Reports.Engine; - -namespace Viper.Areas.Reports.Services; - -public enum ReportOutcomeStatus -{ - Ok, - NotFound, - Forbidden, - Invalid, -} - -/// -/// The result of a report request: a value, or the reason there isn't one. Keeps HTTP concerns -/// in the controller while the service stays testable without a request pipeline. -/// -public sealed record ReportOutcome(ReportOutcomeStatus Status, T? Value, IReadOnlyList Errors); - -public static class ReportOutcome -{ - public static ReportOutcome Ok(T value) - { - return new ReportOutcome(ReportOutcomeStatus.Ok, value, []); - } - - public static ReportOutcome NotFound() - { - return new ReportOutcome(ReportOutcomeStatus.NotFound, default, []); - } - - public static ReportOutcome Forbidden() - { - return new ReportOutcome(ReportOutcomeStatus.Forbidden, default, []); - } - - /// - /// Carries a failure status and its errors over to an outcome of another value type. - /// - internal static ReportOutcome Failed(ReportOutcomeStatus status, IReadOnlyList errors) - { - return new ReportOutcome(status, default, errors); - } - - public static ReportOutcome Invalid(IReadOnlyList errors) - { - ArgumentNullException.ThrowIfNull(errors); - return new ReportOutcome(ReportOutcomeStatus.Invalid, default, errors); - } -} diff --git a/web/Areas/Reports/Services/ReportService.cs b/web/Areas/Reports/Services/ReportService.cs deleted file mode 100644 index 916f9df0d..000000000 --- a/web/Areas/Reports/Services/ReportService.cs +++ /dev/null @@ -1,199 +0,0 @@ -using System.Text.Json; -using Viper.Areas.Reports.Engine; -using Viper.Areas.Reports.Exporters; -using Viper.Classes.Utilities; - -namespace Viper.Areas.Reports.Services; - -/// -/// A report the current user may run, as listed in a catalog. Available is -/// false for a planned report that is listed but not built yet. -/// -public sealed record ReportCatalogItem(string Key, string Title, string Area, string Description, bool Available); - -/// -/// An exported report, ready to send as a download. -/// -public sealed record ReportFile(byte[] Content, string ContentType, string FileName); - -public interface IReportService -{ - /// - /// Reports the current user may run, built and planned, optionally limited to one area and - /// ordered by area and then title. - /// - IReadOnlyList GetCatalog(string? area); - - ReportOutcome GetDefinition(string? key); - - Task> RunAsync(string? key, JsonElement? parameters, CancellationToken ct); - - Task> ExportAsync(string? key, string? format, JsonElement? parameters, CancellationToken ct); -} - -/// -/// Runs reports for the signed-in user: checks access before reading any parameters, binds and -/// validates them, runs the report, and writes an audit log entry for every run and export. -/// -public class ReportService : IReportService -{ - public const string FormatParameter = "format"; - - private readonly IReportRegistry _registry; - private readonly IReportUserService _userService; - private readonly IReadOnlyList _exporters; - private readonly TimeProvider _timeProvider; - private readonly ILogger _logger; - - public ReportService( - IReportRegistry registry, - IReportUserService userService, - IEnumerable exporters, - TimeProvider timeProvider, - ILogger logger) - { - _registry = registry; - _userService = userService; - _exporters = [.. exporters]; - _timeProvider = timeProvider; - _logger = logger; - } - - public IReadOnlyList GetCatalog(string? area) - { - ReportContext context = _userService.GetCurrentContext(); - string? areaFilter = string.IsNullOrWhiteSpace(area) ? null : area.Trim(); - bool InArea(IReportIdentity report) => - areaFilter is null || string.Equals(report.Area, areaFilter, StringComparison.OrdinalIgnoreCase); - - IEnumerable built = _registry.All - .Where(InArea) - .Where(definition => definition.CanRun(context)) - .Select(definition => ToCatalogItem(definition, available: true)); - IEnumerable planned = _registry.Planned - .Where(InArea) - .Where(report => context.HasAnyPermission(report.Permissions)) - .Select(report => ToCatalogItem(report, available: false)); - - return [.. built.Concat(planned) - .OrderBy(item => item.Area, StringComparer.OrdinalIgnoreCase) - .ThenBy(item => item.Title, StringComparer.OrdinalIgnoreCase)]; - } - - public ReportOutcome GetDefinition(string? key) - { - ReportContext context = _userService.GetCurrentContext(); - ReportOutcomeStatus access = CheckAccess(key, context, out IReportDefinition? definition); - return definition is not null - ? ReportOutcome.Ok(definition.GetMetadata(context)) - : ReportOutcome.Failed(access, []); - } - - public async Task> RunAsync(string? key, JsonElement? parameters, CancellationToken ct) - { - ReportContext context = _userService.GetCurrentContext(); - ReportOutcomeStatus access = CheckAccess(key, context, out IReportDefinition? definition); - if (definition is null) - { - return ReportOutcome.Failed(access, []); - } - - ReportOutcome run = await ExecuteAsync(definition, context, parameters, "run", ct); - return run.Value is { } completed - ? ReportOutcome.Ok(completed.Result) - : ReportOutcome.Failed(run.Status, run.Errors); - } - - public async Task> ExportAsync( - string? key, string? format, JsonElement? parameters, CancellationToken ct) - { - ReportContext context = _userService.GetCurrentContext(); - ReportOutcomeStatus access = CheckAccess(key, context, out IReportDefinition? definition); - if (definition is null) - { - return ReportOutcome.Failed(access, []); - } - - IReportExporter? exporter = _exporters.FirstOrDefault( - candidate => string.Equals(candidate.Format, format, StringComparison.OrdinalIgnoreCase)); - if (exporter is null) - { - string supported = string.Join(", ", _exporters.Select(candidate => candidate.Format)); - return ReportOutcome.Invalid( - [new ReportValidationError(FormatParameter, $"Choose an export format: {supported}.")]); - } - - ReportOutcome run = await ExecuteAsync(definition, context, parameters, "export:" + exporter.Format, ct); - if (run.Value is not { } completed) - { - return ReportOutcome.Failed(run.Status, run.Errors); - } - - var export = new ReportExport( - completed.Result, definition.DescribeParameters(completed.Parameters), definition.IsSensitive); - string fileName = ExcelHelper.BuildExportFilename( - new ExportFilenameOptions { ReportName = definition.Title, Extension = exporter.Extension }); - return ReportOutcome.Ok(new ReportFile(exporter.Export(export), exporter.ContentType, fileName)); - } - - /// - /// Finds the report and checks the user may run it. Returns - /// with the definition, or the failure status with a null definition. - /// - private ReportOutcomeStatus CheckAccess(string? key, ReportContext context, out IReportDefinition? definition) - { - definition = null; - IReportDefinition? found = _registry.Find(key); - if (found is null) - { - return ReportOutcomeStatus.NotFound; - } - - if (!found.CanRun(context)) - { - return ReportOutcomeStatus.Forbidden; - } - - definition = found; - return ReportOutcomeStatus.Ok; - } - - private static ReportCatalogItem ToCatalogItem(IReportIdentity report, bool available) - { - return new ReportCatalogItem(report.Key, report.Title, report.Area, report.Description, available); - } - - private async Task> ExecuteAsync( - IReportDefinition definition, ReportContext context, JsonElement? parameters, string action, CancellationToken ct) - { - if (!ReportParameterBinder.TryBind(definition.ParametersType, parameters, out object? bound, out ReportValidationError? bindError)) - { - return ReportOutcome.Invalid([bindError]); - } - - IReadOnlyList errors = definition.PrepareParameters(bound); - if (errors.Count > 0) - { - return ReportOutcome.Invalid(errors); - } - - ReportResult result = await definition.RunAsync(bound, context, _timeProvider.GetLocalNow(), ct); - - // Reports expose salary, demographic and visa data, so every run and export is audited. - // The guard skips serializing the parameters when information logging is off. - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation( - "Report {ReportKey} {Action} by {LoginId} returned {RowCount} rows for parameters {Parameters}", - definition.Key, - action, - LogSanitizer.SanitizeId(context.LoginId), - result.RowCount, - LogSanitizer.SanitizeString(JsonSerializer.Serialize(bound, definition.ParametersType, ReportParameterBinder.JsonOptions))); - } - - return ReportOutcome.Ok(new ReportRun(bound, result)); - } - - private sealed record ReportRun(object Parameters, ReportResult Result); -} diff --git a/web/Areas/Reports/Services/ReportUserService.cs b/web/Areas/Reports/Services/ReportUserService.cs deleted file mode 100644 index c6f87c19b..000000000 --- a/web/Areas/Reports/Services/ReportUserService.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Viper.Areas.Reports.Engine; -using Viper.Classes.SQLContext; -using Viper.Models.AAUD; - -namespace Viper.Areas.Reports.Services; - -public interface IReportUserService -{ - /// - /// The signed-in user as a report context. A request with no resolvable user gets a context - /// with no permissions, so every report check fails closed. - /// - ReportContext GetCurrentContext(); -} - -public class ReportUserService : IReportUserService -{ - private readonly RAPSContext _rapsContext; - private readonly IUserHelper _userHelper; - - public ReportUserService(RAPSContext rapsContext, IUserHelper userHelper) - { - _rapsContext = rapsContext; - _userHelper = userHelper; - } - - public ReportContext GetCurrentContext() - { - AaudUser? user = _userHelper.GetCurrentUser(); - if (user is null) - { - return new ReportContext(null, _ => false); - } - - return new ReportContext(user.LoginId, permission => _userHelper.HasPermission(_rapsContext, user, permission)); - } -} diff --git a/web/Program.cs b/web/Program.cs index 449e26904..e378dd8da 100644 --- a/web/Program.cs +++ b/web/Program.cs @@ -42,7 +42,6 @@ using Viper.Areas.RAPS.Services; using Viper.Areas.ReportBuilder; using Viper.Areas.ReportBuilder.Services; -using Viper.Areas.Reports; using Viper.Classes; using Viper.Classes.HealthChecks; using Viper.Classes.Scheduler; @@ -65,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"; @@ -322,9 +321,6 @@ void RegisterDbContext(string connectionStringKey, Action(); - // Code-defined reports (IReportDefinition) and the registry that indexes them - builder.Services.AddReports(typeof(Program).Assembly); - // 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. @@ -353,7 +349,6 @@ void RegisterDbContext(string connectionStringKey, Action type.Name.EndsWith("Service") || type.Name.EndsWith("Validator"))) From 0d0b51230badbe771f7e5c1c1e40264ccd3d861a Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:54:34 -0800 Subject: [PATCH 05/12] docs: use main's CLAUDE.md as-is The merge from main kept this branch's own extra CRLF/ReSharper/ conflict-marker bullets alongside main's. Drop them so CLAUDE.md matches main exactly. Co-Authored-By: Claude Sonnet 5 --- CLAUDE.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b3228910e..a4228289b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,6 +53,3 @@ When I ask a question ("why does X...", "is Y right?") or make an observation (" - **Plan/smoketest notes**: `PLAN-*.md` and `SMOKETEST-*.md` at the repo root are gitignored local notes. - **Code-review self-check**: If the gitignored `PLAN-code-review-lessons.md` exists at the repo root, run its pre-flight checklist before saying a change is ready to build, test, or commit. - **Commit messages**: Conventional Commits `type(scope): subject` (`feat`|`fix`|`refactor`|`docs`|`test`|`chore`; prefer `feat` for new behavior), branch ticket ID as prefix (e.g. `VPR-104 fix(a11y): ...`). Subject: imperative, max 72 chars, no trailing period, intent not implementation. Body only when needed: `-` bullets that each earn their place (skip plumbing/helpers/test scaffolding), wrapped at 72. -- **Line endings (CRLF)**: Windows checkout and Husky validation require CRLF (`\r\n`). Save new or modified files with CRLF; tools/scripts that default to LF will fail the pre-commit linter. -- **ReSharper & EF Core scaffolding**: Keep scaffolded `partial void OnModelCreatingPartial(...)` signatures in DB context files (deleting them violates `CS0759`); silence a warning on scaffolded code via `Viper.sln.DotSettings` (`/Default/CodeInspection/Highlighting/InspectionSeverities/=/@EntryIndexedValue=DO_NOT_SHOW`) rather than editing it; don't add redundant `?? ""` on non-nullable scaffolded properties. -- **Staged conflict markers (CS8300)**: Resolve every conflict zone before `git add` during a merge; Husky builds staged files on commit, and a residual `<<<<<<<` marker fails the build with `CS8300`. From 6577a79715a596d3738e479b97a6f5c5db669da5 Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:18:40 -0800 Subject: [PATCH 06/12] fix(reports): resolve Fallow dead-code and complexity findings - Add the Reports SPA's entry points to .fallowrc.json; App.vue and reports.ts were flagged dead only because they were missing there, unlike every other area - Drop ReportSaveOutcome and ReportExportOutcome from their export lists; neither has a consumer outside its own file - Split ReportViewer.vue and ReportAdminEdit.vue's loaded-state content into ReportViewerLoaded and ReportAdminEditForm, cutting both templates' cognitive complexity below threshold - Split formatIsoDate's ISO-match guard into isoDateParts and add a test for its previously-uncovered non-date branch, lowering its CRAP score below threshold Co-Authored-By: Claude Sonnet 5 --- VueApp/.fallowrc.json | 2 + .../src/Reports/admin/report-admin-service.ts | 1 - .../components/ReportAdminEditForm.vue | 136 ++++++++++++++++++ VueApp/src/Reports/pages/ReportAdminEdit.vue | 123 ++++------------ .../shared/report-builder/ReportViewer.vue | 69 ++------- .../report-builder/ReportViewerLoaded.vue | 105 ++++++++++++++ .../__tests__/report-builder-format.test.ts | 6 + .../report-builder/report-builder-format.ts | 19 ++- .../report-builder/report-builder-service.ts | 2 +- 9 files changed, 297 insertions(+), 166 deletions(-) create mode 100644 VueApp/src/Reports/components/ReportAdminEditForm.vue create mode 100644 VueApp/src/shared/report-builder/ReportViewerLoaded.vue 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/Reports/admin/report-admin-service.ts b/VueApp/src/Reports/admin/report-admin-service.ts index b696cbd3e..75fbe2ec2 100644 --- a/VueApp/src/Reports/admin/report-admin-service.ts +++ b/VueApp/src/Reports/admin/report-admin-service.ts @@ -123,4 +123,3 @@ class ReportAdminService { const reportAdminService = new ReportAdminService() export { reportAdminService } -export type { ReportSaveOutcome } 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/pages/ReportAdminEdit.vue b/VueApp/src/Reports/pages/ReportAdminEdit.vue index 70a1771a0..32bc809b1 100644 --- a/VueApp/src/Reports/pages/ReportAdminEdit.vue +++ b/VueApp/src/Reports/pages/ReportAdminEdit.vue @@ -21,98 +21,30 @@ > There's no report with that number. - - - - - - - - -
    -
  • - {{ error }} -
  • -
- -
-
- - - - - Unsaved changes - -
- - -
+ v-model="form" + :definition="definition" + :sources="sources" + :sources-failed="sourcesFailed" + :columns-error="source?.columnsError ?? null" + :source-columns="sourceColumns" + :can-add-missing="canAddMissing" + :targets="targets" + :is-view="isView" + :views="views" + :errors="errors" + :conflict="conflict" + :saving="saving" + :is-dirty="isDirty" + :request="request" + :change-source="changeSource" + :add-missing-columns="addMissingColumns" + :save="save" + :set-deleted="setDeleted" + :reload="reload" + :apply-version="applyVersion" + /> 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 index ccdd02113..069b6da0d 100644 --- a/VueApp/src/shared/report-builder/__tests__/report-builder-format.test.ts +++ b/VueApp/src/shared/report-builder/__tests__/report-builder-format.test.ts @@ -32,6 +32,12 @@ describe("cell text", () => { 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"], diff --git a/VueApp/src/shared/report-builder/report-builder-format.ts b/VueApp/src/shared/report-builder/report-builder-format.ts index 615767926..3bf8e0496 100644 --- a/VueApp/src/shared/report-builder/report-builder-format.ts +++ b/VueApp/src/shared/report-builder/report-builder-format.ts @@ -42,14 +42,23 @@ function formatTime(hour: number, minute: string): string { } /** - * 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: - * a text column only reformats full date-times, which only real date values arrive as. + * 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 formatIsoDate(value: string, format: ReportColumnFormat): string | null { +function isoDateParts(value: string, format: ReportColumnFormat) { const parts = ISO_DATE_TIME.exec(value)?.groups const isDateFormat = format === "Date" || format === "DateTime" - if (!parts || (!isDateFormat && parts.hour === undefined)) { + 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}` diff --git a/VueApp/src/shared/report-builder/report-builder-service.ts b/VueApp/src/shared/report-builder/report-builder-service.ts index 2639f01eb..773319026 100644 --- a/VueApp/src/shared/report-builder/report-builder-service.ts +++ b/VueApp/src/shared/report-builder/report-builder-service.ts @@ -77,4 +77,4 @@ class ReportBuilderService { const reportBuilderService = new ReportBuilderService() export { reportBuilderService } -export type { ReportExportOutcome, ReportRunOutcome } +export type { ReportRunOutcome } From 2033878ca4ab7c65efac3c1665f2b1d139f9b6ec Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:34:13 -0800 Subject: [PATCH 07/12] refactor(router): share the authenticate guard between Personnel and Reports Personnel and Reports routers each wrapped useRequireLogin in a near-identical authenticate function, differing only by permission prefix - a new jscpd clone vs main. Extract createAuthenticator() in RequireLogin.ts so both routers call it instead of duplicating it. Co-Authored-By: Claude Sonnet 5 --- .../__tests__/router-permissions.test.ts | 4 ++++ VueApp/src/Personnel/router/index.ts | 16 ++++------------ VueApp/src/Reports/__tests__/router.test.ts | 4 ++++ VueApp/src/Reports/router/index.ts | 17 +++++------------ VueApp/src/composables/RequireLogin.ts | 15 ++++++++++++++- 5 files changed, 31 insertions(+), 25 deletions(-) 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/__tests__/router.test.ts b/VueApp/src/Reports/__tests__/router.test.ts index 9ae271710..b3e3655b4 100644 --- a/VueApp/src/Reports/__tests__/router.test.ts +++ b/VueApp/src/Reports/__tests__/router.test.ts @@ -11,6 +11,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 + }, })) function signIn() { diff --git a/VueApp/src/Reports/router/index.ts b/VueApp/src/Reports/router/index.ts index d2718fe2a..a55213799 100644 --- a/VueApp/src/Reports/router/index.ts +++ b/VueApp/src/Reports/router/index.ts @@ -1,22 +1,15 @@ import { createSpaRouter } from "@/shared/create-spa-router" -import type { NavigationGuard, RouteLocationNormalized } from "vue-router" +import type { NavigationGuard } 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. Which reports they may see is decided by the API, report by report, so - * the only permissions loaded are the Report Builder's own (SVMSecure.Reports.*). - * 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.Reports") - return loginResult === null || loginResult -} +// 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) => { 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 } From b3a0767fc3a48314fb068f7b8e5e15e08259d60e Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:35:03 -0800 Subject: [PATCH 08/12] fix(reports): use QuestPDF's renamed SemanticHeading1 SemanticHeader1 was renamed to SemanticHeading1 in QuestPDF 2026.9; the old name is obsolete and failed the ReSharper PR gate (CS0618). Co-Authored-By: Claude Sonnet 5 --- web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs b/web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs index bd5f044aa..e2c95ea01 100644 --- a/web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs +++ b/web/Areas/ReportBuilder/Exporters/ReportPdfWriter.cs @@ -48,7 +48,7 @@ private static void ComposeHeading(IContainer container, ReportExportDocument do { container.Column(column => { - column.Item().SemanticHeader1().Text(document.Title).SemiBold().FontSize(TitleFontSize); + column.Item().SemanticHeading1().Text(document.Title).SemiBold().FontSize(TitleFontSize); column.Item().Text(ReportExportText.Generated(document.GeneratedAt)); if (ReportExportText.Filters(document.Filters) is { } filters) { From 4c2605d914162cb00f98113bdb25abd577a71804 Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:44:03 -0800 Subject: [PATCH 09/12] test(reports): close Codecov patch-coverage gaps Adds targeted tests for the branches Codecov flagged as missing on this PR: failure/empty-result paths in report-admin-service and use-report-admin-edit, untouched-row and multi-field cases in the admin section components, QSelect's #option/#no-option slots (via a stub, since jsdom never renders Quasar's virtualized list), and the new ReportAdminEditForm's own wiring. Left alone with reasons: the router's lazy-loaded page components (deliberately stubbed out by the shared router-test helper, same as every other SPA here) and two defensive branches that are unreachable through normal rendering. Co-Authored-By: Claude Sonnet 5 --- .../__tests__/report-admin-edit-form.test.ts | 171 ++++++++++++++++++ .../__tests__/report-admin-edit.test.ts | 12 ++ .../__tests__/report-admin-panels.test.ts | 47 +++++ .../__tests__/report-admin-parameters.test.ts | 20 +- .../__tests__/report-admin-sections.test.ts | 80 +++++++- .../__tests__/report-admin-service.test.ts | 21 +++ .../__tests__/use-report-admin-edit.test.ts | 22 +++ .../__tests__/report-choice-field.test.ts | 14 ++ .../__tests__/use-report-builder.test.ts | 31 ++++ 9 files changed, 407 insertions(+), 11 deletions(-) create mode 100644 VueApp/src/Reports/__tests__/report-admin-edit-form.test.ts 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 index c761d5b2a..b3b0a70e9 100644 --- a/VueApp/src/Reports/__tests__/report-admin-edit.test.ts +++ b/VueApp/src/Reports/__tests__/report-admin-edit.test.ts @@ -147,4 +147,16 @@ describe("report admin edit page", () => { 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-panels.test.ts b/VueApp/src/Reports/__tests__/report-admin-panels.test.ts index 69bc55acb..a656920eb 100644 --- a/VueApp/src/Reports/__tests__/report-admin-panels.test.ts +++ b/VueApp/src/Reports/__tests__/report-admin-panels.test.ts @@ -41,6 +41,10 @@ describe("report permissions section", () => { 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", () => { @@ -60,6 +64,49 @@ describe("report permissions section", () => { 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", () => { diff --git a/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts b/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts index 0950dcb5d..e8dd63b47 100644 --- a/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts +++ b/VueApp/src/Reports/__tests__/report-admin-parameters.test.ts @@ -166,8 +166,9 @@ describe("report parameters section", () => { 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]) + const changing = mountParameters([first, second]) const removing = mountParameters([first]) await adding @@ -175,15 +176,26 @@ describe("report parameters section", () => { .find((button) => button.text().includes("Add parameter")) ?.trigger("click") changing - .findComponent(ReportAdminParameterFields) - .vm.$emit("update:modelValue", { ...first, label: "Department" }) + .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)[0]?.label).toBe("Department") + 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() diff --git a/VueApp/src/Reports/__tests__/report-admin-sections.test.ts b/VueApp/src/Reports/__tests__/report-admin-sections.test.ts index 7469fcc9c..4039c2820 100644 --- a/VueApp/src/Reports/__tests__/report-admin-sections.test.ts +++ b/VueApp/src/Reports/__tests__/report-admin-sections.test.ts @@ -63,13 +63,19 @@ describe("report basics section", () => { it("updates the title, area and description, keeping blanks as empty", async () => { expect.hasAssertions() const wrapper = mountBasics() - const [title, area] = wrapper.findAllComponents({ name: "QInput" }) + 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]).toStrictEqual(["Roster", null]) + 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", () => { @@ -89,19 +95,55 @@ describe("report basics section", () => { 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", async () => { + it("edits a column's heading, format and flags, leaving the others alone", async () => { expect.hasAssertions() const column = newColumn("Name") - const wrapper = mountColumns([column]) + 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: "Full name", visible: false }]) + expect(lastColumns(wrapper)).toStrictEqual([{ ...column, label: null, visible: false, sortable: false }, other]) }) it("changes the source column and format", () => { @@ -141,6 +183,17 @@ describe("report columns section", () => { 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) @@ -198,11 +251,24 @@ describe("report display section", () => { 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", " ") - - expect([sort, pdf, lastForm(wrapper).sensitiveNotice]).toStrictEqual([null, true, null]) + 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", () => { diff --git a/VueApp/src/Reports/__tests__/report-admin-service.test.ts b/VueApp/src/Reports/__tests__/report-admin-service.test.ts index cfc6edc01..93b1bae9e 100644 --- a/VueApp/src/Reports/__tests__/report-admin-service.test.ts +++ b/VueApp/src/Reports/__tests__/report-admin-service.test.ts @@ -136,6 +136,18 @@ describe("admin saves", () => { ]) }) + 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 }) @@ -145,6 +157,15 @@ describe("admin saves", () => { 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", () => { diff --git a/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts b/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts index 04410e4ac..50d8ccce7 100644 --- a/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts +++ b/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts @@ -66,6 +66,7 @@ describe("report edit state - loading", () => { 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() }) @@ -227,6 +228,17 @@ describe("report edit state - saving", () => { 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", () => { @@ -271,4 +283,14 @@ describe("report edit state - deleting", () => { 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/shared/report-builder/__tests__/report-choice-field.test.ts b/VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts index ccde8673a..392a915f1 100644 --- a/VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts +++ b/VueApp/src/shared/report-builder/__tests__/report-choice-field.test.ts @@ -58,4 +58,18 @@ describe("choice field", () => { 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__/use-report-builder.test.ts b/VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts index 608d798e4..48a9f294d 100644 --- a/VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts +++ b/VueApp/src/shared/report-builder/__tests__/use-report-builder.test.ts @@ -223,6 +223,21 @@ describe("report builder state - running", () => { 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) @@ -317,6 +332,22 @@ describe("report builder state - running when the form changes", () => { 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", () => { From bdb073ea321354161edf5b27a797abb71f695e6d Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:11:09 -0800 Subject: [PATCH 10/12] test(reports): drop redundant null casts CodeQL flagged Assert.Equal already infers each tuple element's type from the actual side, so the explicit (ReportFilterOperator?)null, (DateTime?)null and (string?)null casts were no-ops. Co-Authored-By: Claude Sonnet 5 --- test/ReportBuilder/ReportAdminServiceTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/ReportBuilder/ReportAdminServiceTests.cs b/test/ReportBuilder/ReportAdminServiceTests.cs index 795267bb9..a521de9a2 100644 --- a/test/ReportBuilder/ReportAdminServiceTests.cs +++ b/test/ReportBuilder/ReportAdminServiceTests.cs @@ -210,7 +210,7 @@ public async Task Create_ProcedureParameters_HaveNoOperatorAndCurrentUserOnesAre 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", (ReportFilterOperator?)null), (parameters[1].ChoicesSource, parameters[1].Operator)); + Assert.Equal(("FacultyRoster", null), (parameters[1].ChoicesSource, parameters[1].Operator)); } // Reading @@ -371,7 +371,7 @@ public async Task Delete_HidesTheReportAndRestoreBringsItBack() ReportAdminDefinition restored = (await _service.RestoreAsync(created.Id, Ct)).Value!; Assert.Equal((Now.DateTime, "jdoe"), (deleted.DeletedOn, deleted.DeletedBy)); - Assert.Equal(((DateTime?)null, (string?)null), (restored.DeletedOn, restored.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], From 4c3c00fe8461a888c4e3dae08302408c06712f7c Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:39:25 -0800 Subject: [PATCH 11/12] fix(reports): close CodeRabbit correctness and concurrency findings - bind parameter names case-insensitively without crashing on a duplicate, reporting it as invalid input instead - make ModifiedOn an EF concurrency token so a race between two saves can't silently overwrite one of them - enforce MaxChoices on a parameter's fixed choice list - bind Date filter values as SqlDbType.Date so pre-1753 dates don't overflow SQL Server's datetime range - reject an explicit search or sort request for a procedure that pages itself in SQL, since it can't act on either - sort a buffered procedure's rows before projecting them, so a default sort column that isn't displayed still works - always pass a bounded @Skip/@Take to a self-paging procedure, even for downloads and unpaginated runs Co-Authored-By: Claude Sonnet 5 --- .../ReportDefinitionValidatorTests.cs | 10 +++ .../ReportParameterBinderTests.cs | 9 +++ test/ReportBuilder/ReportRunServiceTests.cs | 51 ++++++++++++++ .../ReportBuilder/ReportBuilderDbContext.cs | 4 +- .../Services/ReportAdminService.cs | 25 ++++++- .../Services/ReportDefinitionValidator.cs | 5 ++ .../Services/ReportParameterBinder.cs | 13 +++- .../Services/ReportQueryExecutor.cs | 7 ++ .../Services/ReportRunService.cs | 66 ++++++++++++++----- 9 files changed, 168 insertions(+), 22 deletions(-) diff --git a/test/ReportBuilder/ReportDefinitionValidatorTests.cs b/test/ReportBuilder/ReportDefinitionValidatorTests.cs index 8e16b4282..cc4bcba59 100644 --- a/test/ReportBuilder/ReportDefinitionValidatorTests.cs +++ b/test/ReportBuilder/ReportDefinitionValidatorTests.cs @@ -266,6 +266,16 @@ public async Task ChoiceLists_NeedDistinctValues() 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)] diff --git a/test/ReportBuilder/ReportParameterBinderTests.cs b/test/ReportBuilder/ReportParameterBinderTests.cs index 90f1004a2..fadb0be26 100644 --- a/test/ReportBuilder/ReportParameterBinderTests.cs +++ b/test/ReportBuilder/ReportParameterBinderTests.cs @@ -237,6 +237,15 @@ public void UnknownNames_AreErrorsWithTheNameShortened() 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() { diff --git a/test/ReportBuilder/ReportRunServiceTests.cs b/test/ReportBuilder/ReportRunServiceTests.cs index 017d790c1..0858da051 100644 --- a/test/ReportBuilder/ReportRunServiceTests.cs +++ b/test/ReportBuilder/ReportRunServiceTests.cs @@ -680,6 +680,57 @@ public async Task Procedure_ThatPagesItself_PastTheLastPage_HasNoTotal() 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() { diff --git a/web/Areas/ReportBuilder/ReportBuilderDbContext.cs b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs index 65375d847..9194796f3 100644 --- a/web/Areas/ReportBuilder/ReportBuilderDbContext.cs +++ b/web/Areas/ReportBuilder/ReportBuilderDbContext.cs @@ -63,7 +63,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) 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()"); + 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); diff --git a/web/Areas/ReportBuilder/Services/ReportAdminService.cs b/web/Areas/ReportBuilder/Services/ReportAdminService.cs index 3b2ef2a5a..51df04e41 100644 --- a/web/Areas/ReportBuilder/Services/ReportAdminService.cs +++ b/web/Areas/ReportBuilder/Services/ReportAdminService.cs @@ -151,7 +151,18 @@ public async Task> UpdateAsync(int id, (DateTime now, string? who) = Stamp(); report.ModifiedOn = now; report.ModifiedBy = who; - await _context.SaveChangesAsync(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); return ReportAdminOutcome.Ok((await GetAsync(id, ct))!); @@ -235,7 +246,17 @@ private async Task> SetDeletedAsync(in report.DeletedBy = deleted ? who : null; report.ModifiedOn = now; report.ModifiedBy = who; - await _context.SaveChangesAsync(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); } diff --git a/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs b/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs index c5d347464..8809f6334 100644 --- a/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs +++ b/web/Areas/ReportBuilder/Services/ReportDefinitionValidator.cs @@ -233,6 +233,11 @@ private static void CheckOperator(string label, ReportParameterEdit parameter, L 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; } diff --git a/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs b/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs index 1208951f1..ad9e10702 100644 --- a/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs +++ b/web/Areas/ReportBuilder/Services/ReportParameterBinder.cs @@ -52,11 +52,22 @@ public static ReportBindResult Bind( ReportCurrentUser user, IReadOnlyDictionary> choices) { - var values = new Dictionary>(input, StringComparer.OrdinalIgnoreCase); + 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!; diff --git a/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs b/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs index 8eb1cd5a5..ace8376d5 100644 --- a/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs +++ b/web/Areas/ReportBuilder/Services/ReportQueryExecutor.cs @@ -104,6 +104,13 @@ private static SqlCommand Create(SqlConnection connection, string text, IReadOnl { 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 index 4b4c7c3ce..f01c8dd22 100644 --- a/web/Areas/ReportBuilder/Services/ReportRunService.cs +++ b/web/Areas/ReportBuilder/Services/ReportRunService.cs @@ -256,16 +256,25 @@ private static ReportRunOutcome Plan( 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, errors); + (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."); + } - bool screen = mode == ReportRunMode.Screen; - bool paginate = screen && ReportAccess.Paginates(report); int perPage = ReportAccess.PageSize(report); if (paginate && request.PerPage is { } asked) { @@ -311,7 +320,8 @@ private static ReportRunOutcome Plan( /// /// 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. + /// 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, @@ -319,10 +329,17 @@ private static (string? Column, bool Descending, bool Missing) Sort( 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) @@ -418,13 +435,25 @@ private async Task RunViewAsync(RunPlan plan, CancellationToken private async Task RunProcedureAsync(RunPlan plan, CancellationToken ct) { - bool pagesInSql = plan.Paginate && plan.Source.PagesInSql; - ReportSqlCommand command = ReportSqlBuilder.BuildProcedure( - plan.Source.Name, plan.Parameters, pagesInSql ? plan.Skip : null, pagesInSql ? plan.PerPage : null); + // 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, pagesInSql ? plan.PerPage : ReportLimits.MaxRows, plan.Timeout, ct); + command, sqlPaged ? plan.PerPage : ReportLimits.MaxRows, plan.Timeout, ct); - if (pagesInSql) + 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); @@ -439,20 +468,21 @@ private async Task RunProcedureAsync(RunPlan plan, Cancellation }; } - IEnumerable> rows = Project(result.Rows, plan.Columns); - if (plan.Search is not null) - { - rows = rows.Where(row => Matches(row, plan.Search)); - } - + // 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(); - rows = plan.SortDescending - ? rows.OrderByDescending(row => Value(row, plan.SortColumn), comparer) - : rows.OrderBy(row => Value(row, plan.SortColumn), comparer); + 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)] From 3459d42f2c1f4adcafd50d33767782a99c4aee89 Mon Sep 17 00:00:00 2001 From: Jason Francis <134454748+JasonRobertFrancis@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:34:53 -0800 Subject: [PATCH 12/12] fix(reports): close more CodeRabbit correctness findings - keep the form's own version when deleting or restoring with unsaved edits, instead of advancing it past them, so a later save is caught as a conflict rather than silently overwriting what changed since - ignore a history selection or a report-list toggle response that finishes after a newer one started - split the report-with-children queries in ReportAccess and ReportProblemService so permissions, columns and parameters don't multiply each other into one joined result - wrap a report's save, delete and restore together with their history write in one transaction, so a failed history write rolls back the report change too; proven with a SQLite-backed test, since the in-memory provider the other tests use can't roll back for real Co-Authored-By: Claude Sonnet 5 --- .../__tests__/report-admin-list.test.ts | 20 +++ .../__tests__/report-admin-panels.test.ts | 31 +++++ .../__tests__/use-report-admin-edit.test.ts | 17 ++- .../Reports/admin/use-report-admin-edit.ts | 11 +- .../Reports/components/ReportAdminHistory.vue | 8 ++ VueApp/src/Reports/pages/ReportAdminList.vue | 8 ++ .../ReportAdminServiceRollbackTests.cs | 131 ++++++++++++++++++ test/ReportBuilder/ReportAdminServiceTests.cs | 4 +- test/ReportBuilder/ReportBuilderFakes.cs | 19 +++ .../ReportProblemServiceTests.cs | 4 +- test/ReportBuilder/ReportRunServiceTests.cs | 4 +- .../ReportBuilder/ReportViewerServiceTests.cs | 4 +- .../ReportBuilder/Services/ReportAccess.cs | 1 + .../Services/ReportAdminService.cs | 11 +- .../Services/ReportProblemService.cs | 1 + 15 files changed, 253 insertions(+), 21 deletions(-) create mode 100644 test/ReportBuilder/ReportAdminServiceRollbackTests.cs diff --git a/VueApp/src/Reports/__tests__/report-admin-list.test.ts b/VueApp/src/Reports/__tests__/report-admin-list.test.ts index 0e2439c07..b6b6401e9 100644 --- a/VueApp/src/Reports/__tests__/report-admin-list.test.ts +++ b/VueApp/src/Reports/__tests__/report-admin-list.test.ts @@ -3,6 +3,7 @@ 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>() }, @@ -71,4 +72,23 @@ describe("report admin list", () => { 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 index a656920eb..963ea183e 100644 --- a/VueApp/src/Reports/__tests__/report-admin-panels.test.ts +++ b/VueApp/src/Reports/__tests__/report-admin-panels.test.ts @@ -7,6 +7,8 @@ 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: { @@ -200,6 +202,35 @@ describe("report history section", () => { 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", () => { diff --git a/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts b/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts index 50d8ccce7..57e5d7bcb 100644 --- a/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts +++ b/VueApp/src/Reports/__tests__/use-report-admin-edit.test.ts @@ -262,15 +262,26 @@ describe("report edit state - deleting", () => { expect(state.isDirty.value).toBeFalsy() }) - it("keeps unsaved edits when restoring", async () => { + it("keeps unsaved edits when restoring, and the form's own version with them", async () => { expect.hasAssertions() const state = await edit() - service.restore.mockResolvedValue(saved) + 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) - expect([state.form.value.title, state.isDirty.value]).toStrictEqual(["Mine", true]) + // 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 () => { diff --git a/VueApp/src/Reports/admin/use-report-admin-edit.ts b/VueApp/src/Reports/admin/use-report-admin-edit.ts index 49b70d51e..54ef39f66 100644 --- a/VueApp/src/Reports/admin/use-report-admin-edit.ts +++ b/VueApp/src/Reports/admin/use-report-admin-edit.ts @@ -122,8 +122,10 @@ export function useReportAdminEdit(reportId: MaybeRefOrGetter) { } /** - * Deletes or restores the report. Either one is a save on the server, so the form takes the - * new version's time; unsaved edits stay as they are. + * 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 @@ -136,10 +138,9 @@ export function useReportAdminEdit(reportId: MaybeRefOrGetter) { if (updated === null) { return } - const clean = !isDirty.value definition.value = updated - form.value = { ...form.value, lastModifiedOn: updated.report.lastModifiedOn } - if (clean) { + if (!isDirty.value) { + form.value = toForm(updated.report) setInitialState() } } diff --git a/VueApp/src/Reports/components/ReportAdminHistory.vue b/VueApp/src/Reports/components/ReportAdminHistory.vue index 4f638569c..598579731 100644 --- a/VueApp/src/Reports/components/ReportAdminHistory.vue +++ b/VueApp/src/Reports/components/ReportAdminHistory.vue @@ -77,6 +77,8 @@ const loading = ref(false) const failed = ref(false) const unreadable = ref(false) +let selectionId = 0 + function describe(version: ReportHistoryItem): string { const when = formatCell(version.changedOn, "DateTime") return version.changedBy ? `${when} by ${version.changedBy}` : when @@ -90,8 +92,14 @@ async function load(): Promise { versions.value = found ?? [] } +/** Only the latest selection may update the form or the "can't be read" note. */ async function loadVersion(historyId: number): Promise { + selectionId += 1 + const current = selectionId const version = await reportAdminService.getVersion(reportId, historyId) + if (current !== selectionId) { + return + } unreadable.value = !version?.report if (version?.report) { emit("load", version.report) diff --git a/VueApp/src/Reports/pages/ReportAdminList.vue b/VueApp/src/Reports/pages/ReportAdminList.vue index 47e48d171..aa8d99d60 100644 --- a/VueApp/src/Reports/pages/ReportAdminList.vue +++ b/VueApp/src/Reports/pages/ReportAdminList.vue @@ -122,9 +122,17 @@ const includeDeleted = ref(false) const loading = ref(true) const failed = ref(false) +let loadId = 0 + +/** Only the latest toggle's request may update the table. */ async function load(withDeleted: boolean): Promise { + loadId += 1 + const current = loadId loading.value = true const found = await reportAdminService.list(withDeleted) + if (current !== loadId) { + return + } failed.value = found === null reports.value = found ?? [] loading.value = false 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 index a521de9a2..e032cd87e 100644 --- a/test/ReportBuilder/ReportAdminServiceTests.cs +++ b/test/ReportBuilder/ReportAdminServiceTests.cs @@ -23,9 +23,7 @@ public sealed class ReportAdminServiceTests : IDisposable public ReportAdminServiceTests() { - DbContextOptions options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(Guid.NewGuid().ToString()) - .Options; + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); _context = new ReportBuilderDbContext(options); _service = new ReportAdminService( _context, new ReportDefinitionValidator(_catalog, _permissions), _permissions, _users, _runs, new FixedClock()); diff --git a/test/ReportBuilder/ReportBuilderFakes.cs b/test/ReportBuilder/ReportBuilderFakes.cs index 29b9169e2..14cc14ea4 100644 --- a/test/ReportBuilder/ReportBuilderFakes.cs +++ b/test/ReportBuilder/ReportBuilderFakes.cs @@ -1,8 +1,27 @@ +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 { diff --git a/test/ReportBuilder/ReportProblemServiceTests.cs b/test/ReportBuilder/ReportProblemServiceTests.cs index 7a3f5d97a..e8e9515d1 100644 --- a/test/ReportBuilder/ReportProblemServiceTests.cs +++ b/test/ReportBuilder/ReportProblemServiceTests.cs @@ -21,9 +21,7 @@ public sealed class ReportProblemServiceTests : IDisposable public ReportProblemServiceTests() { - DbContextOptions options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(Guid.NewGuid().ToString()) - .Options; + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); _context = new ReportBuilderDbContext(options); _service = new ReportProblemService(_context, new ReportDefinitionValidator(_catalog, _permissions), new FixedClock()); _catalog.Sources.Add(new ReportSourceDetail diff --git a/test/ReportBuilder/ReportRunServiceTests.cs b/test/ReportBuilder/ReportRunServiceTests.cs index 0858da051..0195dc539 100644 --- a/test/ReportBuilder/ReportRunServiceTests.cs +++ b/test/ReportBuilder/ReportRunServiceTests.cs @@ -31,9 +31,7 @@ public sealed class ReportRunServiceTests : IDisposable public ReportRunServiceTests() { - DbContextOptions options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(Guid.NewGuid().ToString()) - .Options; + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); _context = new ReportBuilderDbContext(options); _service = CreateService(_context); _users.Permissions.Add(ViewerPermission); diff --git a/test/ReportBuilder/ReportViewerServiceTests.cs b/test/ReportBuilder/ReportViewerServiceTests.cs index fd214de58..96f06b855 100644 --- a/test/ReportBuilder/ReportViewerServiceTests.cs +++ b/test/ReportBuilder/ReportViewerServiceTests.cs @@ -22,9 +22,7 @@ public sealed class ReportViewerServiceTests : IDisposable public ReportViewerServiceTests() { - DbContextOptions options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(Guid.NewGuid().ToString()) - .Options; + DbContextOptions options = ReportBuilderTestDb.CreateOptions(); _context = new ReportBuilderDbContext(options); _service = new ReportViewerService( _context, _users, new ReportChoiceService(_catalog, _executor), NullLogger.Instance); diff --git a/web/Areas/ReportBuilder/Services/ReportAccess.cs b/web/Areas/ReportBuilder/Services/ReportAccess.cs index 61ff40b2e..6fac8b048 100644 --- a/web/Areas/ReportBuilder/Services/ReportAccess.cs +++ b/web/Areas/ReportBuilder/Services/ReportAccess.cs @@ -24,6 +24,7 @@ public static class ReportAccess .Include(r => r.Permissions) .Include(r => r.Columns) .Include(r => r.Parameters) + .AsSplitQuery() .FirstOrDefaultAsync(r => r.Slug == id && r.DeletedOn == null, ct); } diff --git a/web/Areas/ReportBuilder/Services/ReportAdminService.cs b/web/Areas/ReportBuilder/Services/ReportAdminService.cs index 51df04e41..7f2481dff 100644 --- a/web/Areas/ReportBuilder/Services/ReportAdminService.cs +++ b/web/Areas/ReportBuilder/Services/ReportAdminService.cs @@ -111,9 +111,12 @@ public async Task> CreateAsync(ReportE Apply(report, request, validation); report.Permissions = [.. validation.Permissions.Select(name => new ReportPermission { Permission = name })]; _context.Reports.Add(report); - await _context.SaveChangesAsync(ct); + 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))!); } @@ -151,6 +154,8 @@ public async Task> UpdateAsync(int id, (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); @@ -165,6 +170,7 @@ public async Task> UpdateAsync(int id, } await AddHistoryAsync(report, ReportHistoryAction.Updated, now, who, ct); + await transaction.CommitAsync(ct); return ReportAdminOutcome.Ok((await GetAsync(id, ct))!); } @@ -246,6 +252,8 @@ private async Task> SetDeletedAsync(in 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); @@ -258,6 +266,7 @@ private async Task> SetDeletedAsync(in } await AddHistoryAsync(report, deleted ? ReportHistoryAction.Deleted : ReportHistoryAction.Restored, now, who, ct); + await transaction.CommitAsync(ct); } return ReportAdminOutcome.Ok((await GetAsync(id, ct))!); diff --git a/web/Areas/ReportBuilder/Services/ReportProblemService.cs b/web/Areas/ReportBuilder/Services/ReportProblemService.cs index 02a493ac3..e7f1a4c6c 100644 --- a/web/Areas/ReportBuilder/Services/ReportProblemService.cs +++ b/web/Areas/ReportBuilder/Services/ReportProblemService.cs @@ -64,6 +64,7 @@ public async Task CheckAsync(CancellationToken ct) .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)