Add 'apps/mobile/' from commit '5fa30f365f21531094cd4d2045042bb4f1370ac3'
git-subtree-dir: apps/mobile git-subtree-mainline:86f8987dffgit-subtree-split:5fa30f365f
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import { Stack } from "expo-router";
|
||||
|
||||
export default function MoreLayout() {
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerShown: false,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
import { useLocalSearchParams, router } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Alert, StyleSheet, Text, View } from "react-native";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import {
|
||||
ExpenseFormFields,
|
||||
type ExpenseFormState,
|
||||
} from "@/components/expenses/ExpenseFormFields";
|
||||
import { ReceiptItemSelector } from "@/components/expenses/ReceiptItemSelector";
|
||||
import { LoadingScreen } from "@/components/LoadingScreen";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { SwipeableRow } from "@/components/SwipeableRow";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { fonts, spacing } from "@/constants/theme";
|
||||
import { useAppTheme } from "@/contexts/ThemeContext";
|
||||
import { formatCurrency, formatDate } from "@/lib/format";
|
||||
import { scanReceiptImage, type ReceiptScanResult } from "@/lib/receipt-scan";
|
||||
import { api } from "@/lib/trpc";
|
||||
|
||||
type ReceiptSplitDraft = Pick<
|
||||
ReceiptScanResult,
|
||||
"items" | "subtotal" | "tax" | "total"
|
||||
>;
|
||||
|
||||
export default function ExpenseDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const { colors } = useAppTheme();
|
||||
const utils = api.useUtils();
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [receiptSplit, setReceiptSplit] = useState<ReceiptSplitDraft | null>(
|
||||
null,
|
||||
);
|
||||
const [form, setForm] = useState<ExpenseFormState>({
|
||||
description: "",
|
||||
amountText: "",
|
||||
date: new Date(),
|
||||
category: "",
|
||||
businessId: "",
|
||||
clientId: "",
|
||||
billable: false,
|
||||
reimbursable: false,
|
||||
taxDeductible: false,
|
||||
notes: "",
|
||||
});
|
||||
|
||||
const expenseQuery = api.expenses.getById.useQuery(
|
||||
{ id: id ?? "" },
|
||||
{ enabled: Boolean(id) },
|
||||
);
|
||||
const businessesQuery = api.businesses.getAll.useQuery();
|
||||
const clientsQuery = api.clients.getAll.useQuery();
|
||||
|
||||
const uploadReceipt = api.expenses.uploadReceipt.useMutation({
|
||||
onSuccess: () => void expenseQuery.refetch(),
|
||||
});
|
||||
const deleteReceipt = api.expenses.deleteReceipt.useMutation({
|
||||
onSuccess: () => void expenseQuery.refetch(),
|
||||
});
|
||||
const updateExpense = api.expenses.update.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.expenses.getAll.invalidate();
|
||||
await expenseQuery.refetch();
|
||||
setEditing(false);
|
||||
},
|
||||
});
|
||||
const suggest = api.expenses.suggestFromReceiptText.useMutation();
|
||||
|
||||
const expense = expenseQuery.data;
|
||||
const businesses = businessesQuery.data ?? [];
|
||||
const clients = clientsQuery.data ?? [];
|
||||
|
||||
async function attachAndScan(fromCamera: boolean) {
|
||||
if (!id || !expense) return;
|
||||
|
||||
setScanning(true);
|
||||
try {
|
||||
const result = await scanReceiptImage(
|
||||
fromCamera,
|
||||
{
|
||||
description: expense.description,
|
||||
amountText: String(expense.amount),
|
||||
date: new Date(expense.date),
|
||||
},
|
||||
(input) => suggest.mutateAsync(input),
|
||||
);
|
||||
if (!result) return;
|
||||
|
||||
await uploadReceipt.mutateAsync({
|
||||
expenseId: id,
|
||||
filename: result.image.filename,
|
||||
mimeType: result.image.mimeType,
|
||||
data: result.image.base64,
|
||||
});
|
||||
|
||||
setForm(
|
||||
expenseToForm(expense, {
|
||||
description: result.description,
|
||||
amountText: result.amountText,
|
||||
date: result.date,
|
||||
notes: result.ocrText,
|
||||
}),
|
||||
);
|
||||
setReceiptSplit(
|
||||
result.items.length > 0
|
||||
? {
|
||||
items: result.items,
|
||||
subtotal: result.subtotal,
|
||||
tax: result.tax,
|
||||
total: result.total,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
setEditing(true);
|
||||
|
||||
Alert.alert(
|
||||
"Receipt attached",
|
||||
result.items.length > 0
|
||||
? "Select the owed items, apply the split amount, then save the expense."
|
||||
: "We filled in what we could. Review and save to update this expense.",
|
||||
);
|
||||
} finally {
|
||||
setScanning(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSaveEdits() {
|
||||
if (!id) return;
|
||||
const amount = Number(form.amountText);
|
||||
if (!form.description.trim() || !Number.isFinite(amount) || amount <= 0) {
|
||||
Alert.alert("Invalid fields", "Description and amount are required.");
|
||||
return;
|
||||
}
|
||||
|
||||
updateExpense.mutate({
|
||||
id,
|
||||
description: form.description.trim(),
|
||||
amount,
|
||||
date: form.date,
|
||||
category: form.category || undefined,
|
||||
businessId: form.businessId || undefined,
|
||||
clientId: form.clientId || undefined,
|
||||
billable: form.billable,
|
||||
reimbursable: form.reimbursable,
|
||||
taxDeductible: form.taxDeductible,
|
||||
notes: form.notes.trim() || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
function startEditing() {
|
||||
if (!expense) return;
|
||||
setForm(expenseToForm(expense));
|
||||
setReceiptSplit(null);
|
||||
setEditing(true);
|
||||
}
|
||||
|
||||
if (expenseQuery.isLoading) {
|
||||
return <LoadingScreen message="Loading expense…" />;
|
||||
}
|
||||
|
||||
if (!expense) {
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<TabScrollView header={<PageHeader title="Expense" subtitle="Expense details" />}>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
Expense not found
|
||||
</Text>
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<TabScrollView
|
||||
header={
|
||||
<PageHeader
|
||||
title={expense.description}
|
||||
subtitle={formatDate(expense.date)}
|
||||
/>
|
||||
}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
{editing ? (
|
||||
<>
|
||||
{receiptSplit ? (
|
||||
<ReceiptItemSelector
|
||||
items={receiptSplit.items}
|
||||
subtotal={receiptSplit.subtotal}
|
||||
tax={receiptSplit.tax}
|
||||
total={receiptSplit.total}
|
||||
onApply={(selection) => {
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
amountText: selection.owedTotal.toFixed(2),
|
||||
notes: mergeNotes(selection.notes, current.notes),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<ExpenseFormFields
|
||||
value={form}
|
||||
businesses={businesses}
|
||||
clients={clients}
|
||||
onChange={setForm}
|
||||
/>
|
||||
<Button
|
||||
title="Save changes"
|
||||
loading={updateExpense.isPending}
|
||||
onPress={handleSaveEdits}
|
||||
/>
|
||||
<Button
|
||||
title="Cancel edit"
|
||||
variant="secondary"
|
||||
onPress={() => setEditing(false)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Text style={[styles.amount, { color: colors.foreground }]}>
|
||||
{formatCurrency(expense.amount, expense.currency)}
|
||||
</Text>
|
||||
<View style={styles.metaStack}>
|
||||
<Text style={[styles.meta, { color: colors.mutedForeground }]}>
|
||||
{expense.category || "No category"}
|
||||
{expense.business?.name ? ` · ${expense.business.name}` : ""}
|
||||
{expense.client?.name ? ` · ${expense.client.name}` : ""}
|
||||
</Text>
|
||||
<View style={styles.badges}>
|
||||
{expense.billable ? (
|
||||
<Text
|
||||
style={[
|
||||
styles.badge,
|
||||
{ color: colors.primary, borderColor: colors.border },
|
||||
]}
|
||||
>
|
||||
Billable
|
||||
</Text>
|
||||
) : null}
|
||||
{expense.reimbursable ? (
|
||||
<Text
|
||||
style={[
|
||||
styles.badge,
|
||||
{
|
||||
color: colors.foreground,
|
||||
borderColor: colors.border,
|
||||
},
|
||||
]}
|
||||
>
|
||||
Reimbursable
|
||||
</Text>
|
||||
) : null}
|
||||
{expense.taxDeductible ? (
|
||||
<Text
|
||||
style={[
|
||||
styles.badge,
|
||||
{ color: colors.success, borderColor: colors.border },
|
||||
]}
|
||||
>
|
||||
Tax deductible
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
{expense.notes ? (
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{expense.notes}
|
||||
</Text>
|
||||
) : null}
|
||||
<Button
|
||||
title="Edit expense"
|
||||
variant="secondary"
|
||||
onPress={startEditing}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Text style={[styles.section, { color: colors.foreground }]}>
|
||||
Receipts ({expense.receipts.length})
|
||||
</Text>
|
||||
|
||||
{expense.receipts.map((receipt) => (
|
||||
<SwipeableRow
|
||||
key={receipt.id}
|
||||
actions={[
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
icon: "trash-outline",
|
||||
color: "#fff",
|
||||
backgroundColor: colors.destructive,
|
||||
onPress: () => deleteReceipt.mutate({ id: receipt.id }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Text
|
||||
style={[styles.receiptRow, { color: colors.mutedForeground }]}
|
||||
>
|
||||
{receipt.originalFilename}
|
||||
</Text>
|
||||
</SwipeableRow>
|
||||
))}
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title={scanning ? "Scanning…" : "Scan receipt"}
|
||||
loading={scanning || uploadReceipt.isPending}
|
||||
style={styles.actionButton}
|
||||
onPress={() => void attachAndScan(true)}
|
||||
/>
|
||||
<Button
|
||||
title="Import photo"
|
||||
variant="secondary"
|
||||
loading={scanning || uploadReceipt.isPending}
|
||||
style={styles.actionButton}
|
||||
onPress={() => void attachAndScan(false)}
|
||||
/>
|
||||
</View>
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
amount: {
|
||||
fontSize: 28,
|
||||
fontWeight: "600",
|
||||
},
|
||||
metaStack: {
|
||||
gap: spacing.sm,
|
||||
},
|
||||
meta: {
|
||||
fontFamily: fonts.body,
|
||||
fontSize: 14,
|
||||
},
|
||||
badges: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
badge: {
|
||||
borderWidth: 1,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 4,
|
||||
fontFamily: fonts.bodyMedium,
|
||||
fontSize: 12,
|
||||
},
|
||||
section: {
|
||||
fontSize: 16,
|
||||
fontWeight: "600",
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
receiptRow: {
|
||||
padding: spacing.md,
|
||||
fontSize: 14,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
actionButton: {
|
||||
flex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
function expenseToForm(
|
||||
expense: {
|
||||
description: string;
|
||||
amount: number;
|
||||
date: Date | string;
|
||||
category: string | null;
|
||||
businessId: string | null;
|
||||
clientId: string | null;
|
||||
billable: boolean;
|
||||
reimbursable: boolean;
|
||||
taxDeductible: boolean | null;
|
||||
notes: string | null;
|
||||
},
|
||||
overrides: Partial<ExpenseFormState> = {},
|
||||
): ExpenseFormState {
|
||||
return {
|
||||
description: expense.description,
|
||||
amountText: String(expense.amount),
|
||||
date: new Date(expense.date),
|
||||
category: expense.category ?? "",
|
||||
businessId: expense.businessId ?? "",
|
||||
clientId: expense.clientId ?? "",
|
||||
billable: expense.billable,
|
||||
reimbursable: expense.reimbursable,
|
||||
taxDeductible: expense.taxDeductible ?? false,
|
||||
notes: expense.notes ?? "",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeNotes(prefix: string, existing: string) {
|
||||
const trimmed = existing.trim();
|
||||
if (!trimmed) return prefix;
|
||||
if (trimmed.startsWith("Receipt split")) {
|
||||
const detailsStart = trimmed.indexOf("\n\nReceipt details:");
|
||||
const legacyStart = trimmed.indexOf("\n\nOCR text:");
|
||||
const noteStart = detailsStart >= 0 ? detailsStart : legacyStart;
|
||||
return noteStart >= 0 ? `${prefix}${trimmed.slice(noteStart)}` : prefix;
|
||||
}
|
||||
return `${prefix}\n\nReceipt details:\n${trimmed}`;
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { router } from "expo-router";
|
||||
import { useMemo, useState } from "react";
|
||||
import {
|
||||
RefreshControl,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import type { AppRouter } from "beenvoice/server/api/root";
|
||||
import type { inferRouterOutputs } from "@trpc/server";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import { FilterChip } from "@/components/FilterChip";
|
||||
import { LoadingScreen } from "@/components/LoadingScreen";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { SwipeableRow } from "@/components/SwipeableRow";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { fonts, radii, spacing } from "@/constants/theme";
|
||||
import { useAppTheme } from "@/contexts/ThemeContext";
|
||||
import { formatCurrency, formatDate } from "@/lib/format";
|
||||
import { api } from "@/lib/trpc";
|
||||
import { formatTrpcErrorMessage } from "@/lib/trpc-errors";
|
||||
import type { ThemeColors } from "@/lib/theme-palette";
|
||||
import { useThemedStyles } from "@/lib/use-themed-styles";
|
||||
|
||||
type ExpenseFilter = "all" | "billable" | "receipts";
|
||||
type Expense = inferRouterOutputs<AppRouter>["expenses"]["getAll"][number];
|
||||
|
||||
export default function ExpensesScreen() {
|
||||
const { colors } = useAppTheme();
|
||||
const styles = useThemedStyles(createStyles);
|
||||
const utils = api.useUtils();
|
||||
const [filter, setFilter] = useState<ExpenseFilter>("all");
|
||||
const expensesQuery = api.expenses.getAll.useQuery();
|
||||
|
||||
const deleteExpense = api.expenses.delete.useMutation({
|
||||
onSuccess: () => void utils.expenses.getAll.invalidate(),
|
||||
});
|
||||
|
||||
const expenses = expensesQuery.data ?? [];
|
||||
const filteredExpenses = useMemo(
|
||||
() =>
|
||||
expenses.filter((expense) => {
|
||||
if (filter === "billable") return expense.billable;
|
||||
if (filter === "receipts") return expense.receiptCount > 0;
|
||||
return true;
|
||||
}),
|
||||
[expenses, filter],
|
||||
);
|
||||
const summary = useMemo(() => {
|
||||
const total = filteredExpenses.reduce(
|
||||
(sum, expense) => sum + expense.amount,
|
||||
0,
|
||||
);
|
||||
const billable = filteredExpenses.reduce(
|
||||
(sum, expense) => sum + (expense.billable ? expense.amount : 0),
|
||||
0,
|
||||
);
|
||||
const receiptCount = filteredExpenses.reduce(
|
||||
(sum, expense) => sum + (expense.receiptCount ?? 0),
|
||||
0,
|
||||
);
|
||||
return { total, billable, receiptCount };
|
||||
}, [filteredExpenses]);
|
||||
const groupedExpenses = useMemo(
|
||||
() => groupExpensesByMonth(filteredExpenses),
|
||||
[filteredExpenses],
|
||||
);
|
||||
|
||||
if (expensesQuery.isLoading) {
|
||||
return <LoadingScreen message="Loading expenses..." />;
|
||||
}
|
||||
|
||||
if (expensesQuery.error) {
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<View style={styles.errorBox}>
|
||||
<PageHeader title="Expenses" subtitle="Expense tracking" />
|
||||
<Text style={[styles.errorTitle, { color: colors.foreground }]}>
|
||||
Could not load expenses
|
||||
</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{formatTrpcErrorMessage(expensesQuery.error)}
|
||||
</Text>
|
||||
</View>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<TabScrollView
|
||||
header={
|
||||
<View style={styles.header}>
|
||||
<PageHeader
|
||||
title="Expenses"
|
||||
subtitle={`${expenses.length} recorded expense${expenses.length === 1 ? "" : "s"}`}
|
||||
/>
|
||||
<Button
|
||||
title="Add expense"
|
||||
onPress={() => router.push("/(app)/more/expenses/new" as never)}
|
||||
/>
|
||||
</View>
|
||||
}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={expensesQuery.isRefetching}
|
||||
onRefresh={() => void expensesQuery.refetch()}
|
||||
tintColor={colors.primary}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{expenses.length === 0 ? (
|
||||
<View
|
||||
style={[
|
||||
styles.emptyCard,
|
||||
{ borderColor: colors.border, backgroundColor: colors.cardGlass },
|
||||
]}
|
||||
>
|
||||
<View style={[styles.emptyIcon, { backgroundColor: colors.muted }]}>
|
||||
<Ionicons name="receipt-outline" size={24} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.emptyTitle, { color: colors.foreground }]}>
|
||||
No expenses yet
|
||||
</Text>
|
||||
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
|
||||
Scan a receipt or add a manual entry when something needs to be tracked, billed, or reimbursed.
|
||||
</Text>
|
||||
<Button
|
||||
title="Add expense"
|
||||
onPress={() => router.push("/(app)/more/expenses/new" as never)}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<>
|
||||
<View style={styles.summaryGrid}>
|
||||
<SummaryTile label="Visible total" value={formatCurrency(summary.total)} />
|
||||
<SummaryTile label="Billable" value={formatCurrency(summary.billable)} />
|
||||
<SummaryTile label="Receipts" value={String(summary.receiptCount)} />
|
||||
</View>
|
||||
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={styles.filters}
|
||||
>
|
||||
<FilterChip
|
||||
label="All"
|
||||
active={filter === "all"}
|
||||
onPress={() => setFilter("all")}
|
||||
/>
|
||||
<FilterChip
|
||||
label="Billable"
|
||||
active={filter === "billable"}
|
||||
onPress={() => setFilter("billable")}
|
||||
/>
|
||||
<FilterChip
|
||||
label="With receipts"
|
||||
active={filter === "receipts"}
|
||||
onPress={() => setFilter("receipts")}
|
||||
/>
|
||||
</ScrollView>
|
||||
|
||||
{filteredExpenses.length === 0 ? (
|
||||
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
|
||||
No expenses match this filter.
|
||||
</Text>
|
||||
) : (
|
||||
groupedExpenses.map(([monthLabel, group]) => (
|
||||
<View key={monthLabel} style={styles.monthGroup}>
|
||||
<Text style={[styles.monthLabel, { color: colors.mutedForeground }]}>
|
||||
{monthLabel}
|
||||
</Text>
|
||||
{group.map((expense) => (
|
||||
<ExpenseRow
|
||||
key={expense.id}
|
||||
expense={expense}
|
||||
onDelete={() => deleteExpense.mutate({ id: expense.id })}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
function SummaryTile({ label, value }: { label: string; value: string }) {
|
||||
const { colors } = useAppTheme();
|
||||
const styles = useThemedStyles(createStyles);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
styles.summaryTile,
|
||||
{ borderColor: colors.border, backgroundColor: colors.cardGlass },
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.summaryLabel, { color: colors.mutedForeground }]}>
|
||||
{label}
|
||||
</Text>
|
||||
<Text style={[styles.summaryValue, { color: colors.foreground }]} numberOfLines={1}>
|
||||
{value}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ExpenseRow({ expense, onDelete }: { expense: Expense; onDelete: () => void }) {
|
||||
const { colors } = useAppTheme();
|
||||
const styles = useThemedStyles(createStyles);
|
||||
|
||||
return (
|
||||
<SwipeableRow
|
||||
backgroundColor={colors.cardGlass}
|
||||
contentStyle={({ pressed }) => [
|
||||
styles.row,
|
||||
{ borderColor: colors.border },
|
||||
pressed && styles.rowPressed,
|
||||
]}
|
||||
onPress={() => router.push(`/(app)/more/expenses/${expense.id}` as never)}
|
||||
actions={[
|
||||
{
|
||||
key: "open",
|
||||
label: "Open",
|
||||
icon: "open-outline",
|
||||
color: "#fff",
|
||||
backgroundColor: colors.primary,
|
||||
onPress: () => router.push(`/(app)/more/expenses/${expense.id}` as never),
|
||||
},
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
icon: "trash-outline",
|
||||
color: "#fff",
|
||||
backgroundColor: colors.destructive,
|
||||
onPress: onDelete,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<View style={[styles.categoryIcon, { backgroundColor: colors.muted }]}>
|
||||
<Ionicons name={expenseIcon(expense.category)} size={18} color={colors.primary} />
|
||||
</View>
|
||||
<View style={styles.meta}>
|
||||
<View style={styles.titleRow}>
|
||||
<Text style={[styles.title, { color: colors.foreground }]} numberOfLines={1}>
|
||||
{expense.description}
|
||||
</Text>
|
||||
{expense.receiptCount ? (
|
||||
<View
|
||||
style={[
|
||||
styles.receiptPill,
|
||||
{ borderColor: colors.border, backgroundColor: colors.background },
|
||||
]}
|
||||
>
|
||||
<Ionicons name="document-attach-outline" size={13} color={colors.primary} />
|
||||
<Text style={[styles.receiptPillText, { color: colors.primary }]}>
|
||||
{expense.receiptCount}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<Text style={[styles.sub, { color: colors.mutedForeground }]} numberOfLines={1}>
|
||||
{formatDate(expense.date)}
|
||||
{expense.category ? ` · ${expense.category}` : ""}
|
||||
{expense.client?.name ? ` · ${expense.client.name}` : ""}
|
||||
</Text>
|
||||
<View style={styles.tagRow}>
|
||||
{expense.billable ? (
|
||||
<Text style={[styles.tag, { color: colors.primary, borderColor: colors.border }]}>
|
||||
Billable
|
||||
</Text>
|
||||
) : null}
|
||||
{expense.reimbursable ? (
|
||||
<Text style={[styles.tag, { color: colors.foreground, borderColor: colors.border }]}>
|
||||
Reimbursable
|
||||
</Text>
|
||||
) : null}
|
||||
{expense.taxDeductible ? (
|
||||
<Text style={[styles.tag, { color: colors.success, borderColor: colors.border }]}>
|
||||
Tax
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.amountStack}>
|
||||
<Text style={[styles.amount, { color: colors.foreground }]}>
|
||||
{formatCurrency(expense.amount, expense.currency)}
|
||||
</Text>
|
||||
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
|
||||
</View>
|
||||
</SwipeableRow>
|
||||
);
|
||||
}
|
||||
|
||||
function groupExpensesByMonth(expenses: Expense[]) {
|
||||
const groups = new Map<string, Expense[]>();
|
||||
for (const expense of expenses) {
|
||||
const date = new Date(expense.date);
|
||||
const key = date.toLocaleDateString(undefined, {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
const group = groups.get(key) ?? [];
|
||||
group.push(expense);
|
||||
groups.set(key, group);
|
||||
}
|
||||
return Array.from(groups.entries());
|
||||
}
|
||||
|
||||
function expenseIcon(category: string | null): keyof typeof Ionicons.glyphMap {
|
||||
const normalized = category?.toLowerCase() ?? "";
|
||||
if (normalized.includes("travel") || normalized.includes("mileage")) return "airplane-outline";
|
||||
if (normalized.includes("meal") || normalized.includes("food")) return "restaurant-outline";
|
||||
if (normalized.includes("software") || normalized.includes("subscription")) return "laptop-outline";
|
||||
if (normalized.includes("office") || normalized.includes("supply")) return "briefcase-outline";
|
||||
if (normalized.includes("phone") || normalized.includes("internet")) return "wifi-outline";
|
||||
return "receipt-outline";
|
||||
}
|
||||
|
||||
const createStyles = (colors: ThemeColors) =>
|
||||
StyleSheet.create({
|
||||
header: {
|
||||
gap: spacing.md,
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: 12,
|
||||
borderWidth: 1,
|
||||
borderRadius: radii.lg,
|
||||
},
|
||||
rowPressed: {
|
||||
opacity: 0.82,
|
||||
},
|
||||
categoryIcon: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: radii.md,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
meta: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: spacing.xs,
|
||||
},
|
||||
titleRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
title: {
|
||||
flex: 1,
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 15,
|
||||
},
|
||||
sub: {
|
||||
fontFamily: fonts.body,
|
||||
fontSize: 13,
|
||||
},
|
||||
tagRow: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
gap: spacing.xs,
|
||||
},
|
||||
tag: {
|
||||
borderWidth: 1,
|
||||
borderRadius: radii.pill,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 2,
|
||||
fontFamily: fonts.bodyMedium,
|
||||
fontSize: 11,
|
||||
overflow: "hidden",
|
||||
},
|
||||
amountStack: {
|
||||
alignItems: "flex-end",
|
||||
gap: spacing.xs,
|
||||
},
|
||||
amount: {
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 15,
|
||||
fontVariant: ["tabular-nums"],
|
||||
},
|
||||
summaryGrid: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
gap: spacing.xs,
|
||||
},
|
||||
summaryTile: {
|
||||
flexGrow: 1,
|
||||
flexBasis: "30%",
|
||||
minWidth: 104,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: 12,
|
||||
borderRadius: radii.lg,
|
||||
borderWidth: 1,
|
||||
},
|
||||
summaryLabel: {
|
||||
fontFamily: fonts.bodyMedium,
|
||||
fontSize: 12,
|
||||
textTransform: "uppercase",
|
||||
},
|
||||
summaryValue: {
|
||||
marginTop: 2,
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 20,
|
||||
fontVariant: ["tabular-nums"],
|
||||
},
|
||||
monthGroup: {
|
||||
gap: 2,
|
||||
},
|
||||
monthLabel: {
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 12,
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: 0,
|
||||
paddingHorizontal: spacing.xs,
|
||||
},
|
||||
filters: {
|
||||
gap: spacing.sm,
|
||||
paddingRight: spacing.lg,
|
||||
},
|
||||
receiptPill: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
borderWidth: 1,
|
||||
borderRadius: radii.pill,
|
||||
paddingHorizontal: 7,
|
||||
paddingVertical: 2,
|
||||
},
|
||||
receiptPillText: {
|
||||
fontFamily: fonts.bodyMedium,
|
||||
fontSize: 12,
|
||||
},
|
||||
empty: {
|
||||
fontFamily: fonts.body,
|
||||
fontSize: 14,
|
||||
lineHeight: 20,
|
||||
textAlign: "center",
|
||||
},
|
||||
emptyCard: {
|
||||
alignItems: "center",
|
||||
gap: spacing.sm,
|
||||
padding: spacing.lg,
|
||||
borderWidth: 1,
|
||||
borderRadius: radii.lg,
|
||||
},
|
||||
emptyIcon: {
|
||||
width: 52,
|
||||
height: 52,
|
||||
borderRadius: radii.lg,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
emptyTitle: {
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 17,
|
||||
},
|
||||
errorBox: {
|
||||
padding: spacing.lg,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
errorTitle: {
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 18,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { router } from "expo-router";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Alert, StyleSheet, Text, View } from "react-native";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import {
|
||||
defaultExpenseFormState,
|
||||
ExpenseFormFields,
|
||||
type ExpenseFormState,
|
||||
} from "@/components/expenses/ExpenseFormFields";
|
||||
import { ReceiptItemSelector } from "@/components/expenses/ReceiptItemSelector";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Card } from "@/components/ui/Card";
|
||||
import { fonts, spacing } from "@/constants/theme";
|
||||
import { useAppTheme } from "@/contexts/ThemeContext";
|
||||
import {
|
||||
scanReceiptImage,
|
||||
type PickedReceiptImage,
|
||||
type ReceiptScanResult,
|
||||
} from "@/lib/receipt-scan";
|
||||
import { api } from "@/lib/trpc";
|
||||
|
||||
type ReceiptSplitDraft = Pick<
|
||||
ReceiptScanResult,
|
||||
"items" | "subtotal" | "tax" | "total"
|
||||
>;
|
||||
|
||||
export default function NewExpenseScreen() {
|
||||
const { colors } = useAppTheme();
|
||||
const utils = api.useUtils();
|
||||
const businessesQuery = api.businesses.getAll.useQuery();
|
||||
const clientsQuery = api.clients.getAll.useQuery();
|
||||
|
||||
const businesses = businessesQuery.data ?? [];
|
||||
const clients = clientsQuery.data ?? [];
|
||||
const defaultBusinessId = useMemo(
|
||||
() =>
|
||||
businesses.find((business) => business.isDefault)?.id ??
|
||||
businesses[0]?.id ??
|
||||
"",
|
||||
[businesses],
|
||||
);
|
||||
const [form, setForm] = useState<ExpenseFormState>(() =>
|
||||
defaultExpenseFormState(),
|
||||
);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [pendingReceipt, setPendingReceipt] =
|
||||
useState<PickedReceiptImage | null>(null);
|
||||
const [receiptSplit, setReceiptSplit] = useState<ReceiptSplitDraft | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const createExpense = api.expenses.create.useMutation();
|
||||
const uploadReceipt = api.expenses.uploadReceipt.useMutation();
|
||||
const suggest = api.expenses.suggestFromReceiptText.useMutation();
|
||||
|
||||
async function runScan(fromCamera: boolean) {
|
||||
setScanning(true);
|
||||
try {
|
||||
const result = await scanReceiptImage(
|
||||
fromCamera,
|
||||
{
|
||||
description: form.description,
|
||||
amountText: form.amountText,
|
||||
date: form.date,
|
||||
},
|
||||
(input) => suggest.mutateAsync(input),
|
||||
);
|
||||
if (!result) return;
|
||||
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
description: result.description,
|
||||
amountText: result.amountText,
|
||||
date: result.date,
|
||||
notes: result.ocrText,
|
||||
businessId: current.businessId || defaultBusinessId,
|
||||
}));
|
||||
setPendingReceipt(result.image);
|
||||
setReceiptSplit(
|
||||
result.items.length > 0
|
||||
? {
|
||||
items: result.items,
|
||||
subtotal: result.subtotal,
|
||||
tax: result.tax,
|
||||
total: result.total,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
|
||||
Alert.alert(
|
||||
"Receipt scanned",
|
||||
result.items.length > 0
|
||||
? "Select the items this person owes, then apply the split amount."
|
||||
: result.amountText
|
||||
? `Filled amount $${result.amountText}${result.description ? ` from ${result.description}` : ""}. Review and save.`
|
||||
: "Review the fields and enter the total before saving.",
|
||||
);
|
||||
} finally {
|
||||
setScanning(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
const amount = Number(form.amountText);
|
||||
if (!form.description.trim()) {
|
||||
Alert.alert("Description required", "Enter what this expense was for.");
|
||||
return;
|
||||
}
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
Alert.alert("Amount required", "Enter a valid amount.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const expense = await createExpense.mutateAsync({
|
||||
description: form.description.trim(),
|
||||
amount,
|
||||
date: form.date,
|
||||
currency: "USD",
|
||||
category: form.category || undefined,
|
||||
clientId: form.clientId || undefined,
|
||||
businessId: form.businessId || defaultBusinessId || undefined,
|
||||
billable: form.billable,
|
||||
reimbursable: form.reimbursable,
|
||||
taxDeductible: form.taxDeductible,
|
||||
notes: form.notes.trim() || undefined,
|
||||
});
|
||||
|
||||
if (pendingReceipt) {
|
||||
await uploadReceipt.mutateAsync({
|
||||
expenseId: expense.id,
|
||||
filename: pendingReceipt.filename,
|
||||
mimeType: pendingReceipt.mimeType,
|
||||
data: pendingReceipt.base64,
|
||||
});
|
||||
}
|
||||
|
||||
await utils.expenses.getAll.invalidate();
|
||||
router.replace(`/(app)/more/expenses/${expense.id}` as never);
|
||||
} catch (err) {
|
||||
Alert.alert(
|
||||
"Could not save expense",
|
||||
err instanceof Error ? err.message : "Try again.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<TabScrollView
|
||||
header={
|
||||
<PageHeader
|
||||
title="New expense"
|
||||
subtitle="Add a receipt, fill the details, and save it"
|
||||
/>
|
||||
}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
<Card title="Receipt">
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title={scanning ? "Scanning..." : "Take photo"}
|
||||
variant="secondary"
|
||||
leftIcon="camera-outline"
|
||||
loading={scanning}
|
||||
style={styles.actionButton}
|
||||
onPress={() => void runScan(true)}
|
||||
/>
|
||||
<Button
|
||||
title="Choose photo"
|
||||
variant="secondary"
|
||||
leftIcon="image-outline"
|
||||
loading={scanning}
|
||||
style={styles.actionButton}
|
||||
onPress={() => void runScan(false)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{pendingReceipt ? (
|
||||
<View style={[styles.notice, { backgroundColor: colors.successBg }]}>
|
||||
<Text style={[styles.noticeText, { color: colors.success }]}>
|
||||
Receipt attached. Review the details below before saving.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</Card>
|
||||
|
||||
{receiptSplit ? (
|
||||
<ReceiptItemSelector
|
||||
items={receiptSplit.items}
|
||||
subtotal={receiptSplit.subtotal}
|
||||
tax={receiptSplit.tax}
|
||||
total={receiptSplit.total}
|
||||
onApply={(selection) => {
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
amountText: selection.owedTotal.toFixed(2),
|
||||
notes: mergeNotes(selection.notes, current.notes),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Card title="Details">
|
||||
<ExpenseFormFields
|
||||
value={{
|
||||
...form,
|
||||
businessId: form.businessId || defaultBusinessId,
|
||||
}}
|
||||
businesses={businesses}
|
||||
clients={clients}
|
||||
onChange={setForm}
|
||||
notesLabel="Notes"
|
||||
notesPlaceholder="Internal details"
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<View style={styles.saveActions}>
|
||||
<Button
|
||||
title="Save expense"
|
||||
leftIcon="checkmark-circle-outline"
|
||||
loading={createExpense.isPending}
|
||||
onPress={() => void handleSave()}
|
||||
/>
|
||||
<Button
|
||||
title="Cancel"
|
||||
leftIcon="close-circle-outline"
|
||||
variant="secondary"
|
||||
onPress={() => router.back()}
|
||||
/>
|
||||
</View>
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
actionButton: {
|
||||
flex: 1,
|
||||
},
|
||||
saveActions: {
|
||||
gap: spacing.sm,
|
||||
},
|
||||
notice: {
|
||||
borderRadius: 12,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
noticeText: {
|
||||
fontFamily: fonts.bodyMedium,
|
||||
fontSize: 13,
|
||||
lineHeight: 18,
|
||||
},
|
||||
});
|
||||
|
||||
function mergeNotes(prefix: string, existing: string) {
|
||||
const trimmed = existing.trim();
|
||||
if (!trimmed) return prefix;
|
||||
if (trimmed.startsWith("Receipt split")) {
|
||||
const detailsStart = trimmed.indexOf("\n\nReceipt details:");
|
||||
const legacyStart = trimmed.indexOf("\n\nOCR text:");
|
||||
const noteStart = detailsStart >= 0 ? detailsStart : legacyStart;
|
||||
return noteStart >= 0 ? `${prefix}${trimmed.slice(noteStart)}` : prefix;
|
||||
}
|
||||
return `${prefix}\n\nReceipt details:\n${trimmed}`;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { router } from "expo-router";
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
import { fonts, radii, spacing } from "@/constants/theme";
|
||||
import { useAppTheme } from "@/contexts/ThemeContext";
|
||||
import type { ThemeColors } from "@/lib/theme-palette";
|
||||
import { useThemedStyles } from "@/lib/use-themed-styles";
|
||||
|
||||
type HubItem = {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
href: string;
|
||||
icon: keyof typeof Ionicons.glyphMap;
|
||||
};
|
||||
|
||||
const ITEMS: HubItem[] = [
|
||||
{
|
||||
title: "Expenses",
|
||||
subtitle: "Track costs and attach receipts",
|
||||
href: "/(app)/more/expenses",
|
||||
icon: "receipt-outline",
|
||||
},
|
||||
{
|
||||
title: "Reports",
|
||||
subtitle: "Revenue, hours, and tax summaries",
|
||||
href: "/(app)/more/reports",
|
||||
icon: "bar-chart-outline",
|
||||
},
|
||||
{
|
||||
title: "Recurring invoices",
|
||||
subtitle: "Scheduled billing templates",
|
||||
href: "/(app)/more/recurring",
|
||||
icon: "repeat-outline",
|
||||
},
|
||||
{
|
||||
title: "Time entries",
|
||||
subtitle: "Full history with edit and delete",
|
||||
href: "/(app)/more/time-entries",
|
||||
icon: "time-outline",
|
||||
},
|
||||
{
|
||||
title: "Settings",
|
||||
subtitle: "Account, security, and app preferences",
|
||||
href: "/(app)/more/settings",
|
||||
icon: "settings-outline",
|
||||
},
|
||||
];
|
||||
|
||||
export default function MoreScreen() {
|
||||
const { colors } = useAppTheme();
|
||||
const styles = useThemedStyles(createStyles);
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage>
|
||||
<TabScrollView header={<PageHeader title="More" subtitle="Additional tools" />}>
|
||||
<View style={styles.list}>
|
||||
{ITEMS.map((item) => (
|
||||
<Pressable
|
||||
key={item.href}
|
||||
style={({ pressed }) => [styles.row, pressed && styles.rowPressed]}
|
||||
onPress={() => router.push(item.href as never)}
|
||||
>
|
||||
<View style={[styles.iconWrap, { backgroundColor: colors.muted }]}>
|
||||
<Ionicons name={item.icon} size={22} color={colors.primary} />
|
||||
</View>
|
||||
<View style={styles.copy}>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{item.title}</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.mutedForeground }]}>
|
||||
{item.subtitle}
|
||||
</Text>
|
||||
</View>
|
||||
<Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} />
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const createStyles = (colors: ThemeColors) =>
|
||||
StyleSheet.create({
|
||||
list: {
|
||||
gap: spacing.sm,
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
padding: spacing.md,
|
||||
borderRadius: radii.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
backgroundColor: colors.card,
|
||||
},
|
||||
rowPressed: {
|
||||
opacity: 0.85,
|
||||
},
|
||||
iconWrap: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: radii.md,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
copy: {
|
||||
flex: 1,
|
||||
gap: 2,
|
||||
},
|
||||
title: {
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 16,
|
||||
},
|
||||
subtitle: {
|
||||
fontFamily: fonts.body,
|
||||
fontSize: 13,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { RefreshControl, StyleSheet, Text, View } from "react-native";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import { LoadingScreen } from "@/components/LoadingScreen";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { SwipeableRow } from "@/components/SwipeableRow";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
import { fonts, spacing } from "@/constants/theme";
|
||||
import { useAppTheme } from "@/contexts/ThemeContext";
|
||||
import { formatCurrency, formatDate } from "@/lib/format";
|
||||
import { api } from "@/lib/trpc";
|
||||
|
||||
export default function RecurringScreen() {
|
||||
const { colors } = useAppTheme();
|
||||
const utils = api.useUtils();
|
||||
const query = api.recurringInvoices.getAll.useQuery();
|
||||
|
||||
const pause = api.recurringInvoices.pause.useMutation({
|
||||
onSuccess: () => void query.refetch(),
|
||||
});
|
||||
const resume = api.recurringInvoices.resume.useMutation({
|
||||
onSuccess: () => void query.refetch(),
|
||||
});
|
||||
const generateNow = api.recurringInvoices.generateNow.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.invoices.getAll.invalidate();
|
||||
void query.refetch();
|
||||
},
|
||||
});
|
||||
|
||||
if (query.isLoading) {
|
||||
return <LoadingScreen message="Loading recurring invoices…" />;
|
||||
}
|
||||
|
||||
const items = query.data ?? [];
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<TabScrollView
|
||||
header={
|
||||
<PageHeader
|
||||
title="Recurring"
|
||||
subtitle={`${items.length} schedule${items.length === 1 ? "" : "s"}`}
|
||||
/>
|
||||
}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={query.isRefetching}
|
||||
onRefresh={() => void query.refetch()}
|
||||
tintColor={colors.primary}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{items.length === 0 ? (
|
||||
<Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
|
||||
No recurring invoices yet. Create them on the web dashboard for now.
|
||||
</Text>
|
||||
) : (
|
||||
items.map((item) => (
|
||||
<SwipeableRow
|
||||
key={item.id}
|
||||
actions={[
|
||||
{
|
||||
key: "generate",
|
||||
label: "Run",
|
||||
icon: "play-outline",
|
||||
color: "#fff",
|
||||
backgroundColor: colors.primary,
|
||||
onPress: () => generateNow.mutate({ id: item.id }),
|
||||
},
|
||||
{
|
||||
key: "toggle",
|
||||
label: item.status === "active" ? "Pause" : "Resume",
|
||||
icon: item.status === "active" ? "pause-outline" : "play-outline",
|
||||
color: "#fff",
|
||||
backgroundColor: colors.mutedForeground,
|
||||
onPress: () =>
|
||||
item.status === "active"
|
||||
? pause.mutate({ id: item.id })
|
||||
: resume.mutate({ id: item.id }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<View style={styles.row}>
|
||||
<View style={{ flex: 1, gap: 2 }}>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{item.name}</Text>
|
||||
<Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
|
||||
{item.client?.name ?? "Client"} · {item.schedule} · {item.status}
|
||||
</Text>
|
||||
<Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
|
||||
Next due {formatDate(item.nextDueAt)}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{formatCurrency(
|
||||
item.items.reduce((sum, line) => sum + line.hours * line.rate, 0),
|
||||
item.currency,
|
||||
)}
|
||||
</Text>
|
||||
</View>
|
||||
</SwipeableRow>
|
||||
))
|
||||
)}
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.md,
|
||||
padding: spacing.md,
|
||||
},
|
||||
title: {
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 15,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { RefreshControl, StyleSheet, Text, View } from "react-native";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import { LoadingScreen } from "@/components/LoadingScreen";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { StatCard } from "@/components/StatCard";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
import { Card } from "@/components/ui/Card";
|
||||
import { spacing } from "@/constants/theme";
|
||||
import { useAppTheme } from "@/contexts/ThemeContext";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { formatTrpcErrorMessage } from "@/lib/trpc-errors";
|
||||
import { api } from "@/lib/trpc";
|
||||
|
||||
export default function ReportsScreen() {
|
||||
const { colors } = useAppTheme();
|
||||
const statsQuery = api.dashboard.getStats.useQuery();
|
||||
const expensesQuery = api.expenses.getAll.useQuery();
|
||||
const summaryQuery = api.timeEntries.getSummary.useQuery();
|
||||
|
||||
if (statsQuery.isLoading || expensesQuery.isLoading || summaryQuery.isLoading) {
|
||||
return <LoadingScreen message="Loading reports…" />;
|
||||
}
|
||||
|
||||
if (statsQuery.error) {
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<View style={styles.errorBox}>
|
||||
<PageHeader title="Reports" subtitle="Business performance snapshot" />
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{formatTrpcErrorMessage(statsQuery.error)}
|
||||
</Text>
|
||||
</View>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const stats = statsQuery.data!;
|
||||
const expenseTotal = (expensesQuery.data ?? []).reduce((sum, e) => sum + e.amount, 0);
|
||||
const summary = summaryQuery.data;
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<TabScrollView
|
||||
header={<PageHeader title="Reports" subtitle="Business performance snapshot" />}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={statsQuery.isRefetching}
|
||||
onRefresh={() => {
|
||||
void statsQuery.refetch();
|
||||
void expensesQuery.refetch();
|
||||
void summaryQuery.refetch();
|
||||
}}
|
||||
tintColor={colors.primary}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<View style={styles.grid}>
|
||||
<StatCard label="Revenue" value={formatCurrency(stats.totalRevenue)} />
|
||||
<StatCard label="Pending" value={formatCurrency(stats.pendingAmount)} />
|
||||
<StatCard label="Expenses" value={formatCurrency(expenseTotal)} />
|
||||
<StatCard
|
||||
label="Billable hours"
|
||||
value={summary ? summary.totalHours.toFixed(1) : "0"}
|
||||
hint={summary ? `${summary.count} entries` : undefined}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<Card title="Invoice status">
|
||||
{(stats.statusChartData ?? []).map((item) => (
|
||||
<View key={item.status} style={styles.statusRow}>
|
||||
<Text style={{ color: colors.foreground }}>{item.name}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{item.count} · {formatCurrency(item.value)}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</Card>
|
||||
|
||||
<Card title="Revenue trend (6 mo)">
|
||||
{stats.revenueChartData.map((point) => (
|
||||
<View key={point.month} style={styles.statusRow}>
|
||||
<Text style={{ color: colors.foreground }}>{point.monthLabel}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{formatCurrency(point.revenue)}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</Card>
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
grid: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
gap: spacing.md,
|
||||
},
|
||||
statusRow: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
errorBox: {
|
||||
padding: spacing.lg,
|
||||
gap: spacing.md,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,700 @@
|
||||
import { useState } from "react";
|
||||
import Constants from "expo-constants";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { router } from "expo-router";
|
||||
import {
|
||||
Alert,
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Switch,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import { InstanceUrlField } from "@/components/InstanceUrlField";
|
||||
import { LoadingScreen } from "@/components/LoadingScreen";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { PinPrompt } from "@/components/PinPrompt";
|
||||
import { ShortcutsSetupCard } from "@/components/ShortcutsSetupCard";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Card } from "@/components/ui/Card";
|
||||
import { fonts, spacing } from "@/constants/theme";
|
||||
import { useAccounts } from "@/contexts/AccountsContext";
|
||||
import { useAppLock } from "@/contexts/AppLockContext";
|
||||
import { useAuthClient, useSession } from "@/contexts/AuthContext";
|
||||
import { type ColorMode, useAppTheme } from "@/contexts/ThemeContext";
|
||||
import { startAdditionalAccountSignIn } from "@/lib/add-account";
|
||||
import {
|
||||
confirmRemoveAccount,
|
||||
finishAccountRemoval,
|
||||
} from "@/lib/account-actions";
|
||||
import { performAuthReset } from "@/lib/auth-session";
|
||||
import { api } from "@/lib/trpc";
|
||||
|
||||
const THEME_OPTIONS: { value: ColorMode; label: string }[] = [
|
||||
{ value: "system", label: "System" },
|
||||
{ value: "light", label: "Light" },
|
||||
{ value: "dark", label: "Dark" },
|
||||
];
|
||||
|
||||
export default function SettingsScreen() {
|
||||
const authClient = useAuthClient();
|
||||
const { data: session } = useSession();
|
||||
const {
|
||||
accounts,
|
||||
activeAccount,
|
||||
activeAccountId,
|
||||
apiUrl,
|
||||
switchAccount,
|
||||
removeAccount,
|
||||
refreshAccounts,
|
||||
clearActiveAccount,
|
||||
} = useAccounts();
|
||||
const { colors, colorMode, setColorMode } = useAppTheme();
|
||||
const switchProps = {
|
||||
trackColor: { false: colors.switchTrackOff, true: colors.switchTrackOn },
|
||||
thumbColor: Platform.OS === "android" ? colors.switchThumb : undefined,
|
||||
ios_backgroundColor: colors.switchIosBackground,
|
||||
};
|
||||
const {
|
||||
enabled: lockEnabled,
|
||||
biometricEnabled,
|
||||
biometricAvailable,
|
||||
biometricLabel,
|
||||
enableLock,
|
||||
disableLock,
|
||||
changePin,
|
||||
setUseBiometric,
|
||||
lock,
|
||||
} = useAppLock();
|
||||
const profileQuery = api.settings.getProfile.useQuery();
|
||||
const deleteAccountMutation = api.settings.deleteAccount.useMutation();
|
||||
|
||||
const [pinPrompt, setPinPrompt] = useState<
|
||||
| { mode: "create" }
|
||||
| { mode: "confirm-disable" }
|
||||
| { mode: "change-current" }
|
||||
| { mode: "change-next" }
|
||||
| null
|
||||
>(null);
|
||||
const [pendingPin, setPendingPin] = useState("");
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [refreshingAccounts, setRefreshingAccounts] = useState(false);
|
||||
|
||||
async function handleRefreshAccounts() {
|
||||
setRefreshingAccounts(true);
|
||||
try {
|
||||
await refreshAccounts();
|
||||
await profileQuery.refetch();
|
||||
} finally {
|
||||
setRefreshingAccounts(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleRemoveAccount(accountId: string, label: string) {
|
||||
confirmRemoveAccount(
|
||||
label,
|
||||
() => removeAccount(accountId),
|
||||
async (result) => {
|
||||
await finishAccountRemoval({
|
||||
result,
|
||||
authClient,
|
||||
clearActiveAccount,
|
||||
activeAccountId,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSignOut() {
|
||||
await performAuthReset({
|
||||
authClient,
|
||||
clearActiveAccount,
|
||||
activeAccountId,
|
||||
});
|
||||
router.replace("/(auth)/sign-in");
|
||||
}
|
||||
|
||||
function confirmSignOut() {
|
||||
Alert.alert("Sign out", "Sign out of this account on this device?", [
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Sign out",
|
||||
style: "destructive",
|
||||
onPress: () => void handleSignOut(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
async function handleDeleteAccount() {
|
||||
if (!activeAccountId) return;
|
||||
|
||||
try {
|
||||
await deleteAccountMutation.mutateAsync({
|
||||
confirmText: "DELETE MY ACCOUNT",
|
||||
});
|
||||
const result = await removeAccount(activeAccountId);
|
||||
await finishAccountRemoval({
|
||||
result,
|
||||
authClient,
|
||||
clearActiveAccount,
|
||||
activeAccountId,
|
||||
});
|
||||
if (result.remainingCount > 0) {
|
||||
router.replace("/(auth)/select-account");
|
||||
}
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Could not delete account",
|
||||
error instanceof Error ? error.message : "Please try again.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDeleteAccount() {
|
||||
Alert.alert(
|
||||
"Permanently delete account?",
|
||||
"This deletes your account, invoices, clients, businesses, expenses, time entries, uploaded files, and sign-in data. This cannot be undone.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Delete Account",
|
||||
style: "destructive",
|
||||
onPress: () => void handleDeleteAccount(),
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
function confirmInstanceChange() {
|
||||
Alert.alert(
|
||||
"Server updated",
|
||||
"You may need to sign in again if you switched to a different instance.",
|
||||
[{ text: "OK" }],
|
||||
);
|
||||
}
|
||||
|
||||
function handleLockToggle(next: boolean) {
|
||||
if (next) {
|
||||
setPinPrompt({ mode: "create" });
|
||||
return;
|
||||
}
|
||||
setPinPrompt({ mode: "confirm-disable" });
|
||||
}
|
||||
|
||||
function handleChangePin() {
|
||||
setPendingPin("");
|
||||
setPinPrompt({ mode: "change-current" });
|
||||
}
|
||||
|
||||
function handleBiometricToggle(next: boolean) {
|
||||
void setUseBiometric(next);
|
||||
}
|
||||
|
||||
async function handlePinPromptSubmit(pin: string) {
|
||||
if (pinPrompt?.mode === "create") {
|
||||
try {
|
||||
await enableLock(pin);
|
||||
setPinPrompt(null);
|
||||
} catch (err) {
|
||||
Alert.alert(
|
||||
"Could not enable lock",
|
||||
err instanceof Error ? err.message : "Try again",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (pinPrompt?.mode === "confirm-disable") {
|
||||
const success = await disableLock(pin);
|
||||
if (!success) {
|
||||
Alert.alert("Incorrect PIN", "Could not disable app lock.");
|
||||
return;
|
||||
}
|
||||
setPinPrompt(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pinPrompt?.mode === "change-current") {
|
||||
setPendingPin(pin);
|
||||
setPinPrompt({ mode: "change-next" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (pinPrompt?.mode === "change-next") {
|
||||
const success = await changePin(pendingPin, pin);
|
||||
if (!success) {
|
||||
Alert.alert(
|
||||
"Could not change PIN",
|
||||
"Check your current PIN and try again.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
setPendingPin("");
|
||||
setPinPrompt(null);
|
||||
Alert.alert("PIN updated", "Your app lock PIN has been changed.");
|
||||
}
|
||||
}
|
||||
|
||||
if (profileQuery.isLoading) {
|
||||
return <LoadingScreen message="Loading profile…" />;
|
||||
}
|
||||
|
||||
const profile = profileQuery.data;
|
||||
const appVersion = Constants.expoConfig?.version ?? "1.0.0";
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<PinPrompt
|
||||
visible={pinPrompt !== null}
|
||||
title={
|
||||
pinPrompt?.mode === "create"
|
||||
? "Create PIN"
|
||||
: pinPrompt?.mode === "confirm-disable"
|
||||
? "Disable app lock"
|
||||
: pinPrompt?.mode === "change-current"
|
||||
? "Current PIN"
|
||||
: "New PIN"
|
||||
}
|
||||
message={
|
||||
pinPrompt?.mode === "create" || pinPrompt?.mode === "change-next"
|
||||
? "Choose a 4–6 digit PIN."
|
||||
: pinPrompt?.mode === "confirm-disable"
|
||||
? "Enter your PIN to turn off app lock."
|
||||
: "Enter your current PIN."
|
||||
}
|
||||
confirmLabel={
|
||||
pinPrompt?.mode === "create" || pinPrompt?.mode === "change-next"
|
||||
? "Save"
|
||||
: "Continue"
|
||||
}
|
||||
requireConfirmation={
|
||||
pinPrompt?.mode === "create" || pinPrompt?.mode === "change-next"
|
||||
}
|
||||
onCancel={() => {
|
||||
setPendingPin("");
|
||||
setPinPrompt(null);
|
||||
}}
|
||||
onSubmit={(pin) => void handlePinPromptSubmit(pin)}
|
||||
/>
|
||||
<TabScrollView
|
||||
header={
|
||||
<PageHeader
|
||||
title="Settings"
|
||||
subtitle="Account and app preferences"
|
||||
/>
|
||||
}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
<Card title="Account">
|
||||
<Text style={[styles.name, { color: colors.foreground }]}>
|
||||
{profile?.name ?? session?.user.name ?? "User"}
|
||||
</Text>
|
||||
<Text style={[styles.email, { color: colors.mutedForeground }]}>
|
||||
{profile?.email ?? session?.user.email}
|
||||
</Text>
|
||||
{profile?.role ? (
|
||||
<Text style={[styles.meta, { color: colors.mutedForeground }]}>
|
||||
Role: {profile.role}
|
||||
</Text>
|
||||
) : null}
|
||||
</Card>
|
||||
|
||||
<Card title="Accounts">
|
||||
{accounts.map((account) => {
|
||||
const isActive = account.id === activeAccountId;
|
||||
return (
|
||||
<View
|
||||
key={account.id}
|
||||
style={[
|
||||
styles.accountRow,
|
||||
{
|
||||
borderColor: colors.border,
|
||||
backgroundColor: isActive ? colors.muted : "transparent",
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => void switchAccount(account.id)}
|
||||
style={({ pressed }) => [
|
||||
styles.accountMain,
|
||||
pressed && styles.pressed,
|
||||
]}
|
||||
>
|
||||
<View style={styles.accountMeta}>
|
||||
<Text
|
||||
style={[
|
||||
styles.accountName,
|
||||
{ color: colors.foreground },
|
||||
]}
|
||||
>
|
||||
{account.name || account.email}
|
||||
</Text>
|
||||
<Text
|
||||
style={[
|
||||
styles.accountSub,
|
||||
{ color: colors.mutedForeground },
|
||||
]}
|
||||
>
|
||||
{account.email}
|
||||
</Text>
|
||||
<Text
|
||||
style={[
|
||||
styles.accountSub,
|
||||
{ color: colors.mutedForeground },
|
||||
]}
|
||||
>
|
||||
{account.instanceUrl.replace(/^https?:\/\//, "")}
|
||||
</Text>
|
||||
</View>
|
||||
{isActive ? (
|
||||
<Text
|
||||
style={[styles.activeBadge, { color: colors.primary }]}
|
||||
>
|
||||
Active
|
||||
</Text>
|
||||
) : null}
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Remove ${account.name || account.email}`}
|
||||
hitSlop={8}
|
||||
onPress={() =>
|
||||
handleRemoveAccount(
|
||||
account.id,
|
||||
account.name || account.email,
|
||||
)
|
||||
}
|
||||
style={({ pressed }) => [
|
||||
styles.removeButton,
|
||||
pressed && styles.pressed,
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="trash-outline"
|
||||
size={18}
|
||||
color={colors.destructive}
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
title={refreshingAccounts ? "Refreshing…" : "Refresh accounts"}
|
||||
variant="secondary"
|
||||
disabled={refreshingAccounts}
|
||||
onPress={() => void handleRefreshAccounts()}
|
||||
/>
|
||||
<Button
|
||||
title="Add another account"
|
||||
variant="secondary"
|
||||
onPress={() =>
|
||||
void startAdditionalAccountSignIn(clearActiveAccount)
|
||||
}
|
||||
/>
|
||||
<Text style={[styles.meta, { color: colors.mutedForeground }]}>
|
||||
Tap an account to switch. Refresh updates names from saved sign-in
|
||||
data.
|
||||
</Text>
|
||||
</Card>
|
||||
|
||||
{Platform.OS === "ios" ? (
|
||||
<Card title="Shortcuts & Siri">
|
||||
<ShortcutsSetupCard />
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<Card title="Security">
|
||||
<View style={styles.settingRow}>
|
||||
<View style={styles.settingCopy}>
|
||||
<Text
|
||||
style={[styles.settingTitle, { color: colors.foreground }]}
|
||||
>
|
||||
App lock
|
||||
</Text>
|
||||
<Text style={[styles.meta, { color: colors.mutedForeground }]}>
|
||||
Require a PIN when reopening the app
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={lockEnabled}
|
||||
onValueChange={handleLockToggle}
|
||||
{...switchProps}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{lockEnabled && biometricAvailable ? (
|
||||
<View style={styles.settingRow}>
|
||||
<View style={styles.settingCopy}>
|
||||
<Text
|
||||
style={[styles.settingTitle, { color: colors.foreground }]}
|
||||
>
|
||||
{biometricLabel}
|
||||
</Text>
|
||||
<Text
|
||||
style={[styles.meta, { color: colors.mutedForeground }]}
|
||||
>
|
||||
Unlock with {biometricLabel.toLowerCase()} when available
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={biometricEnabled}
|
||||
onValueChange={handleBiometricToggle}
|
||||
{...switchProps}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{lockEnabled ? (
|
||||
<>
|
||||
<Button
|
||||
title="Change PIN"
|
||||
variant="secondary"
|
||||
onPress={handleChangePin}
|
||||
/>
|
||||
<Button title="Lock now" variant="secondary" onPress={lock} />
|
||||
</>
|
||||
) : null}
|
||||
</Card>
|
||||
|
||||
<Card title="Appearance">
|
||||
<View style={styles.themeRow}>
|
||||
{THEME_OPTIONS.map((option) => {
|
||||
const selected = colorMode === option.value;
|
||||
return (
|
||||
<Pressable
|
||||
key={option.value}
|
||||
accessibilityRole="button"
|
||||
onPress={() => void setColorMode(option.value)}
|
||||
style={[
|
||||
styles.themeChip,
|
||||
{
|
||||
borderColor: selected ? colors.primary : colors.border,
|
||||
backgroundColor: selected
|
||||
? colors.muted
|
||||
: "transparent",
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.themeChipLabel,
|
||||
{
|
||||
color: selected
|
||||
? colors.foreground
|
||||
: colors.mutedForeground,
|
||||
},
|
||||
]}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</Card>
|
||||
|
||||
<Card title="App">
|
||||
<View style={styles.appRow}>
|
||||
<Text style={[styles.meta, { color: colors.mutedForeground }]}>
|
||||
Version
|
||||
</Text>
|
||||
<Text style={[styles.appValue, { color: colors.foreground }]}>
|
||||
{appVersion}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.appRow}>
|
||||
<Text style={[styles.meta, { color: colors.mutedForeground }]}>
|
||||
Platform
|
||||
</Text>
|
||||
<Text style={[styles.appValue, { color: colors.foreground }]}>
|
||||
{Constants.platform?.ios ? "iOS" : "Other"}
|
||||
</Text>
|
||||
</View>
|
||||
</Card>
|
||||
|
||||
<Card title="Delete account">
|
||||
<Text style={[styles.meta, { color: colors.mutedForeground }]}>
|
||||
Permanently delete this account and all of its data from the
|
||||
server. This cannot be undone.
|
||||
</Text>
|
||||
<Button
|
||||
title={
|
||||
deleteAccountMutation.isPending
|
||||
? "Deleting account…"
|
||||
: "Delete Account"
|
||||
}
|
||||
variant="danger"
|
||||
loading={deleteAccountMutation.isPending}
|
||||
disabled={deleteAccountMutation.isPending}
|
||||
onPress={confirmDeleteAccount}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: showAdvanced }}
|
||||
onPress={() => setShowAdvanced((open) => !open)}
|
||||
style={styles.advancedToggle}
|
||||
>
|
||||
<Text
|
||||
style={[styles.advancedLabel, { color: colors.mutedForeground }]}
|
||||
>
|
||||
Advanced
|
||||
</Text>
|
||||
<Ionicons
|
||||
name={showAdvanced ? "chevron-up" : "chevron-down"}
|
||||
size={16}
|
||||
color={colors.mutedForeground}
|
||||
/>
|
||||
</Pressable>
|
||||
|
||||
{showAdvanced ? (
|
||||
<Card title="Server instance">
|
||||
<InstanceUrlField onSaved={confirmInstanceChange} />
|
||||
<Text
|
||||
style={[
|
||||
styles.currentServer,
|
||||
{ color: colors.mutedForeground },
|
||||
]}
|
||||
>
|
||||
Connected to {activeAccount?.instanceUrl ?? apiUrl}
|
||||
</Text>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title="Sign Out"
|
||||
variant="danger"
|
||||
onPress={confirmSignOut}
|
||||
/>
|
||||
</View>
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
name: {
|
||||
fontSize: 20,
|
||||
fontFamily: fonts.heading,
|
||||
},
|
||||
email: {
|
||||
fontSize: 15,
|
||||
fontFamily: fonts.body,
|
||||
},
|
||||
meta: {
|
||||
fontSize: 13,
|
||||
fontFamily: fonts.bodyMedium,
|
||||
},
|
||||
currentServer: {
|
||||
fontSize: 12,
|
||||
fontFamily: fonts.mono,
|
||||
},
|
||||
advancedToggle: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: spacing.xs,
|
||||
minHeight: 36,
|
||||
},
|
||||
advancedLabel: {
|
||||
fontSize: 13,
|
||||
fontFamily: fonts.bodyMedium,
|
||||
},
|
||||
appRow: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
},
|
||||
appValue: {
|
||||
fontSize: 14,
|
||||
fontFamily: fonts.bodyMedium,
|
||||
},
|
||||
accountRow: {
|
||||
borderWidth: 1,
|
||||
borderRadius: 12,
|
||||
paddingLeft: spacing.md,
|
||||
paddingRight: spacing.sm,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
accountMain: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: spacing.md,
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
removeButton: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
minWidth: 36,
|
||||
minHeight: 36,
|
||||
},
|
||||
pressed: {
|
||||
opacity: 0.92,
|
||||
},
|
||||
accountMeta: {
|
||||
flex: 1,
|
||||
gap: 2,
|
||||
},
|
||||
accountName: {
|
||||
fontSize: 15,
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
},
|
||||
accountSub: {
|
||||
fontSize: 12,
|
||||
fontFamily: fonts.body,
|
||||
},
|
||||
activeBadge: {
|
||||
fontSize: 12,
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
},
|
||||
themeRow: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
themeChip: {
|
||||
flex: 1,
|
||||
borderWidth: 1,
|
||||
borderRadius: 10,
|
||||
minHeight: 40,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: spacing.sm,
|
||||
},
|
||||
themeChipLabel: {
|
||||
fontSize: 13,
|
||||
fontFamily: fonts.bodyMedium,
|
||||
lineHeight: 18,
|
||||
...(Platform.OS === "android" ? { includeFontPadding: false } : null),
|
||||
},
|
||||
settingRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: spacing.md,
|
||||
},
|
||||
settingCopy: {
|
||||
flex: 1,
|
||||
gap: 2,
|
||||
},
|
||||
settingTitle: {
|
||||
fontSize: 15,
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
},
|
||||
actions: {
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { RefreshControl, StyleSheet, Text, View } from "react-native";
|
||||
|
||||
import { AppBackground } from "@/components/AppBackground";
|
||||
import { LoadingScreen } from "@/components/LoadingScreen";
|
||||
import { PageHeader } from "@/components/PageHeader";
|
||||
import { SwipeableRow } from "@/components/SwipeableRow";
|
||||
import { TabPage } from "@/components/TabPage";
|
||||
import { TabScrollView } from "@/components/TabScrollView";
|
||||
import { TimeEntryEditSheet } from "@/components/time-clock/TimeEntryEditSheet";
|
||||
import { Card } from "@/components/ui/Card";
|
||||
import { fonts, spacing } from "@/constants/theme";
|
||||
import { useAppTheme } from "@/contexts/ThemeContext";
|
||||
import { formatRunningTimerLabel } from "@/lib/time-clock";
|
||||
import { formatTrpcErrorMessage } from "@/lib/trpc-errors";
|
||||
import { api } from "@/lib/trpc";
|
||||
import type { AppRouter } from "beenvoice/server/api/root";
|
||||
import type { inferRouterOutputs } from "@trpc/server";
|
||||
|
||||
type TimeEntry = inferRouterOutputs<AppRouter>["timeEntries"]["getAll"][number];
|
||||
|
||||
function groupByDate(entries: TimeEntry[]) {
|
||||
const groups = new Map<string, typeof entries>();
|
||||
for (const entry of entries) {
|
||||
const d = new Date(entry.startedAt);
|
||||
const key = d.toLocaleDateString(undefined, {
|
||||
weekday: "long",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
});
|
||||
const list = groups.get(key) ?? [];
|
||||
list.push(entry);
|
||||
groups.set(key, list);
|
||||
}
|
||||
return Array.from(groups.entries());
|
||||
}
|
||||
|
||||
export default function TimeEntriesScreen() {
|
||||
const { colors } = useAppTheme();
|
||||
const [editEntryId, setEditEntryId] = useState<string | null>(null);
|
||||
const entriesQuery = api.timeEntries.getAll.useQuery();
|
||||
|
||||
const completed = useMemo(
|
||||
() => (entriesQuery.data ?? []).filter((entry) => entry.endedAt),
|
||||
[entriesQuery.data],
|
||||
);
|
||||
const grouped = useMemo(() => groupByDate(completed), [completed]);
|
||||
|
||||
if (entriesQuery.isLoading) {
|
||||
return <LoadingScreen message="Loading time entries…" />;
|
||||
}
|
||||
|
||||
if (entriesQuery.error) {
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<View style={styles.errorBox}>
|
||||
<PageHeader title="Time entries" subtitle="Completed work history" />
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{formatTrpcErrorMessage(entriesQuery.error)}
|
||||
</Text>
|
||||
</View>
|
||||
</TabPage>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppBackground>
|
||||
<TabPage showMoreBack>
|
||||
<TabScrollView
|
||||
header={
|
||||
<PageHeader title="Time entries" subtitle={`${completed.length} completed entries`} />
|
||||
}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={entriesQuery.isRefetching}
|
||||
onRefresh={() => void entriesQuery.refetch()}
|
||||
tintColor={colors.primary}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{grouped.length === 0 ? (
|
||||
<Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
|
||||
No completed entries yet. Start the timer from the Timer tab.
|
||||
</Text>
|
||||
) : (
|
||||
grouped.map(([label, entries]) => (
|
||||
<Card key={label} title={label}>
|
||||
{entries.map((entry) => (
|
||||
<SwipeableRow
|
||||
key={entry.id}
|
||||
actions={[
|
||||
{
|
||||
key: "edit",
|
||||
label: "Edit",
|
||||
icon: "create-outline",
|
||||
color: "#fff",
|
||||
backgroundColor: colors.primary,
|
||||
onPress: () => setEditEntryId(entry.id),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<View style={styles.row}>
|
||||
<View style={{ flex: 1, gap: 2 }}>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{formatRunningTimerLabel(entry.description)}
|
||||
</Text>
|
||||
<Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
|
||||
{entry.client?.name ?? "No client"}
|
||||
{entry.invoice
|
||||
? ` · ${entry.invoice.invoicePrefix ?? "#"}${entry.invoice.invoiceNumber}`
|
||||
: " · not billed"}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{entry.hours ?? "—"}h
|
||||
</Text>
|
||||
</View>
|
||||
</SwipeableRow>
|
||||
))}
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
</TabScrollView>
|
||||
</TabPage>
|
||||
|
||||
<TimeEntryEditSheet
|
||||
entryId={editEntryId}
|
||||
visible={editEntryId != null}
|
||||
onClose={() => setEditEntryId(null)}
|
||||
/>
|
||||
</AppBackground>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.md,
|
||||
padding: spacing.md,
|
||||
},
|
||||
title: {
|
||||
fontFamily: fonts.bodySemiBold,
|
||||
fontSize: 14,
|
||||
},
|
||||
errorBox: {
|
||||
padding: spacing.lg,
|
||||
gap: spacing.md,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user