Compare commits

...
10 Commits
52 changed files with 2964 additions and 819 deletions
+4 -2
View File
@@ -10,7 +10,7 @@
"ios": {
"supportsTablet": true,
"bundleIdentifier": "com.beenvoice.app",
"buildNumber": "12",
"buildNumber": "23",
"icon": "./assets/beenvoice.icon",
"infoPlist": {
"ITSAppUsesNonExemptEncryption": false,
@@ -68,6 +68,8 @@
}
],
"./plugins/withSyncWidgetVersions.js",
"./plugins/withLiveActivityBannerFrame.js",
"./plugins/withStableWidgetsChildIdentity.js",
[
"expo-local-authentication",
{
@@ -94,7 +96,7 @@
}
],
[
"expo-mlkit-ocr",
"./plugins/withExpoMlkitOcrEnv.js",
{
"iosEngine": "auto"
}
+4 -12
View File
@@ -37,10 +37,10 @@ export default function AppLayout() {
>
<NativeTabs.Trigger name="index" contentStyle={tabContentStyle} disableAutomaticContentInsets>
<NativeTabs.Trigger.Icon
sf={{ default: "square.grid.2x2", selected: "square.grid.2x2.fill" }}
md="grid_view"
sf={{ default: "house", selected: "house.fill" }}
md="home"
/>
<NativeTabs.Trigger.Label>Dashboard</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="timer" contentStyle={tabContentStyle} disableAutomaticContentInsets>
@@ -67,15 +67,7 @@ export default function AppLayout() {
<NativeTabs.Trigger.Label>Invoices</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="settings" contentStyle={tabContentStyle} disableAutomaticContentInsets>
<NativeTabs.Trigger.Icon
sf={{ default: "gearshape", selected: "gearshape.fill" }}
md="settings"
/>
<NativeTabs.Trigger.Label>Settings</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="more" contentStyle={tabContentStyle} disableAutomaticContentInsets>
<NativeTabs.Trigger name="more" role="more" contentStyle={tabContentStyle} disableAutomaticContentInsets>
<NativeTabs.Trigger.Icon
sf={{ default: "ellipsis.circle", selected: "ellipsis.circle.fill" }}
md="more_horiz"
+64 -5
View File
@@ -1,7 +1,7 @@
import { router } from "expo-router";
import { useState } from "react";
import {
Pressable,
Alert,
RefreshControl,
ScrollView,
StyleSheet,
@@ -15,6 +15,7 @@ import { FloatingActionButton } from "@/components/FloatingActionButton";
import { GlassSurface } from "@/components/GlassSurface";
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";
@@ -38,6 +39,12 @@ export default function EntitiesScreen() {
const clientsQuery = api.clients.getAll.useQuery();
const businessesQuery = api.businesses.getAll.useQuery();
const deleteClient = api.clients.delete.useMutation({
onSuccess: () => void clientsQuery.refetch(),
});
const deleteBusiness = api.businesses.delete.useMutation({
onSuccess: () => void businessesQuery.refetch(),
});
const activeQuery = tab === "clients" ? clientsQuery : businessesQuery;
const isLoading =
@@ -68,6 +75,20 @@ export default function EntitiesScreen() {
else void businessesQuery.refetch();
}
function confirmDelete(id: string, name: string) {
Alert.alert(`Delete ${tab === "clients" ? "client" : "business"}?`, `Remove ${name}?`, [
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: () => {
if (tab === "clients") deleteClient.mutate({ id });
else deleteBusiness.mutate({ id });
},
},
]);
}
return (
<AppBackground>
<TabPage>
@@ -112,8 +133,27 @@ export default function EntitiesScreen() {
</View>
) : (
clients.map((client) => (
<Pressable
<SwipeableRow
key={client.id}
backgroundColor={colors.cardGlass}
actions={[
{
key: "edit",
label: "Edit",
icon: "create-outline",
color: "#fff",
backgroundColor: colors.primary,
onPress: () => router.push(`/(app)/entities/clients/edit/${client.id}`),
},
{
key: "delete",
label: "Delete",
icon: "trash-outline",
color: "#fff",
backgroundColor: colors.destructive,
onPress: () => confirmDelete(client.id, client.name),
},
]}
onPress={() => router.push(`/(app)/entities/clients/${client.id}`)}
>
<GlassSurface style={styles.card}>
@@ -130,7 +170,7 @@ export default function EntitiesScreen() {
) : null}
</View>
</GlassSurface>
</Pressable>
</SwipeableRow>
))
)
) : businesses.length === 0 ? (
@@ -142,8 +182,27 @@ export default function EntitiesScreen() {
</View>
) : (
businesses.map((business) => (
<Pressable
<SwipeableRow
key={business.id}
backgroundColor={colors.cardGlass}
actions={[
{
key: "edit",
label: "Edit",
icon: "create-outline",
color: "#fff",
backgroundColor: colors.primary,
onPress: () => router.push(`/(app)/entities/businesses/edit/${business.id}`),
},
{
key: "delete",
label: "Delete",
icon: "trash-outline",
color: "#fff",
backgroundColor: colors.destructive,
onPress: () => confirmDelete(business.id, business.name),
},
]}
onPress={() => router.push(`/(app)/entities/businesses/${business.id}`)}
>
<GlassSurface style={styles.card}>
@@ -160,7 +219,7 @@ export default function EntitiesScreen() {
{business.email ? <Text style={styles.meta}>{business.email}</Text> : null}
</View>
</GlassSurface>
</Pressable>
</SwipeableRow>
))
)}
</TabScrollView>
+316 -98
View File
@@ -1,30 +1,43 @@
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { Pressable, RefreshControl, StyleSheet, Text, View } from "react-native";
import { Screen } from "@/components/Screen";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
import { AppBackground } from "@/components/AppBackground";
import { PageHeader } from "@/components/PageHeader";
import { GlassSurface } from "@/components/GlassSurface";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { Screen } from "@/components/Screen";
import { StatCard } from "@/components/StatCard";
import { StatusBadge } from "@/components/StatusBadge";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { fonts, radii, spacing } from "@/constants/theme";
import { useSession } from "@/contexts/AuthContext";
import { useAppTheme } from "@/contexts/ThemeContext";
import { formatCurrency, formatDate } from "@/lib/format";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { getInvoiceStatus } from "@/lib/invoice-status";
import type { ThemeColors } from "@/lib/theme-palette";
import { formatElapsedHoursMinutes, resolveClockDescription } from "@/lib/time-clock";
import { formatTrpcErrorMessage } from "@/lib/trpc-errors";
import { useRunningElapsed } from "@/lib/use-running-elapsed";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { api } from "@/lib/trpc";
type ActionItem = {
key: string;
title: string;
detail: string;
icon: keyof typeof Ionicons.glyphMap;
tone: "warning" | "primary" | "success";
onPress: () => void;
};
export default function DashboardScreen() {
const { colors } = useAppTheme();
const styles = useThemedStyles(createDashboardStyles);
const { data: session } = useSession();
const statsQuery = api.dashboard.getStats.useQuery();
const runningQuery = api.timeEntries.getRunning.useQuery(undefined, {
refetchInterval: 30_000,
@@ -32,7 +45,7 @@ export default function DashboardScreen() {
const runningElapsed = useRunningElapsed(runningQuery.data?.startedAt);
if (statsQuery.isLoading) {
return <LoadingScreen message="Loading dashboard…" />;
return <LoadingScreen message="Loading home…" />;
}
if (statsQuery.error) {
@@ -40,8 +53,8 @@ export default function DashboardScreen() {
<AppBackground>
<Screen>
<View style={styles.errorBox}>
<Text style={styles.errorTitle}>Could not load dashboard</Text>
<Text style={styles.errorText}>{statsQuery.error.message}</Text>
<Text style={styles.errorTitle}>Could not load home</Text>
<Text style={styles.errorText}>{formatTrpcErrorMessage(statsQuery.error)}</Text>
</View>
</Screen>
</AppBackground>
@@ -50,27 +63,94 @@ export default function DashboardScreen() {
const stats = statsQuery.data;
if (!stats) {
return <LoadingScreen message="Loading dashboard…" />;
return <LoadingScreen message="Loading home…" />;
}
const now = new Date();
const running = runningQuery.data;
const revenueChange =
stats.revenueChange > 0
? `+${stats.revenueChange.toFixed(0)}% vs last month`
: stats.revenueChange < 0
? `${stats.revenueChange.toFixed(0)}% vs last month`
: "No change vs last month";
const runningClient = running?.client?.name ?? "No client";
const monthInvoices = stats.monthInvoices ?? [];
const monthTotal = monthInvoices.reduce((sum, invoice) => sum + invoice.totalAmount, 0);
const maxRevenue = Math.max(...stats.revenueChartData.map((d) => d.revenue), 1);
const sendReminderDue = stats.sendReminderDue ?? [];
const drafts = stats.recentInvoices.filter((invoice) => invoice.status === "draft");
const pendingInvoices = monthInvoices.filter((invoice) => {
const status = getInvoiceStatus(invoice);
return status === "sent" || status === "overdue";
});
const overdueInvoices = monthInvoices.filter((invoice) => getInvoiceStatus(invoice) === "overdue");
const displayName = session?.user.name?.trim();
const firstName =
(displayName ? displayName.split(/\s+/)[0] : undefined) ??
session?.user.email?.split("@")[0] ??
"there";
const actionItems: ActionItem[] = [
...(running
? [
{
key: "running",
title: "Timer running",
detail: `${formatElapsedHoursMinutes(runningElapsed)} on ${runningClient}`,
icon: "timer-outline" as const,
tone: "success" as const,
onPress: () => router.push("/(app)/timer"),
},
]
: []),
...(overdueInvoices.length > 0
? [
{
key: "overdue",
title: `${overdueInvoices.length} overdue ${overdueInvoices.length === 1 ? "invoice" : "invoices"}`,
detail: `${formatCurrency(overdueInvoices.reduce((sum, invoice) => sum + invoice.totalAmount, 0))} needs follow-up`,
icon: "alert-circle-outline" as const,
tone: "warning" as const,
onPress: () => router.push("/(app)/invoices"),
},
]
: []),
...(drafts.length > 0
? [
{
key: "drafts",
title: `${drafts.length} draft ${drafts.length === 1 ? "invoice" : "invoices"}`,
detail: "Review and send when ready",
icon: "document-text-outline" as const,
tone: "primary" as const,
onPress: () => router.push("/(app)/invoices"),
},
]
: []),
...(pendingInvoices.length > 0
? [
{
key: "pending",
title: `${pendingInvoices.length} awaiting payment`,
detail: `${formatCurrency(pendingInvoices.reduce((sum, invoice) => sum + invoice.totalAmount, 0))} outstanding this month`,
icon: "card-outline" as const,
tone: "primary" as const,
onPress: () => router.push("/(app)/invoices"),
},
]
: []),
];
if (actionItems.length === 0) {
actionItems.push({
key: "clear",
title: "No urgent action items",
detail: "You are clear for the moment",
icon: "checkmark-circle-outline",
tone: "success",
onPress: () => router.push("/(app)/invoices"),
});
}
return (
<AppBackground>
<TabPage>
<TabScrollView
header={
<PageHeader title="Overview" subtitle="Your invoicing at a glance" />
}
header={<PageHeader title={`Hello, ${firstName}`} subtitle="What needs attention now" />}
refreshControl={
<RefreshControl
refreshing={statsQuery.isRefetching || runningQuery.isRefetching}
@@ -82,6 +162,64 @@ export default function DashboardScreen() {
/>
}
>
<View style={styles.quickActions}>
<Button title="Start timer" onPress={() => router.push("/(app)/timer")} />
<Button
title="Invoices"
variant="secondary"
onPress={() => router.push("/(app)/invoices")}
/>
<Button
title="Reports"
variant="secondary"
onPress={() => router.push("/(app)/more/reports" as never)}
/>
</View>
<Card title="Action items">
<View style={styles.actionList}>
{actionItems.map((item) => (
<Pressable
accessibilityRole="button"
key={item.key}
onPress={item.onPress}
style={({ pressed }) => [styles.actionRow, pressed && styles.pressed]}
>
<View
style={[
styles.actionIcon,
{
backgroundColor:
item.tone === "warning"
? colors.warningBg
: item.tone === "success"
? colors.successBg
: colors.muted,
},
]}
>
<Ionicons
name={item.icon}
size={20}
color={
item.tone === "warning"
? colors.warning
: item.tone === "success"
? colors.success
: colors.primary
}
/>
</View>
<View style={styles.actionCopy}>
<Text style={styles.actionTitle}>{item.title}</Text>
<Text style={styles.actionDetail}>{item.detail}</Text>
</View>
<Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} />
</Pressable>
))}
</View>
</Card>
{running ? (
<Pressable onPress={() => router.push("/(app)/timer")}>
<GlassSurface style={styles.runningGlass}>
@@ -92,7 +230,7 @@ export default function DashboardScreen() {
{resolveClockDescription(running.description)}
</Text>
<Text style={styles.runningSub}>
{running.client?.name ?? "No client"}
{runningClient}
{running.invoice
? ` · ${running.invoice.invoicePrefix ?? "#"}${running.invoice.invoiceNumber}`
: ""}
@@ -106,72 +244,93 @@ export default function DashboardScreen() {
</Pressable>
) : null}
{stats.overdueCount > 0 ? (
<GlassSurface style={styles.alertGlass}>
<View style={styles.alertBanner}>
<Text style={styles.alertTitle}>
{stats.overdueCount} overdue {stats.overdueCount === 1 ? "invoice" : "invoices"}
</Text>
<Text style={styles.alertText}>
Follow up on outstanding payments from the Invoices tab.
<Card
title={now.toLocaleDateString("en-US", {
month: "long",
year: "numeric",
})}
>
<View style={styles.monthSummary}>
<View>
<Text style={styles.monthValue}>{formatCurrency(monthTotal)}</Text>
<Text style={styles.monthLabel}>
{monthInvoices.length} {monthInvoices.length === 1 ? "invoice" : "invoices"} this month
</Text>
</View>
</GlassSurface>
) : null}
{sendReminderDue.length > 0 ? (
<GlassSurface style={styles.alertGlass}>
<View style={styles.alertBanner}>
<Text style={styles.alertTitle}>
{sendReminderDue.length} draft{" "}
{sendReminderDue.length === 1 ? "invoice" : "invoices"} ready to send
</Text>
<Text style={styles.alertText}>
{sendReminderDue
.slice(0, 2)
.map(
(inv) =>
`${inv.invoicePrefix ?? "#"}${inv.invoiceNumber} (${inv.client?.name ?? "Client"})`,
)
.join(" · ")}
</Text>
</View>
</GlassSurface>
) : null}
<View style={styles.quickActions}>
<Button title="Start timer" onPress={() => router.push("/(app)/timer")} />
<Button
title="View invoices"
title="New invoice"
variant="secondary"
onPress={() => router.push("/(app)/invoices")}
onPress={() => router.push("/(app)/invoices/new")}
/>
</View>
<View style={styles.monthList}>
{monthInvoices.slice(0, 4).map((invoice) => {
const status = getInvoiceStatus(invoice);
return (
<Pressable
accessibilityRole="button"
key={invoice.id}
onPress={() => router.push(`/(app)/invoices/${invoice.id}`)}
style={({ pressed }) => [styles.monthInvoiceRow, pressed && styles.pressed]}
>
<View style={styles.invoiceMeta}>
<Text style={styles.invoiceTitle}>
{invoice.invoicePrefix}
{invoice.invoiceNumber}
</Text>
<Text style={styles.invoiceClient}>{invoice.client?.name ?? "Client"}</Text>
</View>
<View style={styles.invoiceRight}>
<Text style={styles.invoiceAmount}>
{formatCurrency(invoice.totalAmount, invoice.currency)}
</Text>
<StatusBadge status={status} />
</View>
</Pressable>
);
})}
{monthInvoices.length === 0 ? (
<Text style={styles.empty}>No invoices in this month yet.</Text>
) : null}
</View>
</Card>
{stats.currentDraft ? (
<GlassSurface style={styles.draftGlass}>
<Pressable
style={styles.draftBanner}
onPress={() => router.push(`/(app)/invoices/${stats.currentDraft!.id}`)}
>
<View style={styles.draftCopy}>
<Text style={styles.draftTitle}>Current draft</Text>
<Text style={styles.draftText}>
{stats.currentDraft.client?.name ?? "Client"} ·{" "}
{formatCurrency(stats.currentDraft.totalAmount)} ·{" "}
{stats.currentDraft.totalHours.toFixed(1)}h logged
</Text>
</View>
<Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} />
</Pressable>
</GlassSurface>
) : null}
<View style={styles.statsGrid}>
<View style={styles.statCell}>
<StatCard label="Total revenue" value={formatCurrency(stats.totalRevenue)} />
<StatCard label="Revenue" value={formatCurrency(stats.totalRevenue)} />
</View>
<View style={styles.statCell}>
<StatCard label="Pending" value={formatCurrency(stats.pendingAmount)} />
</View>
<View style={styles.statCell}>
<StatCard
label="Overdue"
value={String(stats.overdueCount)}
hint={stats.overdueCount === 1 ? "invoice" : "invoices"}
/>
<StatCard label="Overdue" value={String(stats.overdueCount)} />
</View>
<Pressable style={styles.statCell} onPress={() => router.push("/(app)/entities")}>
<StatCard
label="Clients"
value={String(stats.totalClients)}
hint={revenueChange}
/>
<StatCard label="Clients" value={String(stats.totalClients)} />
</Pressable>
</View>
<Card title="Revenue (6 months)">
<Card title="Revenue trend">
<View style={styles.chart}>
{stats.revenueChartData.map((point) => {
const barHeight = Math.max(4, (point.revenue / maxRevenue) * 80);
@@ -181,9 +340,6 @@ export default function DashboardScreen() {
<View style={[styles.chartBar, { height: barHeight }]} />
</View>
<Text style={styles.chartLabel}>{point.monthLabel}</Text>
<Text style={styles.chartValue}>
{point.revenue > 0 ? formatCurrency(point.revenue) : "—"}
</Text>
</View>
);
})}
@@ -199,7 +355,7 @@ export default function DashboardScreen() {
return (
<Pressable
key={invoice.id}
style={styles.invoiceRow}
style={({ pressed }) => [styles.recentRow, pressed && styles.pressed]}
onPress={() => router.push(`/(app)/invoices/${invoice.id}`)}
>
<View style={styles.invoiceMeta}>
@@ -207,9 +363,7 @@ export default function DashboardScreen() {
{invoice.invoicePrefix}
{invoice.invoiceNumber}
</Text>
<Text style={styles.invoiceClient}>
{invoice.client?.name ?? "Client"}
</Text>
<Text style={styles.invoiceClient}>{invoice.client?.name ?? "Client"}</Text>
<Text style={styles.invoiceDate}>{formatDate(invoice.issueDate)}</Text>
</View>
<View style={styles.invoiceRight}>
@@ -231,8 +385,38 @@ export default function DashboardScreen() {
const createDashboardStyles = (colors: ThemeColors, isDark: boolean) =>
StyleSheet.create({
safe: {
actionList: {
gap: spacing.xs,
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
minHeight: 58,
paddingVertical: spacing.xs,
},
actionIcon: {
width: 38,
height: 38,
borderRadius: radii.md,
alignItems: "center",
justifyContent: "center",
},
actionCopy: {
flex: 1,
gap: 2,
},
actionTitle: {
color: colors.foreground,
fontFamily: fonts.bodySemiBold,
fontSize: 15,
lineHeight: 20,
},
actionDetail: {
color: colors.mutedForeground,
fontFamily: fonts.body,
fontSize: 12,
lineHeight: 16,
},
runningGlass: {
borderColor: isDark ? "rgba(74, 222, 128, 0.35)" : "#BBF7D0",
@@ -268,27 +452,64 @@ const createDashboardStyles = (colors: ThemeColors, isDark: boolean) =>
fontSize: 18,
color: colors.success,
},
alertBanner: {
padding: spacing.md,
gap: 4,
monthSummary: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: spacing.md,
},
alertGlass: {
borderColor: isDark ? "rgba(251, 191, 36, 0.4)" : "#FDE68A",
monthValue: {
color: colors.foreground,
fontFamily: fonts.heading,
fontSize: 24,
lineHeight: 30,
},
alertTitle: {
fontFamily: fonts.bodySemiBold,
color: colors.warning,
fontSize: 14,
},
alertText: {
fontFamily: fonts.body,
monthLabel: {
color: colors.mutedForeground,
fontSize: 13,
fontFamily: fonts.bodyMedium,
fontSize: 12,
lineHeight: 16,
},
monthList: {
gap: spacing.xs,
},
monthInvoiceRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: spacing.md,
paddingTop: spacing.sm,
borderTopWidth: 1,
borderTopColor: colors.border,
},
quickActions: {
flexDirection: "row",
gap: spacing.sm,
},
draftGlass: {
borderColor: isDark ? "rgba(59, 130, 246, 0.32)" : "#BFDBFE",
},
draftBanner: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
padding: spacing.md,
},
draftCopy: {
flex: 1,
gap: 3,
},
draftTitle: {
fontFamily: fonts.bodySemiBold,
color: colors.primary,
fontSize: 14,
},
draftText: {
fontFamily: fonts.body,
color: colors.mutedForeground,
fontSize: 13,
lineHeight: 18,
},
statsGrid: {
flexDirection: "row",
flexWrap: "wrap",
@@ -327,19 +548,13 @@ const createDashboardStyles = (colors: ThemeColors, isDark: boolean) =>
fontFamily: fonts.bodyMedium,
color: colors.mutedForeground,
},
chartValue: {
fontSize: 9,
fontFamily: fonts.body,
color: colors.mutedForeground,
textAlign: "center",
},
empty: {
color: colors.mutedForeground,
fontSize: 14,
fontFamily: fonts.body,
lineHeight: 20,
},
invoiceRow: {
recentRow: {
flexDirection: "row",
justifyContent: "space-between",
gap: spacing.md,
@@ -375,6 +590,9 @@ const createDashboardStyles = (colors: ThemeColors, isDark: boolean) =>
color: colors.foreground,
fontSize: 15,
},
pressed: {
opacity: 0.85,
},
errorBox: {
flex: 1,
justifyContent: "center",
@@ -391,4 +609,4 @@ const createDashboardStyles = (colors: ThemeColors, isDark: boolean) =>
fontFamily: fonts.body,
lineHeight: 20,
},
});
});
+33 -6
View File
@@ -8,6 +8,7 @@ import { InvoicePdfPreview } from "@/components/invoices/InvoicePdfPreview";
import { InvoiceTotals } from "@/components/invoices/InvoiceTotals";
import { InvoiceDetailActions } from "@/components/invoices/InvoiceDetailActions";
import { LoadingScreen } from "@/components/LoadingScreen";
import { SwipeableRow } from "@/components/SwipeableRow";
import { StatusBadge } from "@/components/StatusBadge";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
@@ -23,6 +24,7 @@ import { api } from "@/lib/trpc";
export default function InvoiceDetailScreen() {
const styles = useThemedStyles(createInvoiceDetailStyles);
const { colors } = useAppTheme();
const { id } = useLocalSearchParams<{ id: string }>();
const utils = api.useUtils();
const scrollPadding = useTabBarScrollPadding();
@@ -50,10 +52,9 @@ export default function InvoiceDetailScreen() {
onError: (err) => Alert.alert("Could not send reminder", err.message),
});
const invoice = invoiceQuery.data;
const previewInput = useMemo(
() => (invoice ? buildPreviewPdfInputFromInvoice(invoice) : null),
[invoice],
() => (invoiceQuery.data ? buildPreviewPdfInputFromInvoice(invoiceQuery.data) : null),
[invoiceQuery.data],
);
if (!id) {
@@ -78,6 +79,7 @@ export default function InvoiceDetailScreen() {
);
}
const invoice = invoiceQuery.data;
const status = getInvoiceStatus(invoice);
const subtotal = invoice.items.reduce((sum, item) => sum + item.amount, 0);
const taxAmount = subtotal * (invoice.taxRate / 100);
@@ -209,8 +211,9 @@ export default function InvoiceDetailScreen() {
add lines manually.
</Text>
) : (
invoice.items.map((item) => (
<View key={item.id} style={styles.lineItem}>
invoice.items.map((item) => {
const line = (
<View style={styles.lineItem}>
<View style={styles.lineMeta}>
<Text style={styles.lineDescription}>{item.description}</Text>
<Text style={styles.lineSub}>
@@ -222,7 +225,31 @@ export default function InvoiceDetailScreen() {
{formatCurrency(item.amount, invoice.currency)}
</Text>
</View>
))
);
if (invoice.status !== "draft") {
return <View key={item.id}>{line}</View>;
}
return (
<SwipeableRow
key={item.id}
backgroundColor={colors.card}
actions={[
{
key: "edit",
label: "Edit",
icon: "create-outline",
color: "#fff",
backgroundColor: colors.primary,
onPress: () => router.push(`/(app)/invoices/edit/${invoice.id}`),
},
]}
>
{line}
</SwipeableRow>
);
})
)}
<InvoiceTotals
subtotal={formatCurrency(subtotal, invoice.currency)}
+10
View File
@@ -196,6 +196,15 @@ export default function InvoiceEditScreen() {
setItems((prev) => prev.filter((_, i) => i !== index));
}
function duplicateItem(index: number) {
setItems((prev) => {
const source = prev[index];
if (!source) return prev;
const copy = { ...source, id: undefined };
return [...prev.slice(0, index + 1), copy, ...prev.slice(index + 1)];
});
}
async function handleSave() {
if (!canSave) return;
setError(null);
@@ -325,6 +334,7 @@ export default function InvoiceEditScreen() {
isLast={index === items.length - 1}
onChange={(patch) => updateItem(index, patch)}
onRemove={() => removeItem(index)}
onDuplicate={isDraft ? () => duplicateItem(index) : undefined}
readOnly={!isDraft}
/>
))}
+76 -8
View File
@@ -2,7 +2,6 @@ import { router } from "expo-router";
import { useState } from "react";
import {
Alert,
Pressable,
RefreshControl,
ScrollView,
StyleSheet,
@@ -16,6 +15,7 @@ import { FloatingActionButton } from "@/components/FloatingActionButton";
import { GlassSurface } from "@/components/GlassSurface";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { SwipeableRow } from "@/components/SwipeableRow";
import { StatusBadge } from "@/components/StatusBadge";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
@@ -25,6 +25,7 @@ import { formatCurrency, formatDate } from "@/lib/format";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { getInvoiceStatus, type InvoiceStatus } from "@/lib/invoice-status";
import { formatTrpcErrorMessage } from "@/lib/trpc-errors";
import { api } from "@/lib/trpc";
const filters: Array<{ label: string; value?: InvoiceStatus | "all" }> = [
@@ -49,6 +50,14 @@ export default function InvoicesScreen() {
onError: (err) => Alert.alert("Update failed", err.message),
});
const deleteInvoice = api.invoices.delete.useMutation({
onSuccess: () => {
utils.invoices.getAll.invalidate();
utils.dashboard.getStats.invalidate();
},
onError: (err) => Alert.alert("Delete failed", err.message),
});
if (invoicesQuery.isLoading) {
return <LoadingScreen message="Loading invoices…" />;
}
@@ -59,7 +68,7 @@ export default function InvoicesScreen() {
<TabPage>
<View style={styles.errorBox}>
<Text style={styles.errorTitle}>Could not load invoices</Text>
<Text style={styles.errorText}>{invoicesQuery.error.message}</Text>
<Text style={styles.errorText}>{formatTrpcErrorMessage(invoicesQuery.error)}</Text>
</View>
</TabPage>
</AppBackground>
@@ -93,6 +102,17 @@ export default function InvoicesScreen() {
]);
}
function confirmDelete(invoiceId: string, label: string) {
Alert.alert("Delete invoice?", `Remove ${label}? This cannot be undone.`, [
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: () => deleteInvoice.mutate({ id: invoiceId }),
},
]);
}
return (
<AppBackground>
<TabPage>
@@ -134,9 +154,60 @@ export default function InvoicesScreen() {
) : (
invoices.map((invoice) => {
const status = getInvoiceStatus(invoice);
const label = `${invoice.invoicePrefix}${invoice.invoiceNumber}`;
const actions = [
{
key: "open",
label: "Open",
icon: "open-outline" as const,
color: "#fff",
backgroundColor: colors.primary,
onPress: () => router.push(`/(app)/invoices/${invoice.id}`),
},
...(status === "draft"
? [
{
key: "edit",
label: "Edit",
icon: "create-outline" as const,
color: "#fff",
backgroundColor: colors.mutedForeground,
onPress: () => router.push(`/(app)/invoices/edit/${invoice.id}`),
},
{
key: "send",
label: "Send",
icon: "send-outline" as const,
color: "#fff",
backgroundColor: colors.success,
onPress: () => router.push(`/(app)/invoices/send/${invoice.id}`),
},
{
key: "delete",
label: "Delete",
icon: "trash-outline" as const,
color: "#fff",
backgroundColor: colors.destructive,
onPress: () => confirmDelete(invoice.id, label),
},
]
: [
{
key: "status",
label: "Status",
icon: "flag-outline" as const,
color: "#fff",
backgroundColor: colors.warning,
onPress: () => promptStatusChange(invoice.id, status),
},
]),
];
return (
<Pressable
<SwipeableRow
key={invoice.id}
actions={actions}
backgroundColor={colors.cardGlass}
onPress={() => router.push(`/(app)/invoices/${invoice.id}`)}
onLongPress={() => promptStatusChange(invoice.id, status)}
>
@@ -144,10 +215,7 @@ export default function InvoicesScreen() {
<View style={styles.cardInner}>
<View style={styles.cardTop}>
<View style={styles.cardMeta}>
<Text style={styles.invoiceNumber}>
{invoice.invoicePrefix}
{invoice.invoiceNumber}
</Text>
<Text style={styles.invoiceNumber}>{label}</Text>
<Text style={styles.clientName}>
{invoice.client?.name ?? "Client"}
</Text>
@@ -162,7 +230,7 @@ export default function InvoicesScreen() {
</View>
</View>
</GlassSurface>
</Pressable>
</SwipeableRow>
);
})
)}
+10
View File
@@ -203,6 +203,15 @@ export default function NewInvoiceScreen() {
setItems((prev) => prev.filter((_, i) => i !== index));
}
function duplicateItem(index: number) {
setItems((prev) => {
const source = prev[index];
if (!source) return prev;
const copy = { ...source, id: undefined };
return [...prev.slice(0, index + 1), copy, ...prev.slice(index + 1)];
});
}
function handleCreate() {
if (!canCreate) return;
setError(null);
@@ -327,6 +336,7 @@ export default function NewInvoiceScreen() {
isLast={index === items.length - 1}
onChange={(patch) => updateItem(index, patch)}
onRemove={() => removeItem(index)}
onDuplicate={() => duplicateItem(index)}
/>
))}
+6 -5
View File
@@ -51,10 +51,10 @@ export default function InvoiceSendScreen() {
onError: (err) => Alert.alert("Could not send invoice", err.message),
});
const invoice = invoiceQuery.data;
const previewInput = useMemo(
() => (invoice ? buildPreviewPdfInputFromInvoice(invoice) : null),
[invoice],
() =>
invoiceQuery.data ? buildPreviewPdfInputFromInvoice(invoiceQuery.data) : null,
[invoiceQuery.data],
);
if (!id) {
@@ -65,10 +65,11 @@ export default function InvoiceSendScreen() {
return <LoadingScreen message="Loading invoice…" />;
}
if (!invoice) {
if (!invoiceQuery.data) {
return <LoadingScreen message="Invoice not found" />;
}
const invoice = invoiceQuery.data;
const status = getInvoiceStatus(invoice);
const clientEmail = invoice.client?.email?.trim() ?? "";
const businessName = invoice.business?.name ?? "Your business";
@@ -91,7 +92,7 @@ export default function InvoiceSendScreen() {
}
sendInvoice.mutate({
invoiceId: invoice!.id,
invoiceId: invoice.id,
customMessage: customMessage.trim() || undefined,
});
}
+20 -21
View File
@@ -1,6 +1,6 @@
import { useLocalSearchParams, router } from "expo-router";
import { useState } from "react";
import { Alert, ScrollView, StyleSheet, Text, View } from "react-native";
import { Alert, StyleSheet, Text, View } from "react-native";
import { AppBackground } from "@/components/AppBackground";
import {
@@ -12,6 +12,7 @@ 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";
@@ -119,7 +120,7 @@ export default function ExpenseDetailScreen() {
"Receipt attached",
result.items.length > 0
? "Select the owed items, apply the split amount, then save the expense."
: "OCR filled the fields below. Save to update this expense.",
: "We filled in what we could. Review and save to update this expense.",
);
} finally {
setScanning(false);
@@ -163,10 +164,12 @@ export default function ExpenseDetailScreen() {
if (!expense) {
return (
<AppBackground>
<TabPage>
<Text style={{ color: colors.mutedForeground, padding: spacing.lg }}>
<TabPage showMoreBack>
<TabScrollView header={<PageHeader title="Expense" subtitle="Expense details" />}>
<Text style={{ color: colors.mutedForeground }}>
Expense not found
</Text>
</TabScrollView>
</TabPage>
</AppBackground>
);
@@ -174,13 +177,16 @@ export default function ExpenseDetailScreen() {
return (
<AppBackground>
<TabPage>
<ScrollView contentContainerStyle={styles.body}>
<TabPage showMoreBack>
<TabScrollView
header={
<PageHeader
title={expense.description}
subtitle={formatDate(expense.date)}
/>
}
keyboardShouldPersistTaps="handled"
>
{editing ? (
<>
{receiptSplit ? (
@@ -316,22 +322,13 @@ export default function ExpenseDetailScreen() {
onPress={() => void attachAndScan(false)}
/>
</View>
<Button
title="Back"
variant="secondary"
onPress={() => router.back()}
/>
</ScrollView>
</TabScrollView>
</TabPage>
</AppBackground>
);
}
const styles = StyleSheet.create({
body: {
padding: spacing.lg,
gap: spacing.md,
},
amount: {
fontSize: 28,
fontWeight: "600",
@@ -362,7 +359,7 @@ const styles = StyleSheet.create({
marginTop: spacing.md,
},
receiptRow: {
paddingVertical: spacing.sm,
padding: spacing.md,
fontSize: 14,
},
actions: {
@@ -408,8 +405,10 @@ function mergeNotes(prefix: string, existing: string) {
const trimmed = existing.trim();
if (!trimmed) return prefix;
if (trimmed.startsWith("Receipt split")) {
const ocrStart = trimmed.indexOf("\n\nOCR text:");
return ocrStart >= 0 ? `${prefix}${trimmed.slice(ocrStart)}` : prefix;
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\nOCR text:\n${trimmed}`;
return `${prefix}\n\nReceipt details:\n${trimmed}`;
}
+272 -141
View File
@@ -1,13 +1,15 @@
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { useMemo, useState } from "react";
import {
Pressable,
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";
@@ -17,15 +19,16 @@ 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 { 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";
import { api } from "@/lib/trpc";
type ExpenseFilter = "all" | "billable" | "receipts";
type Expense = inferRouterOutputs<AppRouter>["expenses"]["getAll"][number];
export default function ExpensesScreen() {
const { colors } = useAppTheme();
@@ -48,24 +51,36 @@ export default function ExpensesScreen() {
}),
[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" />;
return <LoadingScreen message="Loading expenses..." />;
}
if (expensesQuery.error) {
return (
<AppBackground>
<TabPage>
<TabPage showMoreBack>
<View style={styles.errorBox}>
<PageHeader title="Expenses" subtitle="Expense tracking" />
<Text style={[styles.errorTitle, { color: colors.foreground }]}>
Could not load expenses
</Text>
@@ -80,19 +95,19 @@ export default function ExpensesScreen() {
return (
<AppBackground>
<TabPage>
<TabPage showMoreBack>
<TabScrollView
header={
<>
<View style={styles.header}>
<PageHeader
title="Expenses"
subtitle={`${expenses.length} recorded`}
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
@@ -103,42 +118,32 @@ export default function ExpensesScreen() {
}
>
{expenses.length === 0 ? (
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
No expenses yet. Add one with a receipt photo or manual entry.
<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.summary}>
<View>
<Text
style={[
styles.summaryLabel,
{ color: colors.mutedForeground },
]}
>
Visible total
</Text>
<Text
style={[styles.summaryValue, { color: colors.foreground }]}
>
{formatCurrency(total)}
</Text>
</View>
<View style={styles.summaryRight}>
<Text
style={[
styles.summaryLabel,
{ color: colors.mutedForeground },
]}
>
Receipts
</Text>
<Text
style={[styles.summaryValue, { color: colors.foreground }]}
>
{receiptCount}
</Text>
</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
@@ -168,87 +173,19 @@ export default function ExpensesScreen() {
No expenses match this filter.
</Text>
) : (
filteredExpenses.map((expense) => (
<SwipeableRow
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}
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: () => deleteExpense.mutate({ id: expense.id }),
},
]}
>
<Pressable
accessibilityRole="button"
onPress={() =>
router.push(
`/(app)/more/expenses/${expense.id}` as never,
)
}
style={({ pressed }) => [
styles.row,
pressed && styles.rowPressed,
]}
>
<View style={styles.meta}>
<View style={styles.titleRow}>
<Text
style={[styles.title, { color: colors.foreground }]}
numberOfLines={1}
>
{expense.description}
</Text>
{expense.receiptCount ? (
<Text
style={[
styles.receiptPill,
{
color: colors.primary,
borderColor: colors.border,
},
]}
>
{expense.receiptCount}
</Text>
) : null}
expense={expense}
onDelete={() => deleteExpense.mutate({ id: expense.id })}
/>
))}
</View>
<Text
style={[
styles.sub,
{ color: colors.mutedForeground },
]}
numberOfLines={2}
>
{formatDate(expense.date)}
{expense.category ? ` · ${expense.category}` : ""}
{expense.client?.name
? ` · ${expense.client.name}`
: ""}
{expense.billable ? " · Billable" : ""}
</Text>
</View>
<Text
style={[styles.amount, { color: colors.foreground }]}
>
{formatCurrency(expense.amount, expense.currency)}
</Text>
</Pressable>
</SwipeableRow>
))
)}
</>
@@ -259,23 +196,167 @@ export default function ExpensesScreen() {
);
}
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",
justifyContent: "space-between",
gap: spacing.md,
paddingVertical: spacing.md,
borderBottomWidth: 1,
borderBottomColor: colors.border,
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,
gap: 2,
minWidth: 0,
gap: spacing.xs,
},
titleRow: {
flexDirection: "row",
@@ -291,23 +372,42 @@ const createStyles = (colors: ThemeColors) =>
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"],
},
summary: {
summaryGrid: {
flexDirection: "row",
justifyContent: "space-between",
gap: spacing.md,
padding: spacing.md,
borderRadius: 16,
borderWidth: 1,
borderColor: colors.border,
backgroundColor: colors.cardGlass,
flexWrap: "wrap",
gap: spacing.xs,
},
summaryRight: {
alignItems: "flex-end",
summaryTile: {
flexGrow: 1,
flexBasis: "30%",
minWidth: 104,
paddingHorizontal: spacing.md,
paddingVertical: 12,
borderRadius: radii.lg,
borderWidth: 1,
},
summaryLabel: {
fontFamily: fonts.bodyMedium,
@@ -320,25 +420,56 @@ const createStyles = (colors: ThemeColors) =>
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: {
minWidth: 26,
textAlign: "center",
flexDirection: "row",
alignItems: "center",
gap: 2,
borderWidth: 1,
borderRadius: 999,
paddingHorizontal: spacing.sm,
borderRadius: radii.pill,
paddingHorizontal: 7,
paddingVertical: 2,
},
receiptPillText: {
fontFamily: fonts.bodyMedium,
fontSize: 12,
overflow: "hidden",
},
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,
+48 -28
View File
@@ -1,6 +1,6 @@
import { router } from "expo-router";
import { useMemo, useState } from "react";
import { Alert, ScrollView, StyleSheet, Text, View } from "react-native";
import { Alert, StyleSheet, Text, View } from "react-native";
import { AppBackground } from "@/components/AppBackground";
import {
@@ -11,10 +11,11 @@ import {
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 { spacing } from "@/constants/theme";
import { Card } from "@/components/ui/Card";
import { fonts, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { mlKitOcrAvailable } from "@/lib/receipt-ocr";
import {
scanReceiptImage,
type PickedReceiptImage,
@@ -96,7 +97,7 @@ export default function NewExpenseScreen() {
? "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 — OCR could not find a total automatically.",
: "Review the fields and enter the total before saving.",
);
} finally {
setScanning(false);
@@ -150,31 +151,30 @@ export default function NewExpenseScreen() {
return (
<AppBackground>
<TabPage>
<ScrollView
contentContainerStyle={styles.body}
keyboardShouldPersistTaps="handled"
>
<TabPage showMoreBack>
<TabScrollView
header={
<PageHeader
title="New expense"
subtitle={
mlKitOcrAvailable()
? "Scan a receipt with on-device ML Kit OCR"
: "Manual entry (OCR unavailable on this device)"
}
subtitle="Add a receipt, fill the details, and save it"
/>
}
keyboardShouldPersistTaps="handled"
>
<Card title="Receipt">
<View style={styles.actions}>
<Button
title={scanning ? "Scanning" : "Scan receipt"}
title={scanning ? "Scanning..." : "Take photo"}
variant="secondary"
leftIcon="camera-outline"
loading={scanning}
style={styles.actionButton}
onPress={() => void runScan(true)}
/>
<Button
title="Import photo"
title="Choose photo"
variant="secondary"
leftIcon="image-outline"
loading={scanning}
style={styles.actionButton}
onPress={() => void runScan(false)}
@@ -182,10 +182,13 @@ export default function NewExpenseScreen() {
</View>
{pendingReceipt ? (
<Text style={{ color: colors.success, fontSize: 13 }}>
Receipt image ready it will attach when you save.
<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
@@ -203,6 +206,7 @@ export default function NewExpenseScreen() {
/>
) : null}
<Card title="Details">
<ExpenseFormFields
value={{
...form,
@@ -212,30 +216,31 @@ export default function NewExpenseScreen() {
clients={clients}
onChange={setForm}
notesLabel="Notes"
notesPlaceholder="Receipt OCR text or internal 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()}
/>
</ScrollView>
</View>
</TabScrollView>
</TabPage>
</AppBackground>
);
}
const styles = StyleSheet.create({
body: {
padding: spacing.lg,
gap: spacing.md,
},
actions: {
flexDirection: "row",
gap: spacing.sm,
@@ -243,14 +248,29 @@ const styles = StyleSheet.create({
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 ocrStart = trimmed.indexOf("\n\nOCR text:");
return ocrStart >= 0 ? `${prefix}${trimmed.slice(ocrStart)}` : prefix;
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\nOCR text:\n${trimmed}`;
return `${prefix}\n\nReceipt details:\n${trimmed}`;
}
+6
View File
@@ -43,6 +43,12 @@ const ITEMS: HubItem[] = [
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() {
+2 -4
View File
@@ -37,7 +37,7 @@ export default function RecurringScreen() {
return (
<AppBackground>
<TabPage>
<TabPage showMoreBack>
<TabScrollView
header={
<PageHeader
@@ -113,9 +113,7 @@ const styles = StyleSheet.create({
row: {
flexDirection: "row",
gap: spacing.md,
paddingVertical: spacing.md,
borderBottomWidth: 1,
borderBottomColor: "rgba(0,0,0,0.08)",
padding: spacing.md,
},
title: {
fontFamily: fonts.bodySemiBold,
+10 -3
View File
@@ -26,10 +26,13 @@ export default function ReportsScreen() {
if (statsQuery.error) {
return (
<AppBackground>
<TabPage>
<Text style={{ color: colors.mutedForeground, padding: spacing.lg }}>
<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>
);
@@ -41,7 +44,7 @@ export default function ReportsScreen() {
return (
<AppBackground>
<TabPage>
<TabPage showMoreBack>
<TabScrollView
header={<PageHeader title="Reports" subtitle="Business performance snapshot" />}
refreshControl={
@@ -105,4 +108,8 @@ const styles = StyleSheet.create({
justifyContent: "space-between",
paddingVertical: spacing.sm,
},
errorBox: {
padding: spacing.lg,
gap: spacing.md,
},
});
@@ -21,6 +21,7 @@ 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 }[] = [
@@ -89,16 +90,20 @@ export default function SettingsScreen() {
async (result) => {
await finishAccountRemoval({
result,
authClient,
clearActiveAccount,
signOut: () => authClient.signOut(),
activeAccountId,
});
},
);
}
async function handleSignOut() {
await authClient.signOut();
await clearActiveAccount();
await performAuthReset({
authClient,
clearActiveAccount,
activeAccountId,
});
router.replace("/(auth)/sign-in");
}
@@ -182,7 +187,7 @@ export default function SettingsScreen() {
return (
<AppBackground>
<TabPage>
<TabPage showMoreBack>
<PinPrompt
visible={pinPrompt !== null}
title={
+11 -4
View File
@@ -54,10 +54,13 @@ export default function TimeEntriesScreen() {
if (entriesQuery.error) {
return (
<AppBackground>
<TabPage>
<Text style={{ color: colors.mutedForeground, padding: spacing.lg }}>
<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>
);
@@ -65,7 +68,7 @@ export default function TimeEntriesScreen() {
return (
<AppBackground>
<TabPage>
<TabPage showMoreBack>
<TabScrollView
header={
<PageHeader title="Time entries" subtitle={`${completed.length} completed entries`} />
@@ -136,10 +139,14 @@ const styles = StyleSheet.create({
row: {
flexDirection: "row",
gap: spacing.md,
paddingVertical: spacing.sm,
padding: spacing.md,
},
title: {
fontFamily: fonts.bodySemiBold,
fontSize: 14,
},
errorBox: {
padding: spacing.lg,
gap: spacing.md,
},
});
+7
View File
@@ -1,5 +1,12 @@
import { Redirect } from "expo-router";
import { useAccounts } from "@/contexts/AccountsContext";
export default function AuthIndex() {
const { accounts, activeAccountId } = useAccounts();
if (!activeAccountId && accounts.length > 0) {
return <Redirect href="/(auth)/select-account" />;
}
return <Redirect href="/(auth)/sign-in" />;
}
+6 -1
View File
@@ -81,11 +81,16 @@ export default function RegisterScreen() {
const session = await authClient.getSession();
const user = session.data?.user;
if (user) {
await completeSignInAfterAuth(authClient, {
const completed = await completeSignInAfterAuth(authClient, {
apiUrl,
activeAccountId,
registerAccount: saveAccount,
});
if (!completed) {
setError("Account created but session setup failed. Try signing in.");
}
} else {
setError("Account created. Sign in with your email and password.");
}
} catch (err) {
setError(err instanceof Error ? err.message : "Registration failed");
+159
View File
@@ -0,0 +1,159 @@
import { Ionicons } from "@expo/vector-icons";
import { Redirect, router } from "expo-router";
import { useState } from "react";
import { ActivityIndicator, Pressable, StyleSheet, Text, View } from "react-native";
import { AuthCard } from "@/components/auth/AuthCard";
import { AuthCardHeader } from "@/components/auth/AuthCardHeader";
import { AuthScreenLayout } from "@/components/auth/AuthScreenLayout";
import { Button } from "@/components/ui/Button";
import { fonts, radii, spacing } from "@/constants/theme";
import { useAccounts } from "@/contexts/AccountsContext";
import { useAppTheme } from "@/contexts/ThemeContext";
import { startAdditionalAccountSignIn } from "@/lib/add-account";
import { formatServerHost } from "@/lib/server-mode";
function initials(name: string, email: string) {
const source = name.trim() || email.trim();
const parts = source.split(/\s+/).filter(Boolean);
if (parts.length >= 2) {
return `${parts[0]![0] ?? ""}${parts[1]![0] ?? ""}`.toUpperCase();
}
return (source[0] ?? "?").toUpperCase();
}
export default function SelectAccountScreen() {
const { colors } = useAppTheme();
const { accounts, activeAccountId, switchAccount, clearActiveAccount } = useAccounts();
const [selectingId, setSelectingId] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
async function handleSelect(accountId: string) {
if (selectingId) return;
setSelectingId(accountId);
try {
await switchAccount(accountId);
router.replace("/(auth)/sign-in");
} finally {
setSelectingId(null);
}
}
async function handleAddAccount() {
if (adding) return;
setAdding(true);
try {
await startAdditionalAccountSignIn(clearActiveAccount);
} finally {
setAdding(false);
}
}
if (activeAccountId || accounts.length === 0) {
return <Redirect href="/(auth)/sign-in" />;
}
return (
<AuthScreenLayout>
<AuthCard>
<AuthCardHeader
title="Choose account"
description="Select the workspace account to use on this device"
/>
<View style={styles.list}>
{accounts.map((account) => {
const isSelecting = selectingId === account.id;
return (
<Pressable
accessibilityRole="button"
disabled={Boolean(selectingId)}
key={account.id}
onPress={() => void handleSelect(account.id)}
style={({ pressed }) => [
styles.accountRow,
{ backgroundColor: colors.muted, borderColor: colors.border },
pressed && styles.pressed,
]}
>
<View style={[styles.avatar, { backgroundColor: colors.primary }]}>
<Text style={[styles.avatarText, { color: colors.primaryForeground }]}>
{initials(account.name, account.email)}
</Text>
</View>
<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 }]}>
{formatServerHost(account.instanceUrl)}
</Text>
</View>
{isSelecting ? (
<ActivityIndicator color={colors.primary} size="small" />
) : (
<Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} />
)}
</Pressable>
);
})}
</View>
<Button
disabled={Boolean(selectingId)}
loading={adding}
onPress={() => void handleAddAccount()}
title="Sign in to another account"
variant="secondary"
/>
</AuthCard>
</AuthScreenLayout>
);
}
const styles = StyleSheet.create({
list: {
gap: spacing.sm,
},
accountRow: {
minHeight: 72,
borderRadius: radii.lg,
borderWidth: 1,
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
padding: spacing.md,
},
avatar: {
width: 36,
height: 36,
borderRadius: 18,
alignItems: "center",
justifyContent: "center",
},
avatarText: {
fontFamily: fonts.bodySemiBold,
fontSize: 13,
},
accountMeta: {
flex: 1,
gap: 2,
},
accountName: {
fontFamily: fonts.bodySemiBold,
fontSize: 15,
lineHeight: 20,
},
accountSub: {
fontFamily: fonts.body,
fontSize: 12,
lineHeight: 16,
},
pressed: {
opacity: 0.9,
},
});
+9 -8
View File
@@ -18,12 +18,14 @@ import { useAuthClient } from "@/contexts/AuthContext";
import { useAppTheme } from "@/contexts/ThemeContext";
import { fetchAuthCapabilities } from "@/lib/auth-capabilities";
import { signInWithAuthentik } from "@/lib/auth-oauth";
import { prepareAuthScreenSession } from "@/lib/auth-session";
import { completeSignInAfterAuth } from "@/lib/complete-sign-in";
import { formatAuthErrorMessage } from "@/lib/trpc-errors";
import { isRequiredString, isValidEmail, useFieldVisibility } from "@/lib/form-validation";
export default function SignInScreen() {
const authClient = useAuthClient();
const { apiUrl, activeAccountId, registerAccount } = useAccounts();
const { apiUrl, activeAccountId, clearActiveAccount, registerAccount } = useAccounts();
const { colors } = useAppTheme();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
@@ -34,6 +36,10 @@ export default function SignInScreen() {
const [signupsDisabled, setSignupsDisabled] = useState(false);
const { touch, visible, markSubmitted } = useFieldVisibility();
useEffect(() => {
void prepareAuthScreenSession(authClient, activeAccountId, clearActiveAccount);
}, [authClient, activeAccountId, clearActiveAccount]);
useEffect(() => {
let cancelled = false;
@@ -81,12 +87,7 @@ export default function SignInScreen() {
});
if (signInError) {
const message = signInError.message ?? "";
if (message.toLowerCase().includes("internal") || message.includes("500")) {
setError("Server error — is the API running with Postgres? Check beenvoice dev + docker.");
} else {
setError(message || "Invalid email or password");
}
setError(formatAuthErrorMessage(signInError));
return;
}
@@ -108,7 +109,7 @@ export default function SignInScreen() {
);
if (oauthError) {
setError(oauthError.message ?? "Could not sign in with Authentik");
setError(formatAuthErrorMessage(oauthError));
return;
}
+6 -2
View File
@@ -16,6 +16,7 @@ import { View } from "react-native";
import { StatusBar } from "expo-status-bar";
import "react-native-reanimated";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { BrandBackground } from "@/components/BrandBackground";
import { LoadingScreen } from "@/components/LoadingScreen";
@@ -84,6 +85,7 @@ export default function RootLayout() {
}
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<SafeAreaProvider>
<ThemeProvider>
<ThemedChrome>
@@ -95,17 +97,19 @@ export default function RootLayout() {
</ThemedChrome>
</ThemeProvider>
</SafeAreaProvider>
</GestureHandlerRootView>
);
}
function RootNavigator() {
const { data: session, isPending, error } = useSession();
const { data: session, isPending } = useSession();
const { activeAccountId } = useAccounts();
if (isPending) {
return <LoadingScreen message="Checking session…" />;
}
const isAuthenticated = Boolean(session?.user) && !error;
const isAuthenticated = Boolean(session?.user && activeAccountId);
return (
<Stack
+37 -1
View File
@@ -1,4 +1,5 @@
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { useState } from "react";
import {
ActivityIndicator,
@@ -82,6 +83,11 @@ export function AccountSwitcher() {
}
}
function handleOpenSettings() {
setOpen(false);
router.push("/(app)/more/settings" as never);
}
function handleRemove(accountId: string, label: string) {
confirmRemoveAccount(
label,
@@ -92,8 +98,9 @@ export function AccountSwitcher() {
}
await finishAccountRemoval({
result,
authClient,
clearActiveAccount,
signOut: () => authClient.signOut(),
activeAccountId,
});
},
);
@@ -218,6 +225,22 @@ export function AccountSwitcher() {
<Ionicons name="add-circle-outline" size={22} color={colors.primary} />
<Text style={[styles.addLabel, { color: colors.primary }]}>Add account</Text>
</Pressable>
<Pressable
accessibilityRole="button"
onPress={handleOpenSettings}
style={({ pressed }) => [
styles.settingsRow,
{ borderTopColor: colors.border },
pressed && styles.pressed,
]}
>
<Ionicons name="settings-outline" size={21} color={colors.mutedForeground} />
<Text style={[styles.settingsLabel, { color: colors.foreground }]}>
Settings
</Text>
<Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} />
</Pressable>
</ScrollView>
</Pressable>
</Pressable>
@@ -332,6 +355,19 @@ const styles = StyleSheet.create({
fontFamily: fonts.bodySemiBold,
fontSize: 15,
},
settingsRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
paddingHorizontal: spacing.lg,
paddingVertical: spacing.md,
borderTopWidth: StyleSheet.hairlineWidth,
},
settingsLabel: {
flex: 1,
fontFamily: fonts.bodySemiBold,
fontSize: 15,
},
pressed: {
opacity: 0.75,
},
+29 -4
View File
@@ -1,12 +1,18 @@
import { useEffect, useRef } from "react";
import { AppState, type AppStateStatus } from "react-native";
import { useSession } from "@/contexts/AuthContext";
import { useAccounts } from "@/contexts/AccountsContext";
import { useAuthClient, useSession } from "@/contexts/AuthContext";
import { performAuthReset } from "@/lib/auth-session";
import { isRateLimitError } from "@/lib/trpc-errors";
/** Refetch auth session when the app returns to the foreground. */
export function SessionSync() {
const { refetch } = useSession();
const authClient = useAuthClient();
const { activeAccountId, clearActiveAccount } = useAccounts();
const { data: session, refetch } = useSession();
const wasBackgrounded = useRef(false);
const resettingRef = useRef(false);
useEffect(() => {
const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
@@ -17,11 +23,30 @@ export function SessionSync() {
if (nextState !== "active" || !wasBackgrounded.current) return;
wasBackgrounded.current = false;
void refetch();
void (async () => {
await refetch();
const next = await authClient.getSession();
if (next.error && isRateLimitError(next.error)) return;
if (next.data?.user) return;
if (!session?.user || resettingRef.current) return;
resettingRef.current = true;
try {
await performAuthReset({
authClient,
clearActiveAccount,
activeAccountId,
refetchSession: refetch,
});
} finally {
resettingRef.current = false;
}
})();
});
return () => subscription.remove();
}, [refetch]);
}, [authClient, refetch, session?.user, activeAccountId, clearActiveAccount]);
return null;
}
+1 -13
View File
@@ -105,23 +105,11 @@ export function ShortcutHandler() {
const clientId =
pending.clientId || (await getLastTimeClockClientId(activeAccountId)) || "";
if (!clientId) {
await clearPendingShortcut();
setPending(null);
router.push("/(app)/timer");
Alert.alert(
"Choose a client",
"Open the time clock and pick a client once — shortcuts will use it next time.",
);
return;
}
const client = (clientsQuery.data ?? []).find((entry) => entry.id === clientId);
const rate = resolveEffectiveHourlyRate("", client?.defaultHourlyRate);
await clockIn.mutateAsync({
clientId,
clientId: clientId || "",
description: resolveClockDescription(pending.title || DEFAULT_CLOCK_DESCRIPTION),
rate: rate ?? undefined,
});
+78 -4
View File
@@ -1,6 +1,6 @@
import { Ionicons } from "@expo/vector-icons";
import { ReactNode, useRef } from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";
import { Pressable, type PressableProps, StyleSheet, Text, View } from "react-native";
import Swipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
@@ -24,6 +24,9 @@ type SwipeableRowProps = {
actions: SwipeAction[];
enabled?: boolean;
backgroundColor?: string;
onPress?: () => void;
onLongPress?: () => void;
contentStyle?: PressableProps["style"];
};
export function SwipeableRow({
@@ -31,11 +34,63 @@ export function SwipeableRow({
actions,
enabled = true,
backgroundColor,
onPress,
onLongPress,
contentStyle,
}: SwipeableRowProps) {
const { colors } = useAppTheme();
const styles = useThemedStyles(createSwipeableRowStyles);
const rowBackground = backgroundColor ?? colors.background;
const swipeRef = useRef<SwipeableMethods>(null);
const rowOpenRef = useRef(false);
const suppressPressUntilRef = useRef(0);
function suppressContentPress() {
suppressPressUntilRef.current = Date.now() + 350;
}
function handleContentPress() {
if (!onPress) return;
if (rowOpenRef.current || Date.now() < suppressPressUntilRef.current) {
swipeRef.current?.close();
rowOpenRef.current = false;
return;
}
onPress();
}
function renderContent() {
if (!onPress && !onLongPress) {
return (
<View
style={[
styles.row,
{ backgroundColor: rowBackground },
typeof contentStyle === "function" ? undefined : contentStyle,
]}
>
{children}
</View>
);
}
return (
<Pressable
accessibilityRole="button"
onPress={handleContentPress}
onLongPress={onLongPress}
style={(state) => [
styles.row,
{ backgroundColor: rowBackground },
typeof contentStyle === "function" ? contentStyle(state) : contentStyle,
]}
>
{children}
</Pressable>
);
}
function renderRightActions() {
return (
@@ -45,7 +100,9 @@ export function SwipeableRow({
key={action.key}
style={[styles.actionButton, { backgroundColor: action.backgroundColor }]}
onPress={() => {
suppressContentPress();
swipeRef.current?.close();
rowOpenRef.current = false;
action.onPress();
}}
>
@@ -58,12 +115,26 @@ export function SwipeableRow({
}
if (!enabled || actions.length === 0) {
return <View style={[styles.row, { backgroundColor: rowBackground }]}>{children}</View>;
return renderContent();
}
return (
<Swipeable ref={swipeRef} renderRightActions={renderRightActions} overshootRight={false}>
<View style={[styles.row, { backgroundColor: rowBackground }]}>{children}</View>
<Swipeable
ref={swipeRef}
renderRightActions={renderRightActions}
overshootRight={false}
onSwipeableOpenStartDrag={suppressContentPress}
onSwipeableCloseStartDrag={suppressContentPress}
onSwipeableWillOpen={() => {
suppressContentPress();
rowOpenRef.current = true;
}}
onSwipeableWillClose={suppressContentPress}
onSwipeableClose={() => {
rowOpenRef.current = false;
}}
>
{renderContent()}
</Swipeable>
);
}
@@ -72,6 +143,9 @@ const createSwipeableRowStyles = (colors: ThemeColors) =>
StyleSheet.create({
row: {
backgroundColor: colors.background,
borderRadius: radii.lg,
overflow: "hidden",
marginBottom: spacing.xs,
},
actions: {
flexDirection: "row",
+3 -2
View File
@@ -7,16 +7,17 @@ import { useAppTheme } from "@/contexts/ThemeContext";
type TabPageProps = {
children: ReactNode;
showMoreBack?: boolean;
};
/** Tab root — pinned top chrome, scrollable body below. */
export function TabPage({ children }: TabPageProps) {
export function TabPage({ children, showMoreBack = false }: TabPageProps) {
const { isDark } = useAppTheme();
return (
<View style={styles.root}>
<StatusBar style={isDark ? "light" : "dark"} />
<TopChromeBar />
<TopChromeBar showMoreBack={showMoreBack} />
<View style={styles.content}>{children}</View>
</View>
);
+10
View File
@@ -19,11 +19,15 @@ export function TabScrollView({
header,
children,
contentContainerStyle,
refreshControl,
style,
bounces,
alwaysBounceVertical,
...props
}: TabScrollViewProps) {
const scrollRef = useRef<ScrollView>(null);
const bottomPadding = useTabScreenScrollPadding();
const canRefresh = Boolean(refreshControl);
useScrollToTop(scrollRef);
@@ -37,6 +41,12 @@ export function TabScrollView({
contentContainerStyle,
]}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "never" : undefined}
automaticallyAdjustContentInsets={false}
automaticallyAdjustKeyboardInsets={false}
automaticallyAdjustsScrollIndicatorInsets={false}
bounces={bounces ?? canRefresh}
alwaysBounceVertical={alwaysBounceVertical ?? canRefresh}
refreshControl={refreshControl}
scrollIndicatorInsets={{ bottom: bottomPadding }}
{...props}
>
+50 -3
View File
@@ -1,18 +1,49 @@
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { StyleSheet, View } from "react-native";
import { Pressable, Text } from "react-native";
import { AccountSwitcher } from "@/components/AccountSwitcher";
import { Logo } from "@/components/Logo";
import { spacing } from "@/constants/theme";
import { fonts, radii, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { TOP_CHROME_ROW_HEIGHT } from "@/lib/top-chrome-insets";
type TopChromeProps = {
showMoreBack?: boolean;
};
/** Wordmark left, account switcher right — sits on TopChromeBar blur. */
export function TopChrome() {
const { isDark } = useAppTheme();
export function TopChrome({ showMoreBack = false }: TopChromeProps) {
const { colors, isDark } = useAppTheme();
function handleBack() {
if (router.canGoBack()) {
router.back();
return;
}
router.replace("/(app)/more" as never);
}
return (
<View style={styles.row}>
{showMoreBack ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Back to More"
onPress={handleBack}
style={({ pressed }) => [
styles.backButton,
{ borderColor: colors.borderGlass, backgroundColor: colors.cardGlass },
pressed && styles.pressed,
]}
>
<Ionicons name="chevron-back" size={18} color={colors.foreground} />
<Text style={[styles.backLabel, { color: colors.foreground }]}>More</Text>
</Pressable>
) : (
<Logo size="xs" onDark={isDark} />
)}
<AccountSwitcher />
</View>
);
@@ -26,4 +57,20 @@ const styles = StyleSheet.create({
height: TOP_CHROME_ROW_HEIGHT,
paddingHorizontal: spacing.md,
},
backButton: {
minHeight: 36,
flexDirection: "row",
alignItems: "center",
gap: spacing.xs,
paddingHorizontal: spacing.sm,
borderWidth: 1,
borderRadius: radii.pill,
},
backLabel: {
fontFamily: fonts.bodySemiBold,
fontSize: 13,
},
pressed: {
opacity: 0.82,
},
});
+6 -2
View File
@@ -10,8 +10,12 @@ import {
TOP_CHROME_ROW_HEIGHT,
} from "@/lib/top-chrome-insets";
type TopChromeBarProps = {
showMoreBack?: boolean;
};
/** Blurred status-bar chrome with logo + account switcher. */
export function TopChromeBar() {
export function TopChromeBar({ showMoreBack = false }: TopChromeBarProps) {
const insets = useSafeAreaInsets();
const { isDark } = useAppTheme();
const tint = isDark ? "rgba(9, 9, 11, 0.28)" : "rgba(255, 255, 255, 0.32)";
@@ -38,7 +42,7 @@ export function TopChromeBar() {
pointerEvents="none"
style={[StyleSheet.absoluteFill, { backgroundColor: tint }]}
/>
<TopChrome />
<TopChrome showMoreBack={showMoreBack} />
</View>
);
}
+10 -2
View File
@@ -54,7 +54,7 @@ export function ExpenseFormFields({
clients,
onChange,
notesLabel = "Notes",
notesPlaceholder = "Internal details or receipt OCR text",
notesPlaceholder = "Internal details",
}: ExpenseFormFieldsProps) {
const { colors } = useAppTheme();
@@ -172,7 +172,15 @@ export function ExpenseFormFields({
onValueChange: (value: boolean) => void;
}) {
return (
<View style={[styles.flagRow, { borderColor: colors.borderGlass }]}>
<View
style={[
styles.flagRow,
{
borderColor: colors.borderGlass,
backgroundColor: colors.cardGlass,
},
]}
>
<Text style={[styles.flagLabel, { color: colors.foreground }]}>
{label}
</Text>
+7 -2
View File
@@ -80,7 +80,12 @@ export function ReceiptItemSelector({
};
return (
<View style={[styles.wrap, { borderColor: colors.border }]}>
<View
style={[
styles.wrap,
{ borderColor: colors.border, backgroundColor: colors.cardGlass },
]}
>
<View style={styles.header}>
<View style={styles.headerCopy}>
<Text style={[styles.title, { color: colors.foreground }]}>
@@ -140,7 +145,7 @@ export function ReceiptItemSelector({
onPress={() => toggle(item.id)}
style={({ pressed }) => [
styles.item,
{ borderColor: colors.borderGlass },
{ borderColor: colors.borderGlass, backgroundColor: colors.background },
selected && { backgroundColor: colors.muted },
pressed && styles.pressed,
]}
+33 -1
View File
@@ -3,6 +3,7 @@ import { Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { CompactDateField } from "@/components/ui/CompactDateField";
import { CompactStepperInput } from "@/components/ui/CompactStepperInput";
import { SwipeableRow } from "@/components/SwipeableRow";
import { fonts, radii, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { formatCurrency, formatShortDate } from "@/lib/format";
@@ -21,6 +22,7 @@ type LineItemEditorProps = {
currency: string;
onChange: (patch: Partial<EditableLineItem>) => void;
onRemove: () => void;
onDuplicate?: () => void;
readOnly?: boolean;
isLast?: boolean;
};
@@ -38,6 +40,7 @@ export function LineItemEditor({
currency,
onChange,
onRemove,
onDuplicate,
readOnly = false,
isLast = false,
}: LineItemEditorProps) {
@@ -70,7 +73,7 @@ export function LineItemEditor({
);
}
return (
const content = (
<View
style={[
styles.editBlock,
@@ -156,6 +159,35 @@ export function LineItemEditor({
</View>
</View>
);
const swipeActions = [
...(onDuplicate
? [
{
key: "duplicate",
label: "Copy",
icon: "copy-outline" as const,
color: "#fff",
backgroundColor: colors.primary,
onPress: onDuplicate,
},
]
: []),
{
key: "delete",
label: "Delete",
icon: "trash-outline" as const,
color: "#fff",
backgroundColor: colors.destructive,
onPress: onRemove,
},
];
return (
<SwipeableRow actions={swipeActions} backgroundColor={colors.card}>
{content}
</SwipeableRow>
);
}
const styles = StyleSheet.create({
+159 -69
View File
@@ -13,7 +13,9 @@ import { router } from "expo-router";
import { FilterChip } from "@/components/FilterChip";
import { GlassSurface } from "@/components/GlassSurface";
import { LoadingScreen } from "@/components/LoadingScreen";
import { SwipeableRow } from "@/components/SwipeableRow";
import { TabScrollView } from "@/components/TabScrollView";
import { TimeEntryEditSheet } from "@/components/time-clock/TimeEntryEditSheet";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { DateTimeField } from "@/components/ui/DateTimeField";
@@ -98,10 +100,11 @@ export function TimeClockPanel({
const [agoMinutesText, setAgoMinutesText] = useState("60");
const [optionsExpanded, setOptionsExpanded] = useState(false);
const [clientsExpanded, setClientsExpanded] = useState(false);
const [editEntryId, setEditEntryId] = useState<string | null>(null);
const [runningStartedAt, setRunningStartedAt] = useState(() => new Date());
const [featuredClientIds, setFeaturedClientIds] = useState<string[]>([]);
const [storedLastClientId, setStoredLastClientId] = useState<string | null>(null);
const [prefsLoaded, setPrefsLoaded] = useState(false);
const [initialClientResolved, setInitialClientResolved] = useState(Boolean(defaultClientId));
const running = runningQuery.data;
const elapsed = useRunningElapsed(running?.startedAt);
@@ -140,6 +143,15 @@ export function TimeClockPanel({
},
});
const updateRunning = api.timeEntries.updateRunning.useMutation({
onSuccess: async () => {
await Promise.all([
utils.timeEntries.getRunning.invalidate(),
utils.invoices.getBillable.invalidate(),
]);
},
});
const clockOut = api.timeEntries.clockOut.useMutation({
onSuccess: async (data) => {
await endTimeClockLiveActivity();
@@ -184,8 +196,10 @@ export function TimeClockPanel({
if (!running) return;
setClientId(running.clientId ?? "");
setInvoiceId(running.invoiceId ?? "");
setDescription(running.description ?? "");
setStopNote("");
setRateText(running.rate != null ? String(running.rate) : "");
setRunningStartedAt(new Date(running.startedAt));
}, [running]);
useEffect(() => {
@@ -195,32 +209,6 @@ export function TimeClockPanel({
setRateText((current) => current.trim() || clientRateText(client));
}, [clientId, clients, running]);
useEffect(() => {
if (running || defaultClientId || initialClientResolved) return;
if (!prefsLoaded || clients.length === 0) return;
const preferredId =
storedLastClientId && clients.some((client) => client.id === storedLastClientId)
? storedLastClientId
: recentClientIds.find((id) => clients.some((client) => client.id === id)) ?? null;
if (preferredId) {
const client = clients.find((c) => c.id === preferredId);
setClientId(preferredId);
setRateText(clientRateText(client));
}
setInitialClientResolved(true);
}, [
clients,
defaultClientId,
initialClientResolved,
prefsLoaded,
recentClientIds,
running,
storedLastClientId,
]);
useEffect(() => {
if (featuredClientIds.length > 0 || !prefsLoaded || clients.length === 0) return;
@@ -269,8 +257,7 @@ export function TimeClockPanel({
}, [agoMinutes, startMode, startedAt]);
const clockInErrors = useMemo(() => {
const next: { clientId?: string; rate?: string; start?: string } = {};
if (!clientId) next.clientId = "Choose a client to start";
const next: { rate?: string; start?: string } = {};
if (rateText.trim() && parseNonNegativeNumber(rateText) === null) {
next.rate = "Enter a valid hourly rate";
}
@@ -278,7 +265,7 @@ export function TimeClockPanel({
next.start = "Enter how long ago you started";
}
return next;
}, [agoMinutes, clientId, rateText, startMode]);
}, [agoMinutes, rateText, startMode]);
const canClockIn = Object.keys(clockInErrors).length === 0;
@@ -307,14 +294,45 @@ export function TimeClockPanel({
function selectClient(nextClientId: string) {
const client = clients.find((c) => c.id === nextClientId);
if (running) {
updateRunning.mutate({
clientId: nextClientId,
invoiceId: "",
rate: client?.defaultHourlyRate ?? undefined,
});
return;
}
setClientId(nextClientId);
setInvoiceId("");
setRateText(clientRateText(client));
if (!featuredClientIds.includes(nextClientId)) {
if (nextClientId && !featuredClientIds.includes(nextClientId)) {
setClientsExpanded(true);
}
if (nextClientId) {
void persistClientChoice(nextClientId);
}
}
function selectInvoice(nextInvoiceId: string) {
if (running) {
updateRunning.mutate({ invoiceId: nextInvoiceId || "" });
return;
}
setInvoiceId(nextInvoiceId);
}
function handleRunningDescriptionBlur() {
if (!running) return;
const next = resolveClockDescription(description);
if (next === (running.description ?? "")) return;
updateRunning.mutate({ description: next });
}
function handleRunningStartedAtChange(date: Date) {
setRunningStartedAt(date);
if (!running || date > new Date()) return;
updateRunning.mutate({ startedAt: date });
}
function selectStartMode(mode: StartMode) {
setStartMode(mode);
@@ -363,7 +381,9 @@ export function TimeClockPanel({
rate: effectiveRate ?? undefined,
startedAt: backdated,
});
if (clientId) {
await persistClientChoice(clientId);
}
setStartMode("now");
setStartedAt(new Date());
setAgoMinutes(60);
@@ -445,7 +465,7 @@ export function TimeClockPanel({
</>
) : (
<Text style={styles.idleHint}>
Choose a client and clock in. A draft invoice is created automatically if needed.
Start the timer anytime add client, invoice, and details later.
</Text>
)}
</View>
@@ -457,6 +477,62 @@ export function TimeClockPanel({
{running ? (
<View style={styles.formSection}>
<Input
label="What are you working on?"
value={description}
onChangeText={setDescription}
onBlur={handleRunningDescriptionBlur}
placeholder="What are you working on?"
returnKeyType="done"
/>
<DateTimeField
label="Started at"
value={runningStartedAt}
maximumDate={new Date()}
onChange={handleRunningStartedAtChange}
/>
<View style={styles.setupSection}>
<Text style={styles.sectionLabel}>Client</Text>
<View style={styles.chipWrap}>
<FilterChip
label="None"
active={!clientId}
onPress={() => selectClient("")}
/>
{clients.map((client) => (
<FilterChip
key={client.id}
label={client.name}
active={clientId === client.id}
onPress={() => selectClient(client.id)}
/>
))}
</View>
</View>
{clientId ? (
<View style={styles.setupSection}>
<Text style={styles.sectionLabel}>Invoice</Text>
<View style={styles.chipWrap}>
<FilterChip
label="Entry only"
active={!invoiceId}
onPress={() => selectInvoice("")}
/>
{billableInvoices.map((invoice) => (
<FilterChip
key={invoice.id}
label={`${invoice.invoicePrefix ?? "#"}${invoice.invoiceNumber}`}
active={invoiceId === invoice.id}
onPress={() => selectInvoice(invoice.id)}
/>
))}
</View>
</View>
) : null}
<Input
label="Note on stop (optional)"
value={stopNote}
@@ -490,11 +566,16 @@ export function TimeClockPanel({
<Text style={styles.sectionLabel}>Client</Text>
{clients.length === 0 ? (
<Text style={styles.emptyClients}>
Add a client first to start tracking time.
No clients yet you can still start the timer and assign a client later.
</Text>
) : (
<>
<View style={styles.chipWrap}>
<FilterChip
label="No client"
active={!clientId}
onPress={() => selectClient("")}
/>
{featuredClients.map((client) => renderClientChip(client))}
{moreClients.length > 0 ? (
<FilterChip
@@ -511,20 +592,17 @@ export function TimeClockPanel({
) : null}
</>
)}
{clockInErrors.clientId ? (
<Text style={styles.fieldError}>{clockInErrors.clientId}</Text>
) : null}
</View>
{clientId ? (
<View style={styles.setupSection}>
<Text style={styles.sectionLabel}>Invoice</Text>
<Text style={styles.sectionLabel}>Invoice (optional)</Text>
{!clientId ? (
<Text style={styles.emptyClients}>
No invoice for now. Add a client and invoice later if this becomes billable.
</Text>
) : (
<View style={styles.chipWrap}>
<FilterChip
label="Entry only"
active={!invoiceId}
onPress={() => setInvoiceId("")}
/>
<FilterChip label="Entry only" active={!invoiceId} onPress={() => setInvoiceId("")} />
{billableInvoices.map((invoice) => {
const label = `${invoice.invoicePrefix ?? "#"}${invoice.invoiceNumber}`;
return (
@@ -537,10 +615,9 @@ export function TimeClockPanel({
);
})}
</View>
)}
</View>
) : null}
{clientId ? (
<View style={styles.setupSection}>
<Pressable
accessibilityRole="button"
@@ -647,12 +724,11 @@ export function TimeClockPanel({
</View>
) : null}
</View>
) : null}
<Button
title={clockIn.isPending ? "Starting…" : "Start timer"}
loading={clockIn.isPending}
disabled={!canClockIn || clients.length === 0}
disabled={!canClockIn}
showArrow={!clockIn.isPending}
onPress={handleClockIn}
/>
@@ -667,8 +743,35 @@ export function TimeClockPanel({
? `${entry.invoice.invoicePrefix ?? "#"}${entry.invoice.invoiceNumber}`
: null;
const row = (
<>
return (
<SwipeableRow
key={entry.id}
actions={[
{
key: "edit",
label: "Edit",
icon: "create-outline",
color: "#fff",
backgroundColor: colors.primary,
onPress: () => setEditEntryId(entry.id),
},
{
key: "invoice",
label: "Invoice",
icon: "document-text-outline",
color: "#fff",
backgroundColor: colors.mutedForeground,
onPress: () => {
if (entry.invoice?.id) {
router.push(`/(app)/invoices/${entry.invoice.id}`);
} else {
setEditEntryId(entry.id);
}
},
},
]}
>
<View style={styles.entryRow}>
<View style={styles.entryMeta}>
<Text style={styles.entryTitle}>{formatRunningTimerLabel(entry.description)}</Text>
<Text style={styles.entrySub}>
@@ -677,31 +780,18 @@ export function TimeClockPanel({
</Text>
</View>
<Text style={styles.entryHours}>{entry.hours ?? "—"}h</Text>
</>
);
if (!entry.invoice) {
return (
<View key={entry.id} style={styles.entryRow}>
{row}
</View>
);
}
return (
<Pressable
key={entry.id}
accessibilityRole="button"
accessibilityLabel={`View invoice ${invoiceLabel}`}
onPress={() => router.push(`/(app)/invoices/${entry.invoice!.id}`)}
style={({ pressed }) => [styles.entryRow, pressed && styles.entryRowPressed]}
>
{row}
</Pressable>
</SwipeableRow>
);
})}
</Card>
) : null}
<TimeEntryEditSheet
entryId={editEntryId}
visible={editEntryId != null}
onClose={() => setEditEntryId(null)}
/>
</TabScrollView>
);
}
@@ -0,0 +1,267 @@
import { useEffect, useMemo, useState } from "react";
import {
Alert,
Modal,
Pressable,
ScrollView,
StyleSheet,
Text,
View,
} from "react-native";
import { FilterChip } from "@/components/FilterChip";
import { Button } from "@/components/ui/Button";
import { DateTimeField } from "@/components/ui/DateTimeField";
import { Input } from "@/components/ui/Input";
import { fonts, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { formatCurrency } from "@/lib/format";
import { parseNonNegativeNumber } from "@/lib/form-validation";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { api } from "@/lib/trpc";
type TimeEntryEditSheetProps = {
entryId: string | null;
visible: boolean;
onClose: () => void;
};
export function TimeEntryEditSheet({ entryId, visible, onClose }: TimeEntryEditSheetProps) {
const { colors } = useAppTheme();
const styles = useThemedStyles(createStyles);
const utils = api.useUtils();
const entryQuery = api.timeEntries.getById.useQuery(
{ id: entryId ?? "" },
{ enabled: visible && Boolean(entryId) },
);
const clientsQuery = api.clients.getAll.useQuery(undefined, { enabled: visible });
const [description, setDescription] = useState("");
const [clientId, setClientId] = useState("");
const [invoiceId, setInvoiceId] = useState("");
const [rateText, setRateText] = useState("");
const [startedAt, setStartedAt] = useState(() => new Date());
const [endedAt, setEndedAt] = useState(() => new Date());
const billableQuery = api.invoices.getBillable.useQuery(
clientId ? { clientId } : undefined,
{ enabled: visible && Boolean(clientId) },
);
useEffect(() => {
const entry = entryQuery.data;
if (!entry) return;
setDescription(entry.description ?? "");
setClientId(entry.clientId ?? "");
setInvoiceId(entry.invoiceId ?? "");
setRateText(entry.rate != null ? String(entry.rate) : "");
setStartedAt(new Date(entry.startedAt));
setEndedAt(entry.endedAt ? new Date(entry.endedAt) : new Date());
}, [entryQuery.data]);
const hoursPreview = useMemo(() => {
if (endedAt <= startedAt) return null;
return Math.max(0, (endedAt.getTime() - startedAt.getTime()) / 3_600_000);
}, [endedAt, startedAt]);
const rate = parseNonNegativeNumber(rateText);
const updateEntry = api.timeEntries.update.useMutation({
onSuccess: async () => {
await Promise.all([
utils.timeEntries.getAll.invalidate(),
utils.timeEntries.getById.invalidate(),
utils.invoices.getAll.invalidate(),
utils.dashboard.getStats.invalidate(),
]);
onClose();
},
onError: (err) => Alert.alert("Could not save", err.message),
});
const deleteEntry = api.timeEntries.delete.useMutation({
onSuccess: async () => {
await Promise.all([
utils.timeEntries.getAll.invalidate(),
utils.invoices.getAll.invalidate(),
utils.dashboard.getStats.invalidate(),
]);
onClose();
},
onError: (err) => Alert.alert("Could not delete", err.message),
});
function handleSave() {
if (!entryId) return;
if (endedAt <= startedAt) {
Alert.alert("Invalid times", "End time must be after start time.");
return;
}
updateEntry.mutate({
id: entryId,
description,
clientId: clientId || "",
invoiceId: invoiceId || "",
rate: rate ?? undefined,
startedAt,
endedAt,
hours: hoursPreview ?? undefined,
});
}
function confirmDelete() {
if (!entryId) return;
Alert.alert("Delete time entry?", "This removes the entry and any linked invoice line.", [
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: () => deleteEntry.mutate({ id: entryId }),
},
]);
}
return (
<Modal visible={visible} animationType="slide" presentationStyle="pageSheet" onRequestClose={onClose}>
<View style={[styles.container, { backgroundColor: colors.background }]}>
<View style={styles.header}>
<Text style={[styles.title, { color: colors.foreground }]}>Edit time entry</Text>
<Pressable onPress={onClose} hitSlop={8}>
<Text style={[styles.close, { color: colors.mutedForeground }]}>Close</Text>
</Pressable>
</View>
<ScrollView contentContainerStyle={styles.body} keyboardShouldPersistTaps="handled">
{entryQuery.isLoading ? (
<Text style={{ color: colors.mutedForeground }}>Loading</Text>
) : (
<>
<Input label="Description" value={description} onChangeText={setDescription} />
<Text style={[styles.label, { color: colors.foreground }]}>Client</Text>
<View style={styles.chipWrap}>
<FilterChip
label="None"
active={!clientId}
onPress={() => {
setClientId("");
setInvoiceId("");
}}
/>
{(clientsQuery.data ?? []).map((client) => (
<FilterChip
key={client.id}
label={client.name}
active={clientId === client.id}
onPress={() => {
setClientId(client.id);
setInvoiceId("");
}}
/>
))}
</View>
{clientId ? (
<>
<Text style={[styles.label, { color: colors.foreground }]}>Invoice</Text>
<View style={styles.chipWrap}>
<FilterChip
label="Not on invoice"
active={!invoiceId}
onPress={() => setInvoiceId("")}
/>
{(billableQuery.data ?? []).map((invoice) => (
<FilterChip
key={invoice.id}
label={`${invoice.invoicePrefix ?? "#"}${invoice.invoiceNumber}`}
active={invoiceId === invoice.id}
onPress={() => setInvoiceId(invoice.id)}
/>
))}
</View>
</>
) : null}
<Input
label="Hourly rate"
value={rateText}
onChangeText={setRateText}
keyboardType="decimal-pad"
/>
<DateTimeField
label="Started"
value={startedAt}
maximumDate={endedAt}
onChange={setStartedAt}
/>
<DateTimeField label="Ended" value={endedAt} minimumDate={startedAt} onChange={setEndedAt} />
{hoursPreview != null ? (
<Text style={[styles.preview, { color: colors.mutedForeground }]}>
{hoursPreview.toFixed(2)}h
{rate != null && rate > 0
? ` · ${formatCurrency(hoursPreview * rate)}`
: ""}
</Text>
) : null}
<Button title="Save changes" loading={updateEntry.isPending} onPress={handleSave} />
<Button
title="Delete entry"
variant="danger"
loading={deleteEntry.isPending}
onPress={confirmDelete}
/>
</>
)}
</ScrollView>
</View>
</Modal>
);
}
const createStyles = (colors: ThemeColors) =>
StyleSheet.create({
container: {
flex: 1,
},
header: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: spacing.lg,
paddingTop: spacing.lg,
paddingBottom: spacing.md,
borderBottomWidth: 1,
borderBottomColor: colors.border,
},
title: {
fontFamily: fonts.bodySemiBold,
fontSize: 18,
},
close: {
fontFamily: fonts.bodyMedium,
fontSize: 15,
},
body: {
padding: spacing.lg,
gap: spacing.md,
},
label: {
fontFamily: fonts.bodySemiBold,
fontSize: 14,
},
chipWrap: {
flexDirection: "row",
flexWrap: "wrap",
gap: spacing.sm,
},
preview: {
fontFamily: fonts.body,
fontSize: 14,
},
});
+20 -2
View File
@@ -17,6 +17,7 @@ type ButtonProps = PressableProps & {
loading?: boolean;
variant?: "primary" | "secondary" | "danger" | "ghost";
style?: ViewStyle;
leftIcon?: keyof typeof Ionicons.glyphMap;
showArrow?: boolean;
};
@@ -26,6 +27,7 @@ export function Button({
variant = "primary",
disabled,
style,
leftIcon,
showArrow = false,
...props
}: ButtonProps) {
@@ -44,7 +46,11 @@ export function Button({
borderWidth: 1,
borderColor: colors.destructive,
},
ghost: { backgroundColor: "transparent" },
ghost: {
backgroundColor: colors.cardGlass,
borderWidth: 1,
borderColor: colors.borderGlass,
},
} as const;
const labelStyles = {
@@ -73,7 +79,16 @@ export function Button({
/>
) : (
<View style={styles.content}>
<Text style={[styles.label, labelStyles[variant]]}>{title}</Text>
{leftIcon ? (
<Ionicons
name={leftIcon}
size={16}
color={labelStyles[variant].color}
/>
) : null}
<Text style={[styles.label, labelStyles[variant]]} numberOfLines={1}>
{title}
</Text>
{showArrow ? (
<Ionicons
name="arrow-forward"
@@ -99,7 +114,9 @@ const styles = StyleSheet.create({
content: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
minWidth: 0,
},
arrow: {
marginTop: 1,
@@ -113,5 +130,6 @@ const styles = StyleSheet.create({
label: {
fontSize: 14,
fontFamily: fonts.bodyMedium,
flexShrink: 1,
},
});
+3 -8
View File
@@ -67,7 +67,7 @@ export function AccountsProvider({ children }: { children: ReactNode }) {
setRuntimeApiUrl(active.instanceUrl);
} else if (draftUrl) {
setRuntimeApiUrl(draftUrl);
} else {
} else if (!process.env.EXPO_PUBLIC_API_URL?.trim()) {
setRuntimeApiUrl(DEFAULT_API_URL);
}
@@ -166,13 +166,8 @@ export function AccountsProvider({ children }: { children: ReactNode }) {
await saveAccounts(nextAccounts);
if (wasActive) {
const fallback = nextAccounts[0] ?? null;
await saveActiveAccountId(fallback?.id ?? null);
setActiveAccountId(fallback?.id ?? null);
if (fallback) {
setRuntimeApiUrl(fallback.instanceUrl);
setApiUrl(fallback.instanceUrl);
}
await saveActiveAccountId(null);
setActiveAccountId(null);
}
return { wasActive, remainingCount: nextAccounts.length };
+13 -4
View File
@@ -1,24 +1,33 @@
import { router } from "expo-router";
import { Alert } from "react-native";
import type { createAuthClient } from "better-auth/react";
import type { RemoveAccountResult } from "@/contexts/AccountsContext";
import { performAuthReset } from "@/lib/auth-session";
type AuthClient = ReturnType<typeof createAuthClient>;
type FinishAccountRemovalInput = {
result: RemoveAccountResult;
authClient: AuthClient;
clearActiveAccount: () => Promise<void>;
signOut: () => Promise<unknown>;
activeAccountId: string | null;
};
/** Navigate to sign-in when the last saved account was removed. */
export async function finishAccountRemoval({
result,
authClient,
clearActiveAccount,
signOut,
activeAccountId,
}: FinishAccountRemovalInput): Promise<void> {
if (result.remainingCount > 0) return;
await signOut();
await clearActiveAccount();
await performAuthReset({
authClient,
clearActiveAccount,
activeAccountId,
});
router.replace("/(auth)/sign-in");
}
+19 -2
View File
@@ -13,6 +13,23 @@ export type SavedAccount = {
lastUsedAt: number;
};
function isSavedAccount(value: unknown): value is SavedAccount {
if (!value || typeof value !== "object") return false;
const account = value as Partial<SavedAccount>;
return (
typeof account.id === "string" &&
account.id.length > 0 &&
typeof account.instanceUrl === "string" &&
account.instanceUrl.length > 0 &&
typeof account.userId === "string" &&
account.userId.length > 0 &&
typeof account.email === "string" &&
typeof account.name === "string" &&
typeof account.lastUsedAt === "number"
);
}
export function buildAccountId(instanceUrl: string, userId: string) {
const host = instanceUrl.replace(/^https?:\/\//, "").replace(/\/$/, "");
return `${host}::${userId}`;
@@ -26,8 +43,8 @@ export async function loadAccounts(): Promise<SavedAccount[]> {
const raw = await AsyncStorage.getItem(ACCOUNTS_KEY);
if (!raw) return [];
try {
const parsed = JSON.parse(raw) as SavedAccount[];
return Array.isArray(parsed) ? parsed : [];
const parsed = JSON.parse(raw) as unknown;
return Array.isArray(parsed) ? parsed.filter(isSavedAccount) : [];
} catch {
return [];
}
+4 -10
View File
@@ -1,11 +1,5 @@
import { getApiUrl } from "@/lib/config";
type ApiError = { error?: string; message?: string };
async function parseError(res: Response) {
const data = (await res.json().catch(() => ({}))) as ApiError;
return data.error ?? data.message ?? "Something went wrong";
}
import { readHttpErrorMessage } from "@/lib/trpc-errors";
export async function registerAccount(input: {
firstName: string;
@@ -20,7 +14,7 @@ export async function registerAccount(input: {
});
if (!res.ok) {
throw new Error(await parseError(res));
throw new Error(await readHttpErrorMessage(res));
}
}
@@ -32,7 +26,7 @@ export async function requestPasswordReset(email: string) {
});
if (!res.ok) {
throw new Error(await parseError(res));
throw new Error(await readHttpErrorMessage(res));
}
const data = (await res.json()) as { message?: string };
@@ -47,6 +41,6 @@ export async function resetPassword(token: string, password: string) {
});
if (!res.ok) {
throw new Error(await parseError(res));
throw new Error(await readHttpErrorMessage(res));
}
}
+127
View File
@@ -0,0 +1,127 @@
import { getCookie as serializeStoredCookies } from "@better-auth/expo/client";
import * as SecureStore from "expo-secure-store";
import type { createAuthClient } from "better-auth/react";
import { GUEST_AUTH_STORAGE_PREFIX } from "@/lib/auth-storage";
import { normalizeSecureStoreKey } from "@/lib/secure-store-keys";
type AuthClient = ReturnType<typeof createAuthClient>;
const CHUNK_MARKER = "\u0001ba-chunks:";
const SESSION_TOKEN_COOKIE_PART =
/(?:^|;\s*)(?:__Secure-)?[^=]*session_token=([^;]+)/;
const AUTH_COOKIE_DEBUG = process.env.EXPO_PUBLIC_AUTH_COOKIE_DEBUG === "1";
function readSecureStoreValueSync(key: string): string | null {
const value = SecureStore.getItem(key);
if (value == null) return null;
if (!value.startsWith(CHUNK_MARKER)) return value;
const count = Number(value.slice(CHUNK_MARKER.length));
if (!Number.isInteger(count) || count < 1) return null;
let assembled = "";
for (let index = 0; index < count; index += 1) {
const chunk = SecureStore.getItem(`${key}.${index}`);
if (chunk == null) return null;
assembled += chunk;
}
return assembled;
}
function readStoredCookie(storagePrefix: string): string | null {
const raw = readSecureStoreValueSync(
normalizeSecureStoreKey(`${storagePrefix}_cookie`),
);
if (!raw || raw === "{}") return null;
const cookie = serializeStoredCookies(raw);
return cookie.trim() || null;
}
function cookieNames(cookie: string): string[] {
return cookie
.split(";")
.map((part) => part.trim().split("=", 1)[0])
.filter(Boolean);
}
/** Read session cookie string for tRPC requests (Expo client plugin + SecureStore fallback). */
export function getAuthCookie(
authClient: AuthClient,
storagePrefix: string,
): string | null {
const fromClient = (
authClient as AuthClient & { getCookie?: () => string }
).getCookie?.();
if (fromClient?.trim()) {
const cookie = fromClient.trim();
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] using client cookie", {
storagePrefix,
length: cookie.length,
names: cookieNames(cookie),
});
}
return cookie;
}
const fromPrefix = readStoredCookie(storagePrefix);
if (fromPrefix) {
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] using stored cookie", {
storagePrefix,
length: fromPrefix.length,
names: cookieNames(fromPrefix),
});
}
return fromPrefix;
}
const fromGuest =
storagePrefix === GUEST_AUTH_STORAGE_PREFIX
? null
: readStoredCookie(GUEST_AUTH_STORAGE_PREFIX);
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] resolved tRPC cookie", {
storagePrefix,
fallbackPrefix:
fromGuest && storagePrefix !== GUEST_AUTH_STORAGE_PREFIX
? GUEST_AUTH_STORAGE_PREFIX
: null,
hasCookie: Boolean(fromGuest),
length: fromGuest?.length ?? 0,
names: fromGuest ? cookieNames(fromGuest) : [],
});
}
return fromGuest;
}
export function getAuthCookieHeaders(
authClient: AuthClient,
storagePrefix: string,
): Record<string, string> {
const cookie = getAuthCookie(authClient, storagePrefix);
if (!cookie) {
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] no tRPC auth cookie", { storagePrefix });
}
return {};
}
const sessionToken = cookie.match(SESSION_TOKEN_COOKIE_PART)?.[1];
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] sending tRPC auth headers", {
storagePrefix,
cookieLength: cookie.length,
cookieNames: cookieNames(cookie),
hasSessionTokenHeader: Boolean(sessionToken),
});
}
return {
cookie,
Cookie: cookie,
"x-beenvoice-auth-cookie": cookie,
...(sessionToken ? { "x-beenvoice-session-token": sessionToken } : {}),
};
}
+60
View File
@@ -0,0 +1,60 @@
import type { createAuthClient } from "better-auth/react";
import { authStoragePrefix } from "@/lib/accounts";
import {
clearAuthStorage,
GUEST_AUTH_STORAGE_PREFIX,
prepareForAdditionalSignIn,
} from "@/lib/auth-storage";
type AuthClient = ReturnType<typeof createAuthClient>;
type PerformAuthResetInput = {
authClient: AuthClient;
clearActiveAccount: () => Promise<void>;
activeAccountId?: string | null;
refetchSession?: () => Promise<unknown>;
};
/** Sign out, wipe local auth storage, and return to guest mode for a clean sign-in screen. */
export async function performAuthReset({
authClient,
clearActiveAccount,
activeAccountId,
refetchSession,
}: PerformAuthResetInput): Promise<void> {
const accountPrefix = activeAccountId ? authStoragePrefix(activeAccountId) : null;
try {
await authClient.signOut();
} catch {
// Continue clearing local state even when the server session is already gone.
}
if (accountPrefix) {
await clearAuthStorage(accountPrefix);
}
await clearAuthStorage(GUEST_AUTH_STORAGE_PREFIX);
await clearActiveAccount();
await refetchSession?.();
}
/**
* When the auth stack is shown, discard stale SecureStore sessions so sign-in starts clean.
* Expired account sessions switch back to guest storage; orphaned guest copies are cleared.
*/
export async function prepareAuthScreenSession(
authClient: AuthClient,
activeAccountId: string | null,
clearActiveAccount: () => Promise<void>,
): Promise<void> {
const session = await authClient.getSession();
if (session.data?.user) return;
if (activeAccountId) {
await clearAuthStorage(authStoragePrefix(activeAccountId));
await clearActiveAccount();
}
await prepareForAdditionalSignIn();
}
+15 -2
View File
@@ -66,14 +66,23 @@ export async function readStoredSessionUser(prefix: string): Promise<{
}
}
export async function migrateAuthStorage(fromPrefix: string, toPrefix: string): Promise<void> {
export async function migrateAuthStorage(
fromPrefix: string,
toPrefix: string,
options: { clearSource?: boolean } = {},
): Promise<void> {
if (fromPrefix === toPrefix) return;
const clearSource = options.clearSource ?? true;
await Promise.all(
AUTH_STORAGE_SUFFIXES.map((suffix) =>
copySecureStoreEntry(storageKeyForPrefix(fromPrefix, suffix), storageKeyForPrefix(toPrefix, suffix)),
),
);
if (clearSource) {
await clearAuthStorage(fromPrefix);
}
}
export async function clearAuthStorage(prefix: string): Promise<void> {
@@ -122,7 +131,11 @@ export async function finalizeAuthenticatedAccount(input: {
? authStoragePrefix(input.activeAccountId)
: GUEST_AUTH_STORAGE_PREFIX;
await migrateAuthStorage(sourcePrefix, targetPrefix);
if (sourcePrefix !== targetPrefix) {
await clearAuthStorage(targetPrefix);
}
await migrateAuthStorage(sourcePrefix, targetPrefix, { clearSource: false });
await input.registerAccount({
instanceUrl: input.apiUrl,
+8 -2
View File
@@ -1,6 +1,6 @@
import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query";
import { isUnauthorizedError } from "@/lib/trpc-errors";
import { isRateLimitError, isUnauthorizedError } from "@/lib/trpc-errors";
export function createAppQueryClient(onUnauthorized: () => void) {
const handleError = (error: unknown) => {
@@ -16,7 +16,13 @@ export function createAppQueryClient(onUnauthorized: () => void) {
queries: {
staleTime: 30_000,
retry: (failureCount, error) => {
if (isUnauthorizedError(error)) return false;
if (isUnauthorizedError(error) || isRateLimitError(error)) return false;
return failureCount < 1;
},
},
mutations: {
retry: (failureCount, error) => {
if (isRateLimitError(error)) return false;
return failureCount < 1;
},
},
+6 -1
View File
@@ -7,7 +7,11 @@ type RunningEntry = {
description: string;
startedAt: Date | string;
client?: { name: string } | null;
invoice?: { invoicePrefix: string | null; invoiceNumber: string } | null;
invoice?: {
invoicePrefix: string | null;
invoiceNumber: string;
business?: { name: string } | null;
} | null;
};
type LiveActivityHandle = {
@@ -64,6 +68,7 @@ export function buildTimeClockActivityProps(
}),
description: resolveClockDescription(running.description),
clientName: running.client?.name ?? "",
businessName: invoice?.business?.name ?? "",
invoiceLabel: invoice
? `${invoice.invoicePrefix ?? "#"}${invoice.invoiceNumber}`
: "",
+1
View File
@@ -9,5 +9,6 @@ export type TimeClockActivityProps = {
clockTime: string;
description: string;
clientName: string;
businessName: string;
invoiceLabel: string;
};
+116 -3
View File
@@ -1,8 +1,121 @@
import { TRPCClientError } from "@trpc/client";
export function isUnauthorizedError(error: unknown): boolean {
function errorMessage(error: unknown): string {
if (error instanceof TRPCClientError) return error.message;
if (error instanceof Error) return error.message;
if (typeof error === "object" && error !== null && "message" in error) {
const message = (error as { message: unknown }).message;
if (typeof message === "string") return message;
}
return "";
}
function errorStatus(error: unknown): number | undefined {
if (typeof error !== "object" || error === null || !("status" in error)) return undefined;
const status = (error as { status: unknown }).status;
return typeof status === "number" ? status : undefined;
}
export function parseRetryAfterSeconds(value: string | number | null | undefined): number | null {
if (value == null || value === "") return null;
const seconds = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(seconds) || seconds <= 0) return null;
return Math.ceil(seconds);
}
export function isRateLimitError(error: unknown): boolean {
if (errorStatus(error) === 429) return true;
if (error instanceof TRPCClientError && error.data?.code === "TOO_MANY_REQUESTS") {
return true;
}
const message = errorMessage(error).toLowerCase();
return (
error instanceof TRPCClientError &&
(error.data?.code === "UNAUTHORIZED" || error.message === "UNAUTHORIZED")
message.includes("too many") ||
message.includes("rate limit") ||
message.includes("try again later")
);
}
export function isUnauthorizedError(error: unknown): boolean {
if (isRateLimitError(error)) return false;
if (error instanceof TRPCClientError) {
if (error.data?.code === "UNAUTHORIZED") return true;
}
if (errorStatus(error) === 401) return true;
const message = errorMessage(error).toLowerCase();
return message === "unauthorized" || message.includes("not authenticated");
}
export function formatRateLimitMessage(retryAfterSeconds?: number | null): string {
const retryAfter = parseRetryAfterSeconds(retryAfterSeconds ?? null);
if (retryAfter != null) {
if (retryAfter < 60) {
return `Too many attempts. Wait ${retryAfter} second${retryAfter === 1 ? "" : "s"} and try again.`;
}
const minutes = Math.ceil(retryAfter / 60);
return `Too many attempts. Wait about ${minutes} minute${minutes === 1 ? "" : "s"} and try again.`;
}
return "Too many attempts. Please wait a moment and try again.";
}
export function formatTrpcErrorMessage(error: unknown, fallback = "Something went wrong"): string {
if (isRateLimitError(error)) {
return formatRateLimitMessage();
}
if (isUnauthorizedError(error)) {
return "Your session expired. Sign in again to continue.";
}
if (error instanceof TRPCClientError) {
return error.message || fallback;
}
if (error instanceof Error) {
return error.message || fallback;
}
return fallback;
}
type AuthLikeError = {
message?: string;
status?: number;
};
export function formatAuthErrorMessage(error: AuthLikeError | null | undefined): string {
if (!error) return "Something went wrong";
if (isRateLimitError(error)) {
return formatRateLimitMessage();
}
const message = error.message ?? "";
if (message.toLowerCase().includes("internal") || message.includes("500")) {
return "Server error — is the API running with Postgres? Check beenvoice dev + docker.";
}
return message || "Invalid email or password";
}
export async function readHttpErrorMessage(response: Response): Promise<string> {
if (response.status === 429) {
const retryAfter = parseRetryAfterSeconds(
response.headers.get("x-retry-after") ?? response.headers.get("retry-after"),
);
return formatRateLimitMessage(retryAfter);
}
const data = (await response.json().catch(() => ({}))) as {
error?: string;
message?: string;
};
const message = data.error ?? data.message;
if (message && isRateLimitError({ message, status: response.status })) {
return formatRateLimitMessage();
}
return message ?? "Something went wrong";
}
+50 -10
View File
@@ -1,25 +1,65 @@
import { httpBatchLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { useCallback, useRef, useState, type ReactNode } from "react";
import {
useCallback,
useEffect,
useRef,
useState,
type ReactNode,
} from "react";
import SuperJSON from "superjson";
import { useAccounts } from "@/contexts/AccountsContext";
import { useAuthClient, useSession } from "@/contexts/AuthContext";
import { getAuthCookieHeaders } from "@/lib/auth-cookie";
import { performAuthReset } from "@/lib/auth-session";
import { createAppQueryClient } from "@/lib/query-client";
import type { AppRouter } from "beenvoice/server/api/root";
export const api = createTRPCReact<AppRouter>();
export function TRPCProvider({ apiUrl, children }: { apiUrl: string; children: ReactNode }) {
export function TRPCProvider({
apiUrl,
children,
}: {
apiUrl: string;
children: ReactNode;
}) {
const authClient = useAuthClient();
const { authStoragePrefix, activeAccountId, clearActiveAccount } =
useAccounts();
const { refetch } = useSession();
const authStoragePrefixRef = useRef(authStoragePrefix);
authStoragePrefixRef.current = authStoragePrefix;
const mountedRef = useRef(true);
const resettingRef = useRef(false);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const handleUnauthorized = useCallback(async () => {
if (!activeAccountId || resettingRef.current || !mountedRef.current) return;
const session = await authClient.getSession();
if (!session.data?.user) {
await authClient.signOut();
await refetch();
if (session.data?.user || !mountedRef.current) return;
resettingRef.current = true;
try {
await performAuthReset({
authClient,
clearActiveAccount,
activeAccountId,
refetchSession: refetch,
});
} finally {
resettingRef.current = false;
}
}, [authClient, refetch]);
}, [authClient, clearActiveAccount, activeAccountId, refetch]);
const onUnauthorizedRef = useRef(handleUnauthorized);
onUnauthorizedRef.current = handleUnauthorized;
@@ -37,10 +77,10 @@ export function TRPCProvider({ apiUrl, children }: { apiUrl: string; children: R
url: `${apiUrl}/api/trpc`,
transformer: SuperJSON,
headers() {
const cookie = (
authClient as { getCookie?: () => string | null | undefined }
).getCookie?.();
return cookie ? { cookie } : {};
return getAuthCookieHeaders(
authClient,
authStoragePrefixRef.current,
);
},
}),
],
+104
View File
@@ -0,0 +1,104 @@
// @ts-check
const { createRunOncePlugin, withDangerousMod } = require("@expo/config-plugins");
const fs = require("fs");
const path = require("path");
const pkg = require("expo-mlkit-ocr/package.json");
const DISABLE_LINE = "ENV['EXPO_MLKIT_OCR_DISABLE_MLKIT'] = '1'";
const MARKER = "expo-mlkit-ocr: iOS Simulator MLKit handling";
function resolveIosEngine(props = {}) {
const raw = props.iosEngine ?? "auto";
return raw === "auto" || raw === "mlkit" || raw === "vision" ? raw : "auto";
}
function stripMarkedBlock(podfile) {
const lines = podfile.split(/\r?\n/);
const next = [];
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
if (!line.includes(MARKER)) {
next.push(line);
continue;
}
const markerIndent = (line.match(/^\s*/) ?? [""])[0].length;
while (i + 1 < lines.length) {
i += 1;
const candidate = lines[i];
const candidateIndent = (candidate.match(/^\s*/) ?? [""])[0].length;
if (candidate.trim() === "end" && candidateIndent <= markerIndent) {
break;
}
}
}
return next.join("\n");
}
function stripOrphanedMlkitArchPatch(podfile) {
return podfile
.replace(
/\n\s*end\s*\n\s*\n\s*installer\.aggregate_targets\.each do \|aggregate_target\|[\s\S]*?aggregate_target\.user_project\.save\s*\n\s*end\s*\n/g,
"\n",
)
.replace(
/\n\s*if ENV\['EXPO_MLKIT_OCR_DISABLE_MLKIT'\] == '1'\s*\n\s*installer\.pods_project\.targets\.each do \|target\|[\s\S]*?\n\s*end\s*\n/g,
"\n",
);
}
function insertDisableLine(podfile) {
const lines = podfile
.split(/\r?\n/)
.filter((line) => line.trim() !== DISABLE_LINE);
let insertAt = 0;
while (insertAt < lines.length && lines[insertAt].trim().startsWith("#")) {
insertAt += 1;
}
lines.splice(insertAt, 0, DISABLE_LINE);
return lines.join("\n");
}
/** @type {import('@expo/config-plugins').ConfigPlugin<{ iosEngine?: "auto" | "mlkit" | "vision", disableMlkitOnSimulator?: boolean }>} */
function withExpoMlkitOcrEnv(config, props = {}) {
return withDangerousMod(config, [
"ios",
async (config) => {
const podfilePath = path.join(config.modRequest.platformProjectRoot, "Podfile");
if (!fs.existsSync(podfilePath)) {
return config;
}
const iosEngine = resolveIosEngine(props);
const shouldDisableMlkit =
iosEngine !== "mlkit" || props.disableMlkitOnSimulator === true;
let podfile = fs.readFileSync(podfilePath, "utf8");
podfile = stripMarkedBlock(podfile);
podfile = stripOrphanedMlkitArchPatch(podfile);
if (shouldDisableMlkit) {
podfile = insertDisableLine(podfile);
} else {
podfile = podfile
.split(/\r?\n/)
.filter((line) => line.trim() !== DISABLE_LINE)
.join("\n");
}
fs.writeFileSync(podfilePath, podfile.endsWith("\n") ? podfile : `${podfile}\n`);
return config;
},
]);
}
module.exports = createRunOncePlugin(
withExpoMlkitOcrEnv,
"beenvoice-expo-mlkit-ocr-env",
pkg.version,
);
+82
View File
@@ -0,0 +1,82 @@
// @ts-check
const fs = require("fs");
const path = require("path");
const { withDangerousMod } = require("@expo/config-plugins");
const widgetsPath = path.join("node_modules", "expo-widgets", "ios", "Widgets");
const liveActivityBannerSource = `import SwiftUI
import WidgetKit
import ActivityKit
@available(iOS 18.0, *)
struct LiveActivityBanner: View {
@Environment(\\.activityFamily) var activityFamily
var context: ActivityViewContext<LiveActivityAttributes>
var nodes: [String: Any]?
var body: some View {
if let nodes, let node = nodes["banner"] as? [String: Any] {
WidgetsDynamicView(name: context.activityID, kind: .liveActivity, node: node)
} else {
EmptyView()
}
}
}
`;
function patchWidgetLiveActivitySwift(source) {
const target = ` if #available(iOS 18.0, *) {
LiveActivityBanner(context: context, nodes: nodes)
} else if let node = nodes["banner"] as? [String: Any] {
WidgetsDynamicView(name: context.activityID, kind: .liveActivity, node: node)
} else {
EmptyView()
}`;
const framedTarget = ` if #available(iOS 18.0, *) {
LiveActivityBanner(context: context, nodes: nodes)
} else if let node = nodes["banner"] as? [String: Any] {
WidgetsDynamicView(name: context.activityID, kind: .liveActivity, node: node)
.frame(maxWidth: .infinity, alignment: .leading)
} else {
EmptyView()
}`;
const hardcodedBanner = ` if #available(iOS 18.0, *) {
LiveActivityBanner(context: context, nodes: nodes)
} else {
TimeClockNativeActivityBanner(context: context)
}`;
if (source.includes(target)) {
return source;
}
return source.replace(framedTarget, target).replace(hardcodedBanner, target);
}
/** @type {import('@expo/config-plugins').ConfigPlugin} */
function withLiveActivityBannerFrame(config) {
return withDangerousMod(config, [
"ios",
async (config) => {
const sourceDir = path.join(config.modRequest.projectRoot, widgetsPath);
const bannerPath = path.join(sourceDir, "LiveActivityBanner.swift");
const activityPath = path.join(sourceDir, "WidgetLiveActivity.swift");
if (!fs.existsSync(bannerPath) || !fs.existsSync(activityPath)) {
throw new Error(`Could not find expo-widgets live activity sources in ${sourceDir}`);
}
fs.writeFileSync(bannerPath, liveActivityBannerSource);
const activitySource = fs.readFileSync(activityPath, "utf8");
const patchedActivitySource = patchWidgetLiveActivitySwift(activitySource);
if (patchedActivitySource !== activitySource) {
fs.writeFileSync(activityPath, patchedActivitySource);
}
return config;
},
]);
}
module.exports = withLiveActivityBannerFrame;
+256
View File
@@ -0,0 +1,256 @@
// @ts-check
const fs = require("fs");
const path = require("path");
const { withDangerousMod } = require("@expo/config-plugins");
const dynamicViewPath = path.join(
"node_modules",
"expo-widgets",
"ios",
"Widgets",
"DynamicView.swift",
);
// expo-widgets rebuilds every WidgetsDynamicView child with a brand-new random UUID
// on every single render (see the original "Hack to satisfy ExpoSwiftUI.AnyChild"
// comment), so the `ForEach(props.children, id: \.id)` that HStack/VStack use to
// render their children sees a totally different identity set on each re-render.
// SwiftUI then treats every child as removed-and-reinserted instead of updated in
// place, which can make children silently fail to render whenever the parent's
// layout is recomputed (e.g. after a `.frame(maxWidth:)` change). This patch gives
// each child a stable identity derived from its structural position, cached across
// renders, so ForEach can correctly diff instead of thrashing.
const patchedSource = `import SwiftUI
import ExpoModulesCore
import ExpoUI
// TODO(@jakex7): Hack to satisfy ExpoSwiftUI.AnyChild with random UUID value
class NodeIdentityWrapper {
let id: UUID
init(id: UUID) {
self.id = id
}
}
// Reuses the same NodeIdentityWrapper for a given structural key across re-renders,
// so ForEach(id: \\.id) sees a stable identity instead of a fresh UUID every render.
private final class NodeIdentityCache {
static let shared = NodeIdentityCache()
private var wrappers: [String: NodeIdentityWrapper] = [:]
func wrapper(for key: String) -> NodeIdentityWrapper {
if let existing = wrappers[key] {
return existing
}
let created = NodeIdentityWrapper(id: UUID())
wrappers[key] = created
return created
}
}
extension ObjectIdentifier: @retroactive Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(String(describing: self))
}
}
public struct WidgetsDynamicView: View, ExpoSwiftUI.AnyChild {
let node: [String: Any]
let name: String
let kind: WidgetsKind
let entryIndex: Int?
let environmentString: String?
let childKey: String?
private var uuid: NodeIdentityWrapper {
guard let childKey else {
return NodeIdentityWrapper(id: UUID())
}
return NodeIdentityCache.shared.wrapper(for: childKey)
}
public var id: ObjectIdentifier {
ObjectIdentifier(uuid)
}
public init(name: String, kind: WidgetsKind, node: [String: Any]) {
self.name = name
self.kind = kind
self.node = node
self.entryIndex = nil
self.environmentString = nil
self.childKey = node["type"] as? String
}
public init(name: String, kind: WidgetsKind, node: [String: Any], entryIndex: Int?, environmentString: String?) {
self.name = name
self.kind = kind
self.node = node
self.entryIndex = entryIndex
self.environmentString = environmentString
self.childKey = node["type"] as? String
}
private init(name: String, kind: WidgetsKind, node: [String: Any], entryIndex: Int?, environmentString: String?, childKey: String) {
self.name = name
self.kind = kind
self.node = node
self.entryIndex = entryIndex
self.environmentString = environmentString
self.childKey = childKey
}
@ViewBuilder
public var body: some View {
switch node["type"] as? String {
case "TextView":
render(TextView.self, TextViewProps.self, updateProps: updateChildren)
case "HStackView":
render(HStackView.self, HStackViewProps.self, updateProps: updateChildren)
case "VStackView":
render(VStackView.self, VStackViewProps.self, updateProps: updateChildren)
case "ZStackView":
render(ZStackView.self, ZStackViewProps.self, updateProps: updateChildren)
case "RectangleView":
render(RectangleView.self, RectangleViewProps.self)
case "RoundedRectangleView":
render(RoundedRectangleView.self, RoundedRectangleViewProps.self)
case "CapsuleView":
render(CapsuleView.self, CapsuleViewProps.self)
case "CircleView":
render(CircleView.self, CircleViewProps.self)
case "ImageView":
render(ImageView.self, ImageViewProps.self)
case "AccessoryWidgetBackgroundView":
render(AccessoryWidgetBackgroundView.self, AccessoryWidgetBackgroundProps.self)
case "DividerView":
render(DividerView.self, DividerProps.self)
case "EllipseView":
render(EllipseView.self, EllipseViewProps.self)
case "LabelView":
render(LabelView.self, LabelViewProps.self)
case "ProgressView":
render(ProgressView.self, ProgressViewProps.self)
case "SpacerView":
render(SpacerView.self, SpacerViewProps.self)
case "UnevenRoundedRectangleView":
render(UnevenRoundedRectangleView.self, UnevenRoundedRectangleViewProps.self)
case "GaugeView":
render(GaugeView.self, GaugeProps.self)
case "ChartView":
render(ChartView.self, ChartProps.self)
case "Button":
if #available(iOS 17.0, *) {
switch kind {
case .widget:
render(WidgetButtonView.self, ButtonProps.self) { buttonProps in
try updateChildren(buttonProps)
buttonProps.source = name
buttonProps.entryIndex = entryIndex
buttonProps.environmentString = environmentString
}
case .liveActivity:
render(LiveActivityButtonView.self, ButtonProps.self) { buttonProps in
try updateChildren(buttonProps)
buttonProps.source = name
}
}
} else {
render(ExpoUI.Button.self, ExpoUI.ButtonProps.self, updateProps: updateChildren)
}
case "react.fragment":
render(FragmentView.self, FragmentProps.self, updateProps: updateChildren)
case "LinkView":
render(LinkView.self, LinkViewProps.self, updateProps: updateChildren)
#if DEBUG
case "RedBoxView":
render(RedBoxView.self, RedBoxViewProps.self) { redBoxProps in
redBoxProps.source = name
redBoxProps.kind = kind
}
default:
ZStack {
Color.red.opacity(0.5)
Text("Unable to get the view for: \\(node["type"] as? String ?? "undefined")")
}
#else
default:
EmptyView()
#endif
}
}
// MARK: - Render Method
@ViewBuilder
private func render<P, V>(_ viewType: V.Type, _ propsType: P.Type, updateProps: ((_ initialProps: P) throws -> Void)? = nil) -> some View
where P: UIBaseViewProps, V: ExpoSwiftUI.View, V.Props == P {
// immediately invoked closure {}() here because we can't use 'do-catch' inside @ViewBuilder
{
do {
if let rawProps = node["props"] as? [String: Any] {
let props = try propsType.init(rawProps: rawProps, context: WidgetsContext.shared.context)
try updateProps?(props)
return AnyView(UIBaseView<P, V>(props: props).transition(.identity))
}
return AnyView(EmptyView())
} catch {
return AnyView(EmptyView())
}
}()
}
// MARK: - Function that sets children as DynamicView
private func updateChildren<P>(_ initialProps: P) throws
where P: UIBaseViewProps {
let baseKey = childKey ?? (node["type"] as? String ?? "root")
if let props = node["props"] as? [String: Any] {
if let children = props["children"] as? [Any] {
let validChildren = children.compactMap { $0 as? [String: Any] }
initialProps.children = validChildren.enumerated().map { index, childNode in
let childType = childNode["type"] as? String ?? "unknown"
return WidgetsDynamicView(
name: name,
kind: kind,
node: childNode,
entryIndex: entryIndex,
environmentString: environmentString,
childKey: "\\(baseKey).\\(index).\\(childType)"
)
}
} else if let child = props["children"] as? [String: Any] {
let childType = child["type"] as? String ?? "unknown"
initialProps.children = [WidgetsDynamicView(
name: name,
kind: kind,
node: child,
entryIndex: entryIndex,
environmentString: environmentString,
childKey: "\\(baseKey).0.\\(childType)"
)]
}
}
}
}
`;
/** @type {import('@expo/config-plugins').ConfigPlugin} */
function withStableWidgetsChildIdentity(config) {
return withDangerousMod(config, [
"ios",
async (config) => {
const filePath = path.join(config.modRequest.projectRoot, dynamicViewPath);
if (!fs.existsSync(filePath)) {
throw new Error(`Could not find expo-widgets DynamicView.swift at ${filePath}`);
}
fs.writeFileSync(filePath, patchedSource);
return config;
},
]);
}
module.exports = withStableWidgetsChildIdentity;
+69 -87
View File
@@ -1,7 +1,9 @@
import { HStack, Image, Spacer, Text } from "@expo/ui/swift-ui";
import { HStack, Image, Text, VStack } from "@expo/ui/swift-ui";
import {
frame,
font,
foregroundStyle,
layoutPriority,
lineLimit,
minimumScaleFactor,
monospacedDigit,
@@ -12,120 +14,100 @@ import { createLiveActivity, type LiveActivityEnvironment } from "expo-widgets";
import type { TimeClockActivityProps } from "@/lib/time-clock-live-activity.types";
const TIMER_HORIZON_MS = 24 * 60 * 60 * 1000;
function liveTimer(
startedAtMs: number,
modifiers: ReturnType<typeof font>[],
) {
const lower = new Date(startedAtMs);
const upper = new Date(startedAtMs + TIMER_HORIZON_MS);
return (
<Text
timerInterval={{ lower, upper }}
countsDown={false}
modifiers={modifiers}
/>
);
}
function TimeClockActivity(props: TimeClockActivityProps, _environment: LiveActivityEnvironment) {
"widget";
const green = "green";
const title = props.description.trim() || "Clock In";
const clientLabel = props.clientName.trim() || title;
const subtitle = props.invoiceLabel.trim();
const startedAtMs = props.startedAtMs > 0 ? props.startedAtMs : Date.now();
const island = "#FFFFFF";
const businessLabel = props.businessName.trim();
const clientLabel = props.clientName.trim();
const title = clientLabel || businessLabel || "Clock In";
const timerMods = [
font({ design: "monospaced", weight: "bold", size: 20 }),
monospacedDigit(),
foregroundStyle(green),
font({ weight: "bold", size: 17 }),
foregroundStyle({ type: "hierarchical", style: "primary" }),
lineLimit(1),
minimumScaleFactor(0.85),
minimumScaleFactor(0.75),
layoutPriority(2),
frame({ width: 100, alignment: "center" }),
];
const compactTimerMods = [
font({ design: "monospaced", weight: "semibold", size: 11 }),
monospacedDigit(),
foregroundStyle(green),
foregroundStyle(island),
lineLimit(1),
minimumScaleFactor(0.8),
minimumScaleFactor(0.75),
frame({ minWidth: 38, alignment: "center" }),
layoutPriority(2),
];
const clientMods = [
font({ weight: "semibold", size: 13 }),
font({ weight: "bold", size: 17 }),
foregroundStyle({ type: "hierarchical", style: "primary" }),
lineLimit(1),
minimumScaleFactor(0.85),
minimumScaleFactor(0.75),
];
const subtitleMods = [
font({ size: 11 }),
foregroundStyle({ type: "hierarchical", style: "secondary" }),
lineLimit(1),
minimumScaleFactor(0.85),
// Avoid greedy layout primitives here: the live timerInterval Text can
// collapse when paired with Spacer/maxWidth. Fixed centered boxes keep the
// content stable without forcing left/right edge alignment.
const titleRowMods = [
layoutPriority(1),
frame({ width: 140, alignment: "center" }),
];
const sideZoneMods = [
frame({ width: 100, alignment: "center" }),
];
const bannerRowMods = [
padding({ horizontal: 10, vertical: 10 }),
frame({ maxWidth: Infinity, alignment: "center" }),
];
const bannerTimer = liveTimer(startedAtMs, timerMods);
const compactTimer = liveTimer(startedAtMs, compactTimerMods);
return {
banner: (
<HStack alignment="center" spacing={8} modifiers={[padding({ horizontal: 14, vertical: 12 })]}>
const bannerTimer = <Text modifiers={timerMods}>{props.elapsedShort}</Text>;
const compactTimer = <Text modifiers={compactTimerMods}>{props.elapsedShort}</Text>;
const logoLarge = (
<Image
assetName="SplashScreenLogo"
systemName="dollarsign.circle.fill"
size={22}
modifiers={[
foregroundStyle({ type: "hierarchical", style: "primary" }),
frame({ width: 22, height: 22 }),
widgetAccentedRenderingMode("fullColor"),
]}
/>
);
const logoSmall = (
<Image
systemName="dollarsign.circle.fill"
color={green}
size={22}
modifiers={[widgetAccentedRenderingMode("fullColor")]}
color={island}
size={14}
modifiers={[frame({ width: 14, height: 14 }), widgetAccentedRenderingMode("fullColor")]}
/>
<Text modifiers={clientMods}>{clientLabel}</Text>
<Spacer minLength={12} />
);
return {
banner: (
<HStack alignment="center" spacing={8} modifiers={bannerRowMods}>
<VStack alignment="center" modifiers={sideZoneMods}>
{logoLarge}
</VStack>
<VStack alignment="center" spacing={1} modifiers={titleRowMods}>
<Text modifiers={clientMods}>{title}</Text>
</VStack>
{bannerTimer}
</HStack>
),
bannerSmall: (
<HStack alignment="center" spacing={8} modifiers={[padding({ horizontal: 12, vertical: 10 })]}>
<Image
systemName="dollarsign.circle.fill"
color={green}
size={18}
modifiers={[widgetAccentedRenderingMode("fullColor")]}
/>
<Text modifiers={clientMods}>{clientLabel}</Text>
<Spacer minLength={8} />
{compactTimer}
<HStack alignment="center" spacing={8} modifiers={bannerRowMods}>
<VStack alignment="center" modifiers={sideZoneMods}>
{logoLarge}
</VStack>
<VStack alignment="center" spacing={1} modifiers={titleRowMods}>
<Text modifiers={clientMods}>{title}</Text>
</VStack>
{bannerTimer}
</HStack>
),
compactLeading: (
<Image
systemName="dollarsign.circle.fill"
color={green}
size={15}
modifiers={[widgetAccentedRenderingMode("fullColor")]}
/>
),
compactLeading: logoSmall,
compactTrailing: compactTimer,
minimal: (
<Image
systemName="dollarsign.circle.fill"
color={green}
size={12}
modifiers={[widgetAccentedRenderingMode("fullColor")]}
/>
),
expandedLeading: (
<Image
systemName="dollarsign.circle.fill"
color={green}
size={20}
modifiers={[widgetAccentedRenderingMode("fullColor")]}
/>
),
expandedCenter: <Text modifiers={clientMods}>{clientLabel}</Text>,
expandedTrailing: bannerTimer,
expandedBottom: (
<Text modifiers={subtitleMods}>{subtitle || "beenvoice"}</Text>
),
minimal: logoSmall,
};
}