Просмотр исходного кода

Count revenue and tax on the invoice date and payments on the day they were received (#673)

* Count revenue and tax on the invoice date and payments on the day they were received

* Keep a month's collected total when a payment arrives after the job was marked paid

* Backdate a spec's job invoice date along with its start for the tax report
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
3067a28aa5

+ 9 - 5
e2e/support/db.ts

@@ -445,15 +445,19 @@ export async function latestAttachmentUrl(serviceRecordId: string): Promise<stri
 }
 }
 
 
 /**
 /**
- * Backdates a job's scheduled start to an hour ago. A new work order is
- * booked into the shop's next free slot, often tomorrow, and the financial
- * reports run up to the present moment, so a job made by a spec is not in
- * this year's tax report until it is moved into the past.
+ * Backdates a job's scheduled start, and its invoice date when it has one, to
+ * an hour ago. A new work order is booked into the shop's next free slot,
+ * often tomorrow, and the financial reports run up to the present moment and
+ * count a job on its invoice date, so a job made by a spec is not in this
+ * year's tax report until both are moved into the past.
  */
  */
 export async function scheduleServiceRecordInThePast(serviceRecordId: string): Promise<void> {
 export async function scheduleServiceRecordInThePast(serviceRecordId: string): Promise<void> {
   await withDb((db) =>
   await withDb((db) =>
     db.query(
     db.query(
-      `update service_records set "startDateTime" = now() - interval '1 hour' where id = $1`,
+      `update service_records
+          set "startDateTime" = now() - interval '1 hour',
+              "invoiceDate" = case when "invoiceDate" is null then null else now() - interval '1 hour' end
+        where id = $1`,
       [serviceRecordId]
       [serviceRecordId]
     )
     )
   )
   )

+ 1 - 0
messages/bg/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Доставна стойност на резервните части, използвани при обслужванията",
     "partsCostDesc": "Доставна стойност на резервните части, използвани при обслужванията",
     "netProfitDesc": "Нетната печалба от резервни части плюс приходите от труд",
     "netProfitDesc": "Нетната печалба от резервни части плюс приходите от труд",
     "monthlyRevenue": "Месечни приходи",
     "monthlyRevenue": "Месечни приходи",
+    "dateBasisHint": "Приходите и данъците отчитат всяка фактура към датата ѝ на издаване. Събраното отчита всяко плащане в деня, в който е получено.",
     "revenueByType": "Приходи по вид",
     "revenueByType": "Приходи по вид",
     "monthlyBreakdown": "Разбивка по месеци",
     "monthlyBreakdown": "Разбивка по месеци",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/de/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Einkaufskosten der verwendeten Teile",
     "partsCostDesc": "Einkaufskosten der verwendeten Teile",
     "netProfitDesc": "Ersatzteil-Nettogewinn plus Arbeitsumsatz",
     "netProfitDesc": "Ersatzteil-Nettogewinn plus Arbeitsumsatz",
     "monthlyRevenue": "Monatlicher Umsatz",
     "monthlyRevenue": "Monatlicher Umsatz",
+    "dateBasisHint": "Umsatz und Steuer zählen jede Rechnung zu ihrem Rechnungsdatum. Eingenommen zählt jede Zahlung an dem Tag, an dem sie eingegangen ist.",
     "revenueByType": "Umsatz nach Typ",
     "revenueByType": "Umsatz nach Typ",
     "monthlyBreakdown": "Monatliche Aufschlüsselung",
     "monthlyBreakdown": "Monatliche Aufschlüsselung",
     "tableHeaders": {
     "tableHeaders": {

+ 3 - 2
messages/en/reports.json

@@ -50,13 +50,14 @@
     "laborRevenue": "Labor",
     "laborRevenue": "Labor",
     "laborRevenueDesc": "Revenue from labor charges",
     "laborRevenueDesc": "Revenue from labor charges",
     "netProfit": "Total Net Profit",
     "netProfit": "Total Net Profit",
-    "revenueDesc": "Total invoiced from all completed services",
+    "revenueDesc": "Total of the invoices dated in this period.",
     "collectedDesc": "Payments received from customers",
     "collectedDesc": "Payments received from customers",
-    "outstandingDesc": "Invoiced but not yet paid",
+    "outstandingDesc": "Still unpaid on invoices dated in this period.",
     "servicesDesc": "Total completed work orders",
     "servicesDesc": "Total completed work orders",
     "partsCostDesc": "Purchase cost of parts used in services",
     "partsCostDesc": "Purchase cost of parts used in services",
     "netProfitDesc": "Parts net profit plus labor revenue",
     "netProfitDesc": "Parts net profit plus labor revenue",
     "monthlyRevenue": "Monthly Revenue",
     "monthlyRevenue": "Monthly Revenue",
+    "dateBasisHint": "Revenue and tax count each invoice on its invoice date. Collected counts each payment on the day it was received.",
     "revenueByType": "Revenue by Type",
     "revenueByType": "Revenue by Type",
     "monthlyBreakdown": "Monthly Breakdown",
     "monthlyBreakdown": "Monthly Breakdown",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/es/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Coste de compra de piezas usadas en servicios",
     "partsCostDesc": "Coste de compra de piezas usadas en servicios",
     "netProfitDesc": "Beneficio neto de repuestos más ingresos de mano de obra",
     "netProfitDesc": "Beneficio neto de repuestos más ingresos de mano de obra",
     "monthlyRevenue": "Ingresos Mensuales",
     "monthlyRevenue": "Ingresos Mensuales",
+    "dateBasisHint": "Los ingresos y los impuestos cuentan cada factura en su fecha de factura. Lo cobrado cuenta cada pago el día en que se recibió.",
     "revenueByType": "Ingresos por Tipo",
     "revenueByType": "Ingresos por Tipo",
     "monthlyBreakdown": "Desglose Mensual",
     "monthlyBreakdown": "Desglose Mensual",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/fr/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Coût d'achat des pièces utilisées",
     "partsCostDesc": "Coût d'achat des pièces utilisées",
     "netProfitDesc": "Bénéfice net pièces plus revenus main-d'œuvre",
     "netProfitDesc": "Bénéfice net pièces plus revenus main-d'œuvre",
     "monthlyRevenue": "Revenus Mensuels",
     "monthlyRevenue": "Revenus Mensuels",
+    "dateBasisHint": "Le chiffre d’affaires et la taxe comptent chaque facture à sa date de facturation. L’encaissé compte chaque paiement le jour de sa réception.",
     "revenueByType": "Revenus par Type",
     "revenueByType": "Revenus par Type",
     "monthlyBreakdown": "Répartition Mensuelle",
     "monthlyBreakdown": "Répartition Mensuelle",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/it/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Costo di acquisto dei ricambi utilizzati",
     "partsCostDesc": "Costo di acquisto dei ricambi utilizzati",
     "netProfitDesc": "Profitto netto ricambi più ricavi manodopera",
     "netProfitDesc": "Profitto netto ricambi più ricavi manodopera",
     "monthlyRevenue": "Ricavi Mensili",
     "monthlyRevenue": "Ricavi Mensili",
+    "dateBasisHint": "Ricavi e imposte contano ogni fattura alla sua data di fattura. L’incassato conta ogni pagamento nel giorno in cui è stato ricevuto.",
     "revenueByType": "Ricavi per Tipo",
     "revenueByType": "Ricavi per Tipo",
     "monthlyBreakdown": "Riepilogo Mensile",
     "monthlyBreakdown": "Riepilogo Mensile",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/lt/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Paslaugose naudotų dalių pirkimo savikaina",
     "partsCostDesc": "Paslaugose naudotų dalių pirkimo savikaina",
     "netProfitDesc": "Dalių grynasis pelnas plius darbų pajamos",
     "netProfitDesc": "Dalių grynasis pelnas plius darbų pajamos",
     "monthlyRevenue": "Mėnesio pajamos",
     "monthlyRevenue": "Mėnesio pajamos",
+    "dateBasisHint": "Pajamos ir mokesčiai skaičiuojami pagal kiekvienos sąskaitos datą. Surinkta suma skaičiuojama pagal kiekvieno mokėjimo gavimo dieną.",
     "revenueByType": "Pajamos pagal tipą",
     "revenueByType": "Pajamos pagal tipą",
     "monthlyBreakdown": "Mėnesio suskirstymas",
     "monthlyBreakdown": "Mėnesio suskirstymas",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/nb/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Innkjøpskostnad for deler brukt i tjenester",
     "partsCostDesc": "Innkjøpskostnad for deler brukt i tjenester",
     "netProfitDesc": "Netto fortjeneste deler pluss arbeidsinntekter",
     "netProfitDesc": "Netto fortjeneste deler pluss arbeidsinntekter",
     "monthlyRevenue": "Månedlige Inntekter",
     "monthlyRevenue": "Månedlige Inntekter",
+    "dateBasisHint": "Inntekter og avgift teller hver faktura på fakturadatoen. Innbetalt teller hver betaling på dagen den ble mottatt.",
     "revenueByType": "Inntekter etter Type",
     "revenueByType": "Inntekter etter Type",
     "monthlyBreakdown": "Månedlig Oversikt",
     "monthlyBreakdown": "Månedlig Oversikt",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/nl/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Inkoopkosten van gebruikte onderdelen",
     "partsCostDesc": "Inkoopkosten van gebruikte onderdelen",
     "netProfitDesc": "Nettowinst onderdelen plus arbeidsinkomsten",
     "netProfitDesc": "Nettowinst onderdelen plus arbeidsinkomsten",
     "monthlyRevenue": "Maandelijkse Omzet",
     "monthlyRevenue": "Maandelijkse Omzet",
+    "dateBasisHint": "Omzet en btw tellen elke factuur op de factuurdatum. Ontvangen telt elke betaling op de dag dat die binnenkwam.",
     "revenueByType": "Omzet per Type",
     "revenueByType": "Omzet per Type",
     "monthlyBreakdown": "Maandelijks Overzicht",
     "monthlyBreakdown": "Maandelijks Overzicht",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/pl/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Koszt zakupu części użytych w usługach",
     "partsCostDesc": "Koszt zakupu części użytych w usługach",
     "netProfitDesc": "Zysk netto z części plus przychód z robocizny",
     "netProfitDesc": "Zysk netto z części plus przychód z robocizny",
     "monthlyRevenue": "Przychody Miesięczne",
     "monthlyRevenue": "Przychody Miesięczne",
+    "dateBasisHint": "Przychody i podatek liczą każdą fakturę według daty faktury. Wpłacone liczy każdą płatność w dniu jej otrzymania.",
     "revenueByType": "Przychody wg Typu",
     "revenueByType": "Przychody wg Typu",
     "monthlyBreakdown": "Zestawienie Miesięczne",
     "monthlyBreakdown": "Zestawienie Miesięczne",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/pt-BR/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Custo de compra das peças usadas nos serviços",
     "partsCostDesc": "Custo de compra das peças usadas nos serviços",
     "netProfitDesc": "Lucro líquido de peças mais receita de mão de obra",
     "netProfitDesc": "Lucro líquido de peças mais receita de mão de obra",
     "monthlyRevenue": "Receita Mensal",
     "monthlyRevenue": "Receita Mensal",
+    "dateBasisHint": "Receita e impostos contam cada fatura na data da fatura. Recebido conta cada pagamento no dia em que foi recebido.",
     "revenueByType": "Receita por Tipo",
     "revenueByType": "Receita por Tipo",
     "monthlyBreakdown": "Detalhamento Mensal",
     "monthlyBreakdown": "Detalhamento Mensal",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/pt-PT/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Custo de compra das peças usadas nos serviços",
     "partsCostDesc": "Custo de compra das peças usadas nos serviços",
     "netProfitDesc": "Lucro líquido das peças mais a receita de mão de obra",
     "netProfitDesc": "Lucro líquido das peças mais a receita de mão de obra",
     "monthlyRevenue": "Receita mensal",
     "monthlyRevenue": "Receita mensal",
+    "dateBasisHint": "A receita e os impostos contam cada fatura na data da fatura. O recebido conta cada pagamento no dia em que foi recebido.",
     "revenueByType": "Receita por tipo",
     "revenueByType": "Receita por tipo",
     "monthlyBreakdown": "Detalhe mensal",
     "monthlyBreakdown": "Detalhe mensal",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/ru/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Закупочная стоимость запчастей, использованных в услугах",
     "partsCostDesc": "Закупочная стоимость запчастей, использованных в услугах",
     "netProfitDesc": "Чистая прибыль по запчастям плюс доход от работ",
     "netProfitDesc": "Чистая прибыль по запчастям плюс доход от работ",
     "monthlyRevenue": "Ежемесячный доход",
     "monthlyRevenue": "Ежемесячный доход",
+    "dateBasisHint": "Доход и налог учитывают каждый счёт по дате счёта. Получено учитывает каждый платёж в день его поступления.",
     "revenueByType": "Доход по типам",
     "revenueByType": "Доход по типам",
     "monthlyBreakdown": "Помесячная разбивка",
     "monthlyBreakdown": "Помесячная разбивка",
     "tableHeaders": {
     "tableHeaders": {

+ 1 - 0
messages/tr/reports.json

@@ -57,6 +57,7 @@
     "partsCostDesc": "Servislerde kullanılan parçaların alış maliyeti",
     "partsCostDesc": "Servislerde kullanılan parçaların alış maliyeti",
     "netProfitDesc": "Parça net kârı artı işçilik geliri",
     "netProfitDesc": "Parça net kârı artı işçilik geliri",
     "monthlyRevenue": "Aylık Gelir",
     "monthlyRevenue": "Aylık Gelir",
+    "dateBasisHint": "Gelir ve vergi her faturayı fatura tarihinde sayar. Tahsil edilen her ödemeyi alındığı günde sayar.",
     "revenueByType": "Türe Göre Gelir",
     "revenueByType": "Türe Göre Gelir",
     "monthlyBreakdown": "Aylık Döküm",
     "monthlyBreakdown": "Aylık Döküm",
     "tableHeaders": {
     "tableHeaders": {

+ 246 - 0
src/__tests__/db/report-date-basis.db.test.ts

@@ -0,0 +1,246 @@
+/**
+ * The report date filters on a real PostgreSQL (`npm run test:db` with
+ * E2E_DATABASE_URL set).
+ *
+ * The unit tests check the filters' shape. This runs them: a job with an
+ * invoice date counts on it, one without falls back to its start and then
+ * its service date, and the end of the window is exclusive. A null that
+ * Prisma reads differently from what the reports mean shows up here as a
+ * job in the wrong report instead of in a workshop's tax return.
+ *
+ * It makes one workshop of its own and removes it again; it empties nothing.
+ */
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+const url = process.env.E2E_DATABASE_URL ?? ''
+const databaseName = url.split('/').pop()?.split('?')[0]?.toLowerCase() ?? ''
+if (url && !/test|e2e/.test(databaseName)) {
+  throw new Error(
+    `Refusing to use database "${databaseName}": its name must say test or e2e, like the rest of this suite.`
+  )
+}
+
+// Set before the app's modules load, so the client connects to the test database.
+process.env.DATABASE_URL = url
+
+const stamp = randomUUID().slice(0, 8)
+
+let db: typeof import('@/lib/db')['db']
+let dates: typeof import('@/features/reports/Lib/reportDates')
+let organizationId = ''
+
+/** November 2026, end exclusive. */
+const RANGE = { gte: new Date('2026-11-01T00:00:00Z'), lt: new Date('2026-12-01T00:00:00Z') }
+const SEP = new Date('2026-09-10T10:00:00Z')
+const OCT = new Date('2026-10-10T10:00:00Z')
+const NOV = new Date('2026-11-10T10:00:00Z')
+
+interface Row {
+  title: string
+  serviceDate: Date
+  startDateTime: Date | null
+  invoiceDate: Date | null
+  manuallyPaid?: boolean
+  manuallyPaidAt?: Date | null
+  /** Counts in November by its document date (revenue, tax). */
+  document: boolean
+  /** Counts in November by its work date (jobs, hours, parts). */
+  work: boolean
+  /** Counts as marked paid by hand in November. */
+  manual?: boolean
+}
+
+const ROWS: Row[] = [
+  // Started in September, invoiced in November.
+  {
+    title: 'invoiced-in',
+    serviceDate: SEP,
+    startDateTime: SEP,
+    invoiceDate: NOV,
+    document: true,
+    work: false,
+  },
+  // Started in November, invoiced in September: the invoice date wins.
+  {
+    title: 'invoiced-before',
+    serviceDate: NOV,
+    startDateTime: NOV,
+    invoiceDate: SEP,
+    document: false,
+    work: true,
+  },
+  // Not invoiced yet: counts on its start.
+  {
+    title: 'uninvoiced-started-in',
+    serviceDate: SEP,
+    startDateTime: NOV,
+    invoiceDate: null,
+    document: true,
+    work: true,
+  },
+  // A start outside the window is not overridden by a service date inside it.
+  {
+    title: 'uninvoiced-started-before',
+    serviceDate: NOV,
+    startDateTime: SEP,
+    invoiceDate: null,
+    document: false,
+    work: false,
+  },
+  // Legacy: neither date, counts on its service date.
+  {
+    title: 'legacy-in',
+    serviceDate: NOV,
+    startDateTime: null,
+    invoiceDate: null,
+    document: true,
+    work: true,
+  },
+  {
+    title: 'legacy-before',
+    serviceDate: OCT,
+    startDateTime: null,
+    invoiceDate: null,
+    document: false,
+    work: false,
+  },
+  // Invoiced in November with no start: in by document, out by work (service date in September).
+  {
+    title: 'invoiced-no-start',
+    serviceDate: SEP,
+    startDateTime: null,
+    invoiceDate: NOV,
+    document: true,
+    work: false,
+  },
+  // The window's edges: the first instant is in, the end is not.
+  {
+    title: 'edge-start',
+    serviceDate: SEP,
+    startDateTime: SEP,
+    invoiceDate: RANGE.gte,
+    document: true,
+    work: false,
+  },
+  {
+    title: 'edge-end',
+    serviceDate: SEP,
+    startDateTime: RANGE.lt,
+    invoiceDate: RANGE.lt,
+    document: false,
+    work: false,
+  },
+  // Marked paid by hand in November on a September invoice.
+  {
+    title: 'manual-marked-in',
+    serviceDate: SEP,
+    startDateTime: SEP,
+    invoiceDate: SEP,
+    manuallyPaid: true,
+    manuallyPaidAt: NOV,
+    document: false,
+    work: false,
+    manual: true,
+  },
+  // Marked in October on a November invoice: the day it was marked wins.
+  {
+    title: 'manual-marked-before',
+    serviceDate: NOV,
+    startDateTime: NOV,
+    invoiceDate: NOV,
+    manuallyPaid: true,
+    manuallyPaidAt: OCT,
+    document: true,
+    work: true,
+    manual: false,
+  },
+  // Marked before that day was recorded: falls back to the document date.
+  {
+    title: 'manual-unrecorded-in',
+    serviceDate: SEP,
+    startDateTime: SEP,
+    invoiceDate: NOV,
+    manuallyPaid: true,
+    manuallyPaidAt: null,
+    document: true,
+    work: false,
+    manual: true,
+  },
+  {
+    title: 'manual-unrecorded-before',
+    serviceDate: NOV,
+    startDateTime: NOV,
+    invoiceDate: SEP,
+    manuallyPaid: true,
+    manuallyPaidAt: null,
+    document: false,
+    work: true,
+    manual: false,
+  },
+]
+
+beforeAll(async () => {
+  ;({ db } = await import('@/lib/db'))
+  dates = await import('@/features/reports/Lib/reportDates')
+  const organization = await db.organization.create({ data: { name: `Report dates ${stamp}` } })
+  organizationId = organization.id
+  for (const row of ROWS) {
+    await db.serviceRecord.create({
+      data: {
+        organizationId,
+        title: row.title,
+        serviceDate: row.serviceDate,
+        startDateTime: row.startDateTime,
+        invoiceDate: row.invoiceDate,
+        manuallyPaid: row.manuallyPaid ?? false,
+        manuallyPaidAt: row.manuallyPaidAt ?? null,
+      },
+    })
+  }
+})
+
+afterAll(async () => {
+  // The jobs go with the workshop.
+  if (organizationId) await db.organization.deleteMany({ where: { id: organizationId } })
+})
+
+async function titles(filter: ReturnType<typeof dates.documentDateIn>) {
+  const rows = await db.serviceRecord.findMany({
+    where: { organizationId, AND: [filter] },
+    select: { title: true },
+  })
+  return rows.map((r) => r.title).sort()
+}
+
+const expected = (pick: (row: Row) => boolean | undefined) =>
+  ROWS.filter((row) => pick(row))
+    .map((row) => row.title)
+    .sort()
+
+describe('the report date filters on PostgreSQL', () => {
+  it('finds the jobs whose document date is in the window', async () => {
+    expect(await titles(dates.documentDateIn(RANGE))).toEqual(expected((r) => r.document))
+  })
+
+  it('finds the jobs whose work date is in the window', async () => {
+    expect(await titles(dates.workDateIn(RANGE))).toEqual(expected((r) => r.work))
+  })
+
+  it('finds the jobs marked paid by hand in the window', async () => {
+    expect(await titles(dates.manualPaidIn(RANGE))).toEqual(expected((r) => r.manual))
+  })
+
+  it('agrees with documentDateOf and workDateOf on every row', async () => {
+    const rows = await db.serviceRecord.findMany({
+      where: { organizationId },
+      select: { title: true, serviceDate: true, startDateTime: true, invoiceDate: true },
+    })
+    const inRange = (d: Date) => d >= RANGE.gte && d < RANGE.lt
+    for (const row of rows) {
+      const want = ROWS.find((r) => r.title === row.title)!
+      expect(inRange(dates.documentDateOf(row)), row.title).toBe(want.document)
+      expect(inRange(dates.workDateOf(row)), row.title).toBe(want.work)
+    }
+  })
+})

+ 11 - 0
src/__tests__/features/reports/completed-only.test.ts

@@ -13,6 +13,7 @@ vi.mock('@/lib/db', () => ({
   db: {
   db: {
     user: { findUnique: vi.fn() },
     user: { findUnique: vi.fn() },
     serviceRecord: { findMany: vi.fn() },
     serviceRecord: { findMany: vi.fn() },
+    payment: { findMany: vi.fn() },
     $queryRaw: vi.fn(),
     $queryRaw: vi.fn(),
   },
   },
 }))
 }))
@@ -39,6 +40,7 @@ beforeEach(() => {
   vi.resetAllMocks()
   vi.resetAllMocks()
   setupAuth()
   setupAuth()
   vi.mocked(db.serviceRecord.findMany).mockResolvedValue([])
   vi.mocked(db.serviceRecord.findMany).mockResolvedValue([])
+  vi.mocked(db.payment.findMany).mockResolvedValue([])
 })
 })
 
 
 describe('reports', () => {
 describe('reports', () => {
@@ -47,6 +49,15 @@ describe('reports', () => {
     expect(whereOf().status).toBeUndefined()
     expect(whereOf().status).toBeUndefined()
   })
   })
 
 
+  it('count only payments on completed jobs, and jobs marked paid by hand, when the switch is on', async () => {
+    await getRevenueReport({ startDate: '2026-01-01', endDate: '2026-01-31', completedOnly: true })
+    const wheres = vi.mocked(db.serviceRecord.findMany).mock.calls.map((c) => (c[0] as any).where)
+    expect(wheres).toHaveLength(2)
+    for (const where of wheres) expect(where.status).toBe('completed')
+    const paymentWhere = (vi.mocked(db.payment.findMany).mock.calls[0][0] as any).where
+    expect(paymentWhere.serviceRecord).toEqual({ organizationId: 'org-1', status: 'completed' })
+  })
+
   it('count only completed jobs when the switch is on', async () => {
   it('count only completed jobs when the switch is on', async () => {
     await getServiceReport({ startDate: '2026-01-01', endDate: '2026-01-31', completedOnly: true })
     await getServiceReport({ startDate: '2026-01-01', endDate: '2026-01-31', completedOnly: true })
     expect(whereOf().status).toBe('completed')
     expect(whereOf().status).toBe('completed')

+ 383 - 0
src/__tests__/features/reports/report-date-basis.test.ts

@@ -0,0 +1,383 @@
+/**
+ * Which month a job counts in on the revenue and tax reports.
+ *
+ * Revenue and tax follow the invoice date, not the day the job started: a
+ * job opened in September and invoiced in November is November's revenue.
+ * Collected follows each payment's own date. The workshop here is in
+ * Auckland, so every instant below sits on a different day there than in UTC.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+// A plain function, so resetAllMocks cannot blank it.
+vi.mock('@/lib/workshop-timezone', () => ({ workshopTimeZone: async () => 'Pacific/Auckland' }))
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    serviceRecord: { findMany: vi.fn() },
+    payment: { findMany: vi.fn() },
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import {
+  getRevenueReport,
+  getServiceReport,
+  getTaxReport,
+  getTechnicianReport,
+} from '@/features/reports/Actions/reportActions'
+
+/** 31 Aug 13:00Z is 1 Sep 01:00 in Auckland (NZST, +12). */
+const SEP_1 = new Date('2026-08-31T13:00:00Z')
+/** 14 Sep 12:00Z is 15 Sep 00:00 in Auckland. */
+const SEP_15 = new Date('2026-09-14T12:00:00Z')
+/** 31 Oct 12:00Z is 1 Nov 01:00 in Auckland (NZDT, +13): October in UTC, November there. */
+const NOV_1 = new Date('2026-10-31T12:00:00Z')
+/** 19 Nov 12:00Z is 20 Nov 01:00 in Auckland. */
+const NOV_20 = new Date('2026-11-19T12:00:00Z')
+
+/** 1 Sep to 30 Nov on the workshop's calendar. */
+const WINDOW = { startDate: '2026-09-01', endDate: '2026-11-30' }
+/** The same window as instants: Auckland midnight on 1 Sep, and on 1 Dec (exclusive). */
+const RANGE = {
+  gte: new Date('2026-08-31T12:00:00.000Z'),
+  lt: new Date('2026-11-30T11:00:00.000Z'),
+}
+
+function job(fields: Record<string, unknown>) {
+  return {
+    serviceDate: SEP_1,
+    startDateTime: SEP_1,
+    invoiceDate: null,
+    totalAmount: 1000,
+    cost: 0,
+    type: 'repair',
+    taxRate: 0,
+    taxInclusive: false,
+    subtotal: 1000,
+    discountAmount: 0,
+    manuallyPaid: false,
+    manuallyPaidAt: null,
+    payments: [],
+    partItems: [],
+    laborItems: [],
+    ...fields,
+  }
+}
+
+const isManualQuery = (args: any) =>
+  (args?.where?.AND ?? []).some((c: any) => c.manuallyPaid === true)
+
+/** The invoices query answers `invoices`, the paid-by-hand query `manual`. */
+function seed({
+  invoices = [],
+  manual = [],
+  payments = [],
+}: {
+  invoices?: unknown[]
+  manual?: unknown[]
+  payments?: { amount: number; date: Date }[]
+}) {
+  vi.mocked(db.serviceRecord.findMany).mockImplementation((async (args: any) =>
+    isManualQuery(args) ? manual : invoices) as any)
+  vi.mocked(db.payment.findMany).mockResolvedValue(payments as any)
+}
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  vi.mocked(getCachedSession).mockResolvedValue({ user: { id: 'u1', email: 'a@b.c' } } as any)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: 'org-1',
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as any)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as any)
+  seed({})
+})
+
+const months = (data: any) =>
+  data.monthly.map((m: any) => ({ month: m.month, revenue: m.revenue, collected: m.collected }))
+
+describe('revenue', () => {
+  it('asks for invoices dated in the workshop window, falling back to start and service date', async () => {
+    await getRevenueReport(WINDOW)
+
+    const where = (vi.mocked(db.serviceRecord.findMany).mock.calls[0][0] as any).where
+    expect(where.AND).toEqual([
+      {
+        OR: [
+          { invoiceDate: RANGE },
+          { invoiceDate: null, startDateTime: RANGE },
+          { invoiceDate: null, startDateTime: null, serviceDate: RANGE },
+        ],
+      },
+    ])
+    const paymentWhere = (vi.mocked(db.payment.findMany).mock.calls[0][0] as any).where
+    expect(paymentWhere).toEqual({ date: RANGE, serviceRecord: { organizationId: 'org-1' } })
+  })
+
+  it('counts a job started in September and invoiced in November in November', async () => {
+    seed({ invoices: [job({ startDateTime: SEP_1, invoiceDate: NOV_1 })] })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([{ month: '2026-11', revenue: 1000, collected: 0 }])
+  })
+
+  it('counts a November payment on a September invoice as collected in November', async () => {
+    seed({
+      invoices: [job({ invoiceDate: SEP_15, payments: [{ amount: 400 }] })],
+      payments: [{ amount: 400, date: NOV_1 }],
+    })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([
+      { month: '2026-09', revenue: 1000, collected: 0 },
+      { month: '2026-11', revenue: 0, collected: 400 },
+    ])
+    expect(data?.summary.totalCollected).toBe(400)
+    expect(data?.summary.outstanding).toBe(600)
+  })
+
+  it('puts the months in order whatever order the rows come in', async () => {
+    seed({
+      invoices: [job({ invoiceDate: NOV_20 }), job({ invoiceDate: SEP_15 })],
+      payments: [{ amount: 50, date: NOV_1 }],
+    })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(data?.monthly.map((m: any) => m.month)).toEqual(['2026-09', '2026-11'])
+  })
+
+  it('counts a job with neither an invoice date nor a start on its service date', async () => {
+    seed({ invoices: [job({ invoiceDate: null, startDateTime: null, serviceDate: NOV_1 })] })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([{ month: '2026-11', revenue: 1000, collected: 0 }])
+  })
+
+  it('counts a payment refunded through the ledger off what was collected', async () => {
+    seed({
+      payments: [
+        { amount: 100, date: NOV_1 },
+        { amount: -40, date: NOV_20 },
+      ],
+    })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(data?.summary.totalCollected).toBe(60)
+    expect(months(data)).toEqual([{ month: '2026-11', revenue: 0, collected: 60 }])
+  })
+})
+
+describe('jobs marked paid by hand', () => {
+  it('count as collected on the day they were marked', async () => {
+    seed({
+      manual: [job({ invoiceDate: SEP_15, manuallyPaid: true, manuallyPaidAt: NOV_1 })],
+    })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([{ month: '2026-11', revenue: 0, collected: 1000 }])
+  })
+
+  it('count on the invoice date when marked before that day was recorded', async () => {
+    seed({ manual: [job({ invoiceDate: SEP_15, manuallyPaid: true, manuallyPaidAt: null })] })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([{ month: '2026-09', revenue: 0, collected: 1000 }])
+  })
+
+  it('add only what the payments did not cover', async () => {
+    seed({
+      manual: [
+        job({
+          totalAmount: 200,
+          invoiceDate: SEP_15,
+          manuallyPaid: true,
+          manuallyPaidAt: NOV_1,
+          payments: [{ amount: 50, date: SEP_15 }],
+        }),
+      ],
+      payments: [{ amount: 50, date: SEP_15 }],
+    })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([
+      { month: '2026-09', revenue: 0, collected: 50 },
+      { month: '2026-11', revenue: 0, collected: 150 },
+    ])
+    expect(data?.summary.totalCollected).toBe(200)
+  })
+
+  /** 1000 marked paid on 15 September, then `later` arrives on 1 November. */
+  const markedInSeptember = (later: number) => {
+    const payment = { amount: later, date: NOV_1 }
+    seed({
+      manual: [
+        job({
+          invoiceDate: SEP_15,
+          manuallyPaid: true,
+          manuallyPaidAt: SEP_15,
+          payments: [payment],
+        }),
+      ],
+      payments: [payment],
+    })
+  }
+
+  it('keep September as it was when a refund arrives after the job was marked paid', async () => {
+    markedInSeptember(-100)
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([
+      { month: '2026-09', revenue: 0, collected: 1000 },
+      { month: '2026-11', revenue: 0, collected: -100 },
+    ])
+  })
+
+  it('keep September as it was when a payment arrives after the job was marked paid', async () => {
+    markedInSeptember(300)
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([
+      { month: '2026-09', revenue: 0, collected: 1000 },
+      { month: '2026-11', revenue: 0, collected: 300 },
+    ])
+  })
+
+  it('take every payment off when the day it was marked was not recorded', async () => {
+    const payment = { amount: 300, date: NOV_1 }
+    seed({
+      manual: [
+        job({
+          invoiceDate: SEP_15,
+          manuallyPaid: true,
+          manuallyPaidAt: null,
+          payments: [payment],
+        }),
+      ],
+      payments: [payment],
+    })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(months(data)).toEqual([
+      { month: '2026-09', revenue: 0, collected: 700 },
+      { month: '2026-11', revenue: 0, collected: 300 },
+    ])
+  })
+
+  it('ask for jobs marked in the window, or unmarked-date jobs dated in it', async () => {
+    await getRevenueReport(WINDOW)
+
+    const manualCall = vi
+      .mocked(db.serviceRecord.findMany)
+      .mock.calls.find(([args]) => isManualQuery(args))
+    expect((manualCall?.[0] as any).where.AND[0]).toEqual({
+      manuallyPaid: true,
+      OR: [
+        { manuallyPaidAt: RANGE },
+        {
+          manuallyPaidAt: null,
+          AND: [
+            {
+              OR: [
+                { invoiceDate: RANGE },
+                { invoiceDate: null, startDateTime: RANGE },
+                { invoiceDate: null, startDateTime: null, serviceDate: RANGE },
+              ],
+            },
+          ],
+        },
+      ],
+    })
+  })
+})
+
+describe('outstanding', () => {
+  it('is what is still unpaid on each invoice in the window, never below nothing', async () => {
+    seed({
+      invoices: [
+        // Overpaid: owes nothing, and does not cancel out what the next one owes.
+        job({ totalAmount: 100, invoiceDate: SEP_15, payments: [{ amount: 150 }] }),
+        job({ totalAmount: 200, invoiceDate: NOV_1, payments: [{ amount: 50 }] }),
+        // Marked paid by hand: owes nothing.
+        job({ totalAmount: 300, invoiceDate: NOV_1, manuallyPaid: true }),
+      ],
+    })
+
+    const { data } = await getRevenueReport(WINDOW)
+
+    expect(data?.summary.outstanding).toBe(150)
+  })
+})
+
+describe('tax', () => {
+  const taxed = (fields: Record<string, unknown>) => ({
+    serviceDate: SEP_1,
+    startDateTime: SEP_1,
+    invoiceDate: null,
+    subtotal: 100,
+    taxableSubtotal: 100,
+    taxRate: 25,
+    taxAmount: 25,
+    taxInclusive: false,
+    taxComponents: null,
+    totalAmount: 125,
+    ...fields,
+  })
+
+  it('counts each invoice in the month of its invoice date, months in order', async () => {
+    seed({
+      invoices: [
+        taxed({ startDateTime: SEP_1, invoiceDate: NOV_1 }),
+        taxed({ startDateTime: SEP_1, invoiceDate: SEP_15 }),
+      ],
+    })
+
+    const { data } = await getTaxReport(WINDOW)
+
+    expect(data?.monthly.map((m: any) => [m.month, m.taxCollected])).toEqual([
+      ['2026-09', 25],
+      ['2026-11', 25],
+    ])
+    const where = (vi.mocked(db.serviceRecord.findMany).mock.calls[0][0] as any).where
+    expect(where.AND[0].OR[0]).toEqual({ invoiceDate: RANGE })
+  })
+})
+
+describe('workload reports', () => {
+  const workDate = {
+    OR: [{ startDateTime: RANGE }, { startDateTime: null, serviceDate: RANGE }],
+  }
+
+  it('count a job with no start on its service date', async () => {
+    await getServiceReport(WINDOW)
+
+    const where = (vi.mocked(db.serviceRecord.findMany).mock.calls[0][0] as any).where
+    expect(where.AND).toEqual([workDate])
+    expect(where.startDateTime).toBeUndefined()
+  })
+
+  it('keep the technician filter beside the date filter', async () => {
+    await getTechnicianReport(WINDOW)
+
+    const where = (vi.mocked(db.serviceRecord.findMany).mock.calls[0][0] as any).where
+    expect(where.OR).toEqual([{ technicianId: { not: null } }, { techName: { not: null } }])
+    expect(where.AND).toEqual([workDate])
+  })
+})

+ 10 - 4
src/__tests__/features/reports/report-schedule-timezone.test.ts

@@ -32,6 +32,7 @@ vi.mock('@/lib/db', () => ({
     user: { findUnique: vi.fn(), findMany: vi.fn() },
     user: { findUnique: vi.fn(), findMany: vi.fn() },
     appSetting: { findMany: vi.fn() },
     appSetting: { findMany: vi.fn() },
     serviceRecord: { findMany: vi.fn() },
     serviceRecord: { findMany: vi.fn() },
+    payment: { findMany: vi.fn() },
     organization: { findUnique: vi.fn() },
     organization: { findUnique: vi.fn() },
     reportSchedule: { create: vi.fn(), update: vi.fn() },
     reportSchedule: { create: vi.fn(), update: vi.fn() },
   },
   },
@@ -108,6 +109,7 @@ describe('processOneSchedule', () => {
         laborItems: [],
         laborItems: [],
       },
       },
     ] as any)
     ] as any)
+    vi.mocked(db.payment.findMany).mockResolvedValue([] as any)
     vi.mocked(db.user.findMany).mockResolvedValue([] as any)
     vi.mocked(db.user.findMany).mockResolvedValue([] as any)
     vi.mocked(db.organization.findUnique).mockResolvedValue({ name: 'Shop' } as any)
     vi.mocked(db.organization.findUnique).mockResolvedValue({ name: 'Shop' } as any)
     vi.mocked(db.reportSchedule.update).mockResolvedValue({} as any)
     vi.mocked(db.reportSchedule.update).mockResolvedValue({} as any)
@@ -126,11 +128,15 @@ describe('processOneSchedule', () => {
       'America/Chicago'
       'America/Chicago'
     )
     )
 
 
-    const where = vi.mocked(db.serviceRecord.findMany).mock.calls[0][0]?.where as any
-    expect(where.startDateTime).toEqual({
+    // Whole days, the end exclusive: the start of tomorrow in Chicago.
+    const range = {
       gte: new Date('2026-06-24T05:00:00.000Z'),
       gte: new Date('2026-06-24T05:00:00.000Z'),
-      lte: new Date('2026-07-02T04:59:59.999Z'),
-    })
+      lt: new Date('2026-07-02T05:00:00.000Z'),
+    }
+    const where = vi.mocked(db.serviceRecord.findMany).mock.calls[0][0]?.where as any
+    expect(where.AND[0].OR[0]).toEqual({ invoiceDate: range })
+    const paymentWhere = vi.mocked(db.payment.findMany).mock.calls[0][0]?.where as any
+    expect(paymentWhere.date).toEqual(range)
 
 
     const element = vi.mocked(renderToBuffer).mock.calls[0][0] as any
     const element = vi.mocked(renderToBuffer).mock.calls[0][0] as any
     expect(element.props.dateRange).toBe('Jun 24, 2026 – Jul 1, 2026')
     expect(element.props.dateRange).toBe('Jun 24, 2026 – Jul 1, 2026')

+ 2 - 0
src/__tests__/features/reports/reports-tax.test.ts

@@ -30,6 +30,7 @@ vi.mock('@/lib/db', () => ({
   db: {
   db: {
     user: { findUnique: vi.fn() },
     user: { findUnique: vi.fn() },
     serviceRecord: { findMany: vi.fn() },
     serviceRecord: { findMany: vi.fn() },
+    payment: { findMany: vi.fn() },
     servicePart: { findMany: vi.fn() },
     servicePart: { findMany: vi.fn() },
     customer: { findMany: vi.fn() },
     customer: { findMany: vi.fn() },
     vehicle: { findFirst: vi.fn() },
     vehicle: { findFirst: vi.fn() },
@@ -64,6 +65,7 @@ function setupAuth() {
 
 
 beforeEach(() => {
 beforeEach(() => {
   vi.resetAllMocks()
   vi.resetAllMocks()
+  vi.mocked(db.payment.findMany).mockResolvedValue([])
 })
 })
 
 
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------

+ 2 - 0
src/app/(authenticated)/reports/reports-client.tsx

@@ -1136,6 +1136,7 @@ export default function ReportsClient({
                     </CardContent>
                     </CardContent>
                   </Card>
                   </Card>
                 </div>
                 </div>
+                <p className="text-xs text-muted-foreground">{t('revenue.dateBasisHint')}</p>
 
 
                 {/* Net Profit breakdown */}
                 {/* Net Profit breakdown */}
                 <AppCard title={t('revenue.netProfit')}>
                 <AppCard title={t('revenue.netProfit')}>
@@ -1523,6 +1524,7 @@ export default function ReportsClient({
                     </CardContent>
                     </CardContent>
                   </Card>
                   </Card>
                 </div>
                 </div>
+                <p className="text-xs text-muted-foreground">{t('revenue.dateBasisHint')}</p>
 
 
                 {taxData.monthly.length > 0 && (
                 {taxData.monthly.length > 0 && (
                   <AppCard title={t('tax.monthlyTaxCollected')}>
                   <AppCard title={t('tax.monthlyTaxCollected')}>

+ 22 - 187
src/features/reports/Actions/reportActions.ts

@@ -4,8 +4,9 @@ import { db } from '@/lib/db'
 import { listOrgEntries } from '@/features/time-tracking/Lib/timeEntries'
 import { listOrgEntries } from '@/features/time-tracking/Lib/timeEntries'
 import { withAuth } from '@/lib/with-auth'
 import { withAuth } from '@/lib/with-auth'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
-import { earnedLineTotal, netLineTotal, taxedNetAmountOf } from '@/lib/tax'
-import { TaxByRateTable } from '../Lib/taxByRate'
+import { earnedLineTotal, netLineTotal } from '@/lib/tax'
+import { computeRevenue, computeTax } from '../Lib/financialReports'
+import { workDateIn, workDateOf } from '../Lib/reportDates'
 import { zonedDate, zonedDayKey, zonedParts } from '@/lib/timezone'
 import { zonedDate, zonedDayKey, zonedParts } from '@/lib/timezone'
 import { workshopDayRange, workshopMonthKey } from '@/lib/workshop-datetime'
 import { workshopDayRange, workshopMonthKey } from '@/lib/workshop-datetime'
 import { isShopFeeLine } from '@/features/settings/Lib/shopFee'
 import { isShopFeeLine } from '@/features/settings/Lib/shopFee'
@@ -54,120 +55,9 @@ export async function getRevenueReport(params: ReportRange) {
   return withAuth(
   return withAuth(
     async ({ organizationId }) => {
     async ({ organizationId }) => {
       const { tz, start, end } = await reportWindow(organizationId, params)
       const { tz, start, end } = await reportWindow(organizationId, params)
-
-      const records = await db.serviceRecord.findMany({
-        where: {
-          organizationId,
-          startDateTime: { gte: start, lt: end },
-          ...statusScope(params.completedOnly),
-        },
-        select: {
-          serviceDate: true,
-          startDateTime: true,
-          totalAmount: true,
-          cost: true,
-          type: true,
-          taxRate: true,
-          taxInclusive: true,
-          subtotal: true,
-          discountAmount: true,
-          manuallyPaid: true,
-          payments: { select: { amount: true } },
-          partItems: { select: { unitCost: true, quantity: true, total: true, taxable: true } },
-          laborItems: { select: { total: true, taxable: true } },
-        },
-        orderBy: [{ startDateTime: { sort: 'asc', nulls: 'last' } }, { serviceDate: 'asc' }],
+      return computeRevenue(organizationId, { gte: start, lt: end }, tz, {
+        completedOnly: params.completedOnly,
       })
       })
-
-      // Monthly breakdown.
-      // `revenue` is the gross customer-facing total (what was charged).
-      // `partsRevenue` and `laborRevenue` are NET (pre-tax) and carry their
-      // share of the job's discount, so they add up consistently with
-      // `partsCost` (which is always net) for profit math.
-      const monthly: Record<
-        string,
-        {
-          revenue: number
-          collected: number
-          count: number
-          partsCost: number
-          partsRevenue: number
-          laborRevenue: number
-        }
-      > = {}
-      let totalRevenue = 0
-      let totalCollected = 0
-      let totalCount = 0
-      let totalPartsCost = 0
-      let totalPartsRevenue = 0
-      let totalLaborRevenue = 0
-
-      // Type breakdown
-      const byType: Record<string, { revenue: number; count: number }> = {}
-
-      for (const r of records) {
-        const total = r.totalAmount > 0 ? r.totalAmount : r.cost
-        const paid = r.manuallyPaid ? total : r.payments.reduce((s, p) => s + p.amount, 0)
-        const partsCost = r.partItems.reduce((s, p) => s + p.unitCost * p.quantity, 0)
-        const partsRevenue = r.partItems.reduce(
-          (s, p) => s + earnedLineTotal(p.total, r, p.taxable),
-          0
-        )
-        const laborRevenue = r.laborItems.reduce(
-          (s, l) => s + earnedLineTotal(l.total, r, l.taxable),
-          0
-        )
-        const _date = r.startDateTime ?? r.serviceDate
-        const month = workshopMonthKey(_date, tz)
-
-        if (!monthly[month])
-          monthly[month] = {
-            revenue: 0,
-            collected: 0,
-            count: 0,
-            partsCost: 0,
-            partsRevenue: 0,
-            laborRevenue: 0,
-          }
-        monthly[month].revenue += total
-        monthly[month].collected += paid
-        monthly[month].count += 1
-        monthly[month].partsCost += partsCost
-        monthly[month].partsRevenue += partsRevenue
-        monthly[month].laborRevenue += laborRevenue
-
-        totalRevenue += total
-        totalCollected += paid
-        totalCount += 1
-        totalPartsCost += partsCost
-        totalPartsRevenue += partsRevenue
-        totalLaborRevenue += laborRevenue
-
-        if (!byType[r.type]) byType[r.type] = { revenue: 0, count: 0 }
-        byType[r.type].revenue += total
-        byType[r.type].count += 1
-      }
-
-      return {
-        monthly: Object.entries(monthly).map(([month, data]) => ({
-          month,
-          ...data,
-          partsNetProfit: data.partsRevenue - data.partsCost,
-          netProfit: data.partsRevenue - data.partsCost + data.laborRevenue,
-        })),
-        byType: Object.entries(byType).map(([type, data]) => ({ type, ...data })),
-        summary: {
-          totalRevenue,
-          totalCollected,
-          outstanding: totalRevenue - totalCollected,
-          totalCount,
-          totalPartsCost,
-          totalPartsRevenue,
-          totalPartsNetProfit: totalPartsRevenue - totalPartsCost,
-          totalLaborRevenue,
-          netProfit: totalPartsRevenue - totalPartsCost + totalLaborRevenue,
-        },
-      }
     },
     },
     { requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.REPORTS }] }
     { requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.REPORTS }] }
   )
   )
@@ -181,7 +71,7 @@ export async function getServiceReport(params: ReportRange) {
       const records = await db.serviceRecord.findMany({
       const records = await db.serviceRecord.findMany({
         where: {
         where: {
           organizationId,
           organizationId,
-          startDateTime: { gte: start, lt: end },
+          AND: [workDateIn({ gte: start, lt: end })],
           ...statusScope(params.completedOnly),
           ...statusScope(params.completedOnly),
         },
         },
         select: {
         select: {
@@ -225,7 +115,7 @@ export async function getCustomerReport(params: ReportRange) {
             select: {
             select: {
               serviceRecords: {
               serviceRecords: {
                 where: {
                 where: {
-                  startDateTime: { gte: start, lt: end },
+                  AND: [workDateIn({ gte: start, lt: end })],
                   ...statusScope(params.completedOnly),
                   ...statusScope(params.completedOnly),
                 },
                 },
                 select: { totalAmount: true, cost: true },
                 select: { totalAmount: true, cost: true },
@@ -268,7 +158,7 @@ export async function getTechnicianReport(params: ReportRange) {
       const records = await db.serviceRecord.findMany({
       const records = await db.serviceRecord.findMany({
         where: {
         where: {
           organizationId,
           organizationId,
-          startDateTime: { gte: start, lt: end },
+          AND: [workDateIn({ gte: start, lt: end })],
           ...statusScope(params.completedOnly),
           ...statusScope(params.completedOnly),
           OR: [{ technicianId: { not: null } }, { techName: { not: null } }],
           OR: [{ technicianId: { not: null } }, { techName: { not: null } }],
         },
         },
@@ -343,7 +233,7 @@ export async function getTechnicianTimeReport(params: ReportRange) {
         db.serviceRecord.findMany({
         db.serviceRecord.findMany({
           where: {
           where: {
             organizationId,
             organizationId,
-            startDateTime: { gte: start, lt: end },
+            AND: [workDateIn({ gte: start, lt: end })],
             ...statusScope(params.completedOnly),
             ...statusScope(params.completedOnly),
             technicianId: { not: null },
             technicianId: { not: null },
           },
           },
@@ -465,7 +355,7 @@ export async function getPartsUsageReport(params: ReportRange) {
         where: {
         where: {
           serviceRecord: {
           serviceRecord: {
             organizationId,
             organizationId,
-            startDateTime: { gte: start, lt: end },
+            AND: [workDateIn({ gte: start, lt: end })],
             ...statusScope(params.completedOnly),
             ...statusScope(params.completedOnly),
           },
           },
         },
         },
@@ -560,7 +450,7 @@ export async function getJobAnalyticsReport(params: ReportRange) {
       const records = await db.serviceRecord.findMany({
       const records = await db.serviceRecord.findMany({
         where: {
         where: {
           organizationId,
           organizationId,
-          startDateTime: { gte: start, lt: end },
+          AND: [workDateIn({ gte: start, lt: end })],
           ...statusScope(params.completedOnly),
           ...statusScope(params.completedOnly),
         },
         },
         select: {
         select: {
@@ -611,15 +501,14 @@ export async function getJobAnalyticsReport(params: ReportRange) {
       ]
       ]
       const dayCount = [0, 0, 0, 0, 0, 0, 0]
       const dayCount = [0, 0, 0, 0, 0, 0, 0]
       for (const r of records) {
       for (const r of records) {
-        dayCount[zonedParts(r.startDateTime ?? r.serviceDate, tz).weekday] += 1
+        dayCount[zonedParts(workDateOf(r), tz).weekday] += 1
       }
       }
       const dayOfWeek = dayNames.map((day, i) => ({ day, count: dayCount[i] }))
       const dayOfWeek = dayNames.map((day, i) => ({ day, count: dayCount[i] }))
 
 
       // Monthly trend
       // Monthly trend
       const monthly: Record<string, { count: number; revenue: number }> = {}
       const monthly: Record<string, { count: number; revenue: number }> = {}
       for (const r of records) {
       for (const r of records) {
-        const _d = r.startDateTime ?? r.serviceDate
-        const month = workshopMonthKey(_d, tz)
+        const month = workshopMonthKey(workDateOf(r), tz)
         if (!monthly[month]) monthly[month] = { count: 0, revenue: 0 }
         if (!monthly[month]) monthly[month] = { count: 0, revenue: 0 }
         monthly[month].count += 1
         monthly[month].count += 1
         monthly[month].revenue += r.totalAmount > 0 ? r.totalAmount : r.cost
         monthly[month].revenue += r.totalAmount > 0 ? r.totalAmount : r.cost
@@ -655,7 +544,7 @@ export async function getCustomerRetentionReport(params: ReportRange) {
             select: {
             select: {
               serviceRecords: {
               serviceRecords: {
                 where: {
                 where: {
-                  startDateTime: { gte: start, lt: end },
+                  AND: [workDateIn({ gte: start, lt: end })],
                   ...statusScope(params.completedOnly),
                   ...statusScope(params.completedOnly),
                 },
                 },
                 select: { serviceDate: true, startDateTime: true, totalAmount: true, cost: true },
                 select: { serviceDate: true, startDateTime: true, totalAmount: true, cost: true },
@@ -686,7 +575,7 @@ export async function getCustomerRetentionReport(params: ReportRange) {
         for (const v of c.vehicles) {
         for (const v of c.vehicles) {
           for (const sr of v.serviceRecords) {
           for (const sr of v.serviceRecords) {
             visits.push({
             visits.push({
-              date: sr.startDateTime ?? sr.serviceDate,
+              date: workDateOf(sr),
               amount: sr.totalAmount > 0 ? sr.totalAmount : sr.cost,
               amount: sr.totalAmount > 0 ? sr.totalAmount : sr.cost,
             })
             })
           }
           }
@@ -909,7 +798,7 @@ export async function getVehicleReport(params: ReportRange & { vehicleId: string
         where: {
         where: {
           vehicleId: params.vehicleId,
           vehicleId: params.vehicleId,
           organizationId,
           organizationId,
-          startDateTime: { gte: start, lt: end },
+          AND: [workDateIn({ gte: start, lt: end })],
           ...statusScope(params.completedOnly),
           ...statusScope(params.completedOnly),
         },
         },
         select: {
         select: {
@@ -939,6 +828,8 @@ export async function getVehicleReport(params: ReportRange & { vehicleId: string
         },
         },
         orderBy: [{ startDateTime: { sort: 'desc', nulls: 'last' } }, { serviceDate: 'desc' }],
         orderBy: [{ startDateTime: { sort: 'desc', nulls: 'last' } }, { serviceDate: 'desc' }],
       })
       })
+      // Newest work first, a legacy job with no start among them by its service date.
+      records.sort((a, b) => workDateOf(b).getTime() - workDateOf(a).getTime())
 
 
       let totalCost = 0
       let totalCost = 0
       let totalPartsUsed = 0
       let totalPartsUsed = 0
@@ -973,8 +864,7 @@ export async function getVehicleReport(params: ReportRange & { vehicleId: string
         typeCounts[r.type].count += 1
         typeCounts[r.type].count += 1
         typeCounts[r.type].totalCost += total
         typeCounts[r.type].totalCost += total
 
 
-        const _d = r.startDateTime ?? r.serviceDate
-        const month = workshopMonthKey(_d, tz)
+        const month = workshopMonthKey(workDateOf(r), tz)
         if (!monthly[month]) monthly[month] = { partsCost: 0, laborCost: 0, totalCost: 0, count: 0 }
         if (!monthly[month]) monthly[month] = { partsCost: 0, laborCost: 0, totalCost: 0, count: 0 }
         monthly[month].partsCost += partsCost
         monthly[month].partsCost += partsCost
         monthly[month].laborCost += laborCost
         monthly[month].laborCost += laborCost
@@ -1034,7 +924,7 @@ export async function getVehicleReport(params: ReportRange & { vehicleId: string
           title: r.title,
           title: r.title,
           type: r.type,
           type: r.type,
           status: r.status,
           status: r.status,
-          date: zonedDayKey(r.startDateTime ?? r.serviceDate, tz),
+          date: zonedDayKey(workDateOf(r), tz),
           totalAmount: r.totalAmount > 0 ? r.totalAmount : r.cost,
           totalAmount: r.totalAmount > 0 ? r.totalAmount : r.cost,
           partsCount: r.partItems.reduce((s, p) => s + p.quantity, 0),
           partsCount: r.partItems.reduce((s, p) => s + p.quantity, 0),
           laborHours: r.laborItems.reduce((s, l) => s + laborHours(l), 0),
           laborHours: r.laborItems.reduce((s, l) => s + laborHours(l), 0),
@@ -1050,64 +940,9 @@ export async function getTaxReport(params: ReportRange) {
   return withAuth(
   return withAuth(
     async ({ organizationId }) => {
     async ({ organizationId }) => {
       const { tz, start, end } = await reportWindow(organizationId, params)
       const { tz, start, end } = await reportWindow(organizationId, params)
-
-      const records = await db.serviceRecord.findMany({
-        where: {
-          organizationId,
-          startDateTime: { gte: start, lt: end },
-          ...statusScope(params.completedOnly),
-        },
-        select: {
-          serviceDate: true,
-          startDateTime: true,
-          subtotal: true,
-          taxableSubtotal: true,
-          taxRate: true,
-          taxAmount: true,
-          taxInclusive: true,
-          taxComponents: true,
-          totalAmount: true,
-        },
-        orderBy: [{ startDateTime: { sort: 'asc', nulls: 'last' } }, { serviceDate: 'asc' }],
+      return computeTax(organizationId, { gte: start, lt: end }, tz, {
+        completedOnly: params.completedOnly,
       })
       })
-
-      const monthly: Record<
-        string,
-        { taxCollected: number; invoiceCount: number; taxableAmount: number }
-      > = {}
-      const byRate = new TaxByRateTable()
-      let totalTaxCollected = 0
-      let totalTaxableAmount = 0
-      let totalInvoices = 0
-
-      for (const r of records) {
-        if (r.taxAmount <= 0) continue
-
-        const _dt = r.startDateTime ?? r.serviceDate
-        const month = workshopMonthKey(_dt, tz)
-
-        // The taxable base = total - tax. This is the net amount on which tax
-        // was calculated, and it works in BOTH inclusive and exclusive modes
-        // (and accounts for any discount applied).
-        const taxableBase = taxedNetAmountOf(r)
-
-        if (!monthly[month]) monthly[month] = { taxCollected: 0, invoiceCount: 0, taxableAmount: 0 }
-        monthly[month].taxCollected += r.taxAmount
-        monthly[month].invoiceCount += 1
-        monthly[month].taxableAmount += taxableBase
-
-        byRate.add(r)
-
-        totalTaxCollected += r.taxAmount
-        totalTaxableAmount += taxableBase
-        totalInvoices += 1
-      }
-
-      return {
-        monthly: Object.entries(monthly).map(([month, data]) => ({ month, ...data })),
-        byRate: byRate.list(),
-        summary: { totalTaxCollected, totalTaxableAmount, totalInvoices },
-      }
     },
     },
     { requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.REPORTS }] }
     { requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.REPORTS }] }
   )
   )

+ 256 - 0
src/features/reports/Lib/financialReports.ts

@@ -0,0 +1,256 @@
+import { db } from '@/lib/db'
+import { earnedLineTotal, taxedNetAmountOf } from '@/lib/tax'
+import { workshopMonthKey } from '@/lib/workshop-datetime'
+import { type DateRange, documentDateIn, documentDateOf, manualPaidIn } from './reportDates'
+import { TaxByRateTable } from './taxByRate'
+
+/**
+ * The revenue and tax reports, shared by the reports screen and the
+ * scheduled report emails so the two cannot count differently.
+ *
+ * Revenue and tax count each invoice on its invoice date (see
+ * `documentDateOf`). Collected counts each payment on the day it was
+ * received, whichever month the invoice is in, and a job marked paid by
+ * hand on the day it was marked.
+ */
+
+export interface FinancialReportOptions {
+  /** Only work orders marked completed; open ones are left out. */
+  completedOnly?: boolean
+}
+
+function statusScope(options: FinancialReportOptions) {
+  return options.completedOnly ? { status: 'completed' } : {}
+}
+
+const chargedTotal = (r: { totalAmount: number; cost: number }) =>
+  r.totalAmount > 0 ? r.totalAmount : r.cost
+
+const sumPayments = (payments: { amount: number }[]) => payments.reduce((s, p) => s + p.amount, 0)
+
+/** Oldest invoice first, so the by-type and by-rate rows keep a steady order. */
+const byDocumentDate = <T extends Parameters<typeof documentDateOf>[0]>(records: T[]) =>
+  records
+    .map((r) => ({ r, at: documentDateOf(r).getTime() }))
+    .sort((a, b) => a.at - b.at)
+    .map(({ r }) => r)
+
+interface RevenueMonth {
+  revenue: number
+  collected: number
+  count: number
+  partsCost: number
+  partsRevenue: number
+  laborRevenue: number
+}
+
+export async function computeRevenue(
+  organizationId: string,
+  range: DateRange,
+  timeZone: string,
+  options: FinancialReportOptions = {}
+) {
+  const scope = statusScope(options)
+  const [records, payments, manuallyPaid] = await Promise.all([
+    // Invoices dated in the window: what was charged.
+    db.serviceRecord.findMany({
+      where: { organizationId, ...scope, AND: [documentDateIn(range)] },
+      select: {
+        serviceDate: true,
+        startDateTime: true,
+        invoiceDate: true,
+        totalAmount: true,
+        cost: true,
+        type: true,
+        taxRate: true,
+        taxInclusive: true,
+        subtotal: true,
+        discountAmount: true,
+        manuallyPaid: true,
+        payments: { select: { amount: true } },
+        partItems: { select: { unitCost: true, quantity: true, total: true, taxable: true } },
+        laborItems: { select: { total: true, taxable: true } },
+      },
+    }),
+    // Payments received in the window, whichever invoice they pay. A refund
+    // a ledger reported is a negative amount and comes off.
+    db.payment.findMany({
+      where: { date: range, serviceRecord: { organizationId, ...scope } },
+      select: { amount: true, date: true },
+    }),
+    // Jobs marked paid by hand in the window: the part no payment covers.
+    db.serviceRecord.findMany({
+      where: { organizationId, ...scope, AND: [manualPaidIn(range)] },
+      select: {
+        serviceDate: true,
+        startDateTime: true,
+        invoiceDate: true,
+        manuallyPaid: true,
+        manuallyPaidAt: true,
+        totalAmount: true,
+        cost: true,
+        payments: { select: { amount: true, date: true } },
+      },
+    }),
+  ])
+
+  // `revenue` is the gross customer-facing total (what was charged).
+  // `partsRevenue` and `laborRevenue` are NET (pre-tax) and carry their
+  // share of the job's discount, so they add up consistently with
+  // `partsCost` (which is always net) for profit math.
+  const monthly: Record<string, RevenueMonth> = {}
+  const month = (date: Date) => {
+    const key = workshopMonthKey(date, timeZone)
+    if (!monthly[key])
+      monthly[key] = {
+        revenue: 0,
+        collected: 0,
+        count: 0,
+        partsCost: 0,
+        partsRevenue: 0,
+        laborRevenue: 0,
+      }
+    return monthly[key]
+  }
+
+  let totalRevenue = 0
+  let totalCollected = 0
+  let outstanding = 0
+  let totalCount = 0
+  let totalPartsCost = 0
+  let totalPartsRevenue = 0
+  let totalLaborRevenue = 0
+  const byType: Record<string, { revenue: number; count: number }> = {}
+
+  for (const r of byDocumentDate(records)) {
+    const total = chargedTotal(r)
+    const partsCost = r.partItems.reduce((s, p) => s + p.unitCost * p.quantity, 0)
+    const partsRevenue = r.partItems.reduce((s, p) => s + earnedLineTotal(p.total, r, p.taxable), 0)
+    const laborRevenue = r.laborItems.reduce(
+      (s, l) => s + earnedLineTotal(l.total, r, l.taxable),
+      0
+    )
+
+    const m = month(documentDateOf(r))
+    m.revenue += total
+    m.count += 1
+    m.partsCost += partsCost
+    m.partsRevenue += partsRevenue
+    m.laborRevenue += laborRevenue
+
+    totalRevenue += total
+    totalCount += 1
+    totalPartsCost += partsCost
+    totalPartsRevenue += partsRevenue
+    totalLaborRevenue += laborRevenue
+    // Still owed on this invoice today, whenever it was paid.
+    if (!r.manuallyPaid) outstanding += Math.max(0, total - sumPayments(r.payments))
+
+    if (!byType[r.type]) byType[r.type] = { revenue: 0, count: 0 }
+    byType[r.type].revenue += total
+    byType[r.type].count += 1
+  }
+
+  for (const p of payments) {
+    month(p.date).collected += p.amount
+    totalCollected += p.amount
+  }
+
+  for (const r of manuallyPaid) {
+    if (!r.manuallyPaid) continue
+    // What the payments had covered when it was marked. A payment or refund
+    // after that counts in its own month, so a closed month never changes.
+    // Marked before that day was recorded: every payment, as there is no cut-off.
+    const markedAt = r.manuallyPaidAt
+    const coveredBefore = markedAt ? r.payments.filter((p) => p.date <= markedAt) : r.payments
+    const remainder = Math.max(0, chargedTotal(r) - sumPayments(coveredBefore))
+    if (remainder === 0) continue
+    month(r.manuallyPaidAt ?? documentDateOf(r)).collected += remainder
+    totalCollected += remainder
+  }
+
+  return {
+    monthly: Object.entries(monthly)
+      .sort(([a], [b]) => a.localeCompare(b))
+      .map(([key, data]) => ({
+        month: key,
+        ...data,
+        partsNetProfit: data.partsRevenue - data.partsCost,
+        netProfit: data.partsRevenue - data.partsCost + data.laborRevenue,
+      })),
+    byType: Object.entries(byType).map(([type, data]) => ({ type, ...data })),
+    summary: {
+      totalRevenue,
+      totalCollected,
+      outstanding,
+      totalCount,
+      totalPartsCost,
+      totalPartsRevenue,
+      totalPartsNetProfit: totalPartsRevenue - totalPartsCost,
+      totalLaborRevenue,
+      netProfit: totalPartsRevenue - totalPartsCost + totalLaborRevenue,
+    },
+  }
+}
+
+export async function computeTax(
+  organizationId: string,
+  range: DateRange,
+  timeZone: string,
+  options: FinancialReportOptions = {}
+) {
+  const records = await db.serviceRecord.findMany({
+    where: { organizationId, ...statusScope(options), AND: [documentDateIn(range)] },
+    select: {
+      serviceDate: true,
+      startDateTime: true,
+      invoiceDate: true,
+      subtotal: true,
+      taxableSubtotal: true,
+      taxRate: true,
+      taxAmount: true,
+      taxInclusive: true,
+      taxComponents: true,
+      totalAmount: true,
+    },
+  })
+
+  const monthly: Record<
+    string,
+    { taxCollected: number; invoiceCount: number; taxableAmount: number }
+  > = {}
+  const byRate = new TaxByRateTable()
+  let totalTaxCollected = 0
+  let totalTaxableAmount = 0
+  let totalInvoices = 0
+
+  for (const r of byDocumentDate(records)) {
+    if (r.taxAmount <= 0) continue
+
+    const month = workshopMonthKey(documentDateOf(r), timeZone)
+
+    // The taxable base = total - tax. This is the net amount on which tax
+    // was calculated, and it works in BOTH inclusive and exclusive modes
+    // (and accounts for any discount applied).
+    const taxableBase = taxedNetAmountOf(r)
+
+    if (!monthly[month]) monthly[month] = { taxCollected: 0, invoiceCount: 0, taxableAmount: 0 }
+    monthly[month].taxCollected += r.taxAmount
+    monthly[month].invoiceCount += 1
+    monthly[month].taxableAmount += taxableBase
+
+    byRate.add(r)
+
+    totalTaxCollected += r.taxAmount
+    totalTaxableAmount += taxableBase
+    totalInvoices += 1
+  }
+
+  return {
+    monthly: Object.entries(monthly)
+      .sort(([a], [b]) => a.localeCompare(b))
+      .map(([month, data]) => ({ month, ...data })),
+    byRate: byRate.list(),
+    summary: { totalTaxCollected, totalTaxableAmount, totalInvoices },
+  }
+}

+ 69 - 0
src/features/reports/Lib/reportDates.ts

@@ -0,0 +1,69 @@
+import type { Prisma } from '@/generated/prisma/client'
+import { effectiveInvoiceDate } from '@/lib/invoice-utils'
+
+/**
+ * Which day a work order counts on in a report.
+ *
+ * Money follows the invoice (accrual): revenue and tax count on the invoice
+ * date, the date the invoice is printed with. A job opened in September and
+ * invoiced in November is November's revenue. Before a job is invoiced it has
+ * no invoice date, so it counts on its start, and a legacy job with neither
+ * on its service date.
+ *
+ * Workload follows the work: jobs, hours, parts and customers count on the
+ * day the job started, or its service date when it has no start.
+ *
+ * The `...In` helpers are the same rules as Prisma filters. Each is an `OR`,
+ * so a caller puts it inside `AND: [...]` and never spreads it at the top
+ * level, where it would overwrite an `OR` of the caller's own.
+ */
+
+export interface DateRange {
+  gte: Date
+  lt: Date
+}
+
+type DocumentDated = {
+  invoiceDate?: Date | string | null
+  startDateTime?: Date | string | null
+  serviceDate: Date | string
+}
+
+/** The day a job's money counts on: its invoice date, else its start, else its service date. */
+export function documentDateOf(r: DocumentDated): Date {
+  return effectiveInvoiceDate(r)
+}
+
+/** Jobs whose document date (see `documentDateOf`) falls in the range. */
+export function documentDateIn(range: DateRange): Prisma.ServiceRecordWhereInput {
+  return {
+    OR: [
+      { invoiceDate: range },
+      { invoiceDate: null, startDateTime: range },
+      { invoiceDate: null, startDateTime: null, serviceDate: range },
+    ],
+  }
+}
+
+/** The day a job's work counts on: its start, else its service date. */
+export function workDateOf(r: { startDateTime?: Date | null; serviceDate: Date }): Date {
+  return r.startDateTime ?? r.serviceDate
+}
+
+/** Jobs whose work date (see `workDateOf`) falls in the range. */
+export function workDateIn(range: DateRange): Prisma.ServiceRecordWhereInput {
+  return {
+    OR: [{ startDateTime: range }, { startDateTime: null, serviceDate: range }],
+  }
+}
+
+/**
+ * Jobs marked paid by hand in the range: on the day they were marked, or,
+ * for a job marked before that day was recorded, on its document date.
+ */
+export function manualPaidIn(range: DateRange): Prisma.ServiceRecordWhereInput {
+  return {
+    manuallyPaid: true,
+    OR: [{ manuallyPaidAt: range }, { manuallyPaidAt: null, AND: [documentDateIn(range)] }],
+  }
+}

+ 24 - 164
src/lib/cron/report-schedules.ts

@@ -7,8 +7,9 @@ import React from 'react'
 import { sendOrgMail, getOrgFromAddress } from '@/lib/email'
 import { sendOrgMail, getOrgFromAddress } from '@/lib/email'
 import { ReportPDF } from '@/features/reports/Components/ReportPDF'
 import { ReportPDF } from '@/features/reports/Components/ReportPDF'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
-import { earnedLineTotal, taxedNetAmountOf } from '@/lib/tax'
-import { TaxByRateTable } from '@/features/reports/Lib/taxByRate'
+import { earnedLineTotal } from '@/lib/tax'
+import { computeRevenue, computeTax } from '@/features/reports/Lib/financialReports'
+import { workDateIn, workDateOf } from '@/features/reports/Lib/reportDates'
 import {
 import {
   addZonedDays,
   addZonedDays,
   atZonedTime,
   atZonedTime,
@@ -62,10 +63,13 @@ function calculateNextRunDate(current: Date, frequency: string, timeZone: string
   return atZonedTime(next, '08:00', timeZone)
   return atZonedTime(next, '08:00', timeZone)
 }
 }
 
 
-/** Whole workshop days, from the start of the period to the end of today. */
+/**
+ * Whole workshop days, from the start of the period to the end of today.
+ * `end` is exclusive, the start of tomorrow: query with `lt`.
+ */
 function getDateRange(dateRange: string, now: Date, timeZone: string): { start: Date; end: Date } {
 function getDateRange(dateRange: string, now: Date, timeZone: string): { start: Date; end: Date } {
   const today = startOfZonedDay(now, timeZone)
   const today = startOfZonedDay(now, timeZone)
-  const end = new Date(addZonedDays(today, 1, timeZone).getTime() - 1)
+  const end = addZonedDays(today, 1, timeZone)
   let start: Date
   let start: Date
 
 
   switch (dateRange) {
   switch (dateRange) {
@@ -104,6 +108,7 @@ function getDateRange(dateRange: string, now: Date, timeZone: string): { start:
   return { start, end }
   return { start, end }
 }
 }
 
 
+/** The period as the email reads it; `end` is exclusive, so the last day shown is the one before. */
 function formatDateRange(start: Date, end: Date, timeZone: string): string {
 function formatDateRange(start: Date, end: Date, timeZone: string): string {
   const fmt = (d: Date) =>
   const fmt = (d: Date) =>
     d.toLocaleDateString('en-US', {
     d.toLocaleDateString('en-US', {
@@ -112,117 +117,16 @@ function formatDateRange(start: Date, end: Date, timeZone: string): string {
       day: 'numeric',
       day: 'numeric',
       year: 'numeric',
       year: 'numeric',
     })
     })
-  return `${fmt(start)} – ${fmt(end)}`
+  return `${fmt(start)} – ${fmt(new Date(end.getTime() - 1))}`
 }
 }
 
 
 // --------------- internal report fetchers ---------------
 // --------------- internal report fetchers ---------------
-// These replicate the logic from reportActions.ts but accept orgId directly
-
-async function fetchRevenue(orgId: string, start: Date, end: Date, timeZone: string) {
-  const records = await db.serviceRecord.findMany({
-    where: { organizationId: orgId, startDateTime: { gte: start, lte: end } },
-    select: {
-      serviceDate: true,
-      startDateTime: true,
-      totalAmount: true,
-      cost: true,
-      type: true,
-      taxRate: true,
-      taxInclusive: true,
-      subtotal: true,
-      discountAmount: true,
-      manuallyPaid: true,
-      payments: { select: { amount: true } },
-      partItems: { select: { unitCost: true, quantity: true, total: true, taxable: true } },
-      laborItems: { select: { total: true, taxable: true } },
-    },
-    orderBy: [{ startDateTime: { sort: 'asc', nulls: 'last' } }, { serviceDate: 'asc' }],
-  })
-
-  const monthly: Record<
-    string,
-    {
-      revenue: number
-      collected: number
-      count: number
-      partsCost: number
-      partsRevenue: number
-      laborRevenue: number
-    }
-  > = {}
-  const byType: Record<string, { revenue: number; count: number }> = {}
-  let totalRevenue = 0,
-    totalCollected = 0,
-    totalCount = 0,
-    totalPartsCost = 0,
-    totalPartsRevenue = 0,
-    totalLaborRevenue = 0
-
-  for (const r of records) {
-    const total = r.totalAmount > 0 ? r.totalAmount : r.cost
-    const paid = r.manuallyPaid ? total : r.payments.reduce((s, p) => s + p.amount, 0)
-    const partsCost = r.partItems.reduce((s, p) => s + p.unitCost * p.quantity, 0)
-    // Net (pre-tax) parts/labor, after the job's discount, so profit math works in both tax modes.
-    const partsRevenue = r.partItems.reduce((s, p) => s + earnedLineTotal(p.total, r, p.taxable), 0)
-    const laborRevenue = r.laborItems.reduce(
-      (s, l) => s + earnedLineTotal(l.total, r, l.taxable),
-      0
-    )
-    const _d = r.startDateTime ?? r.serviceDate
-    const month = workshopMonthKey(_d, timeZone)
-
-    if (!monthly[month])
-      monthly[month] = {
-        revenue: 0,
-        collected: 0,
-        count: 0,
-        partsCost: 0,
-        partsRevenue: 0,
-        laborRevenue: 0,
-      }
-    monthly[month].revenue += total
-    monthly[month].collected += paid
-    monthly[month].count += 1
-    monthly[month].partsCost += partsCost
-    monthly[month].partsRevenue += partsRevenue
-    monthly[month].laborRevenue += laborRevenue
-    totalRevenue += total
-    totalCollected += paid
-    totalCount += 1
-    totalPartsCost += partsCost
-    totalPartsRevenue += partsRevenue
-    totalLaborRevenue += laborRevenue
-
-    if (!byType[r.type]) byType[r.type] = { revenue: 0, count: 0 }
-    byType[r.type].revenue += total
-    byType[r.type].count += 1
-  }
-
-  return {
-    monthly: Object.entries(monthly).map(([month, d]) => ({
-      month,
-      ...d,
-      partsNetProfit: d.partsRevenue - d.partsCost,
-      netProfit: d.partsRevenue - d.partsCost + d.laborRevenue,
-    })),
-    byType: Object.entries(byType).map(([type, d]) => ({ type, ...d })),
-    summary: {
-      totalRevenue,
-      totalCollected,
-      outstanding: totalRevenue - totalCollected,
-      totalCount,
-      totalPartsCost,
-      totalPartsRevenue,
-      totalPartsNetProfit: totalPartsRevenue - totalPartsCost,
-      totalLaborRevenue,
-      netProfit: totalPartsRevenue - totalPartsCost + totalLaborRevenue,
-    },
-  }
-}
+// Revenue and tax are the reports screen's own (Lib/financialReports.ts).
+// The rest replicate the logic from reportActions.ts but accept orgId directly.
 
 
 async function fetchServices(orgId: string, start: Date, end: Date) {
 async function fetchServices(orgId: string, start: Date, end: Date) {
   const records = await db.serviceRecord.findMany({
   const records = await db.serviceRecord.findMany({
-    where: { organizationId: orgId, startDateTime: { gte: start, lte: end } },
+    where: { organizationId: orgId, AND: [workDateIn({ gte: start, lt: end })] },
     select: { type: true, status: true },
     select: { type: true, status: true },
   })
   })
   const byStatus: Record<string, number> = {}
   const byStatus: Record<string, number> = {}
@@ -248,7 +152,7 @@ async function fetchCustomers(orgId: string, start: Date, end: Date) {
       vehicles: {
       vehicles: {
         select: {
         select: {
           serviceRecords: {
           serviceRecords: {
-            where: { startDateTime: { gte: start, lte: end } },
+            where: { AND: [workDateIn({ gte: start, lt: end })] },
             select: { totalAmount: true, cost: true },
             select: { totalAmount: true, cost: true },
           },
           },
         },
         },
@@ -279,7 +183,7 @@ async function fetchTechnicians(orgId: string, start: Date, end: Date) {
   const records = await db.serviceRecord.findMany({
   const records = await db.serviceRecord.findMany({
     where: {
     where: {
       organizationId: orgId,
       organizationId: orgId,
-      startDateTime: { gte: start, lte: end },
+      AND: [workDateIn({ gte: start, lt: end })],
       OR: [{ technicianId: { not: null } }, { techName: { not: null } }],
       OR: [{ technicianId: { not: null } }, { techName: { not: null } }],
     },
     },
     select: {
     select: {
@@ -326,7 +230,7 @@ async function fetchTechnicians(orgId: string, start: Date, end: Date) {
 
 
 async function fetchParts(orgId: string, start: Date, end: Date) {
 async function fetchParts(orgId: string, start: Date, end: Date) {
   const parts = await db.servicePart.findMany({
   const parts = await db.servicePart.findMany({
-    where: { serviceRecord: { organizationId: orgId, startDateTime: { gte: start, lte: end } } },
+    where: { serviceRecord: { organizationId: orgId, AND: [workDateIn({ gte: start, lt: end })] } },
     select: {
     select: {
       name: true,
       name: true,
       partNumber: true,
       partNumber: true,
@@ -388,7 +292,7 @@ async function fetchParts(orgId: string, start: Date, end: Date) {
 
 
 async function fetchJobAnalytics(orgId: string, start: Date, end: Date, timeZone: string) {
 async function fetchJobAnalytics(orgId: string, start: Date, end: Date, timeZone: string) {
   const records = await db.serviceRecord.findMany({
   const records = await db.serviceRecord.findMany({
-    where: { organizationId: orgId, startDateTime: { gte: start, lte: end } },
+    where: { organizationId: orgId, AND: [workDateIn({ gte: start, lt: end })] },
     select: {
     select: {
       type: true,
       type: true,
       totalAmount: true,
       totalAmount: true,
@@ -410,7 +314,7 @@ async function fetchJobAnalytics(orgId: string, start: Date, end: Date, timeZone
       (s, l) => s + (isShopFeeLine(l) ? 0 : l.hours),
       (s, l) => s + (isShopFeeLine(l) ? 0 : l.hours),
       0
       0
     )
     )
-    const _d = r.startDateTime ?? r.serviceDate
+    const _d = workDateOf(r)
     dayCount[zonedParts(_d, timeZone).weekday] += 1
     dayCount[zonedParts(_d, timeZone).weekday] += 1
     const month = workshopMonthKey(_d, timeZone)
     const month = workshopMonthKey(_d, timeZone)
     if (!monthly[month]) monthly[month] = { count: 0, revenue: 0 }
     if (!monthly[month]) monthly[month] = { count: 0, revenue: 0 }
@@ -447,7 +351,7 @@ async function fetchRetention(orgId: string, start: Date, end: Date) {
       vehicles: {
       vehicles: {
         select: {
         select: {
           serviceRecords: {
           serviceRecords: {
-            where: { startDateTime: { gte: start, lte: end } },
+            where: { AND: [workDateIn({ gte: start, lt: end })] },
             select: { serviceDate: true, startDateTime: true, totalAmount: true, cost: true },
             select: { serviceDate: true, startDateTime: true, totalAmount: true, cost: true },
             orderBy: [{ startDateTime: { sort: 'asc', nulls: 'last' } }, { serviceDate: 'asc' }],
             orderBy: [{ startDateTime: { sort: 'asc', nulls: 'last' } }, { serviceDate: 'asc' }],
           },
           },
@@ -471,7 +375,7 @@ async function fetchRetention(orgId: string, start: Date, end: Date) {
     for (const v of c.vehicles)
     for (const v of c.vehicles)
       for (const sr of v.serviceRecords)
       for (const sr of v.serviceRecords)
         visits.push({
         visits.push({
-          date: sr.startDateTime ?? sr.serviceDate,
+          date: workDateOf(sr),
           amount: sr.totalAmount > 0 ? sr.totalAmount : sr.cost,
           amount: sr.totalAmount > 0 ? sr.totalAmount : sr.cost,
         })
         })
     if (visits.length === 0) continue
     if (visits.length === 0) continue
@@ -614,52 +518,6 @@ async function fetchPastDue(orgId: string, timeZone: string) {
   }
   }
 }
 }
 
 
-async function fetchTax(orgId: string, start: Date, end: Date, timeZone: string) {
-  const records = await db.serviceRecord.findMany({
-    where: { organizationId: orgId, startDateTime: { gte: start, lte: end } },
-    select: {
-      serviceDate: true,
-      startDateTime: true,
-      subtotal: true,
-      taxableSubtotal: true,
-      taxRate: true,
-      taxAmount: true,
-      taxInclusive: true,
-      taxComponents: true,
-      totalAmount: true,
-    },
-    orderBy: [{ startDateTime: { sort: 'asc', nulls: 'last' } }, { serviceDate: 'asc' }],
-  })
-  const monthly: Record<
-    string,
-    { taxCollected: number; invoiceCount: number; taxableAmount: number }
-  > = {}
-  const byRate = new TaxByRateTable()
-  let totalTaxCollected = 0,
-    totalTaxableAmount = 0,
-    totalInvoices = 0
-  for (const r of records) {
-    if (r.taxAmount <= 0) continue
-    const _d = r.startDateTime ?? r.serviceDate
-    const month = workshopMonthKey(_d, timeZone)
-    // Net taxable base = totalAmount - taxAmount, valid for both modes.
-    const taxableBase = taxedNetAmountOf(r)
-    if (!monthly[month]) monthly[month] = { taxCollected: 0, invoiceCount: 0, taxableAmount: 0 }
-    monthly[month].taxCollected += r.taxAmount
-    monthly[month].invoiceCount += 1
-    monthly[month].taxableAmount += taxableBase
-    byRate.add(r)
-    totalTaxCollected += r.taxAmount
-    totalTaxableAmount += taxableBase
-    totalInvoices += 1
-  }
-  return {
-    monthly: Object.entries(monthly).map(([month, d]) => ({ month, ...d })),
-    byRate: byRate.list(),
-    summary: { totalTaxCollected, totalTaxableAmount, totalInvoices },
-  }
-}
-
 // --------------- process a single schedule ---------------
 // --------------- process a single schedule ---------------
 
 
 export async function processOneSchedule(
 export async function processOneSchedule(
@@ -717,9 +575,11 @@ export async function processOneSchedule(
     inventoryData,
     inventoryData,
   ] = await Promise.all([
   ] = await Promise.all([
     sections.includes('revenue')
     sections.includes('revenue')
-      ? fetchRevenue(schedule.organizationId, start, end, timeZone)
+      ? computeRevenue(schedule.organizationId, { gte: start, lt: end }, timeZone)
+      : null,
+    sections.includes('tax')
+      ? computeTax(schedule.organizationId, { gte: start, lt: end }, timeZone)
       : null,
       : null,
-    sections.includes('tax') ? fetchTax(schedule.organizationId, start, end, timeZone) : null,
     sections.includes('pastDue') ? fetchPastDue(schedule.organizationId, timeZone) : null,
     sections.includes('pastDue') ? fetchPastDue(schedule.organizationId, timeZone) : null,
     sections.includes('services') ? fetchServices(schedule.organizationId, start, end) : null,
     sections.includes('services') ? fetchServices(schedule.organizationId, start, end) : null,
     sections.includes('customers') ? fetchCustomers(schedule.organizationId, start, end) : null,
     sections.includes('customers') ? fetchCustomers(schedule.organizationId, start, end) : null,