From 0df4be1820e4495e4ddd7cc284e478da0853fc26 Mon Sep 17 00:00:00 2001 From: Nathnael Date: Thu, 13 Aug 2026 12:44:06 +0000 Subject: [PATCH] style: overview revamp --- .../overview/dto/overview-response.dto.ts | 61 ++- .../modules/overview/overview.repository.ts | 259 ++++++++++++- .../src/modules/overview/overview.service.ts | 30 +- apps/edr-freight-web/backoffice/src/App.tsx | 17 + .../src/components/layout/route-meta.ts | 28 ++ .../overview/OverviewKpiSection.tsx | 167 --------- .../overview/OverviewPageHeader.tsx | 66 ---- .../overview/OverviewRecentBookingsTable.tsx | 138 ++++--- .../overview/OverviewTabContent.tsx | 119 ------ .../overview/overview-domains.config.ts | 88 +++++ .../src/components/overview/overview.css | 7 +- .../components/overview/summary/CountUp.tsx | 44 +++ .../summary/OverviewActivityHeatmap.tsx | 125 +++++++ .../summary/OverviewAttentionCard.tsx | 149 ++++++++ .../overview/summary/OverviewHero.tsx | 140 +++++++ .../overview/summary/OverviewHeroKpis.tsx | 67 ++++ .../overview/summary/OverviewNetworkCard.tsx | 88 +++++ .../summary/OverviewPipelineFunnel.tsx | 113 ++++++ .../overview/summary/OverviewRevenueMix.tsx | 143 +++++++ .../summary/OverviewRevenueVolumeChart.tsx | 172 +++++++++ .../overview/summary/OverviewSankeyFlow.tsx | 170 +++++++++ .../overview/summary/SummaryCard.tsx | 65 ++++ .../overview/summary/chart-style.ts | 14 + .../overview/summary/flow-colors.ts | 25 ++ .../overview/summary/mergeTrend.test.ts | 56 +++ .../components/overview/summary/mergeTrend.ts | 63 ++++ .../overview/summary/overview-summary.css | 65 ++++ .../tabs/OverviewBookingsTabPanel.tsx | 6 - .../tabs/OverviewContractsTabPanel.tsx | 6 - .../tabs/OverviewOperationsTabPanel.tsx | 6 - .../src/components/page/KpiStrip.tsx | 12 +- .../pages/dashboard/OverviewDomainPage.tsx | 145 ++++++++ .../src/pages/dashboard/OverviewPage.tsx | 352 +++++++----------- packages/types/src/freight/overview.ts | 50 ++- 34 files changed, 2412 insertions(+), 644 deletions(-) delete mode 100644 apps/edr-freight-web/backoffice/src/components/overview/OverviewKpiSection.tsx delete mode 100644 apps/edr-freight-web/backoffice/src/components/overview/OverviewPageHeader.tsx delete mode 100644 apps/edr-freight-web/backoffice/src/components/overview/OverviewTabContent.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/overview-domains.config.ts create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/CountUp.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewActivityHeatmap.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewAttentionCard.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHero.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHeroKpis.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewNetworkCard.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewPipelineFunnel.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueMix.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueVolumeChart.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewSankeyFlow.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/SummaryCard.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/chart-style.ts create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/flow-colors.ts create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.test.ts create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.ts create mode 100644 apps/edr-freight-web/backoffice/src/components/overview/summary/overview-summary.css create mode 100644 apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewDomainPage.tsx diff --git a/apps/edr-freight-api/src/modules/overview/dto/overview-response.dto.ts b/apps/edr-freight-api/src/modules/overview/dto/overview-response.dto.ts index 005dad08a..1bd22c7c0 100644 --- a/apps/edr-freight-api/src/modules/overview/dto/overview-response.dto.ts +++ b/apps/edr-freight-api/src/modules/overview/dto/overview-response.dto.ts @@ -21,6 +21,7 @@ export class OverviewContractKpisDto { export class OverviewOperationsKpisDto { @ApiProperty() trainsActive!: number; @ApiProperty() wagonsAvailable!: number; + @ApiProperty() wagonsTotal!: number; @ApiProperty() containersInTransit!: number; @ApiProperty() cargoesLoaded!: number; @ApiProperty() schedulesUpcoming!: number; @@ -108,6 +109,41 @@ export class OverviewRecentContractDto { @ApiProperty() createdAt!: string; } +export class OverviewPeriodTotalsDto { + @ApiProperty() bookingsCreated!: number; + @ApiProperty() revenueEtb!: number; + @ApiProperty() revenueUsd!: number; + @ApiProperty() tons!: number; +} + +export class OverviewRevenueSliceDto { + @ApiProperty() label!: string; + @ApiProperty() amountEtb!: number; + @ApiProperty() amountUsd!: number; +} + +export class OverviewTonsTrendPointDto { + @ApiProperty({ example: '2026-06-01' }) date!: string; + @ApiProperty() tons!: number; +} + +export class OverviewRevenueFlowDto { + @ApiProperty() direction!: string; + @ApiProperty() freightType!: string; + @ApiProperty() amountEtb!: number; + @ApiProperty() amountUsd!: number; +} + +export class OverviewHeatmapCellDto { + @ApiProperty({ description: 'ISO weekday, 1 = Monday … 7 = Sunday' }) + dow!: number; + + @ApiProperty({ description: '3-hour block, 0 = 00–03 … 7 = 21–24' }) + block!: number; + + @ApiProperty() count!: number; +} + export class OverviewResponseDto { @ApiProperty({ type: OverviewKpisDto }) kpis!: OverviewKpisDto; @@ -124,8 +160,29 @@ export class OverviewResponseDto { @ApiProperty({ type: [OverviewPaymentTrendPointDto] }) paymentTrend!: OverviewPaymentTrendPointDto[]; - @ApiProperty({ type: [OverviewRecentBookingDto] }) - recentBookings!: OverviewRecentBookingDto[]; + @ApiProperty({ type: OverviewPeriodTotalsDto }) + current!: OverviewPeriodTotalsDto; + + @ApiProperty({ type: OverviewPeriodTotalsDto }) + previous!: OverviewPeriodTotalsDto; + + @ApiProperty({ type: [OverviewRevenueSliceDto] }) + revenueByDirection!: OverviewRevenueSliceDto[]; + + @ApiProperty({ type: [OverviewRevenueSliceDto] }) + revenueByFreightType!: OverviewRevenueSliceDto[]; + + @ApiProperty({ type: [OverviewPaymentTrendPointDto] }) + previousPaymentTrend!: OverviewPaymentTrendPointDto[]; + + @ApiProperty({ type: [OverviewTonsTrendPointDto] }) + tonsTrend!: OverviewTonsTrendPointDto[]; + + @ApiProperty({ type: [OverviewRevenueFlowDto] }) + revenueFlows!: OverviewRevenueFlowDto[]; + + @ApiProperty({ type: [OverviewHeatmapCellDto] }) + bookingHeatmap!: OverviewHeatmapCellDto[]; @ApiProperty() generatedAt!: string; } diff --git a/apps/edr-freight-api/src/modules/overview/overview.repository.ts b/apps/edr-freight-api/src/modules/overview/overview.repository.ts index c61320d8c..18b6bb54d 100644 --- a/apps/edr-freight-api/src/modules/overview/overview.repository.ts +++ b/apps/edr-freight-api/src/modules/overview/overview.repository.ts @@ -155,6 +155,7 @@ export class OverviewRepository { async getOperationsKpis(): Promise<{ trainsActive: number; wagonsAvailable: number; + wagonsTotal: number; containersInTransit: number; cargoesLoaded: number; schedulesUpcoming: number; @@ -163,6 +164,7 @@ export class OverviewRepository { const [ trainsActive, wagonsAvailable, + wagonsTotal, containersInTransit, cargoesLoaded, schedulesUpcoming, @@ -185,6 +187,10 @@ export class OverviewRepository { status: Freight.WagonStatus.Available, }) .getCount(), + this.wagonRepository + .createQueryBuilder("wagon") + .where("wagon.deleted_at IS NULL") + .getCount(), this.containerRepository .createQueryBuilder("container") .where("container.deleted_at IS NULL") @@ -218,6 +224,7 @@ export class OverviewRepository { return { trainsActive, wagonsAvailable, + wagonsTotal, containersInTransit, cargoesLoaded, schedulesUpcoming, @@ -345,9 +352,16 @@ export class OverviewRepository { ); } + /** + * Daily successful-payment revenue for a `days`-wide window shifted back by + * `offsetDays` — `0` (default) is the current window ending today, + * `offsetDays: days` is the immediately preceding window (the ghost-line + * comparison series on the overview chart). + */ async getPaymentTrend( days: number, dirs?: string[], + offsetDays = 0, ): Promise<{ date: string; amountEtb: number; amountUsd: number }[]> { const scope = bookingRefScopeSql("payment.ref_id", dirs); const rows = await this.paymentRepository @@ -366,8 +380,8 @@ export class OverviewRepository { ) .where("payment.status = :status", { status: "success" }) .andWhere( - `COALESCE(payment.paid_at, payment.created_at) >= CURRENT_DATE - :days::int + 1`, - { days }, + `COALESCE(payment.paid_at, payment.created_at) >= CURRENT_DATE - :offsetDays::int - :days::int + 1 AND COALESCE(payment.paid_at, payment.created_at) < CURRENT_DATE - :offsetDays::int + 1`, + { days, offsetDays }, ) .andWhere(scope.sql, scope.params) .groupBy(`COALESCE(payment.paid_at, payment.created_at)::date`) @@ -546,6 +560,247 @@ export class OverviewRepository { })); } + /** + * Bookings created, revenue and tonnage for one `days`-wide window, shifted + * back by `offsetDays`. Called twice by the service — `offsetDays: 0` for + * the current period, `offsetDays: days` for the immediately preceding + * one-of-the-same-length period — so the page can show a real vs-prior-period + * delta instead of a bare count. + */ + async getPeriodTotals( + days: number, + offsetDays: number, + dirs?: string[], + ): Promise<{ + bookingsCreated: number; + revenueEtb: number; + revenueUsd: number; + tons: number; + }> { + const bookingScope = directionScopeSql("booking.trade_direction", dirs); + const paymentScope = bookingRefScopeSql("payment.ref_id", dirs); + const cargoScope = directionScopeSql("booking.trade_direction", dirs); + const windowSql = (column: string) => + `${column} >= CURRENT_DATE - :offsetDays::int - :days::int + 1 AND ${column} < CURRENT_DATE - :offsetDays::int + 1`; + + const [bookingsCreated, revenueRow, tonsRow] = await Promise.all([ + this.bookingRepository + .createQueryBuilder("booking") + .where("booking.deleted_at IS NULL") + .andWhere(EXCLUDE_GENERAL_CONTRACT_BOOKINGS) + .andWhere(bookingScope.sql, bookingScope.params) + .andWhere(windowSql("booking.created_at"), { days, offsetDays }) + .getCount(), + this.paymentRepository + .createQueryBuilder("payment") + .select( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'ETB'), 0)`, + "revenueEtb", + ) + .addSelect( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD'), 0)`, + "revenueUsd", + ) + .where("payment.status = :status", { status: "success" }) + .andWhere( + windowSql("COALESCE(payment.paid_at, payment.created_at)"), + { days, offsetDays }, + ) + .andWhere(paymentScope.sql, paymentScope.params) + .getRawOne<{ revenueEtb: string; revenueUsd: string }>(), + this.cargoRepository + .createQueryBuilder("cargo") + .leftJoin(Booking, "booking", "booking.id = cargo.booking_id") + .select(`COALESCE(SUM(cargo.weight), 0) / 1000`, "tons") + .where("cargo.deleted_at IS NULL") + .andWhere(windowSql("cargo.created_at"), { days, offsetDays }) + .andWhere(cargoScope.sql, cargoScope.params) + .getRawOne<{ tons: string }>(), + ]); + + return { + bookingsCreated, + revenueEtb: Number(revenueRow?.revenueEtb ?? 0), + revenueUsd: Number(revenueRow?.revenueUsd ?? 0), + tons: Number(tonsRow?.tons ?? 0), + }; + } + + /** Revenue for the selected range, split by booking trade direction. */ + async getRevenueByDirection( + days: number, + dirs?: string[], + ): Promise<{ label: string; amountEtb: number; amountUsd: number }[]> { + const scope = bookingRefScopeSql("payment.ref_id", dirs); + const rows = await this.paymentRepository + .createQueryBuilder("payment") + .leftJoin(Booking, "booking", "booking.id::text = payment.ref_id") + .select("booking.trade_direction", "label") + .addSelect( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'ETB'), 0)`, + "amountEtb", + ) + .addSelect( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD'), 0)`, + "amountUsd", + ) + .where("payment.status = :status", { status: "success" }) + .andWhere( + `COALESCE(payment.paid_at, payment.created_at) >= CURRENT_DATE - :days::int + 1`, + { days }, + ) + .andWhere(scope.sql, scope.params) + .andWhere("booking.trade_direction IS NOT NULL") + .groupBy("booking.trade_direction") + .getRawMany<{ label: string; amountEtb: string; amountUsd: string }>(); + + return rows.map((row) => ({ + label: row.label, + amountEtb: Number(row.amountEtb), + amountUsd: Number(row.amountUsd), + })); + } + + /** Revenue for the selected range, split by booking freight type. */ + async getRevenueByFreightType( + days: number, + dirs?: string[], + ): Promise<{ label: string; amountEtb: number; amountUsd: number }[]> { + const scope = bookingRefScopeSql("payment.ref_id", dirs); + const rows = await this.paymentRepository + .createQueryBuilder("payment") + .leftJoin(Booking, "booking", "booking.id::text = payment.ref_id") + .select("booking.freight_type", "label") + .addSelect( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'ETB'), 0)`, + "amountEtb", + ) + .addSelect( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD'), 0)`, + "amountUsd", + ) + .where("payment.status = :status", { status: "success" }) + .andWhere( + `COALESCE(payment.paid_at, payment.created_at) >= CURRENT_DATE - :days::int + 1`, + { days }, + ) + .andWhere(scope.sql, scope.params) + .andWhere("booking.freight_type IS NOT NULL") + .groupBy("booking.freight_type") + .getRawMany<{ label: string; amountEtb: string; amountUsd: string }>(); + + return rows.map((row) => ({ + label: row.label, + amountEtb: Number(row.amountEtb), + amountUsd: Number(row.amountUsd), + })); + } + + /** Daily cargo tonnage for the selected range — hero sparkline series. */ + async getTonsTrend( + days: number, + dirs?: string[], + ): Promise<{ date: string; tons: number }[]> { + const scope = directionScopeSql("booking.trade_direction", dirs); + const rows = await this.cargoRepository + .createQueryBuilder("cargo") + .leftJoin(Booking, "booking", "booking.id = cargo.booking_id") + .select(`to_char(cargo.created_at::date, 'YYYY-MM-DD')`, "date") + .addSelect(`COALESCE(SUM(cargo.weight), 0) / 1000`, "tons") + .where("cargo.deleted_at IS NULL") + .andWhere(scope.sql, scope.params) + .andWhere(`cargo.created_at >= CURRENT_DATE - :days::int + 1`, { days }) + .groupBy("cargo.created_at::date") + .orderBy("cargo.created_at::date", "ASC") + .getRawMany<{ date: string; tons: string }>(); + + return rows.map((row) => ({ date: row.date, tons: Number(row.tons) })); + } + + /** + * Revenue for the selected range as direction → freight-type flows — the + * Sankey on the overview. One row per (direction, freight type) pair. + */ + async getRevenueFlows( + days: number, + dirs?: string[], + ): Promise< + { + direction: string; + freightType: string; + amountEtb: number; + amountUsd: number; + }[] + > { + const scope = bookingRefScopeSql("payment.ref_id", dirs); + const rows = await this.paymentRepository + .createQueryBuilder("payment") + .leftJoin(Booking, "booking", "booking.id::text = payment.ref_id") + .select("booking.trade_direction", "direction") + .addSelect("booking.freight_type", "freightType") + .addSelect( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'ETB'), 0)`, + "amountEtb", + ) + .addSelect( + `COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD'), 0)`, + "amountUsd", + ) + .where("payment.status = :status", { status: "success" }) + .andWhere( + `COALESCE(payment.paid_at, payment.created_at) >= CURRENT_DATE - :days::int + 1`, + { days }, + ) + .andWhere(scope.sql, scope.params) + .andWhere("booking.trade_direction IS NOT NULL") + .andWhere("booking.freight_type IS NOT NULL") + .groupBy("booking.trade_direction") + .addGroupBy("booking.freight_type") + .getRawMany<{ + direction: string; + freightType: string; + amountEtb: string; + amountUsd: string; + }>(); + + return rows.map((row) => ({ + direction: row.direction, + freightType: row.freightType, + amountEtb: Number(row.amountEtb), + amountUsd: Number(row.amountUsd), + })); + } + + /** + * Booking arrivals bucketed by ISO weekday (1 = Mon … 7 = Sun) and 3-hour + * block (0 = 00–03 … 7 = 21–24) — the demand-rhythm heatmap. Buckets use + * the database server's timezone, same as every ::date grouping here. + */ + async getBookingHeatmap( + days: number, + dirs?: string[], + ): Promise<{ dow: number; block: number; count: number }[]> { + const scope = directionScopeSql("booking.trade_direction", dirs); + const rows = await this.bookingRepository + .createQueryBuilder("booking") + .select("EXTRACT(ISODOW FROM booking.created_at)::int", "dow") + .addSelect("FLOOR(EXTRACT(HOUR FROM booking.created_at) / 3)::int", "block") + .addSelect("COUNT(*)::int", "count") + .where("booking.deleted_at IS NULL") + .andWhere(EXCLUDE_GENERAL_CONTRACT_BOOKINGS) + .andWhere(scope.sql, scope.params) + .andWhere(`booking.created_at >= CURRENT_DATE - :days::int + 1`, { days }) + .groupBy("EXTRACT(ISODOW FROM booking.created_at)::int") + .addGroupBy("FLOOR(EXTRACT(HOUR FROM booking.created_at) / 3)::int") + .getRawMany<{ dow: string; block: string; count: string }>(); + + return rows.map((row) => ({ + dow: Number(row.dow), + block: Number(row.block), + count: Number(row.count), + })); + } + async getTrainStatusBreakdown(): Promise< { status: string; count: number }[] > { diff --git a/apps/edr-freight-api/src/modules/overview/overview.service.ts b/apps/edr-freight-api/src/modules/overview/overview.service.ts index 399bf4f72..a10bb8816 100644 --- a/apps/edr-freight-api/src/modules/overview/overview.service.ts +++ b/apps/edr-freight-api/src/modules/overview/overview.service.ts @@ -56,7 +56,14 @@ export class OverviewService { bookingTrend, statusCounts, paymentTrend, - recentBookings, + current, + previous, + revenueByDirection, + revenueByFreightType, + previousPaymentTrend, + tonsTrend, + revenueFlows, + bookingHeatmap, ] = await Promise.all([ this.overviewRepository.getBookingKpis(dirs), this.overviewRepository.getContractKpis(dirs), @@ -67,7 +74,14 @@ export class OverviewService { this.overviewRepository.getBookingTrend(days, dirs), this.overviewRepository.getStatusCounts(dirs), this.overviewRepository.getPaymentTrend(days, dirs), - this.overviewRepository.getRecentBookings(8, dirs), + this.overviewRepository.getPeriodTotals(days, 0, dirs), + this.overviewRepository.getPeriodTotals(days, days, dirs), + this.overviewRepository.getRevenueByDirection(days, dirs), + this.overviewRepository.getRevenueByFreightType(days, dirs), + this.overviewRepository.getPaymentTrend(days, dirs, days), + this.overviewRepository.getTonsTrend(days, dirs), + this.overviewRepository.getRevenueFlows(days, dirs), + this.overviewRepository.getBookingHeatmap(days, dirs), ]); const { bookingsByPipeline, bookingsByStatus } = @@ -86,10 +100,14 @@ export class OverviewService { bookingsByStatus, bookingsByPipeline, paymentTrend, - recentBookings: recentBookings.map((row) => ({ - ...row, - createdAt: row.createdAt.toISOString(), - })), + current, + previous, + revenueByDirection, + revenueByFreightType, + previousPaymentTrend, + tonsTrend, + revenueFlows, + bookingHeatmap, generatedAt: new Date().toISOString(), }; } diff --git a/apps/edr-freight-web/backoffice/src/App.tsx b/apps/edr-freight-web/backoffice/src/App.tsx index a9b9db226..b9b96de08 100644 --- a/apps/edr-freight-web/backoffice/src/App.tsx +++ b/apps/edr-freight-web/backoffice/src/App.tsx @@ -40,6 +40,8 @@ import InvoiceDetailPage from "./pages/invoices/InvoiceDetailPage"; import FinanceHubPage from "./pages/invoices/FinanceHubPage"; import MyProfilePage from "./pages/dashboard/MyProfilePage"; import OverviewPage from "./pages/dashboard/OverviewPage"; +import OverviewDomainPage from "./pages/dashboard/OverviewDomainPage"; +import { OVERVIEW_DOMAINS } from "./components/overview/overview-domains.config"; import ReportsIndexRedirect from "./pages/reports/ReportsIndexRedirect"; import ReportPage from "./pages/reports/ReportPage"; import AuditLogsPage from "./pages/AuditLogsPage"; @@ -222,6 +224,21 @@ const App = () => { } /> + {/* One drill-down route per overview domain — the old per-tab charts, + now each on its own page. Single source of truth for the + permission gate is OVERVIEW_DOMAINS, shared with the summary + page's "View all" links. */} + {OVERVIEW_DOMAINS.map((domain) => ( + + + + } + /> + ))} = [ subtitle: "Dashboard summary and key metrics", }, }, + { + prefix: "/dashboard/overview/bookings", + meta: { title: "Bookings", subtitle: "Booking volume, pipeline, and recent activity" }, + }, + { + prefix: "/dashboard/overview/contracts", + meta: { title: "Contracts", subtitle: "Contract volume, pipeline, and recent activity" }, + }, + { + prefix: "/dashboard/overview/billing", + meta: { title: "Billing", subtitle: "Revenue, payments, and collection status" }, + }, + { + prefix: "/dashboard/overview/operations", + meta: { title: "Operations", subtitle: "Trains, schedules, containers, and cargo" }, + }, + { + prefix: "/dashboard/overview/fleet", + meta: { title: "Fleet", subtitle: "Wagon and train fleet status" }, + }, + { + prefix: "/dashboard/overview/customers", + meta: { title: "Customers", subtitle: "Customer growth and top accounts" }, + }, + { + prefix: "/dashboard/overview/staff", + meta: { title: "Staff", subtitle: "Employee and user account status" }, + }, { prefix: "/dashboard/profile", meta: { diff --git a/apps/edr-freight-web/backoffice/src/components/overview/OverviewKpiSection.tsx b/apps/edr-freight-web/backoffice/src/components/overview/OverviewKpiSection.tsx deleted file mode 100644 index ea99d098e..000000000 --- a/apps/edr-freight-web/backoffice/src/components/overview/OverviewKpiSection.tsx +++ /dev/null @@ -1,167 +0,0 @@ -import { - AlertCircle, - Banknote, - Box, - Clock, - Container, - CreditCard, - FileText, - Train, - Truck, - UserCheck, - Users, - Wallet, -} from "lucide-react"; -import { Group, Paper, Stack, Text } from "@mantine/core"; - -import type { IOverviewKpis } from "@/types/overview"; -import { OverviewKpiCard } from "./OverviewKpiCard"; - -function formatCurrency(amount: number, currency: "ETB" | "USD") { - return new Intl.NumberFormat("en-US", { - style: "currency", - currency, - maximumFractionDigits: 0, - }).format(amount); -} - -export function OverviewKpiSection({ kpis }: { kpis: IOverviewKpis }) { - const bookingItems = [ - { - label: "Active bookings", - value: kpis.bookings.totalActive, - icon: FileText, - accent: "emerald" as const, - }, - { - label: "Needs action", - value: kpis.bookings.needsAction, - icon: AlertCircle, - accent: "amber" as const, - }, - { - label: "Urgent", - value: kpis.bookings.urgent, - icon: Clock, - accent: "rose" as const, - }, - { - label: "In approval", - value: kpis.bookings.inApproval, - icon: UserCheck, - accent: "sky" as const, - }, - { - label: "Submitted today", - value: kpis.bookings.submittedToday, - icon: FileText, - }, - ]; - - const operationsItems = [ - { - label: "Active trains", - value: kpis.operations.trainsActive, - icon: Train, - accent: "emerald" as const, - }, - { - label: "Wagons available", - value: kpis.operations.wagonsAvailable, - icon: Truck, - }, - { - label: "Containers in transit", - value: kpis.operations.containersInTransit, - icon: Container, - }, - { - label: "Cargoes loaded", - value: kpis.operations.cargoesLoaded, - icon: Box, - }, - ]; - - const billingItems = [ - { - label: "Revenue MTD (ETB)", - value: formatCurrency(kpis.billing.revenueMtdEtb, "ETB"), - icon: Banknote, - accent: "emerald" as const, - }, - { - label: "Revenue MTD (USD)", - value: formatCurrency(kpis.billing.revenueMtdUsd, "USD"), - icon: Wallet, - }, - { - label: "Pending payments", - value: kpis.billing.pendingPayments, - icon: CreditCard, - accent: "amber" as const, - }, - { - label: "Successful MTD", - value: kpis.billing.successfulPaymentsMtd, - icon: Banknote, - }, - ]; - - const peopleItems = [ - { - label: "Total customers", - value: kpis.customers.totalCustomers, - icon: Users, - }, - { - label: "New this month", - value: kpis.customers.newCustomersThisMonth, - icon: Users, - accent: "emerald" as const, - }, - { - label: "Active employees", - value: kpis.staff.activeEmployees, - icon: UserCheck, - }, - { - label: "Active users", - value: kpis.staff.activeUsers, - icon: Users, - }, - ]; - - const sections = [ - { title: "Bookings", items: bookingItems }, - { title: "Operations", items: operationsItems }, - { title: "Billing", items: billingItems }, - { title: "Customers & staff", items: peopleItems }, - ]; - - return ( - - {sections.map((section) => ( - - - {section.title} - - - {section.items.map((item) => ( - - ))} - - - ))} - - ); -} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/OverviewPageHeader.tsx b/apps/edr-freight-web/backoffice/src/components/overview/OverviewPageHeader.tsx deleted file mode 100644 index 529981add..000000000 --- a/apps/edr-freight-web/backoffice/src/components/overview/OverviewPageHeader.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { ActionIcon, Group, SegmentedControl, Text } from "@mantine/core"; -import { RefreshCw } from "lucide-react"; - -import type { OverviewRange } from "@/types/overview"; - -const RANGE_OPTIONS = [ - { label: "7 days", value: "7d" }, - { label: "30 days", value: "30d" }, - { label: "90 days", value: "90d" }, -]; - -function formatRelativeTime(iso: string | undefined) { - if (!iso) return "—"; - const diffMs = Date.now() - new Date(iso).getTime(); - const minutes = Math.floor(diffMs / 60_000); - if (minutes < 1) return "just now"; - if (minutes < 60) return `${minutes}m ago`; - const hours = Math.floor(minutes / 60); - if (hours < 24) return `${hours}h ago`; - return new Date(iso).toLocaleString(); -} - -interface OverviewPageHeaderProps { - range: OverviewRange; - onRangeChange: (range: OverviewRange) => void; - generatedAt?: string; - onRefresh: () => void; - isRefreshing?: boolean; -} - -export function OverviewPageHeader({ - range, - onRangeChange, - generatedAt, - onRefresh, - isRefreshing, -}: OverviewPageHeaderProps) { - return ( - - - Updated {formatRelativeTime(generatedAt)} - - - onRangeChange(value as OverviewRange)} - data={RANGE_OPTIONS} - size="sm" - radius="lg" - color="edr-green" - /> - - - - - - ); -} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/OverviewRecentBookingsTable.tsx b/apps/edr-freight-web/backoffice/src/components/overview/OverviewRecentBookingsTable.tsx index b13f5c473..e1ceaec1c 100644 --- a/apps/edr-freight-web/backoffice/src/components/overview/OverviewRecentBookingsTable.tsx +++ b/apps/edr-freight-web/backoffice/src/components/overview/OverviewRecentBookingsTable.tsx @@ -1,9 +1,11 @@ -import { useNavigate } from "react-router-dom"; -import { Paper, Stack, Table, Text } from "@mantine/core"; +import { History } from "lucide-react"; +import { Link, useNavigate } from "react-router-dom"; +import { Table, Text } from "@mantine/core"; import { BookingPriorityBadge } from "@/components/bookings/BookingPriorityBadge"; import { BookingStatusBadge } from "@/components/bookings/BookingStatusBadge"; import type { IOverviewRecentBooking } from "@/types/overview"; +import { SummaryCard } from "./summary/SummaryCard"; function formatAmount(amount: number | null, currency: string | null) { if (amount == null) return "—"; @@ -23,56 +25,90 @@ export function OverviewRecentBookingsTable({ const navigate = useNavigate(); return ( - - - Recent bookings - {bookings.length === 0 ? ( - - No recent bookings - - ) : ( - - - - Reference - Customer - Status - Priority - Amount - Created - - - - {bookings.map((booking) => ( - navigate(`/dashboard/booking-requests/${booking.id}`)} - > - - - {booking.reference} - - - {booking.customerLabel} - - - - - - - + + View all → + + } + > + {bookings.length === 0 ? ( + + No recent bookings + + ) : ( +
+ + + {["Reference", "Customer", "Status", "Priority", "Amount", "Created"].map( + (header) => ( + + {header} + + ), + )} + + + + {bookings.map((booking) => ( + navigate(`/dashboard/booking-requests/${booking.id}`)} + > + + + {booking.reference} + + + + + {booking.customerLabel} + + + + + + + + + + {formatAmount(booking.totalAmount, booking.paymentCurrency)} - - + + + + {new Date(booking.createdAt).toLocaleDateString()} - - - ))} - -
- )} -
-
+ + + + ))} + + + )} + ); } diff --git a/apps/edr-freight-web/backoffice/src/components/overview/OverviewTabContent.tsx b/apps/edr-freight-web/backoffice/src/components/overview/OverviewTabContent.tsx deleted file mode 100644 index cf71198a6..000000000 --- a/apps/edr-freight-web/backoffice/src/components/overview/OverviewTabContent.tsx +++ /dev/null @@ -1,119 +0,0 @@ -import { AlertCircle } from "lucide-react"; -import { Alert, Button, Center, Loader, Paper, Skeleton, Stack } from "@mantine/core"; - -import { - useOverviewBillingTab, - useOverviewBookingsTab, - useOverviewContractsTab, - useOverviewCustomersTab, - useOverviewOperationsTab, - useOverviewStaffTab, -} from "@/hooks/useOverview"; -import type { OverviewRange, OverviewTabKey } from "@/types/overview"; -import { OverviewBillingTabPanel } from "./tabs/OverviewBillingTabPanel"; -import { OverviewBookingsTabPanel } from "./tabs/OverviewBookingsTabPanel"; -import { OverviewContractsTabPanel } from "./tabs/OverviewContractsTabPanel"; -import { OverviewCustomersTabPanel } from "./tabs/OverviewCustomersTabPanel"; -import { OverviewFleetTabPanel } from "./tabs/OverviewFleetTabPanel"; -import { OverviewOperationsTabPanel } from "./tabs/OverviewOperationsTabPanel"; -import { OverviewStaffTabPanel } from "./tabs/OverviewStaffTabPanel"; - -function TabSkeleton() { - return ( - - - - - - ); -} - -interface OverviewTabContentProps { - tab: OverviewTabKey; - range: OverviewRange; -} - -export function OverviewTabContent({ tab, range }: OverviewTabContentProps) { - const bookings = useOverviewBookingsTab(range, tab === "bookings"); - const contracts = useOverviewContractsTab(range, tab === "contracts"); - const billing = useOverviewBillingTab(range, tab === "billing"); - // Fleet reuses the operations dataset — same query key, so switching between - // the two tabs costs one fetch. - const operations = useOverviewOperationsTab( - range, - tab === "operations" || tab === "fleet", - ); - const customers = useOverviewCustomersTab(range, tab === "customers"); - const staff = useOverviewStaffTab(range, tab === "staff"); - - const query = - tab === "bookings" - ? bookings - : tab === "contracts" - ? contracts - : tab === "billing" - ? billing - : tab === "operations" || tab === "fleet" - ? operations - : tab === "customers" - ? customers - : staff; - - const { isLoading, isError, refetch, isFetching } = query; - - if (isLoading) { - return ; - } - - if (isError || !query.data) { - return ( - - } - color="red" - title="Failed to load tab data" - variant="light" - > - - Could not load {tab} metrics. Please try again. - - - - - ); - } - - return ( - - {isFetching && ( -
- -
- )} - - {tab === "bookings" && bookings.data && ( - - )} - {tab === "contracts" && contracts.data && ( - - )} - {tab === "billing" && billing.data && ( - - )} - {tab === "operations" && operations.data && ( - - )} - {tab === "fleet" && operations.data && ( - - )} - {tab === "customers" && customers.data && ( - - )} - {tab === "staff" && staff.data && ( - - )} -
- ); -} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/overview-domains.config.ts b/apps/edr-freight-web/backoffice/src/components/overview/overview-domains.config.ts new file mode 100644 index 000000000..4d106eeeb --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/overview-domains.config.ts @@ -0,0 +1,88 @@ +import { + Banknote, + FileSignature, + FileText, + Train, + TrainFront, + UserCheck, + Users, + type LucideIcon, +} from "lucide-react"; + +import { FREIGHT_PERMS } from "@/lib/permissions"; +import type { OverviewTabKey } from "@/types/overview"; + +/** + * Single source of truth for the seven overview drill-down pages — used both + * to build the `/dashboard/overview/:domain` routes in App.tsx and to render + * each page's header in OverviewDomainPage. One list, no duplicated permission + * arrays to drift out of sync. + */ +export const OVERVIEW_DOMAINS: Array<{ + key: OverviewTabKey; + label: string; + subtitle: string; + icon: LucideIcon; + /** Any of these keys grants the page. */ + permission: string[]; +}> = [ + { + key: "bookings", + label: "Bookings", + subtitle: "Booking volume, pipeline, and recent activity", + icon: FileText, + permission: [FREIGHT_PERMS.bookings.view], + }, + { + key: "contracts", + label: "Contracts", + subtitle: "Contract volume, pipeline, and recent activity", + icon: FileSignature, + permission: [FREIGHT_PERMS.contracts.view], + }, + { + key: "billing", + label: "Billing", + subtitle: "Revenue, payments, and collection status", + icon: Banknote, + permission: [FREIGHT_PERMS.bookings.view, FREIGHT_PERMS.payments.view], + }, + { + key: "operations", + label: "Operations", + subtitle: "Trains, schedules, containers, and cargo", + icon: Train, + permission: [ + FREIGHT_PERMS.trainScheduling.view, + FREIGHT_PERMS.warehouseInventory.view, + FREIGHT_PERMS.firstMile.view, + FREIGHT_PERMS.lastMile.view, + ], + }, + { + key: "fleet", + label: "Fleet", + subtitle: "Wagon and train fleet status", + icon: TrainFront, + permission: [FREIGHT_PERMS.wagons.view, FREIGHT_PERMS.trainScheduling.view], + }, + { + key: "customers", + label: "Customers", + subtitle: "Customer growth and top accounts", + icon: Users, + permission: [FREIGHT_PERMS.customers.view], + }, + { + key: "staff", + label: "Staff", + subtitle: "Employee and user account status", + icon: UserCheck, + permission: [ + FREIGHT_PERMS.admin, + FREIGHT_PERMS.staff.roles.view, + FREIGHT_PERMS.staff.employeeRegistration.view, + FREIGHT_PERMS.staff.roleAssignment.view, + ], + }, +]; diff --git a/apps/edr-freight-web/backoffice/src/components/overview/overview.css b/apps/edr-freight-web/backoffice/src/components/overview/overview.css index 86b468df3..10b358bbd 100644 --- a/apps/edr-freight-web/backoffice/src/components/overview/overview.css +++ b/apps/edr-freight-web/backoffice/src/components/overview/overview.css @@ -1,5 +1,8 @@ /* ============================================================ - EDR Freight — Overview page styles (hero controls + tabs) + EDR Freight — shared "premium" tab bar + segmented control styles. + Named after the overview page they were first built for, but now shared + by BookingStatusTabs, ContractStatusTabs, and ReceiveInventoryModal — + do not remove `.ov-tablist` / `.ov-tab` without checking those importers. ============================================================ */ /* ---- Hero range segmented control (on gradient) ---- */ @@ -19,7 +22,7 @@ color: var(--mantine-color-edr-green-7); } -/* ---- Premium tab bar ---- */ +/* ---- Premium tab bar (BookingStatusTabs, ContractStatusTabs, ReceiveInventoryModal) ---- */ .ov-tablist { display: flex; flex-wrap: wrap; diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/CountUp.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/CountUp.tsx new file mode 100644 index 000000000..28802e321 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/CountUp.tsx @@ -0,0 +1,44 @@ +import { useEffect, useRef, useState } from "react"; + +const DURATION_MS = 750; + +function prefersReducedMotion() { + return ( + typeof window !== "undefined" && + window.matchMedia("(prefers-reduced-motion: reduce)").matches + ); +} + +/** + * Animates a number from 0 to `value` (ease-out) on mount and whenever the + * value changes — the hero-KPI count-up. Renders the final value immediately + * when the user prefers reduced motion. + */ +export function CountUp({ + value, + format = (n) => Math.round(n).toLocaleString(), +}: { + value: number; + format?: (n: number) => string; +}) { + const [display, setDisplay] = useState(() => (prefersReducedMotion() ? value : 0)); + const frame = useRef(0); + + useEffect(() => { + if (prefersReducedMotion()) { + setDisplay(value); + return; + } + const start = performance.now(); + const tick = (now: number) => { + const t = Math.min(1, (now - start) / DURATION_MS); + const eased = 1 - (1 - t) ** 3; + setDisplay(value * eased); + if (t < 1) frame.current = requestAnimationFrame(tick); + }; + frame.current = requestAnimationFrame(tick); + return () => cancelAnimationFrame(frame.current); + }, [value]); + + return <>{format(display)}; +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewActivityHeatmap.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewActivityHeatmap.tsx new file mode 100644 index 000000000..4f1958265 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewActivityHeatmap.tsx @@ -0,0 +1,125 @@ +import { Fragment } from "react"; +import { CalendarClock } from "lucide-react"; +import { Badge, Group, Stack, Text, Tooltip } from "@mantine/core"; + +import type { IOverviewHeatmapCell } from "@/types/overview"; +import { SummaryCard } from "./SummaryCard"; + +/** ISO weekday order, 1 = Monday. */ +const DAY_LABELS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; +/** 3-hour blocks, 0 = 00–03 … 7 = 21–24. */ +const BLOCK_LABELS = ["12a", "3a", "6a", "9a", "12p", "3p", "6p", "9p"]; + +/** Map an intensity in (0, 1] to the brand-green ramp; zero stays neutral. */ +function cellColor(count: number, max: number) { + if (count === 0) return "var(--mantine-color-gray-1)"; + const shade = Math.max(1, Math.min(7, Math.ceil((count / max) * 7))); + return `var(--mantine-color-edr-green-${shade})`; +} + +interface OverviewActivityHeatmapProps { + cells: IOverviewHeatmapCell[]; +} + +/** + * When demand arrives: booking submissions by weekday × 3-hour block for the + * selected range. The bright cells (and the peak badge) are the hours the + * intake team needs to be staffed for. + */ +export function OverviewActivityHeatmap({ cells }: OverviewActivityHeatmapProps) { + const countByCell = new Map(cells.map((c) => [`${c.dow}-${c.block}`, c.count])); + const max = Math.max(0, ...cells.map((c) => c.count)); + const peak = cells.reduce( + (best, c) => (c.count > (best?.count ?? 0) ? c : best), + null, + ); + + return ( + + Peak {DAY_LABELS[peak.dow - 1]} {BLOCK_LABELS[peak.block]} + + ) : null + } + > + {max === 0 ? ( + + No bookings in this period + + ) : ( + +
+ + {BLOCK_LABELS.map((label) => ( + + {label} + + ))} + {DAY_LABELS.map((day, dayIndex) => ( + + + {day} + + {BLOCK_LABELS.map((_, block) => { + const count = countByCell.get(`${dayIndex + 1}-${block}`) ?? 0; + return ( + +
+ + ); + })} + + ))} +
+ + + Less + + {[0, 2, 4, 6].map((shade) => ( +
+ ))} + + More + + + + )} + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewAttentionCard.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewAttentionCard.tsx new file mode 100644 index 000000000..142b8814f --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewAttentionCard.tsx @@ -0,0 +1,149 @@ +import { + AlertCircle, + Banknote, + BellRing, + Check, + ChevronRight, + Clock, + FileSignature, + ShieldCheck, +} from "lucide-react"; +import { Link } from "react-router-dom"; +import { Badge, Group, Stack, Text, ThemeIcon } from "@mantine/core"; + +import type { IOverviewBillingKpis, IOverviewBookingKpis, IOverviewContractKpis } from "@/types/overview"; +import { SummaryCard } from "./SummaryCard"; + +interface OverviewAttentionCardProps { + bookings: IOverviewBookingKpis; + contracts: IOverviewContractKpis; + billing: IOverviewBillingKpis; +} + +/** + * The work queue, demoted below the money/volume story but still one glance + * away — this page is read by executives first, staff second. Every row + * links to the real filtered (or closest available) list; none are dead ends. + */ +export function OverviewAttentionCard({ bookings, contracts, billing }: OverviewAttentionCardProps) { + const rows = [ + { + key: "needsAction", + label: "Bookings needing action", + count: bookings.needsAction, + icon: AlertCircle, + href: "/dashboard/booking-requests", + }, + { + key: "urgent", + label: "Urgent bookings", + count: bookings.urgent, + icon: Clock, + href: "/dashboard/booking-requests", + }, + { + key: "contractsApproval", + label: "Contracts in approval", + count: contracts.inApproval, + icon: FileSignature, + href: "/dashboard/contract-requests", + }, + { + key: "contractsClearance", + label: "Contracts in clearance", + count: contracts.inClearance, + icon: ShieldCheck, + href: "/dashboard/contracts/clearance", + }, + { + key: "pendingPayments", + label: "Pending payments", + count: billing.pendingPayments, + icon: Banknote, + href: "/dashboard/payments", + }, + ]; + const openItems = rows.reduce((sum, row) => sum + row.count, 0); + const allClear = openItems === 0; + + return ( + + {openItems.toLocaleString()} open + + ) + } + > + {allClear ? ( + + + + + All clear + + Nothing waiting on you right now. + + + ) : ( + + {rows.map((row) => { + const Icon = row.icon; + const active = row.count > 0; + return ( + + + + + + + + {row.label} + + + + + {row.count} + + + + + + ); + })} + + )} + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHero.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHero.tsx new file mode 100644 index 000000000..04e2b273f --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHero.tsx @@ -0,0 +1,140 @@ +import { RefreshCw } from "lucide-react"; +import { ActionIcon, Badge, Group, SegmentedControl, Stack, Text } from "@mantine/core"; + +import { useAuth } from "@/auth/useAuth"; +import { freightBrand } from "@/theme/freight-brand"; +import type { OverviewRange } from "@/types/overview"; +import "@/components/overview/overview.css"; + +const RANGE_OPTIONS = [ + { label: "7 days", value: "7d" }, + { label: "30 days", value: "30d" }, + { label: "90 days", value: "90d" }, +]; + +function formatRelativeTime(iso: string | undefined) { + if (!iso) return "—"; + const diffMs = Date.now() - new Date(iso).getTime(); + const minutes = Math.floor(diffMs / 60_000); + if (minutes < 1) return "just now"; + if (minutes < 60) return `${minutes}m ago`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}h ago`; + return new Date(iso).toLocaleString(); +} + +function greeting(hour: number) { + if (hour < 12) return "Good morning"; + if (hour < 18) return "Good afternoon"; + return "Good evening"; +} + +interface OverviewHeroProps { + range: OverviewRange; + onRangeChange: (range: OverviewRange) => void; + generatedAt?: string; + onRefresh: () => void; + isRefreshing?: boolean; +} + +/** + * Brand-gradient greeting banner: time-of-day greeting with the signed-in + * user's first name, today's date, freshness badge, and the range controls. + * Extra bottom padding leaves room for the KPI strip to overlap it. + */ +export function OverviewHero({ + range, + onRangeChange, + generatedAt, + onRefresh, + isRefreshing, +}: OverviewHeroProps) { + const { user } = useAuth(); + const fullName = (user?.name?.en ?? user?.name?.am)?.trim(); + const firstName = fullName ? fullName.split(/\s+/)[0] : undefined; + const now = new Date(); + const dateLabel = now.toLocaleDateString(undefined, { + weekday: "long", + day: "numeric", + month: "long", + year: "numeric", + }); + + return ( +
+ {/* Soft highlight so the flat gradient reads as a lit surface. */} +
+ + + + {greeting(now.getHours())} + {firstName ? `, ${firstName}` : ""} 👋 + + + + {dateLabel} + + + Updated {formatRelativeTime(generatedAt)} + + + + + onRangeChange(value as OverviewRange)} + data={RANGE_OPTIONS} + size="sm" + radius="lg" + classNames={{ + root: "ov-seg-root", + indicator: "ov-seg-indicator", + label: "ov-seg-label", + }} + /> + + + + + +
+ ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHeroKpis.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHeroKpis.tsx new file mode 100644 index 000000000..32ee768d1 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewHeroKpis.tsx @@ -0,0 +1,67 @@ +import { Banknote, FileSignature, FileText, Package } from "lucide-react"; + +import { KpiStrip, type KpiItem } from "@/components/page"; +import type { IOverviewKpis, IOverviewPeriodTotals } from "@/types/overview"; +import { CountUp } from "./CountUp"; + +function formatCurrency(amount: number, currency: "ETB" | "USD") { + return new Intl.NumberFormat("en-US", { + style: "currency", + currency, + maximumFractionDigits: 0, + }).format(amount); +} + +/** Period-over-period % change, or undefined when there's no prior baseline to compare against. */ +function pctDelta(current: number, previous: number): number | undefined { + if (previous === 0) return undefined; + return Math.round(((current - previous) / previous) * 100); +} + +interface OverviewHeroKpisProps { + kpis: IOverviewKpis; + current: IOverviewPeriodTotals; + previous: IOverviewPeriodTotals; + rangeLabel: string; +} + +/** + * The four numbers an executive reads first: money and volume for the + * selected range, plus what's currently in flight. Revenue and cargo carry a + * real vs-prior-period delta; the two workflow snapshots don't, because + * "active bookings/contracts" is a point-in-time gauge, not a period total — + * showing a delta for it would mean inventing a comparison that isn't real. + */ +export function OverviewHeroKpis({ kpis, current, previous, rangeLabel }: OverviewHeroKpisProps) { + const items: KpiItem[] = [ + { + label: `Revenue (${rangeLabel})`, + value: formatCurrency(n, "ETB")} />, + hint: formatCurrency(current.revenueUsd, "USD"), + icon: Banknote, + color: "yellow", + delta: pctDelta(current.revenueEtb, previous.revenueEtb), + }, + { + label: "Cargo moved", + value: `${Math.round(n).toLocaleString()} t`} />, + icon: Package, + color: "edr-green", + delta: pctDelta(current.tons, previous.tons), + }, + { + label: "Active bookings", + value: , + icon: FileText, + color: "edr-green", + }, + { + label: "Active contracts", + value: , + icon: FileSignature, + color: "edr-green", + }, + ]; + + return ; +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewNetworkCard.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewNetworkCard.tsx new file mode 100644 index 000000000..57a1a1fdc --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewNetworkCard.tsx @@ -0,0 +1,88 @@ +import { + CalendarClock, + Container as ContainerIcon, + Send, + Train, + TrainFront, +} from "lucide-react"; +import { Group, SimpleGrid, Stack, Text } from "@mantine/core"; + +import { MiniRing } from "@/components/common/MiniGraph"; +import type { IOverviewOperationsKpis } from "@/types/overview"; +import { CountUp } from "./CountUp"; +import { SummaryCard } from "./SummaryCard"; + +const STATS: Array<{ + key: keyof IOverviewOperationsKpis; + label: string; + icon: typeof Train; +}> = [ + { key: "trainsActive", label: "Trains active", icon: Train }, + { key: "dispatchedToday", label: "Dispatched today", icon: Send }, + { key: "schedulesUpcoming", label: "Upcoming departures", icon: CalendarClock }, + { key: "containersInTransit", label: "Containers in transit", icon: ContainerIcon }, +]; + +/** Network snapshot: four operational stats plus real wagon-utilization (available / total), not a decorative gauge. */ +export function OverviewNetworkCard({ kpis }: { kpis: IOverviewOperationsKpis }) { + const utilizationPct = kpis.wagonsTotal > 0 ? (kpis.wagonsAvailable / kpis.wagonsTotal) * 100 : null; + + return ( + + View fleet → + + } + > + + + + + {utilizationPct != null ? `${Math.round(utilizationPct)}%` : "—"} + + + + + Wagons available + + + {kpis.wagonsAvailable.toLocaleString()} + + {" "} + / {kpis.wagonsTotal.toLocaleString()} + + + + + + + {STATS.map((stat) => { + const Icon = stat.icon; + return ( + + + + + + + + {stat.label} + + + + ); + })} + + + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewPipelineFunnel.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewPipelineFunnel.tsx new file mode 100644 index 000000000..f28540298 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewPipelineFunnel.tsx @@ -0,0 +1,113 @@ +import { Filter } from "lucide-react"; +import { Link } from "react-router-dom"; +import { Badge, Stack, Text } from "@mantine/core"; + +import { BOOKING_LIST_TABS } from "@/features/bookings/booking-status.config"; +import type { IOverviewPipelineCount } from "@/types/overview"; +import { SummaryCard } from "./SummaryCard"; + +/** Sequential green ramp from the theme's own edr-green scale — rising intensity as bookings progress through the pipeline. */ +const RAMP_SHADES = [3, 4, 5, 5, 6, 6, 7, 8, 9]; + +interface OverviewPipelineFunnelProps { + data: IOverviewPipelineCount[]; +} + +/** Booking pipeline by stage, in workflow order. Each row deep-links to the exact statuses it represents. */ +export function OverviewPipelineFunnel({ data }: OverviewPipelineFunnelProps) { + const rows = data + .map((item) => ({ + ...item, + tab: BOOKING_LIST_TABS.find((t) => t.key === item.stage), + })) + .filter((row) => row.tab); + const maxCount = Math.max(1, ...rows.map((r) => r.count)); + const total = rows.reduce((sum, r) => sum + r.count, 0); + const hasData = total > 0; + + return ( + + {total.toLocaleString()} in pipeline + + ) : null + } + > + {!hasData ? ( + + No bookings in pipeline + + ) : ( + + {rows.map((row, index) => { + const statuses = row.tab?.statuses; + const href = statuses?.length + ? `/dashboard/booking-requests?statuses=${statuses.join(",")}` + : "/dashboard/booking-requests"; + const shade = RAMP_SHADES[Math.min(index, RAMP_SHADES.length - 1)]; + + return ( + + + {row.tab?.label ?? row.stage} + +
+
+
+ + {row.count} + + + ); + })} + + )} + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueMix.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueMix.tsx new file mode 100644 index 000000000..c2839350b --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueMix.tsx @@ -0,0 +1,143 @@ +import { PieChart } from "lucide-react"; +import { Stack, Text } from "@mantine/core"; + +import type { IOverviewRevenueSlice } from "@/types/overview"; +import { DIRECTION_COLORS, FLOW_FALLBACK_COLOR, FREIGHT_TYPE_COLORS } from "./flow-colors"; +import { CountUp } from "./CountUp"; +import { SummaryCard } from "./SummaryCard"; + +function formatEtb(amount: number) { + return new Intl.NumberFormat("en-US", { + style: "currency", + currency: "ETB", + maximumFractionDigits: 0, + }).format(amount); +} + +const DIRECTION_LABELS: Record = { + IMPORT: "Import", + EXPORT: "Export", + DOMESTIC: "Domestic", +}; + +const FREIGHT_TYPE_LABELS: Record = { + CONTAINER: "Container", + BULK: "Bulk", +}; + +/** One breakdown's proportion bar + legend, sized by ETB revenue (no FX rate exists to fold USD in). */ +function MixRow({ + title, + slices, + labels, + colors, +}: { + title: string; + slices: IOverviewRevenueSlice[]; + labels: Record; + colors: Record; +}) { + const total = slices.reduce((sum, s) => sum + s.amountEtb, 0); + + return ( + + + {title} + + {total === 0 ? ( + + No revenue in this period + + ) : ( + <> +
+ {slices + .filter((s) => s.amountEtb > 0) + .map((s) => ( +
+ ))} +
+ + {slices + .filter((s) => s.amountEtb > 0) + .map((s) => ( +
+ + + {labels[s.label] ?? s.label} + + {formatEtb(s.amountEtb)} + + {Math.round((s.amountEtb / total) * 100)}% + +
+ ))} +
+ + )} + + ); +} + +interface OverviewRevenueMixProps { + byDirection: IOverviewRevenueSlice[]; + byFreightType: IOverviewRevenueSlice[]; +} + +/** ETB revenue split two ways — trade direction and freight type — anchored by the range total. */ +export function OverviewRevenueMix({ byDirection, byFreightType }: OverviewRevenueMixProps) { + const total = byDirection.reduce((sum, s) => sum + s.amountEtb, 0); + + return ( + + +
+ + + + + attributed to a trade direction + +
+ + +
+
+ ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueVolumeChart.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueVolumeChart.tsx new file mode 100644 index 000000000..12b20a45e --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewRevenueVolumeChart.tsx @@ -0,0 +1,172 @@ +import { + Area, + Bar, + CartesianGrid, + ComposedChart, + Line, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; +import { ChartColumnBig } from "lucide-react"; +import { Group, Text } from "@mantine/core"; + +import type { IOverviewPaymentTrendPoint, IOverviewTrendPoint } from "@/types/overview"; +import { overviewChartColors } from "../overview.styles"; +import { chartAxisTick, chartGridStroke, chartTooltipStyle } from "./chart-style"; +import { mergeTrend } from "./mergeTrend"; +import { SummaryCard } from "./SummaryCard"; + +function formatDateLabel(date: string) { + return new Date(`${date}T00:00:00`).toLocaleDateString(undefined, { + month: "short", + day: "numeric", + }); +} + +function formatEtb(amount: number) { + return new Intl.NumberFormat("en-US", { + style: "currency", + currency: "ETB", + maximumFractionDigits: 0, + }).format(amount); +} + +const compact = new Intl.NumberFormat("en-US", { notation: "compact" }); + +/** Dot-and-label legend row rendered in the card header instead of recharts' default. */ +function LegendDot({ color, dashed, label }: { color: string; dashed?: boolean; label: string }) { + return ( + + {dashed ? ( + + + + ) : ( + + )} + + {label} + + + ); +} + +interface OverviewRevenueVolumeChartProps { + bookingTrend: IOverviewTrendPoint[]; + paymentTrend: IOverviewPaymentTrendPoint[]; + previousPaymentTrend: IOverviewPaymentTrendPoint[]; + rangeDays: number; +} + +/** + * Volume and money in one read: bars are bookings created per day, the gold + * area is ETB revenue per day, and the dashed ghost line is the preceding + * period's revenue shifted onto the same axis — "are we pacing ahead of last + * period" at a glance. + */ +export function OverviewRevenueVolumeChart({ + bookingTrend, + paymentTrend, + previousPaymentTrend, + rangeDays, +}: OverviewRevenueVolumeChartProps) { + const data = mergeTrend(bookingTrend, paymentTrend, previousPaymentTrend, rangeDays); + const hasData = data.some((point) => point.bookings > 0 || point.revenueEtb > 0); + + return ( + + + + + + } + > + {!hasData ? ( + + No activity in this period + + ) : ( + + + + + + + + + + + + compact.format(Number(value))} + tick={chartAxisTick} + axisLine={false} + tickLine={false} + width={44} + /> + formatDateLabel(String(value))} + formatter={(value, name) => + name === "Bookings" ? [value, name] : [formatEtb(Number(value)), name] + } + contentStyle={chartTooltipStyle} + /> + + + + + + )} + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewSankeyFlow.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewSankeyFlow.tsx new file mode 100644 index 000000000..1e4597ee9 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/OverviewSankeyFlow.tsx @@ -0,0 +1,170 @@ +import { Waypoints } from "lucide-react"; +import { ResponsiveContainer, Sankey, Tooltip, type SankeyLinkProps } from "recharts"; +import { Text } from "@mantine/core"; + +import type { IOverviewRevenueFlow } from "@/types/overview"; +import { chartTooltipStyle } from "./chart-style"; +import { SummaryCard } from "./SummaryCard"; +import { + DIRECTION_COLORS, + FLOW_FALLBACK_COLOR, + FLOW_LABELS, + FREIGHT_TYPE_COLORS, +} from "./flow-colors"; + +function formatEtb(amount: number) { + return new Intl.NumberFormat("en-US", { + style: "currency", + currency: "ETB", + maximumFractionDigits: 0, + }).format(amount); +} + +interface SankeyNodeDatum { + name: string; + key: string; + color: string; +} + +/** Build recharts Sankey data: direction nodes on the left, freight types on the right. */ +function toSankeyData(flows: IOverviewRevenueFlow[]) { + const active = flows.filter((f) => f.amountEtb > 0); + const nodes: SankeyNodeDatum[] = []; + const indexByKey = new Map(); + const nodeIndex = (key: string, color: string) => { + const existing = indexByKey.get(key); + if (existing != null) return existing; + nodes.push({ name: FLOW_LABELS[key] ?? key, key, color }); + indexByKey.set(key, nodes.length - 1); + return nodes.length - 1; + }; + + // Register directions first so they all land on the left column. + for (const flow of active) { + nodeIndex(flow.direction, DIRECTION_COLORS[flow.direction] ?? FLOW_FALLBACK_COLOR); + } + const links = active.map((flow) => ({ + source: indexByKey.get(flow.direction)!, + target: nodeIndex( + flow.freightType, + FREIGHT_TYPE_COLORS[flow.freightType] ?? FLOW_FALLBACK_COLOR, + ), + value: flow.amountEtb, + })); + + return { nodes, links }; +} + +function FlowNode({ + x, + y, + width, + height, + index, + payload, +}: { + x: number; + y: number; + width: number; + height: number; + index: number; + payload: { name?: string; value?: number; color?: string }; +}) { + // Labels sit to the right of every bar: the right margin reserves room for + // the last column, and the pale ribbons stay readable under the left one. + return ( + + + + {payload.name} + + + {formatEtb(payload.value ?? 0)} + + + ); +} + +/** Ribbon tinted by its source direction — the corridor keeps its color across the chart. */ +function FlowLink({ + sourceX, + targetX, + sourceY, + targetY, + sourceControlX, + targetControlX, + linkWidth, + index, + payload, +}: SankeyLinkProps) { + // Custom node fields (color) ride along on the layout node recharts hands back. + const source = payload.source as { color?: string }; + return ( + + ); +} + +interface OverviewSankeyFlowProps { + flows: IOverviewRevenueFlow[]; +} + +/** + * Where the money runs: ETB revenue as ribbons from trade direction to + * freight type. Ribbon thickness is proportional to revenue, so the biggest + * corridor is unmissable. + */ +export function OverviewSankeyFlow({ flows }: OverviewSankeyFlowProps) { + const data = toSankeyData(flows); + + return ( + + {data.links.length === 0 ? ( + + No revenue in this period + + ) : ( + + + formatEtb(Number(value))} + contentStyle={chartTooltipStyle} + /> + + + )} + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/SummaryCard.tsx b/apps/edr-freight-web/backoffice/src/components/overview/summary/SummaryCard.tsx new file mode 100644 index 000000000..cfd022fe9 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/SummaryCard.tsx @@ -0,0 +1,65 @@ +import type { LucideIcon } from "lucide-react"; +import { Group, Stack, Text, ThemeIcon } from "@mantine/core"; +import type { ElementType, ReactNode } from "react"; +import { Link } from "react-router-dom"; + +import "./overview-summary.css"; + +interface SummaryCardProps { + icon: LucideIcon; + /** Mantine color for the icon chip. */ + accent?: string; + title: string; + subtitle?: string; + /** Right side of the header — a legend, badge, or link. */ + action?: ReactNode; + /** Makes the whole card a link (adds the hover lift). */ + to?: string; + minHeight?: number; + children: ReactNode; +} + +/** + * Shared chrome for every overview card: soft gradient surface, layered + * shadow, icon-chip header with title/subtitle, optional action slot. + * One look for the whole page instead of eight flat white boxes. + */ +export function SummaryCard({ + icon: Icon, + accent = "edr-green", + title, + subtitle, + action, + to, + minHeight = 340, + children, +}: SummaryCardProps) { + const Root: ElementType = to ? Link : "div"; + return ( + + + + + + + + + {title} + + {subtitle ? ( + + {subtitle} + + ) : null} + + + {action} + + {children} + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/chart-style.ts b/apps/edr-freight-web/backoffice/src/components/overview/summary/chart-style.ts new file mode 100644 index 000000000..9f7dbae8d --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/chart-style.ts @@ -0,0 +1,14 @@ +import type { CSSProperties } from "react"; + +/** Shared recharts styling for the overview summary charts. */ +export const chartGridStroke = "#EEF1F5"; + +export const chartAxisTick = { fontSize: 11, fill: "#8fa0b2" } as const; + +export const chartTooltipStyle: CSSProperties = { + borderRadius: 12, + border: "1px solid #EEF1F5", + boxShadow: "0 8px 24px rgba(16, 32, 47, 0.1)", + fontSize: 12, + padding: "8px 12px", +}; diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/flow-colors.ts b/apps/edr-freight-web/backoffice/src/components/overview/summary/flow-colors.ts new file mode 100644 index 000000000..f3c7a2ace --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/flow-colors.ts @@ -0,0 +1,25 @@ +/** + * Fixed colors + labels for trade directions and freight types, shared by the + * revenue mix and Sankey so the same entity is always the same color (and + * matches the operations departure chart's direction hexes). + */ +export const DIRECTION_COLORS: Record = { + EXPORT: "#D98A0B", + IMPORT: "#0369a1", + DOMESTIC: "#7c3aed", +}; + +export const FREIGHT_TYPE_COLORS: Record = { + CONTAINER: "#1B9E7A", + BULK: "#34D9AE", +}; + +export const FLOW_LABELS: Record = { + IMPORT: "Import", + EXPORT: "Export", + DOMESTIC: "Domestic", + CONTAINER: "Container", + BULK: "Bulk", +}; + +export const FLOW_FALLBACK_COLOR = "#94a3b8"; diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.test.ts b/apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.test.ts new file mode 100644 index 000000000..369b19237 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; + +import { mergeTrend } from "./mergeTrend"; + +describe("mergeTrend", () => { + it("unions dates from both trends, zero-filling the side that has no row", () => { + const result = mergeTrend( + [ + { date: "2026-06-01", count: 3 }, + { date: "2026-06-02", count: 5 }, + ], + [{ date: "2026-06-02", amountEtb: 1000, amountUsd: 0 }], + ); + + expect(result).toEqual([ + { date: "2026-06-01", bookings: 3, revenueEtb: 0 }, + { date: "2026-06-02", bookings: 5, revenueEtb: 1000 }, + ]); + }); + + it("sorts chronologically regardless of input order", () => { + const result = mergeTrend( + [{ date: "2026-06-03", count: 1 }], + [{ date: "2026-06-01", amountEtb: 500, amountUsd: 0 }], + ); + + expect(result.map((p) => p.date)).toEqual(["2026-06-01", "2026-06-03"]); + }); + + it("returns an empty series when both trends are empty", () => { + expect(mergeTrend([], [])).toEqual([]); + }); + + it("shifts the previous period forward so day N lands on day N of the current window", () => { + const result = mergeTrend( + [{ date: "2026-06-08", count: 2 }], + [], + [ + // 7d range: 2026-06-01 + 7 = 2026-06-08 (existing row), 06-02 + 7 = 06-09 (new row) + { date: "2026-06-01", amountEtb: 400, amountUsd: 0 }, + { date: "2026-06-02", amountEtb: 250, amountUsd: 0 }, + ], + 7, + ); + + expect(result).toEqual([ + { date: "2026-06-08", bookings: 2, revenueEtb: 0, prevRevenueEtb: 400 }, + { date: "2026-06-09", bookings: 0, revenueEtb: 0, prevRevenueEtb: 250 }, + ]); + }); + + it("shifts across a month boundary without timezone drift", () => { + const result = mergeTrend([], [], [{ date: "2026-05-28", amountEtb: 100, amountUsd: 0 }], 7); + expect(result[0].date).toBe("2026-06-04"); + }); +}); diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.ts b/apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.ts new file mode 100644 index 000000000..0ddc0d705 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/mergeTrend.ts @@ -0,0 +1,63 @@ +import type { IOverviewPaymentTrendPoint, IOverviewTrendPoint } from "@/types/overview"; + +export interface RevenueVolumePoint { + date: string; + bookings: number; + revenueEtb: number; + /** Same-offset day of the preceding period — the ghost comparison line. */ + prevRevenueEtb?: number; +} + +/** `date` (YYYY-MM-DD) plus `days` days, in UTC so no DST/timezone drift. */ +export function shiftDate(date: string, days: number): string { + const parsed = new Date(`${date}T00:00:00Z`); + parsed.setUTCDate(parsed.getUTCDate() + days); + return parsed.toISOString().slice(0, 10); +} + +/** + * Merge the booking-count trend and the payment trend into one date-keyed + * series for the combined volume/revenue chart. Both trends only carry rows + * for days with activity (no zero-filled gaps), so this unions the dates + * rather than assuming they line up. + * + * When the previous period's payment trend is provided, each of its days is + * shifted forward by `shiftDays` (the range length) so day N of the prior + * window lands on day N of the current one, and lands in `prevRevenueEtb`. + */ +export function mergeTrend( + bookingTrend: IOverviewTrendPoint[], + paymentTrend: IOverviewPaymentTrendPoint[], + previousPaymentTrend: IOverviewPaymentTrendPoint[] = [], + shiftDays = 0, +): RevenueVolumePoint[] { + const byDate = new Map(); + + for (const point of bookingTrend) { + byDate.set(point.date, { date: point.date, bookings: point.count, revenueEtb: 0 }); + } + for (const point of paymentTrend) { + const existing = byDate.get(point.date); + if (existing) { + existing.revenueEtb = point.amountEtb; + } else { + byDate.set(point.date, { date: point.date, bookings: 0, revenueEtb: point.amountEtb }); + } + } + for (const point of previousPaymentTrend) { + const date = shiftDate(point.date, shiftDays); + const existing = byDate.get(date); + if (existing) { + existing.prevRevenueEtb = point.amountEtb; + } else { + byDate.set(date, { + date, + bookings: 0, + revenueEtb: 0, + prevRevenueEtb: point.amountEtb, + }); + } + } + + return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date)); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/summary/overview-summary.css b/apps/edr-freight-web/backoffice/src/components/overview/summary/overview-summary.css new file mode 100644 index 000000000..0391010b8 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/overview/summary/overview-summary.css @@ -0,0 +1,65 @@ +/* Staggered fade-up entrance for the overview bands. Delay is set inline per + band; disabled entirely for reduced-motion users. */ +.ov-band { + animation: ov-rise 420ms ease-out both; +} + +@keyframes ov-rise { + from { + opacity: 0; + transform: translateY(14px); + } + to { + opacity: 1; + transform: none; + } +} + +@media (prefers-reduced-motion: reduce) { + .ov-band { + animation: none; + } +} + +/* ---- Shared card chrome (SummaryCard) ---- */ +.ov-card { + display: block; + height: 100%; + background: linear-gradient(180deg, #ffffff 0%, #fbfdfc 100%); + border: 1px solid var(--mantine-color-edr-border-0); + border-radius: 20px; + padding: 20px; + color: inherit; + text-decoration: none; + box-shadow: + 0 1px 2px rgba(16, 32, 47, 0.04), + 0 12px 32px -18px rgba(16, 32, 47, 0.14); + transition: + box-shadow 180ms ease, + transform 180ms ease, + border-color 180ms ease; +} +/* The lift is a click affordance — only linked cards get it. */ +.ov-card--link:hover { + box-shadow: + 0 2px 4px rgba(16, 32, 47, 0.05), + 0 20px 44px -18px rgba(16, 32, 47, 0.2); + border-color: var(--mantine-color-edr-green-2); + transform: translateY(-2px); +} + +/* Soft inset panel for grouping content inside a card. */ +.ov-inset { + background: var(--mantine-color-gray-0); + border: 1px solid var(--mantine-color-gray-1); + border-radius: 14px; +} + +/* Interactive list row inside a card. */ +.ov-row { + border-radius: 12px; + transition: background 140ms ease; +} +.ov-row:hover { + background: var(--mantine-color-gray-0); +} diff --git a/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewBookingsTabPanel.tsx b/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewBookingsTabPanel.tsx index cacba63e1..696741873 100644 --- a/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewBookingsTabPanel.tsx +++ b/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewBookingsTabPanel.tsx @@ -59,12 +59,6 @@ export function OverviewBookingsTabPanel({ data }: OverviewBookingsTabPanelProps accent: "sky", hint: "Pending sign-off", }, - { - label: "Submitted today", - value: data.kpis.submittedToday, - icon: FileText, - hint: "New since midnight", - }, ]} /> diff --git a/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewContractsTabPanel.tsx b/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewContractsTabPanel.tsx index e185f40d2..9265da37d 100644 --- a/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewContractsTabPanel.tsx +++ b/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewContractsTabPanel.tsx @@ -76,12 +76,6 @@ export function OverviewContractsTabPanel({ accent: "rose", hint: "Customs / documents", }, - { - label: "Created today", - value: data.kpis.createdToday, - icon: FileSignature, - hint: "New since midnight", - }, ]} /> diff --git a/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewOperationsTabPanel.tsx b/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewOperationsTabPanel.tsx index 675a81b32..b335ccf9c 100644 --- a/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewOperationsTabPanel.tsx +++ b/apps/edr-freight-web/backoffice/src/components/overview/tabs/OverviewOperationsTabPanel.tsx @@ -1,5 +1,4 @@ import { - Box, CalendarClock, Container as ContainerIcon, Send, @@ -78,11 +77,6 @@ export function OverviewOperationsTabPanel({ data }: OverviewOperationsTabPanelP value: data.kpis.containersInTransit, icon: ContainerIcon, }, - { - label: "Cargoes loaded", - value: data.kpis.cargoesLoaded, - icon: Box, - }, ]} /> diff --git a/apps/edr-freight-web/backoffice/src/components/page/KpiStrip.tsx b/apps/edr-freight-web/backoffice/src/components/page/KpiStrip.tsx index 6b90d6c8a..01a80db61 100644 --- a/apps/edr-freight-web/backoffice/src/components/page/KpiStrip.tsx +++ b/apps/edr-freight-web/backoffice/src/components/page/KpiStrip.tsx @@ -103,8 +103,16 @@ export function KpiStrip({ items, loading = false }: KpiStripProps) { component="span" fz="xs" fw={700} - c={item.delta > 0 ? "edr-green" : "red"} - style={{ whiteSpace: "nowrap" }} + c={item.delta > 0 ? "edr-green.7" : "red.7"} + style={{ + whiteSpace: "nowrap", + background: + item.delta > 0 + ? "var(--mantine-color-edr-green-0)" + : "var(--mantine-color-red-0)", + borderRadius: 999, + padding: "1px 7px", + }} > {item.delta > 0 ? "▲" : "▼"} {Math.abs(item.delta)} diff --git a/apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewDomainPage.tsx b/apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewDomainPage.tsx new file mode 100644 index 000000000..25ede8b4e --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewDomainPage.tsx @@ -0,0 +1,145 @@ +import { useState } from "react"; +import { useParams } from "react-router-dom"; +import { AlertCircle, RefreshCw } from "lucide-react"; +import { ActionIcon, Alert, Button, Center, Loader, Paper, SegmentedControl, Skeleton, Stack } from "@mantine/core"; + +import { PageContainer, PageHeader } from "@/components/page"; +import { OVERVIEW_DOMAINS } from "@/components/overview/overview-domains.config"; +import { OverviewBillingTabPanel } from "@/components/overview/tabs/OverviewBillingTabPanel"; +import { OverviewBookingsTabPanel } from "@/components/overview/tabs/OverviewBookingsTabPanel"; +import { OverviewContractsTabPanel } from "@/components/overview/tabs/OverviewContractsTabPanel"; +import { OverviewCustomersTabPanel } from "@/components/overview/tabs/OverviewCustomersTabPanel"; +import { OverviewFleetTabPanel } from "@/components/overview/tabs/OverviewFleetTabPanel"; +import { OverviewOperationsTabPanel } from "@/components/overview/tabs/OverviewOperationsTabPanel"; +import { OverviewStaffTabPanel } from "@/components/overview/tabs/OverviewStaffTabPanel"; +import { + useOverviewBillingTab, + useOverviewBookingsTab, + useOverviewContractsTab, + useOverviewCustomersTab, + useOverviewOperationsTab, + useOverviewStaffTab, +} from "@/hooks/useOverview"; +import type { OverviewRange, OverviewTabKey } from "@/types/overview"; + +const RANGE_OPTIONS = [ + { label: "7 days", value: "7d" }, + { label: "30 days", value: "30d" }, + { label: "90 days", value: "90d" }, +]; + +function DomainSkeleton() { + return ( + + + + + + ); +} + +/** + * One domain's full depth — what used to be a tab panel on the overview page + * is now its own page, reached from that domain's "View all →" link. Same + * per-domain hooks and panel components as before; only the tab-switch + * wrapper (OverviewTabContent) is gone, replaced by a route param. + */ +export default function OverviewDomainPage() { + const { domain } = useParams<{ domain: OverviewTabKey }>(); + const [range, setRange] = useState("30d"); + + const meta = OVERVIEW_DOMAINS.find((d) => d.key === domain); + + const bookings = useOverviewBookingsTab(range, domain === "bookings"); + const contracts = useOverviewContractsTab(range, domain === "contracts"); + const billing = useOverviewBillingTab(range, domain === "billing"); + // Fleet reuses the operations dataset — same query key, so switching between + // the two pages costs no extra fetch. + const operations = useOverviewOperationsTab( + range, + domain === "operations" || domain === "fleet", + ); + const customers = useOverviewCustomersTab(range, domain === "customers"); + const staff = useOverviewStaffTab(range, domain === "staff"); + + const query = + domain === "bookings" + ? bookings + : domain === "contracts" + ? contracts + : domain === "billing" + ? billing + : domain === "operations" || domain === "fleet" + ? operations + : domain === "customers" + ? customers + : staff; + + const { isLoading, isError, refetch, isFetching } = query; + + return ( + + + setRange(value as OverviewRange)} + data={RANGE_OPTIONS} + size="sm" + radius="lg" + color="edr-green" + /> + void refetch()} + loading={isFetching && !isLoading} + > + + + + } + /> + + {isLoading ? ( + + ) : isError || !query.data ? ( + + } color="red" title="Failed to load" variant="light"> + + Could not load {meta?.label ?? "this"} metrics. Please try again. + + + + + ) : ( + + {isFetching && ( +
+ +
+ )} + + {domain === "bookings" && bookings.data && } + {domain === "contracts" && contracts.data && } + {domain === "billing" && billing.data && } + {domain === "operations" && operations.data && ( + + )} + {domain === "fleet" && operations.data && } + {domain === "customers" && customers.data && } + {domain === "staff" && staff.data && } +
+ )} +
+ ); +} diff --git a/apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewPage.tsx b/apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewPage.tsx index 008149adb..aa29fa0cf 100644 --- a/apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewPage.tsx +++ b/apps/edr-freight-web/backoffice/src/pages/dashboard/OverviewPage.tsx @@ -1,141 +1,61 @@ import { useState } from "react"; -import { - AlertCircle, - Banknote, - FileSignature, - FileText, - Train, - TrainFront, - UserCheck, - Users, -} from "lucide-react"; -import { - Alert, - Badge, - Button, - Container, - Skeleton, - Stack, - Tabs, -} from "@mantine/core"; +import { AlertCircle } from "lucide-react"; +import { Alert, Button, Grid, Skeleton, Stack, Text } from "@mantine/core"; import { useQueryClient } from "@tanstack/react-query"; -import { useAuth } from "@/auth/useAuth"; -import { OverviewPageHeader } from "@/components/overview/OverviewPageHeader"; -import { OverviewTabContent } from "@/components/overview/OverviewTabContent"; -import "@/components/overview/overview.css"; +import { PageContainer } from "@/components/page"; +import { OverviewActivityHeatmap } from "@/components/overview/summary/OverviewActivityHeatmap"; +import { OverviewAttentionCard } from "@/components/overview/summary/OverviewAttentionCard"; +import { OverviewHero } from "@/components/overview/summary/OverviewHero"; +import { OverviewHeroKpis } from "@/components/overview/summary/OverviewHeroKpis"; +import { OverviewNetworkCard } from "@/components/overview/summary/OverviewNetworkCard"; +import { OverviewPipelineFunnel } from "@/components/overview/summary/OverviewPipelineFunnel"; +import { OverviewRevenueMix } from "@/components/overview/summary/OverviewRevenueMix"; +import { OverviewRevenueVolumeChart } from "@/components/overview/summary/OverviewRevenueVolumeChart"; +import { OverviewSankeyFlow } from "@/components/overview/summary/OverviewSankeyFlow"; import { QUERY_KEYS } from "@/constants/QUERY_KEYS"; import { useOverview } from "@/hooks/useOverview"; -import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions"; -import type { OverviewRange, OverviewTabKey } from "@/types/overview"; +import type { OverviewRange } from "@/types/overview"; +import "@/components/overview/summary/overview-summary.css"; -const TAB_ITEMS: Array<{ - value: OverviewTabKey; - label: string; - icon: typeof FileText; - kpiKey: - | "bookings" - | "contracts" - | "billing" - | "operations" - | "customers" - | "staff"; - metricKey: string; - /** Any of these keys grants the tab. */ - permission: string[]; -}> = [ - { - value: "bookings", - label: "Bookings", - icon: FileText, - kpiKey: "bookings", - metricKey: "totalActive", - permission: [FREIGHT_PERMS.bookings.view], - }, - { - value: "contracts", - label: "Contracts", - icon: FileSignature, - kpiKey: "contracts", - metricKey: "totalActive", - permission: [FREIGHT_PERMS.contracts.view], - }, - { - value: "billing", - label: "Billing", - icon: Banknote, - kpiKey: "billing", - metricKey: "successfulPaymentsMtd", - permission: [FREIGHT_PERMS.bookings.view, FREIGHT_PERMS.payments.view], - }, - { - value: "operations", - label: "Operations", - icon: Train, - kpiKey: "operations", - metricKey: "trainsActive", - permission: [ - FREIGHT_PERMS.trainScheduling.view, - FREIGHT_PERMS.warehouseInventory.view, - FREIGHT_PERMS.firstMile.view, - FREIGHT_PERMS.lastMile.view, - ], - }, - { - value: "fleet", - label: "Fleet", - icon: TrainFront, - kpiKey: "operations", - metricKey: "wagonsAvailable", - permission: [FREIGHT_PERMS.wagons.view, FREIGHT_PERMS.trainScheduling.view], - }, - { - value: "customers", - label: "Customers", - icon: Users, - kpiKey: "customers", - metricKey: "totalCustomers", - permission: [FREIGHT_PERMS.customers.view], - }, - { - value: "staff", - label: "Staff", - icon: UserCheck, - kpiKey: "staff", - metricKey: "activeEmployees", - permission: [ - FREIGHT_PERMS.admin, - FREIGHT_PERMS.staff.roles.view, - FREIGHT_PERMS.staff.employeeRegistration.view, - FREIGHT_PERMS.staff.roleAssignment.view, - ], - }, -]; +const RANGE_LABEL: Record = { "7d": "7d", "30d": "30d", "90d": "90d" }; +const RANGE_DAYS: Record = { "7d": 7, "30d": 30, "90d": 90 }; -function HeaderSkeleton() { +/** Uppercase section eyebrow — matches the WarehouseDashboardPage convention. */ +function SectionTitle({ children }: { children: string }) { return ( - - - + + {children} + + ); +} + +/** One page band: eyebrow + content, with a staggered entrance by index. */ +function Band({ index, title, children }: { index: number; title: string; children: React.ReactNode }) { + return ( + + {title} + {children} + + ); +} + +function OverviewSkeleton() { + return ( + + + + + ); } const OverviewPage = () => { const [range, setRange] = useState("30d"); - const [activeTab, setActiveTab] = useState("bookings"); const queryClient = useQueryClient(); - const { user } = useAuth(); - const { data: summary, isLoading, isError, error, refetch, isFetching } = useOverview(range); + const { data, isLoading, isError, error, refetch, isFetching } = useOverview(range); - // Permission-scoped view: only tabs the user may see; a restricted role - // (e.g. operations) gets a summary 403 — that is not a connection problem. - const visibleTabs = TAB_ITEMS.filter((tab) => - tab.permission.some((key) => hasPermission(user, key)), - ); - const currentTab = visibleTabs.some((t) => t.value === activeTab) - ? activeTab - : visibleTabs[0]?.value; const accessDenied = (error as { response?: { status?: number } } | null)?.response?.status === 403; @@ -144,97 +64,113 @@ const OverviewPage = () => { void queryClient.invalidateQueries({ queryKey: QUERY_KEYS.OVERVIEW.ROOT }); }; - const getTabBadge = (tab: (typeof TAB_ITEMS)[number]) => { - if (!summary?.kpis) return 0; - const group = summary.kpis[tab.kpiKey] as unknown as Record; - return group[tab.metricKey] ?? 0; - }; - return ( - - - {isLoading && !summary ? ( - - ) : ( - - )} + + {/* Gradient greeting hero; the KPI strip overlaps its bottom edge. */} +
+ + {data ? ( +
+ +
+ ) : null} +
- {isError && !accessDenied && ( - } - color="red" - title="Unable to load dashboard summary" - variant="light" - > - - Check your connection and try again. - - - - )} + {isError && !accessDenied && ( + } + color="red" + title="Unable to load dashboard summary" + variant="light" + mt="lg" + > + + Check your connection and try again. + + + + )} - {visibleTabs.length === 0 && !isLoading && !isError && ( - - Your role has no access to any overview section. - - )} + {accessDenied && ( + + Your role has no access to the overview. + + )} - {visibleTabs.length > 0 && ( - - setActiveTab((value as OverviewTabKey) ?? visibleTabs[0].value) - } - variant="pills" - color="edr-green" - keepMounted={false} - classNames={{ list: "ov-tablist", tab: "ov-tab" }} - > - - {visibleTabs.map((tab) => { - const Icon = tab.icon; - const isActive = currentTab === tab.value; - return ( - } - rightSection={ - summary ? ( - - {getTabBadge(tab)} - - ) : undefined - } - > - {tab.label} - - ); - })} - + {isLoading && !data ? ( + + + + ) : data ? ( + + {/* Band 1 — revenue & volume: growing, making money, pacing vs last period. */} + + + + + + + + + + - {visibleTabs.map((tab) => ( - - - - ))} - - )} -
-
+ {/* Band 2 — where the money runs, and what's waiting on someone. */} + + + + + + + + + + + + {/* Band 3 — the network now, and when demand arrives. */} + + + + + + + + + + + + {/* Band 4 — the booking pipeline, full width so every stage bar has room. */} + + + +
+ ) : null} + ); }; diff --git a/packages/types/src/freight/overview.ts b/packages/types/src/freight/overview.ts index e3d98bc00..4972db10d 100644 --- a/packages/types/src/freight/overview.ts +++ b/packages/types/src/freight/overview.ts @@ -13,6 +13,7 @@ export interface IOverviewBookingKpis { export interface IOverviewOperationsKpis { trainsActive: number; wagonsAvailable: number; + wagonsTotal: number; containersInTransit: number; cargoesLoaded: number; schedulesUpcoming: number; @@ -99,13 +100,60 @@ export interface IOverviewRecentContract { createdAt: string; } +/** Bookings/revenue/tonnage totals for one range-wide window. */ +export interface IOverviewPeriodTotals { + bookingsCreated: number; + revenueEtb: number; + revenueUsd: number; + tons: number; +} + +/** One label's revenue split, e.g. a trade direction or freight type. */ +export interface IOverviewRevenueSlice { + label: string; + amountEtb: number; + amountUsd: number; +} + +export interface IOverviewTonsTrendPoint { + date: string; + tons: number; +} + +/** One direction → freight-type revenue flow (Sankey link). */ +export interface IOverviewRevenueFlow { + direction: string; + freightType: string; + amountEtb: number; + amountUsd: number; +} + +/** Booking arrivals for one weekday × 3-hour block. */ +export interface IOverviewHeatmapCell { + /** ISO weekday, 1 = Monday … 7 = Sunday. */ + dow: number; + /** 3-hour block, 0 = 00–03 … 7 = 21–24. */ + block: number; + count: number; +} + export interface IOverviewDashboard { kpis: IOverviewKpis; bookingTrend: IOverviewTrendPoint[]; bookingsByStatus: IOverviewStatusCount[]; bookingsByPipeline: IOverviewPipelineCount[]; paymentTrend: IOverviewPaymentTrendPoint[]; - recentBookings: IOverviewRecentBooking[]; + /** Totals for the selected range, ending today. */ + current: IOverviewPeriodTotals; + /** Totals for the immediately preceding range of the same length — the delta baseline. */ + previous: IOverviewPeriodTotals; + revenueByDirection: IOverviewRevenueSlice[]; + revenueByFreightType: IOverviewRevenueSlice[]; + /** The preceding same-length window's daily revenue — ghost-line comparison. */ + previousPaymentTrend: IOverviewPaymentTrendPoint[]; + tonsTrend: IOverviewTonsTrendPoint[]; + revenueFlows: IOverviewRevenueFlow[]; + bookingHeatmap: IOverviewHeatmapCell[]; generatedAt: string; }