# Dashboard Refactor
## Overview
This merge request performs a major cleanup and architectural refactor of the dashboard component system.
The primary goals were:
* Consolidate dashboard state handling
* Standardize component contracts
* Remove duplicated transaction aggregation logic
* Simplify theming
* Eliminate unnecessary wrapper/view layers
* Improve maintainability and type safety
---
# Major Changes
## Dashboard Architecture Refactor
### Consolidated State API
Introduced a centralized `DashboardStateSetters` interface:
```ts
export interface DashboardStateSetters {
setSelectedPeriodId: (id: DashboardSelectedPeriodId) => void;
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
toggleFlow: () => void;
togglePeriodType: () => void;
toggleComparison: () => void;
}
```
This removes scattered prop drilling and standardizes dashboard interaction handling.
---
### Introduced Shared `ComponentProps`
All dashboard widgets now consume a unified contract:
```ts
export interface ComponentProps extends DashboardSection {
reportData: ReportData;
state: DashboardState;
stateSetters: DashboardStateSetters;
isFetching: boolean;
colorScheme: {
primary: string;
light: string;
text: string;
};
}
```
Benefits:
* Consistent widget APIs
* Reduced repetitive prop definitions
* Easier extensibility
* Cleaner component composition
---
### Removed `Dashboard.view.tsx`
The view/container split was removed.
Dashboard rendering now lives directly inside:
```ts
Dashboard.tsx
```
Benefits:
* Reduced indirection
* Easier navigation
* Lower cognitive overhead
* Simpler state flow
---
## Dashboard Config Cleanup
Removed legacy `style.size` configuration from dashboard sections.
Before:
```ts
style: {
size: 12,
}
```
Now:
```ts
{
id: "items",
title: "Recent Transactions",
component: LatestItems,
}
```
This simplifies section configuration and removes unnecessary abstraction.
---
# Shared Transaction Utilities
## Added `extractFilteredTransactions`
Created a reusable transaction extraction helper:
```ts
extractFilteredTransactions(
reportData,
selectedPeriodId,
selectedGroupKey
)
```
This centralizes:
* Period resolution
* Group filtering
* Tag filtering
* Payee filtering
Previously duplicated across:
* LatestItems
* TopTags
* TopPayees
---
## Added `aggregateTransactions`
Created a reusable aggregation utility:
```ts
aggregateTransactions(
transactions,
keyExtractor,
limit
)
```
Benefits:
* Removes repeated Map aggregation logic
* Standardizes sorting and totals
* Simplifies adapters significantly
---
# HistoryChart Refactor
## Split Models vs Props
Separated:
* data models
* component props
* view props
into dedicated files.
New:
```txt
HistoryChart.models.ts
HistoryChart.props.ts
```
Benefits:
* Cleaner typing boundaries
* Better maintainability
* Reduced coupling
---
## Migrated to Shared Dashboard State
HistoryChart now consumes:
```ts
state
stateSetters
```
instead of individual props.
This aligns it with the new dashboard architecture.
---
# LatestItems Refactor
## Simplified Component Contract
Removed duplicated props:
* flow
* header
* accentColor
* selectedPeriodId
* selectedGroupKey
Now inherited from shared `ComponentProps`.
---
## Added Auto Reset on Flow Change
```ts
React.useEffect(() => {
setVisibleCount(5);
}, [flow]);
```
Improves UX when switching inflow/outflow views.
---
# ProgressCard Refactor
## Removed `ProgressCard.tsx`
Deleted unnecessary wrapper component.
Rendering logic now lives directly in:
```txt
ProgressCard.view.tsx
```
---
## Introduced `ProgressCard.props.ts`
Separated props into dedicated interfaces:
```ts
ProgressCardProps
ProgressCardViewProps
```
---
## Reworked Styling System
Removed dependency on:
```ts
colorTheme
```
Now fully driven by:
```ts
colorScheme
```
Benefits:
* Consistent dashboard-wide theming
* Better dark mode behavior
* Reduced MUI palette coupling
---
## Improved Visual Consistency
Updated:
* borders
* shadows
* progress bar styling
* dark mode surfaces
* selection state styling
to use standardized dashboard colors.
---
# TopTags & TopPayees Refactor
## Removed Duplicated Aggregation Logic
Both adapters now use:
```ts
extractFilteredTransactions()
aggregateTransactions()
```
instead of maintaining separate filtering/aggregation implementations.
Benefits:
* Less code duplication
* Consistent behavior
* Easier future maintenance
---
## Migrated to Shared Component Props
Both components now consume:
```ts
ComponentProps
```
via:
```ts
ProgressCardProps
```
This aligns all dashboard widgets under the same architecture.
---
# Theme System Cleanup
## Consolidated AppTheme
Moved to:
```txt
src/shared-theme/AppTheme.tsx
```
and removed unused duplicate implementations.
---
## Added Explicit Color Mode Context
Introduced:
```ts
ColorModeContext
```
with:
* `mode`
* `setMode`
* `toggleColorMode`
This provides a cleaner foundation for future theme controls.
---
## Simplified Theme Creation
Replaced older MUI experimental color scheme setup with:
```ts
getDesignTokens(mode)
```
Benefits:
* Easier to reason about
* Cleaner light/dark handling
* Less framework complexity
---
## Added Global CssBaseline
```tsx
<CssBaseline />
```
is now applied centrally inside `AppTheme`.
---
# Type Safety Improvements
## Removed Optional Fields Where Invalid
Several previously optional fields are now required:
```ts
title: string
background: string
text: string
isFetching: boolean
style.palette
```
Benefits:
* Stronger guarantees
* Fewer runtime fallbacks
* Simpler rendering logic
---
# Cleanup Summary
## Removed
* `Dashboard.view.tsx`
* `ProgressCard.tsx`
* legacy prop duplication
* repeated transaction extraction logic
* repeated aggregation logic
* unused style configuration
* legacy theme configuration complexity
---
## Added
* centralized dashboard state setters
* reusable transaction helpers
* reusable aggregation helper
* unified component props
* dedicated prop definition files
* explicit color mode context
* consolidated theme provider
---
# Result
The dashboard system is now:
* significantly more maintainable
* easier to extend
* more type-safe
* less repetitive
* more consistent across widgets
* cleaner in terms of state ownership
* simpler to theme and customize
Reviewed-on: #5
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
231 lines
6.3 KiB
TypeScript
231 lines
6.3 KiB
TypeScript
import {
|
|
ReportPeriod,
|
|
ReportBucket,
|
|
GroupKey,
|
|
PeriodType,
|
|
ReportData,
|
|
Transaction,
|
|
} from "../features/report";
|
|
|
|
// ─── Types ────────────────────────────────────────────────────
|
|
|
|
export type PeriodKey = PeriodType;
|
|
|
|
export type DecoratedPeriod = ReportPeriod & {
|
|
id: string;
|
|
label: string;
|
|
};
|
|
|
|
// ─── Period helpers ───────────────────────────────────────────
|
|
|
|
const PREFIX_TO_KEY: Record<string, PeriodKey> = {
|
|
D: "daily",
|
|
W: "weekly",
|
|
M: "monthly",
|
|
ALL: "all",
|
|
};
|
|
|
|
/**
|
|
* Derive the period key from a decorated-period id.
|
|
* E.g. `"W:2026-04-28_2026-05-04"` → `"weekly"`
|
|
*/
|
|
export function periodIdToKey(periodId: string): PeriodKey {
|
|
const prefix = periodId.split(":")[0];
|
|
return PREFIX_TO_KEY[prefix] ?? "all";
|
|
}
|
|
|
|
// ─── Metric helpers ───────────────────────────────────────────
|
|
|
|
export function getAmount(period: ReportPeriod): number {
|
|
return period.metric.sum;
|
|
}
|
|
|
|
function mergeMetric(a: ReportPeriod["metric"], b: ReportPeriod["metric"]) {
|
|
const sum = a.sum + b.sum;
|
|
const count = a.count + b.count;
|
|
|
|
return {
|
|
...a,
|
|
sum,
|
|
count,
|
|
average: count > 0 ? sum / count : 0,
|
|
transactions:
|
|
a.transactions || b.transactions
|
|
? [...(a.transactions || []), ...(b.transactions || [])]
|
|
: undefined,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Merge periods with the same id across all buckets, summing
|
|
* their metrics and concatenating transactions.
|
|
*
|
|
* Returns sorted by start date ascending.
|
|
*/
|
|
export function mergeBucketPeriods(
|
|
buckets: ReportBucket[],
|
|
key: PeriodKey
|
|
): DecoratedPeriod[] {
|
|
const map = new Map<string, DecoratedPeriod>();
|
|
|
|
for (const bucket of buckets) {
|
|
const periods = (bucket.periods[key] || []) as DecoratedPeriod[];
|
|
|
|
for (const p of periods) {
|
|
const existing = map.get(p.id);
|
|
|
|
if (!existing) {
|
|
map.set(p.id, {
|
|
...p,
|
|
metric: { ...p.metric },
|
|
});
|
|
} else {
|
|
map.set(p.id, {
|
|
...existing,
|
|
metric: mergeMetric(existing.metric, p.metric),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
return Array.from(map.values()).sort(
|
|
(a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()
|
|
);
|
|
}
|
|
|
|
// ─── Formatting ───────────────────────────────────────────────
|
|
|
|
export const formatCurrency = (val: number) => {
|
|
const absVal = Math.abs(val);
|
|
if (absVal >= 100000) {
|
|
return `₹ ${(val / 100000).toFixed(2)}L`;
|
|
}
|
|
if (absVal >= 1000) {
|
|
return `₹ ${(val / 1000).toFixed(2)}k`;
|
|
}
|
|
return `₹ ${val.toFixed(2)}`;
|
|
};
|
|
|
|
export const getPercentage = (progressAmount: number, totalAmount: number) => {
|
|
if (!totalAmount) return 0;
|
|
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
|
|
};
|
|
|
|
// ─── Group filtering ──────────────────────────────────────────
|
|
|
|
/**
|
|
* Check if a bucket's group_key matches the selected GroupKey.
|
|
* Every dimension present in `selected` must exist in the bucket
|
|
* and contain all the selected values.
|
|
*/
|
|
export function matchesGroupKey(
|
|
bucket: ReportBucket,
|
|
selected: GroupKey
|
|
): boolean {
|
|
for (const [dim, values] of Object.entries(selected)) {
|
|
const bucketValues = bucket.group_key[dim];
|
|
if (!bucketValues) return false;
|
|
if (!(values as string[]).every((v) => bucketValues.includes(v)))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Return only buckets matching the selected group key,
|
|
* or all buckets if no selection.
|
|
*/
|
|
export function filterBuckets(
|
|
buckets: ReportBucket[],
|
|
selectedGroupKey: GroupKey | null
|
|
): ReportBucket[] {
|
|
if (!selectedGroupKey) return buckets;
|
|
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
|
|
}
|
|
|
|
export function extractFilteredTransactions(
|
|
reportData: ReportData,
|
|
selectedPeriodId: string | null | undefined,
|
|
selectedGroupKey: GroupKey | null | undefined
|
|
): Transaction[] {
|
|
let txns: Transaction[] = [];
|
|
|
|
if (selectedPeriodId) {
|
|
const key = periodIdToKey(selectedPeriodId);
|
|
const periods = mergeBucketPeriods(reportData.buckets, key);
|
|
const selected = periods.find((p) => p.id === selectedPeriodId);
|
|
txns = selected?.metric.transactions || [];
|
|
} else {
|
|
const periods = mergeBucketPeriods(reportData.buckets, "all");
|
|
if (periods.length > 0) {
|
|
const period = periods.reduce((latest, p) =>
|
|
new Date(p.start).getTime() > new Date(latest.start).getTime()
|
|
? p
|
|
: latest
|
|
, periods[0]);
|
|
txns = period?.metric.transactions || [];
|
|
}
|
|
}
|
|
|
|
if (selectedGroupKey) {
|
|
txns = txns.filter((txn) => {
|
|
let match = true;
|
|
if (selectedGroupKey.tags && selectedGroupKey.tags.length > 0) {
|
|
if (!txn.tags) {
|
|
match = false;
|
|
} else {
|
|
const txnTags = txn.tags.map((t: any) =>
|
|
typeof t === "string" ? t : t.name
|
|
);
|
|
if (
|
|
!selectedGroupKey.tags.every((selectedTag) =>
|
|
txnTags.includes(selectedTag)
|
|
)
|
|
) {
|
|
match = false;
|
|
}
|
|
}
|
|
}
|
|
if (match && selectedGroupKey.payee && selectedGroupKey.payee.length > 0) {
|
|
if (!txn.payee || !txn.payee.name) {
|
|
match = false;
|
|
} else {
|
|
if (!selectedGroupKey.payee.includes(txn.payee.name)) {
|
|
match = false;
|
|
}
|
|
}
|
|
}
|
|
return match;
|
|
});
|
|
}
|
|
|
|
return txns;
|
|
}
|
|
|
|
export function aggregateTransactions(
|
|
transactions: Transaction[],
|
|
keyExtractor: (txn: Transaction) => string[],
|
|
limit = 4
|
|
): { items: { name: string; amount: number }[]; total: number } {
|
|
const map = new Map<string, number>();
|
|
|
|
for (const txn of transactions) {
|
|
const keys = keyExtractor(txn);
|
|
for (const key of keys) {
|
|
map.set(key, (map.get(key) || 0) + txn.amount);
|
|
}
|
|
}
|
|
|
|
const items = Array.from(map.entries()).map(([name, amount]) => ({
|
|
name,
|
|
amount,
|
|
}));
|
|
|
|
items.sort((a, b) => b.amount - a.amount);
|
|
|
|
const top = items.slice(0, limit);
|
|
const total = top.reduce((sum, item) => sum + item.amount, 0);
|
|
|
|
return { items: top, total };
|
|
}
|