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 @@ + + + + {{ heading }} + + + Loading reports + + + The report list could not be loaded. Please try again later. + + + + + + {{ report.title }} + {{ report.description }} + + + + + + + + + + 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 @@ + + + + + {{ cell.value }} + + + + + + + + + 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 @@ + + + + + {{ table.total.label }} + + {{ formatPlainNumber(value) }} + + + + + + + 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 @@ + + + + + + + + + + + + Run report + + + + + + + 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 @@ + + + + Loading report + + + + + + This report isn't available. It may not be built yet, or you may not have access to it. + + + + + + {{ definition.description }} + + + + + + + {{ error }} + + + + + + + Running report + + + + + + + + + CSV + + + + + + + + + + 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 @@ + + + + {{ total.label }} + {{ formatReportTotal(total, columns) }} + + + + + + + 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 @@ + + + {{ formatGeneratedAt(result.generatedAt) }} · {{ rowCountText }} + + + + No rows match these parameters. + + + + + + {{ group.label }} + + + + + {{ chart.title }} + + + + + + + + {{ pivot.title }} + + + + + {{ chart.title }} + + + + + + + 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
{{ definition.description }}
{{ formatGeneratedAt(result.generatedAt) }} · {{ rowCountText }}