refactor: extract shared expense/report module into src/common
Collapse the Expenses page into a single src/Expense.tsx file and rename the Reports page to src/Reports/Report.tsx, extracting their shared transaction-list UI, date/grouping helpers, field configs, and types into an expense/report-agnostic src/common module. Update ReportViewer and GenerateReportPanel to consume the shared components, rewire main.jsx imports, and remove the old src/Expense/ folder and src/Reports/Reports.tsx.
This commit is contained in:
@@ -10,32 +10,15 @@ import {
|
||||
} from "@mui/material";
|
||||
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useResource, useAppContext, formatCurrency } from "../../react-openapi";
|
||||
import { PageHeader } from "../ui/PageHeader";
|
||||
import { EmptyState } from "../ui/EmptyState";
|
||||
import { ExpenseList } from "./ExpenseList";
|
||||
import { ExpenseItem, ExpenseFieldConfigs, isExpense, currentMonthKey, monthKey, monthLabel, parseOccurredAt } from "./types";
|
||||
|
||||
function StatCard({ label, value, hint }: { label: string; value: string; hint?: string }) {
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
sx={{ p: 2.5, borderRadius: 3, flex: 1, minWidth: 180 }}
|
||||
>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="h5" fontWeight={700} sx={{ mt: 0.5, letterSpacing: "-0.02em" }}>
|
||||
{value}
|
||||
</Typography>
|
||||
{hint && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{hint}
|
||||
</Typography>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
import { useResource, useAppContext, formatCurrency } from "../react-openapi";
|
||||
import { PageHeader } from "./ui/PageHeader";
|
||||
import { EmptyState } from "./ui/EmptyState";
|
||||
import { StatCard } from "./common/components/StatCard";
|
||||
import { TransactionList } from "./common/components/TransactionList";
|
||||
import { buildTxnFieldConfigs } from "./common/utils/fieldConfigs";
|
||||
import { isExpense } from "./common/utils/transactions";
|
||||
import { currentMonthKey, monthKey, monthLabel, parseOccurredAt } from "./common/utils/dates";
|
||||
import type { ExpenseItem } from "./common/types";
|
||||
|
||||
export default function Expense() {
|
||||
const navigate = useNavigate();
|
||||
@@ -43,33 +26,7 @@ export default function Expense() {
|
||||
const { resources } = useAppContext();
|
||||
const [items, setItems] = useState<ExpenseItem[] | null>(null);
|
||||
|
||||
const fieldConfigs = useMemo<ExpenseFieldConfigs | null>(() => {
|
||||
if (!resource) return null;
|
||||
const find = (name: string) => resource.fields.find((f) => f.name === name);
|
||||
const entity = find("entity");
|
||||
const amount = find("amount");
|
||||
const account = find("account");
|
||||
const tags = find("tags");
|
||||
const occurredAt = find("occurred_at");
|
||||
const entitiesRes = resources.find((r) => r.name === "entities");
|
||||
const accountsRes = resources.find((r) => r.name === "accounts");
|
||||
const tagsRes = resources.find((r) => r.name === "tags");
|
||||
const logo = entitiesRes?.fields.find((f) => f.name === "logo");
|
||||
if (!entity || !amount || !account || !tags || !occurredAt || !logo) return null;
|
||||
return {
|
||||
entity,
|
||||
amount,
|
||||
account,
|
||||
tags,
|
||||
occurredAt,
|
||||
logo,
|
||||
formats: {
|
||||
entity: entitiesRes?.displayFormat ?? "{name}",
|
||||
account: accountsRes?.displayFormat ?? "{name}",
|
||||
tags: tagsRes?.displayFormat ?? "{name}",
|
||||
},
|
||||
};
|
||||
}, [resource, resources]);
|
||||
const fieldConfigs = useMemo(() => buildTxnFieldConfigs(resources), [resources]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
@@ -80,7 +37,7 @@ export default function Expense() {
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, []);
|
||||
}, [list]);
|
||||
|
||||
const sorted = useMemo(
|
||||
() =>
|
||||
@@ -161,7 +118,7 @@ export default function Expense() {
|
||||
<StatCard label="Income" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
||||
</Box>
|
||||
|
||||
{fieldConfigs && <ExpenseList items={sorted} fields={fieldConfigs} />}
|
||||
{fieldConfigs && <TransactionList items={sorted} fields={fieldConfigs} />}
|
||||
</>
|
||||
)}
|
||||
</Container>
|
||||
@@ -17,7 +17,8 @@ import AddIcon from "@mui/icons-material/Add";
|
||||
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
|
||||
import { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
|
||||
import { useToast } from "../ui/Toast";
|
||||
import { apiErrorMessage, groupTypeEnum, isDdmmyyyy, periodHints } from "./types";
|
||||
import { isDdmmyyyy } from "../common/utils/dates";
|
||||
import { apiErrorMessage, groupTypeEnum, periodHints } from "./types";
|
||||
|
||||
interface GroupRow {
|
||||
id: number;
|
||||
|
||||
@@ -5,30 +5,14 @@ import { useResource, useAppContext, formatCurrency } from "../../react-openapi"
|
||||
import { useToast } from "../ui/Toast";
|
||||
import { PageHeader } from "../ui/PageHeader";
|
||||
import { EmptyState } from "../ui/EmptyState";
|
||||
import { StatCard } from "../common/components/StatCard";
|
||||
import { buildTxnFieldConfigs } from "../common/utils/fieldConfigs";
|
||||
import { GenerateReportPanel } from "./GenerateReportPanel";
|
||||
import { ReportList } from "./ReportList";
|
||||
import { ReportViewer } from "./ReportViewer";
|
||||
import { apiErrorMessage, buildReportFieldConfigs, buildTxnFieldConfigs } from "./types";
|
||||
import { apiErrorMessage, buildReportFieldConfigs } from "./types";
|
||||
|
||||
function StatCard({ label, value, hint }: { label: string; value: string; hint?: string }) {
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3, flex: 1, minWidth: 180 }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="h5" fontWeight={700} sx={{ mt: 0.5, letterSpacing: "-0.02em" }}>
|
||||
{value}
|
||||
</Typography>
|
||||
{hint && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{hint}
|
||||
</Typography>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Reports() {
|
||||
export default function Report() {
|
||||
const { resources } = useAppContext();
|
||||
const { showToast } = useToast();
|
||||
const { list, loading, error } = useResource("reports");
|
||||
@@ -9,9 +9,6 @@ import {
|
||||
Skeleton,
|
||||
TextField,
|
||||
Autocomplete,
|
||||
Accordion,
|
||||
AccordionSummary,
|
||||
AccordionDetails,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
@@ -19,14 +16,12 @@ import {
|
||||
TableHead,
|
||||
TableRow,
|
||||
} from "@mui/material";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import CachedIcon from "@mui/icons-material/Cached";
|
||||
import { useAppContext, useResource, ListCellRenderer, CurrencyField, applyDisplayFormat, formatCurrency } from "../../react-openapi";
|
||||
import { groupByMonth } from "../Expense/ExpenseList";
|
||||
import type { ExpenseItem, ExpenseFieldConfigs } from "../Expense/types";
|
||||
import { monthLabel } from "../Expense/types";
|
||||
import type { TxnFieldConfigs } from "./types";
|
||||
import { useAppContext, useResource, formatCurrency } from "../../react-openapi";
|
||||
import { StatCard } from "../common/components/StatCard";
|
||||
import { TransactionList } from "../common/components/TransactionList";
|
||||
import type { TxnFieldConfigs } from "../common/types";
|
||||
import { aggregateSlice, buildPivot, metricLabels } from "./types";
|
||||
|
||||
interface ReportViewerProps {
|
||||
@@ -37,83 +32,6 @@ interface ReportViewerProps {
|
||||
onRegenerated: (report: any) => void;
|
||||
}
|
||||
|
||||
function StatCard({ label, value, color }: { label: string; value: string; color?: string }) {
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3, flex: 1, minWidth: 150 }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ mt: 0.5, letterSpacing: "-0.02em", color }}>
|
||||
{value}
|
||||
</Typography>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
const ReportTxnRow = React.memo(function ReportTxnRow({
|
||||
item,
|
||||
currency,
|
||||
fields,
|
||||
}: {
|
||||
item: ExpenseItem;
|
||||
currency: string;
|
||||
fields: ExpenseFieldConfigs;
|
||||
}) {
|
||||
const itemCurrency = item.account?.currency ?? currency;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
px: 2,
|
||||
py: 1.25,
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 2,
|
||||
backgroundColor: "background.paper",
|
||||
transition: "background-color 160ms ease, border-color 160ms ease",
|
||||
"&:hover": {
|
||||
backgroundColor: "action.hover",
|
||||
borderColor: "primary.light",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
flexShrink: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{item.entity?.logo ? (
|
||||
<ListCellRenderer field={fields.logo} value={item.entity.logo} />
|
||||
) : (
|
||||
<Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: "action.hover" }} />
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ flex: "0 1 auto", minWidth: 0 }}>
|
||||
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem", lineHeight: 1.3 }}>
|
||||
{item.entity ? applyDisplayFormat(item.entity, fields.formats.entity) : "Unknown"}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
|
||||
<Box sx={{ color: "text.secondary" }}>
|
||||
<ListCellRenderer field={fields.occurredAt} value={item.occurred_at} />
|
||||
</Box>
|
||||
{item.account?.name && (
|
||||
<ListCellRenderer field={fields.account} value={item.account} displayFormat={fields.formats.account} />
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<CurrencyField value={item.amount} currency={itemCurrency} large />
|
||||
</Box>
|
||||
);
|
||||
});
|
||||
|
||||
export function ReportViewer({ id, version, fields, onClose, onRegenerated }: ReportViewerProps) {
|
||||
const { schemas } = useAppContext();
|
||||
const { get } = useResource("reports");
|
||||
@@ -124,7 +42,6 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
||||
const [reload, setReload] = useState(0);
|
||||
const [selectedPeriod, setSelectedPeriod] = useState("*");
|
||||
const [selectedPayee, setSelectedPayee] = useState("*");
|
||||
const [openMonth, setOpenMonth] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
@@ -165,8 +82,6 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
||||
[data, selectedPeriod, selectedPayee],
|
||||
);
|
||||
|
||||
const months = useMemo(() => groupByMonth(slice.txns), [slice.txns]);
|
||||
|
||||
const pivot = useMemo(
|
||||
() => buildPivot(data ?? [], groupOptions.period, groupOptions.payee),
|
||||
[data, groupOptions],
|
||||
@@ -297,11 +212,7 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
||||
const value = metricValue(m.key);
|
||||
if (value == null) return null;
|
||||
return (
|
||||
<Paper
|
||||
key={m.key}
|
||||
variant="outlined"
|
||||
sx={{ px: 1.5, py: 1, borderRadius: 2 }}
|
||||
>
|
||||
<Paper key={m.key} variant="outlined" sx={{ px: 1.5, py: 1, borderRadius: 2 }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
|
||||
{m.label}
|
||||
</Typography>
|
||||
@@ -363,74 +274,15 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
||||
</TableContainer>
|
||||
)}
|
||||
|
||||
{months.length === 0 ? (
|
||||
{slice.txns.length === 0 ? (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No transactions in this slice.
|
||||
</Typography>
|
||||
</Paper>
|
||||
) : (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||
{months.map((group) => (
|
||||
<Accordion
|
||||
key={group.key}
|
||||
disableGutters
|
||||
expanded={openMonth === group.key}
|
||||
onChange={(_, isExpanded) => setOpenMonth(isExpanded ? group.key : null)}
|
||||
TransitionProps={{ unmountOnExit: true }}
|
||||
sx={{
|
||||
border: "1px solid",
|
||||
borderColor: openMonth === group.key ? "primary.main" : "divider",
|
||||
borderRadius: 2,
|
||||
overflow: "hidden",
|
||||
boxShadow: "none",
|
||||
backgroundColor: "background.paper",
|
||||
"&:before": { display: "none" },
|
||||
"&:hover": { borderColor: "primary.light" },
|
||||
}}
|
||||
>
|
||||
<AccordionSummary
|
||||
expandIcon={<ExpandMoreIcon />}
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
"& .MuiAccordionSummary-content": { alignItems: "center", gap: 1.5, minWidth: 0 },
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
{monthLabel(group.key)}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Typography variant="body2" fontWeight={700} color="error.main">
|
||||
{formatCurrency(group.spent, group.currency)}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.disabled">
|
||||
/
|
||||
</Typography>
|
||||
<Typography variant="body2" fontWeight={700} color="success.main">
|
||||
{formatCurrency(group.income, group.currency)}
|
||||
</Typography>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails sx={{ p: 1.5, pt: 1 }}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
{fields &&
|
||||
group.items.map((item) => (
|
||||
<ReportTxnRow
|
||||
key={item.id ?? `${group.key}-${item.occurred_at}-${item.amount}`}
|
||||
item={item}
|
||||
currency={group.currency}
|
||||
fields={fields as ExpenseFieldConfigs}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
) : fields ? (
|
||||
<TransactionList items={slice.txns} fields={fields} />
|
||||
) : null}
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
||||
|
||||
const DDMMYYYY = /^(\d{2})-(\d{2})-(\d{4})$/;
|
||||
import { parseDdmmyyyy } from "../common/utils/dates";
|
||||
|
||||
export interface ParsedGroupKey {
|
||||
period?: { granularity: string; label: string };
|
||||
@@ -53,15 +52,6 @@ export interface PivotTable {
|
||||
totals: PivotCell[];
|
||||
}
|
||||
|
||||
export interface TxnFieldConfigs {
|
||||
entity: FieldConfig;
|
||||
amount: FieldConfig;
|
||||
account: FieldConfig;
|
||||
occurredAt: FieldConfig;
|
||||
logo: FieldConfig;
|
||||
formats: { entity: string; account: string };
|
||||
}
|
||||
|
||||
export interface ReportFieldConfigs {
|
||||
groupLabel: FieldConfig;
|
||||
granularity: FieldConfig;
|
||||
@@ -94,36 +84,6 @@ export function parseCacheKey(key: string): ParsedGroupKey {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function isDdmmyyyy(value?: string): boolean {
|
||||
if (!value) return true;
|
||||
const m = value.match(DDMMYYYY);
|
||||
if (!m) return false;
|
||||
const [, dd, mm, yyyy] = m;
|
||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||
return !(
|
||||
Number.isNaN(d.getTime()) ||
|
||||
d.getDate() !== Number(dd) ||
|
||||
d.getMonth() !== Number(mm) - 1 ||
|
||||
d.getFullYear() !== Number(yyyy)
|
||||
);
|
||||
}
|
||||
|
||||
export function parseDdmmyyyy(value: string): Date {
|
||||
const m = value.match(DDMMYYYY);
|
||||
if (!m) throw new Error(`Date is not DD-MM-YYYY: ${value}`);
|
||||
const [, dd, mm, yyyy] = m;
|
||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||
if (
|
||||
Number.isNaN(d.getTime()) ||
|
||||
d.getDate() !== Number(dd) ||
|
||||
d.getMonth() !== Number(mm) - 1 ||
|
||||
d.getFullYear() !== Number(yyyy)
|
||||
) {
|
||||
throw new Error(`Invalid date: ${value}`);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
export function apiErrorMessage(e: any): string {
|
||||
if (e?.response?.data) {
|
||||
const d = e.response.data;
|
||||
@@ -263,30 +223,6 @@ export function buildPivot(groups: ReportGroupLike[], periodOrder: string[], pay
|
||||
return { rows, payees, totals };
|
||||
}
|
||||
|
||||
export function buildTxnFieldConfigs(resources: ResourceConfig[]): TxnFieldConfigs | null {
|
||||
const expensesRes = resources.find((r) => r.name === "expenses");
|
||||
const entitiesRes = resources.find((r) => r.name === "entities");
|
||||
const accountsRes = resources.find((r) => r.name === "accounts");
|
||||
const find = (res: ResourceConfig | undefined, name: string) => res?.fields.find((f) => f.name === name);
|
||||
const entity = find(expensesRes, "entity");
|
||||
const amount = find(expensesRes, "amount");
|
||||
const account = find(expensesRes, "account");
|
||||
const occurredAt = find(expensesRes, "occurred_at");
|
||||
const logo = find(entitiesRes, "logo");
|
||||
if (!entity || !amount || !account || !occurredAt || !logo) return null;
|
||||
return {
|
||||
entity,
|
||||
amount,
|
||||
account,
|
||||
occurredAt,
|
||||
logo,
|
||||
formats: {
|
||||
entity: entitiesRes?.displayFormat ?? "{name}",
|
||||
account: accountsRes?.displayFormat ?? "{name}",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
||||
const reportsRes = resources.find((r) => r.name === "reports");
|
||||
if (!reportsRes) return null;
|
||||
|
||||
26
src/common/components/StatCard.tsx
Normal file
26
src/common/components/StatCard.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Paper, Typography } from "@mui/material";
|
||||
|
||||
interface StatCardProps {
|
||||
label: string;
|
||||
value: string;
|
||||
color?: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export function StatCard({ label, value, color, hint }: StatCardProps) {
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3, flex: 1, minWidth: 180 }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="h5" fontWeight={700} sx={{ mt: 0.5, letterSpacing: "-0.02em", color }}>
|
||||
{value}
|
||||
</Typography>
|
||||
{hint && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{hint}
|
||||
</Typography>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -12,116 +12,18 @@ import {
|
||||
import { alpha } from "@mui/material/styles";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||
import { ListCellRenderer, CurrencyField, applyDisplayFormat, formatCurrency } from "../../react-openapi";
|
||||
import type { ExpenseItem, ExpenseFieldConfigs } from "./types";
|
||||
import { isExpense, monthKey, monthLabel, parseOccurredAt } from "./types";
|
||||
import { formatCurrency } from "../../../react-openapi";
|
||||
import type { ExpenseItem, TxnFieldConfigs } from "../types";
|
||||
import { groupByMonth } from "../utils/transactions";
|
||||
import { monthLabel } from "../utils/dates";
|
||||
import { TransactionRow } from "./TransactionRow";
|
||||
|
||||
interface GroupedMonth {
|
||||
key: string;
|
||||
interface TransactionListProps {
|
||||
items: ExpenseItem[];
|
||||
spent: number;
|
||||
income: number;
|
||||
currency: string;
|
||||
fields: TxnFieldConfigs;
|
||||
}
|
||||
|
||||
function groupByMonth(items: ExpenseItem[]): GroupedMonth[] {
|
||||
const map = new Map<string, ExpenseItem[]>();
|
||||
for (const item of items) {
|
||||
const key = monthKey(item.occurred_at);
|
||||
const list = map.get(key) ?? [];
|
||||
list.push(item);
|
||||
map.set(key, list);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.map(([key, list]) => {
|
||||
const sorted = [...list].sort(
|
||||
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
||||
);
|
||||
const currency = sorted.find((it) => it.account?.currency)?.account?.currency ?? "INR";
|
||||
const spent = sorted.filter(isExpense).reduce((sum, it) => sum + Math.abs(it.amount ?? 0), 0);
|
||||
const income = sorted.filter((it) => !isExpense(it)).reduce((sum, it) => sum + (it.amount ?? 0), 0);
|
||||
return { key, items: sorted, spent, income, currency };
|
||||
})
|
||||
.sort((a, b) => b.key.localeCompare(a.key));
|
||||
}
|
||||
|
||||
interface ExpenseRowProps {
|
||||
item: ExpenseItem;
|
||||
currency: string;
|
||||
fields: ExpenseFieldConfigs;
|
||||
}
|
||||
|
||||
const ExpenseRow = React.memo(function ExpenseRow({ item, currency, fields }: ExpenseRowProps) {
|
||||
const itemCurrency = item.account?.currency ?? currency;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
px: 2,
|
||||
py: 1.25,
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 2,
|
||||
backgroundColor: "background.paper",
|
||||
transition: "background-color 160ms ease, border-color 160ms ease",
|
||||
"&:hover": {
|
||||
backgroundColor: "action.hover",
|
||||
borderColor: "primary.light",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
flexShrink: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{item.entity?.logo ? (
|
||||
<ListCellRenderer field={fields.logo} value={item.entity.logo} />
|
||||
) : (
|
||||
<Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: "action.hover" }} />
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ flex: "0 1 auto", minWidth: 0 }}>
|
||||
<Typography
|
||||
variant="body1"
|
||||
fontWeight={600}
|
||||
noWrap
|
||||
sx={{ fontSize: "0.9375rem", lineHeight: 1.3 }}
|
||||
>
|
||||
{item.entity ? applyDisplayFormat(item.entity, fields.formats.entity) : "Unknown"}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
|
||||
<Box sx={{ color: "text.secondary" }}>
|
||||
<ListCellRenderer field={fields.occurredAt} value={item.occurred_at} />
|
||||
</Box>
|
||||
{item.account?.name && (
|
||||
<ListCellRenderer
|
||||
field={fields.account}
|
||||
value={item.account}
|
||||
displayFormat={fields.formats.account}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<CurrencyField value={item.amount} currency={itemCurrency} large />
|
||||
</Box>
|
||||
);
|
||||
});
|
||||
|
||||
interface ExpenseListProps {
|
||||
items: ExpenseItem[];
|
||||
fields: ExpenseFieldConfigs;
|
||||
}
|
||||
|
||||
export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
export function TransactionList({ items, fields }: TransactionListProps) {
|
||||
const [activeMonth, setActiveMonth] = useState<string | null>(null);
|
||||
const [openMonth, setOpenMonth] = useState<string | null>(null);
|
||||
const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
|
||||
@@ -259,7 +161,7 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
<AccordionDetails sx={{ p: 1.5, pt: 1 }}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
{group.items.map((item) => (
|
||||
<ExpenseRow
|
||||
<TransactionRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
currency={group.currency}
|
||||
@@ -347,6 +249,4 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export { groupByMonth };
|
||||
}
|
||||
71
src/common/components/TransactionRow.tsx
Normal file
71
src/common/components/TransactionRow.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
import React from "react";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { ListCellRenderer, CurrencyField, applyDisplayFormat } from "../../../react-openapi";
|
||||
import type { ExpenseItem, TxnFieldConfigs } from "../types";
|
||||
|
||||
interface TransactionRowProps {
|
||||
item: ExpenseItem;
|
||||
currency: string;
|
||||
fields: TxnFieldConfigs;
|
||||
}
|
||||
|
||||
export const TransactionRow = React.memo(function TransactionRow({ item, currency, fields }: TransactionRowProps) {
|
||||
const itemCurrency = item.account?.currency ?? currency;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
px: 2,
|
||||
py: 1.25,
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 2,
|
||||
backgroundColor: "background.paper",
|
||||
transition: "background-color 160ms ease, border-color 160ms ease",
|
||||
"&:hover": {
|
||||
backgroundColor: "action.hover",
|
||||
borderColor: "primary.light",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
flexShrink: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{item.entity?.logo ? (
|
||||
<ListCellRenderer field={fields.logo} value={item.entity.logo} />
|
||||
) : (
|
||||
<Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: "action.hover" }} />
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ flex: "0 1 auto", minWidth: 0 }}>
|
||||
<Typography
|
||||
variant="body1"
|
||||
fontWeight={600}
|
||||
noWrap
|
||||
sx={{ fontSize: "0.9375rem", lineHeight: 1.3 }}
|
||||
>
|
||||
{item.entity ? applyDisplayFormat(item.entity, fields.formats.entity) : "Unknown"}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
|
||||
<Box sx={{ color: "text.secondary" }}>
|
||||
<ListCellRenderer field={fields.occurredAt} value={item.occurred_at} />
|
||||
</Box>
|
||||
{item.account?.name && (
|
||||
<ListCellRenderer field={fields.account} value={item.account} displayFormat={fields.formats.account} />
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<CurrencyField value={item.amount} currency={itemCurrency} large />
|
||||
</Box>
|
||||
);
|
||||
});
|
||||
29
src/common/types.ts
Normal file
29
src/common/types.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { FieldConfig } from "../../react-openapi";
|
||||
|
||||
export interface ExpenseItem {
|
||||
id: string;
|
||||
entity?: { name?: string; type?: string; logo?: string } | null;
|
||||
amount: number;
|
||||
account?: { name?: string; number?: string; type?: string; currency?: string } | null;
|
||||
tags?: { icon?: string; name?: string }[];
|
||||
occurred_at?: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface GroupedMonth {
|
||||
key: string;
|
||||
items: ExpenseItem[];
|
||||
spent: number;
|
||||
income: number;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
export interface TxnFieldConfigs {
|
||||
entity: FieldConfig;
|
||||
amount: FieldConfig;
|
||||
account: FieldConfig;
|
||||
occurredAt: FieldConfig;
|
||||
logo: FieldConfig;
|
||||
formats: { entity: string; account: string };
|
||||
}
|
||||
@@ -1,36 +1,7 @@
|
||||
import type { FieldConfig } from "../../react-openapi";
|
||||
|
||||
export interface ExpenseItem {
|
||||
id: string;
|
||||
entity?: { name?: string; type?: string; logo?: string } | null;
|
||||
amount: number;
|
||||
account?: { name?: string; number?: string; type?: string; currency?: string } | null;
|
||||
tags?: { icon?: string; name?: string }[];
|
||||
occurred_at?: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface ExpenseFieldConfigs {
|
||||
entity: FieldConfig;
|
||||
amount: FieldConfig;
|
||||
account: FieldConfig;
|
||||
tags: FieldConfig;
|
||||
occurredAt: FieldConfig;
|
||||
logo: FieldConfig;
|
||||
formats: {
|
||||
entity: string;
|
||||
account: string;
|
||||
tags: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function isExpense(item: ExpenseItem): boolean {
|
||||
return (item.amount ?? 0) < 0;
|
||||
}
|
||||
const DDMMYYYY = /^(\d{2})-(\d{2})-(\d{4})$/;
|
||||
|
||||
export function parseOccurredAt(value?: string): Date {
|
||||
const m = value?.match(/^(\d{2})-(\d{2})-(\d{4})$/);
|
||||
const m = value?.match(DDMMYYYY);
|
||||
if (!m) {
|
||||
throw new Error(`Expense occurred_at is not DD-MM-YYYY: ${value}`);
|
||||
}
|
||||
@@ -47,6 +18,36 @@ export function parseOccurredAt(value?: string): Date {
|
||||
return d;
|
||||
}
|
||||
|
||||
export function isDdmmyyyy(value?: string): boolean {
|
||||
if (!value) return true;
|
||||
const m = value.match(DDMMYYYY);
|
||||
if (!m) return false;
|
||||
const [, dd, mm, yyyy] = m;
|
||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||
return !(
|
||||
Number.isNaN(d.getTime()) ||
|
||||
d.getDate() !== Number(dd) ||
|
||||
d.getMonth() !== Number(mm) - 1 ||
|
||||
d.getFullYear() !== Number(yyyy)
|
||||
);
|
||||
}
|
||||
|
||||
export function parseDdmmyyyy(value: string): Date {
|
||||
const m = value.match(DDMMYYYY);
|
||||
if (!m) throw new Error(`Date is not DD-MM-YYYY: ${value}`);
|
||||
const [, dd, mm, yyyy] = m;
|
||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||
if (
|
||||
Number.isNaN(d.getTime()) ||
|
||||
d.getDate() !== Number(dd) ||
|
||||
d.getMonth() !== Number(mm) - 1 ||
|
||||
d.getFullYear() !== Number(yyyy)
|
||||
) {
|
||||
throw new Error(`Invalid date: ${value}`);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
export function monthKey(value?: string): string {
|
||||
const d = parseOccurredAt(value);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
26
src/common/utils/fieldConfigs.ts
Normal file
26
src/common/utils/fieldConfigs.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { ResourceConfig } from "../../../react-openapi";
|
||||
import type { TxnFieldConfigs } from "../types";
|
||||
|
||||
export function buildTxnFieldConfigs(resources: ResourceConfig[]): TxnFieldConfigs | null {
|
||||
const expensesRes = resources.find((r) => r.name === "expenses");
|
||||
const entitiesRes = resources.find((r) => r.name === "entities");
|
||||
const accountsRes = resources.find((r) => r.name === "accounts");
|
||||
const find = (res: ResourceConfig | undefined, name: string) => res?.fields.find((f) => f.name === name);
|
||||
const entity = find(expensesRes, "entity");
|
||||
const amount = find(expensesRes, "amount");
|
||||
const account = find(expensesRes, "account");
|
||||
const occurredAt = find(expensesRes, "occurred_at");
|
||||
const logo = find(entitiesRes, "logo");
|
||||
if (!entity || !amount || !account || !occurredAt || !logo) return null;
|
||||
return {
|
||||
entity,
|
||||
amount,
|
||||
account,
|
||||
occurredAt,
|
||||
logo,
|
||||
formats: {
|
||||
entity: entitiesRes?.displayFormat ?? "{name}",
|
||||
account: accountsRes?.displayFormat ?? "{name}",
|
||||
},
|
||||
};
|
||||
}
|
||||
27
src/common/utils/transactions.ts
Normal file
27
src/common/utils/transactions.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { ExpenseItem, GroupedMonth } from "../types";
|
||||
import { monthKey, parseOccurredAt } from "./dates";
|
||||
|
||||
export function isExpense(item: ExpenseItem): boolean {
|
||||
return (item.amount ?? 0) < 0;
|
||||
}
|
||||
|
||||
export function groupByMonth(items: ExpenseItem[]): GroupedMonth[] {
|
||||
const map = new Map<string, ExpenseItem[]>();
|
||||
for (const item of items) {
|
||||
const key = monthKey(item.occurred_at);
|
||||
const list = map.get(key) ?? [];
|
||||
list.push(item);
|
||||
map.set(key, list);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.map(([key, list]) => {
|
||||
const sorted = [...list].sort(
|
||||
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
||||
);
|
||||
const currency = sorted.find((it) => it.account?.currency)?.account?.currency ?? "INR";
|
||||
const spent = sorted.filter(isExpense).reduce((sum, it) => sum + Math.abs(it.amount ?? 0), 0);
|
||||
const income = sorted.filter((it) => !isExpense(it)).reduce((sum, it) => sum + (it.amount ?? 0), 0);
|
||||
return { key, items: sorted, spent, income, currency };
|
||||
})
|
||||
.sort((a, b) => b.key.localeCompare(a.key));
|
||||
}
|
||||
@@ -17,8 +17,8 @@ import {
|
||||
import Home from './Home';
|
||||
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
||||
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
|
||||
import Expense from './Expense/Expense';
|
||||
import Reports from './Reports/Reports';
|
||||
import Expense from './Expense';
|
||||
import Reports from './Reports/Report';
|
||||
import { AppProvider, useAppContext, Admin, ProfileRoutes } from '../react-openapi';
|
||||
import { AuthProvider, AuthPage, useAuth, ProfileCreate, ProfileEdit, ProfileView } from "../react-auth";
|
||||
import Header from './Header';
|
||||
|
||||
Reference in New Issue
Block a user