Per-user auth via Nextcloud Login Flow v2, Tailwind UI rewrite
- auth.py/auth_routes.py: Login Flow v2 (verified against real NC source/docs) - no OAuth2 client registration needed, backend polls server-side so no CORS issues. Sessions are hashed-token cookies; NC app passwords encrypted at rest (Fernet). Every /api/* route guarded by a blueprint-wide before_request, not per-route decorators, so future routes are protected by default. - receipts/groups scoped per owner_nc_user_id; cross-user access 404s. - nc_client/cospend_client take (username, app_password) per call instead of one shared global credential - each user's uploads/shares/ bills now happen as themselves. - Frontend: LoginGate component drives the login flow (open NC login in a new tab, poll our backend, done). - Merged the old separate review step into the split screen, redesigned with Tailwind (was unstyled/broken), default-excluded-per-item splitting with one-click "include everyone" fixed, DD.MM.YYYY date field, receipt-icon branding. - Dropped LLM bounding-box highlighting - unreliable on real receipts, plain photo upload instead. - Only mention who a bill is split with in its title when there's more than one bill off the same receipt to disambiguate.
This commit is contained in:
@@ -1,199 +0,0 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #fafafa;
|
||||
--fg: #1a1a1a;
|
||||
--accent: #2b6cb0;
|
||||
--border: #ddd;
|
||||
--danger: #c0392b;
|
||||
--selected: #e3f0ff;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #17181a;
|
||||
--fg: #eee;
|
||||
--border: #3a3a3a;
|
||||
--selected: #1c3350;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font-family:
|
||||
system-ui,
|
||||
-apple-system,
|
||||
'Segoe UI',
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
.app {
|
||||
max-width: 480px;
|
||||
margin: 0 auto;
|
||||
padding: 1rem 1rem 3rem;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.step h1,
|
||||
.step h2 {
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: #888;
|
||||
font-size: 0.9rem;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.9rem;
|
||||
margin: 0.75rem 0;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background: transparent;
|
||||
color: var(--accent);
|
||||
border: 1px solid var(--accent);
|
||||
}
|
||||
|
||||
button.icon-btn {
|
||||
width: auto;
|
||||
padding: 0.4rem 0.6rem;
|
||||
margin: 0;
|
||||
background: transparent;
|
||||
color: var(--danger);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
padding: 0.6rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.meta-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
|
||||
.meta-row label {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: 0.85rem;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.item-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.item-row {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.item-row input[type='text'],
|
||||
.item-row input:not([type]) {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.item-row input[type='number'] {
|
||||
width: 5.5rem;
|
||||
}
|
||||
|
||||
.item-list.selectable li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 0.7rem 0.75rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 0.4rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.item-list.selectable li.selected {
|
||||
background: var(--selected);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.member-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.member-list label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 0.35rem 0.75rem;
|
||||
}
|
||||
|
||||
.payer-select {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.group-name {
|
||||
width: 100%;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.total {
|
||||
font-weight: 600;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.submitted-groups {
|
||||
background: var(--selected);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.summary-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.summary-list li {
|
||||
padding: 0.6rem 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
+32
-31
@@ -1,52 +1,53 @@
|
||||
import { useState } from 'react'
|
||||
import './App.css'
|
||||
import { CaptureStep } from './components/CaptureStep'
|
||||
import { ReviewStep } from './components/ReviewStep'
|
||||
import { GroupStep } from './components/GroupStep'
|
||||
import { LoginGate } from './components/LoginGate'
|
||||
import { SummaryStep } from './components/SummaryStep'
|
||||
import type { Group, Item } from './types'
|
||||
|
||||
type Stage =
|
||||
| { name: 'capture' }
|
||||
| { name: 'review'; receiptId: string; items: Item[]; storeName: string | null; date: string }
|
||||
| { name: 'group'; receiptId: string; items: Item[] }
|
||||
| { name: 'group'; receiptId: string; items: Item[]; storeName: string | null; date: string }
|
||||
| { name: 'summary'; groups: Group[] }
|
||||
|
||||
export default function App() {
|
||||
const [stage, setStage] = useState<Stage>({ name: 'capture' })
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
{stage.name === 'capture' && (
|
||||
<CaptureStep
|
||||
onExtracted={(receiptId, items, storeName, date) =>
|
||||
setStage({ name: 'review', receiptId, items, storeName, date: date || today() })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<LoginGate>
|
||||
{({ ncUserId, logout }) => (
|
||||
<div className="mx-auto min-h-screen max-w-2xl px-4 pb-16 pt-8 sm:px-6">
|
||||
<div className="mb-4 flex items-center justify-end gap-2 text-xs text-neutral-400">
|
||||
<span>{ncUserId}</span>
|
||||
<button onClick={logout} className="underline hover:text-neutral-600 dark:hover:text-neutral-200">
|
||||
log out
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{stage.name === 'review' && (
|
||||
<ReviewStep
|
||||
receiptId={stage.receiptId}
|
||||
initialItems={stage.items}
|
||||
initialStoreName={stage.storeName}
|
||||
initialDate={stage.date}
|
||||
onConfirmed={(items) => setStage({ name: 'group', receiptId: stage.receiptId, items })}
|
||||
/>
|
||||
)}
|
||||
{stage.name === 'capture' && (
|
||||
<CaptureStep
|
||||
onExtracted={(receiptId, items, storeName, date) =>
|
||||
setStage({ name: 'group', receiptId, items, storeName, date: date || today() })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{stage.name === 'group' && (
|
||||
<GroupStep
|
||||
receiptId={stage.receiptId}
|
||||
items={stage.items}
|
||||
onAllDone={(groups) => setStage({ name: 'summary', groups })}
|
||||
/>
|
||||
)}
|
||||
{stage.name === 'group' && (
|
||||
<GroupStep
|
||||
receiptId={stage.receiptId}
|
||||
initialItems={stage.items}
|
||||
initialStoreName={stage.storeName}
|
||||
initialDate={stage.date}
|
||||
onAllDone={(groups) => setStage({ name: 'summary', groups })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{stage.name === 'summary' && (
|
||||
<SummaryStep groups={stage.groups} onRestart={() => setStage({ name: 'capture' })} />
|
||||
{stage.name === 'summary' && (
|
||||
<SummaryStep groups={stage.groups} onRestart={() => setStage({ name: 'capture' })} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</LoginGate>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+43
-12
@@ -2,11 +2,19 @@ import type { CospendProject, Group, Item, Member, Receipt, SubmitResult } from
|
||||
|
||||
const BASE = import.meta.env.VITE_API_BASE_URL ?? ''
|
||||
|
||||
export class UnauthorizedError extends Error {}
|
||||
|
||||
async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${BASE}/api${path}`, {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
...init,
|
||||
// Auth is a cookie now (see auth.py) - needed even same-origin-via-proxy
|
||||
// in dev, and required for a cross-origin prod deployment.
|
||||
credentials: 'include',
|
||||
headers: init?.body instanceof FormData ? init.headers : { 'Content-Type': 'application/json', ...init?.headers },
|
||||
})
|
||||
if (res.status === 401) {
|
||||
throw new UnauthorizedError('not logged in')
|
||||
}
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body.error || `${res.status} ${res.statusText}`)
|
||||
@@ -15,52 +23,75 @@ async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
}
|
||||
|
||||
export const api = {
|
||||
getMe(): Promise<{ nc_user_id: string }> {
|
||||
return req('/api/me')
|
||||
},
|
||||
|
||||
authStart(): Promise<{ flow_id: string; login_url: string }> {
|
||||
return req('/auth/login/start', { method: 'POST' })
|
||||
},
|
||||
|
||||
authPoll(
|
||||
flowId: string,
|
||||
): Promise<{ status: 'pending' | 'expired' | 'done'; nc_user_id?: string }> {
|
||||
return req(`/auth/login/poll?flow_id=${encodeURIComponent(flowId)}`)
|
||||
},
|
||||
|
||||
logout(): Promise<{ status: string }> {
|
||||
return req('/auth/logout', { method: 'POST' })
|
||||
},
|
||||
|
||||
uploadReceipt(
|
||||
file: File | Blob,
|
||||
): Promise<{ id: string; items: Item[]; store_name: string | null; date: string }> {
|
||||
const form = new FormData()
|
||||
form.append('image', file, 'receipt.jpg')
|
||||
return req('/receipts', { method: 'POST', body: form })
|
||||
return req('/api/receipts', { method: 'POST', body: form })
|
||||
},
|
||||
|
||||
getReceipt(id: string): Promise<Receipt> {
|
||||
return req(`/receipts/${id}`)
|
||||
return req(`/api/receipts/${id}`)
|
||||
},
|
||||
|
||||
updateItems(id: string, items: Item[]): Promise<Receipt> {
|
||||
return req(`/receipts/${id}/items`, { method: 'PATCH', body: JSON.stringify({ items }) })
|
||||
return req(`/api/receipts/${id}/items`, { method: 'PATCH', body: JSON.stringify({ items }) })
|
||||
},
|
||||
|
||||
updateMeta(id: string, meta: { store_name?: string; date?: string }): Promise<Receipt> {
|
||||
return req(`/receipts/${id}/meta`, { method: 'PATCH', body: JSON.stringify(meta) })
|
||||
return req(`/api/receipts/${id}/meta`, { method: 'PATCH', body: JSON.stringify(meta) })
|
||||
},
|
||||
|
||||
getProjects(): Promise<{ projects: CospendProject[]; default_project_id: string | null }> {
|
||||
return req('/cospend/projects')
|
||||
return req('/api/cospend/projects')
|
||||
},
|
||||
|
||||
getMembers(projectId: string): Promise<Member[]> {
|
||||
return req(`/cospend/projects/${projectId}/members`)
|
||||
async getMembers(projectId: string): Promise<Member[]> {
|
||||
// Cospend returns member ids as JSON numbers; normalize to strings here
|
||||
// so every consumer downstream can rely on the Member/Group types'
|
||||
// `string` id fields actually being strings, not silently numbers.
|
||||
const raw = await req<Array<{ id: number | string; name: string }>>(
|
||||
`/api/cospend/projects/${projectId}/members`,
|
||||
)
|
||||
return raw.map((m) => ({ id: String(m.id), name: m.name }))
|
||||
},
|
||||
|
||||
createGroup(
|
||||
receiptId: string,
|
||||
group: {
|
||||
name: string
|
||||
cospend_project_id: string
|
||||
payer_member_id: string
|
||||
member_ids: string[]
|
||||
item_ids: string[]
|
||||
},
|
||||
): Promise<{ id: string }> {
|
||||
return req(`/receipts/${receiptId}/groups`, { method: 'POST', body: JSON.stringify(group) })
|
||||
return req(`/api/receipts/${receiptId}/groups`, { method: 'POST', body: JSON.stringify(group) })
|
||||
},
|
||||
|
||||
submitGroup(receiptId: string, groupId: string): Promise<SubmitResult> {
|
||||
return req(`/receipts/${receiptId}/groups/${groupId}/submit`, { method: 'POST' })
|
||||
return req(`/api/receipts/${receiptId}/groups/${groupId}/submit`, { method: 'POST' })
|
||||
},
|
||||
|
||||
listGroups(receiptId: string): Promise<Group[]> {
|
||||
return req(`/receipts/${receiptId}/groups`)
|
||||
return req(`/api/receipts/${receiptId}/groups`)
|
||||
},
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 8.5 KiB |
@@ -1,4 +1,5 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { CiReceipt } from 'react-icons/ci'
|
||||
import { api } from '../api'
|
||||
import type { Item } from '../types'
|
||||
|
||||
@@ -10,6 +11,7 @@ export function CaptureStep({ onExtracted }: Props) {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [dragging, setDragging] = useState(false)
|
||||
|
||||
async function handleFile(file: File | undefined) {
|
||||
if (!file) return
|
||||
@@ -25,10 +27,33 @@ export function CaptureStep({ onExtracted }: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
function onDrop(e: React.DragEvent<HTMLDivElement>) {
|
||||
e.preventDefault()
|
||||
setDragging(false)
|
||||
const file = [...e.dataTransfer.files].find((f) => f.type.startsWith('image/'))
|
||||
handleFile(file)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="step capture-step">
|
||||
<h1>wgBill</h1>
|
||||
<p>Take a photo of the receipt to get started.</p>
|
||||
<div
|
||||
className={`flex min-h-[70vh] flex-col items-center justify-center rounded-2xl border-2 border-dashed p-10 text-center transition-colors ${
|
||||
dragging
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-950/30'
|
||||
: 'border-transparent'
|
||||
}`}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
setDragging(true)
|
||||
}}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<CiReceipt className="h-16 w-16 text-blue-600 dark:text-blue-400" />
|
||||
<h1 className="mt-2 text-3xl font-bold tracking-tight">wgBill</h1>
|
||||
<p className="mt-2 text-neutral-500 dark:text-neutral-400">
|
||||
Take a photo of the receipt to get started.
|
||||
</p>
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
@@ -37,10 +62,19 @@ export function CaptureStep({ onExtracted }: Props) {
|
||||
hidden
|
||||
onChange={(e) => handleFile(e.target.files?.[0])}
|
||||
/>
|
||||
<button disabled={loading} onClick={() => inputRef.current?.click()}>
|
||||
<button
|
||||
disabled={loading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="mt-6 w-full max-w-xs rounded-xl bg-blue-600 px-6 py-3 font-semibold text-white shadow-sm transition hover:bg-blue-500 disabled:opacity-50 sm:w-auto"
|
||||
>
|
||||
{loading ? 'Reading receipt…' : 'Take photo'}
|
||||
</button>
|
||||
{error && <p className="error">{error}</p>}
|
||||
|
||||
<p className="mt-4 text-sm text-neutral-400 dark:text-neutral-500">
|
||||
or drop an image anywhere on this page
|
||||
</p>
|
||||
|
||||
{error && <p className="mt-4 text-sm text-red-500">{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,31 +1,65 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { CiReceipt } from 'react-icons/ci'
|
||||
import { api } from '../api'
|
||||
import type { CospendProject, Group, Item, Member } from '../types'
|
||||
|
||||
// <input type="date">'s displayed format follows the browser/OS locale, not
|
||||
// anything we control from the page - so for a fixed DD.MM.YYYY display we
|
||||
// use a plain text field instead, converting to/from the ISO date the
|
||||
// backend expects.
|
||||
function isoToEu(iso: string): string {
|
||||
const [y, m, d] = iso.split('-')
|
||||
return y && m && d ? `${d}.${m}.${y}` : ''
|
||||
}
|
||||
function euToIso(eu: string): string | null {
|
||||
const match = /^(\d{1,2})\.(\d{1,2})\.(\d{4})$/.exec(eu.trim())
|
||||
if (!match) return null
|
||||
const [, d, m, y] = match
|
||||
return `${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`
|
||||
}
|
||||
|
||||
interface Props {
|
||||
receiptId: string
|
||||
items: Item[]
|
||||
initialItems: Item[]
|
||||
initialStoreName: string | null
|
||||
initialDate: string
|
||||
onAllDone: (groups: Group[]) => void
|
||||
}
|
||||
|
||||
export function GroupStep({ receiptId, items, onAllDone }: Props) {
|
||||
/** One computed bill: a distinct set of owers, and the items assigned to it. */
|
||||
interface Partition {
|
||||
memberIds: string[]
|
||||
items: Item[]
|
||||
total: number
|
||||
}
|
||||
|
||||
export function GroupStep({
|
||||
receiptId,
|
||||
initialItems,
|
||||
initialStoreName,
|
||||
initialDate,
|
||||
onAllDone,
|
||||
}: Props) {
|
||||
// --- receipt-level fields (was the separate "review" step) ---
|
||||
const [items, setItems] = useState<Item[]>(initialItems)
|
||||
const [storeName, setStoreName] = useState(initialStoreName ?? '')
|
||||
const [date, setDate] = useState(initialDate)
|
||||
const [dateText, setDateText] = useState(isoToEu(initialDate))
|
||||
|
||||
// --- cospend data ---
|
||||
const [projects, setProjects] = useState<CospendProject[]>([])
|
||||
const [projectId, setProjectId] = useState<string | null>(null)
|
||||
const [members, setMembers] = useState<Member[]>([])
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
|
||||
const [remainingIds, setRemainingIds] = useState<Set<string>>(new Set(items.map((i) => i.id)))
|
||||
const [groups, setGroups] = useState<Group[]>([])
|
||||
|
||||
// current draft
|
||||
const [name, setName] = useState('WG')
|
||||
const [payerId, setPayerId] = useState<string | null>(null)
|
||||
const [selectedMemberIds, setSelectedMemberIds] = useState<Set<string>>(new Set())
|
||||
const [selectedItemIds, setSelectedItemIds] = useState<Set<string>>(new Set())
|
||||
// itemId -> set of member ids splitting that item. Missing/empty = excluded.
|
||||
const [itemMembers, setItemMembers] = useState<Record<string, Set<string>>>({})
|
||||
const [customizing, setCustomizing] = useState<string | null>(null)
|
||||
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// load Cospend projects once, pick the configured default (or the only one)
|
||||
useEffect(() => {
|
||||
api
|
||||
.getProjects()
|
||||
@@ -37,78 +71,124 @@ export function GroupStep({ receiptId, items, onAllDone }: Props) {
|
||||
.catch((e) => setLoadError(e instanceof Error ? e.message : String(e)))
|
||||
}, [])
|
||||
|
||||
// load members whenever the selected project changes
|
||||
useEffect(() => {
|
||||
if (!projectId) return
|
||||
api
|
||||
.getMembers(projectId)
|
||||
.then((m) => {
|
||||
Promise.all([api.getMembers(projectId), api.getMe()])
|
||||
.then(([m, { nc_user_id }]) => {
|
||||
setMembers(m)
|
||||
if (m.length > 0) {
|
||||
setPayerId(m[0].id)
|
||||
setSelectedMemberIds(new Set(m.map((mm) => mm.id)))
|
||||
setPayerId(fuzzyMatchMember(m, nc_user_id)?.id ?? m[0].id)
|
||||
}
|
||||
})
|
||||
.catch((e) => setLoadError(e instanceof Error ? e.message : String(e)))
|
||||
}, [projectId])
|
||||
|
||||
function toggleItem(id: string) {
|
||||
setSelectedItemIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.has(id) ? next.delete(id) : next.add(id)
|
||||
const allMemberIds = useMemo(() => members.map((m) => m.id), [members])
|
||||
|
||||
function updateItem(id: string, patch: Partial<Item>) {
|
||||
setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)))
|
||||
}
|
||||
|
||||
function removeItem(id: string) {
|
||||
setItems((prev) => prev.filter((it) => it.id !== id))
|
||||
setItemMembers((prev) => {
|
||||
const next = { ...prev }
|
||||
delete next[id]
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
function toggleMember(id: string) {
|
||||
setSelectedMemberIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.has(id) ? next.delete(id) : next.add(id)
|
||||
function addItem() {
|
||||
const id = crypto.randomUUID()
|
||||
setItems((prev) => [...prev, { id, label: '', price: 0 }])
|
||||
}
|
||||
|
||||
function isIncluded(itemId: string) {
|
||||
return (itemMembers[itemId]?.size ?? 0) > 0
|
||||
}
|
||||
|
||||
/** The primary, one-click action: off -> everyone, on -> off. */
|
||||
function toggleIncluded(itemId: string) {
|
||||
setItemMembers((prev) => {
|
||||
const next = { ...prev }
|
||||
if (isIncluded(itemId)) {
|
||||
delete next[itemId]
|
||||
} else {
|
||||
next[itemId] = new Set(allMemberIds)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const remainingItems = items.filter((i) => remainingIds.has(i.id))
|
||||
const groupTotal = items
|
||||
.filter((i) => selectedItemIds.has(i.id))
|
||||
.reduce((sum, i) => sum + i.price, 0)
|
||||
function toggleItemMember(itemId: string, memberId: string) {
|
||||
setItemMembers((prev) => {
|
||||
const current = new Set(prev[itemId] ?? [])
|
||||
current.has(memberId) ? current.delete(memberId) : current.add(memberId)
|
||||
const next = { ...prev, [itemId]: current }
|
||||
if (current.size === 0) delete next[itemId]
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
async function submitCurrentGroup() {
|
||||
if (!projectId) {
|
||||
setError('pick a Cospend project')
|
||||
// Group included items by identical ower-set - each distinct set becomes
|
||||
// its own bill, since a Cospend bill can only have one split.
|
||||
const partitions: Partition[] = useMemo(() => {
|
||||
const byKey = new Map<string, Partition>()
|
||||
for (const item of items) {
|
||||
const memberSet = itemMembers[item.id]
|
||||
if (!memberSet || memberSet.size === 0) continue
|
||||
const memberIds = [...memberSet].sort()
|
||||
const key = memberIds.join(',')
|
||||
const existing = byKey.get(key)
|
||||
if (existing) {
|
||||
existing.items.push(item)
|
||||
existing.total += item.price
|
||||
} else {
|
||||
byKey.set(key, { memberIds, items: [item], total: item.price })
|
||||
}
|
||||
}
|
||||
return [...byKey.values()]
|
||||
}, [items, itemMembers])
|
||||
|
||||
const excludedCount = items.length - partitions.reduce((n, p) => n + p.items.length, 0)
|
||||
|
||||
function memberName(id: string) {
|
||||
return members.find((m) => m.id === id)?.name ?? id
|
||||
}
|
||||
|
||||
async function submitAll() {
|
||||
if (!projectId || !payerId) {
|
||||
setError('pick a Cospend project and who paid')
|
||||
return
|
||||
}
|
||||
if (!payerId || selectedMemberIds.size === 0 || selectedItemIds.size === 0) {
|
||||
setError('pick a payer, at least one member, and at least one item')
|
||||
if (partitions.length === 0) {
|
||||
setError('include at least one item')
|
||||
return
|
||||
}
|
||||
setSubmitting(true)
|
||||
setError(null)
|
||||
try {
|
||||
const { id: groupId } = await api.createGroup(receiptId, {
|
||||
name,
|
||||
cospend_project_id: projectId,
|
||||
payer_member_id: payerId,
|
||||
member_ids: [...selectedMemberIds],
|
||||
item_ids: [...selectedItemIds],
|
||||
})
|
||||
const result = await api.submitGroup(receiptId, groupId)
|
||||
const allGroups = await api.listGroups(receiptId)
|
||||
setGroups(allGroups)
|
||||
await api.updateItems(receiptId, items)
|
||||
await api.updateMeta(receiptId, { store_name: storeName, date })
|
||||
|
||||
setRemainingIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
selectedItemIds.forEach((id) => next.delete(id))
|
||||
return next
|
||||
})
|
||||
const wasLastGroup = remainingItems.length === selectedItemIds.size
|
||||
setSelectedItemIds(new Set())
|
||||
setName('WG')
|
||||
|
||||
if (wasLastGroup) {
|
||||
onAllDone(allGroups)
|
||||
// Create every group first, then submit - so by the time any of them
|
||||
// submits, the backend can see the receipt's real total bill count
|
||||
// (and only mention who's splitting it in the title when there's more
|
||||
// than one bill to tell apart).
|
||||
const groupIds: string[] = []
|
||||
for (const partition of partitions) {
|
||||
const { id: groupId } = await api.createGroup(receiptId, {
|
||||
cospend_project_id: projectId,
|
||||
payer_member_id: payerId,
|
||||
member_ids: partition.memberIds,
|
||||
item_ids: partition.items.map((i) => i.id),
|
||||
})
|
||||
groupIds.push(groupId)
|
||||
}
|
||||
void result
|
||||
for (const groupId of groupIds) {
|
||||
await api.submitGroup(receiptId, groupId)
|
||||
}
|
||||
onAllDone(await api.listGroups(receiptId))
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
@@ -117,108 +197,220 @@ export function GroupStep({ receiptId, items, onAllDone }: Props) {
|
||||
}
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<div className="step">
|
||||
<p className="error">Couldn't load Cospend data: {loadError}</p>
|
||||
</div>
|
||||
)
|
||||
return <p className="mt-8 text-center text-red-500">Couldn't load Cospend data: {loadError}</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="step group-step">
|
||||
<h2>Who's splitting this?</h2>
|
||||
<p className="hint">
|
||||
Select the items for one splitting arrangement, pick who's in on it, submit. Repeat for
|
||||
any items that need a different group (e.g. only your snack).
|
||||
</p>
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<CiReceipt className="h-8 w-8 shrink-0 text-blue-600 dark:text-blue-400" />
|
||||
<h2 className="text-2xl font-bold">Split the receipt</h2>
|
||||
</div>
|
||||
|
||||
<label className="payer-select">
|
||||
Cospend project
|
||||
<select value={projectId ?? ''} onChange={(e) => setProjectId(e.target.value)}>
|
||||
<option value="" disabled>
|
||||
select a project…
|
||||
</option>
|
||||
{projects.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{groups.length > 0 && (
|
||||
<div className="submitted-groups">
|
||||
{groups.map((g) => (
|
||||
<p key={g.id}>
|
||||
✓ {g.name} bill created —{' '}
|
||||
<a href={g.share_url ?? '#'} target="_blank" rel="noreferrer">
|
||||
receipt
|
||||
</a>
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<input
|
||||
className="group-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="group name (e.g. WG, just me + Alex)"
|
||||
/>
|
||||
|
||||
<h3>Items ({remainingItems.length} left)</h3>
|
||||
<ul className="item-list selectable">
|
||||
{remainingItems.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className={selectedItemIds.has(item.id) ? 'selected' : ''}
|
||||
onClick={() => toggleItem(item.id)}
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<Field label="Store">
|
||||
<input
|
||||
value={storeName}
|
||||
placeholder="(unreadable)"
|
||||
onChange={(e) => setStoreName(e.target.value)}
|
||||
className="input"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Date">
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
placeholder="TT.MM.JJJJ"
|
||||
value={dateText}
|
||||
onChange={(e) => {
|
||||
setDateText(e.target.value)
|
||||
const iso = euToIso(e.target.value)
|
||||
if (iso) setDate(iso)
|
||||
}}
|
||||
className="input"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Cospend project">
|
||||
<select
|
||||
value={projectId ?? ''}
|
||||
onChange={(e) => setProjectId(e.target.value)}
|
||||
className="input"
|
||||
>
|
||||
<span>{item.label || '(unnamed)'}</span>
|
||||
<span>{item.price.toFixed(2)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<h3>Split with</h3>
|
||||
<ul className="member-list">
|
||||
{members.map((m) => (
|
||||
<li key={m.id}>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedMemberIds.has(m.id)}
|
||||
onChange={() => toggleMember(m.id)}
|
||||
/>
|
||||
{m.name}
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<label className="payer-select">
|
||||
Paid by
|
||||
<select value={payerId ?? ''} onChange={(e) => setPayerId(e.target.value)}>
|
||||
{members.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.name}
|
||||
<option value="" disabled>
|
||||
select…
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{projects.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Paid by">
|
||||
<select
|
||||
value={payerId ?? ''}
|
||||
onChange={(e) => setPayerId(e.target.value)}
|
||||
className="input"
|
||||
>
|
||||
{members.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<p className="total">Group total: {groupTotal.toFixed(2)}</p>
|
||||
{error && <p className="error">{error}</p>}
|
||||
<ul className="space-y-2">
|
||||
{items.map((item) => {
|
||||
const included = isIncluded(item.id)
|
||||
const selectedMembers = itemMembers[item.id] ?? new Set<string>()
|
||||
return (
|
||||
<li
|
||||
key={item.id}
|
||||
className={`rounded-xl border p-3 transition-colors ${
|
||||
included
|
||||
? 'border-blue-300 bg-blue-50 dark:border-blue-800 dark:bg-blue-950/30'
|
||||
: 'border-neutral-200 dark:border-neutral-800'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleIncluded(item.id)}
|
||||
aria-pressed={included}
|
||||
className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-md border text-xs font-bold transition-colors ${
|
||||
included
|
||||
? 'border-blue-600 bg-blue-600 text-white'
|
||||
: 'border-neutral-300 text-transparent dark:border-neutral-600'
|
||||
}`}
|
||||
>
|
||||
✓
|
||||
</button>
|
||||
|
||||
<button disabled={submitting || selectedItemIds.size === 0} onClick={submitCurrentGroup}>
|
||||
{submitting ? 'Creating bill…' : 'Create bill for this group'}
|
||||
<input
|
||||
value={item.label}
|
||||
placeholder="item"
|
||||
onChange={(e) => updateItem(item.id, { label: e.target.value })}
|
||||
className="min-w-0 flex-1 rounded-md border border-transparent bg-transparent px-1.5 py-1 text-sm focus:border-neutral-300 focus:bg-white focus:outline-none dark:focus:border-neutral-700 dark:focus:bg-neutral-900"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={item.price}
|
||||
onChange={(e) => updateItem(item.id, { price: Number(e.target.value) })}
|
||||
className="w-20 shrink-0 rounded-md border border-transparent bg-transparent px-1.5 py-1 text-right text-sm tabular-nums focus:border-neutral-300 focus:bg-white focus:outline-none dark:focus:border-neutral-700 dark:focus:bg-neutral-900"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCustomizing(customizing === item.id ? null : item.id)}
|
||||
className="shrink-0 rounded-md px-2 py-1 text-xs text-neutral-500 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:bg-neutral-800"
|
||||
>
|
||||
{included ? memberInitials(selectedMembers, members) : 'excluded'} ▾
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeItem(item.id)}
|
||||
aria-label="remove item"
|
||||
className="shrink-0 rounded-md px-1.5 py-1 text-neutral-400 hover:text-red-500"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{customizing === item.id && (
|
||||
<div className="mt-2 flex flex-wrap gap-2 border-t border-neutral-200 pt-2 dark:border-neutral-800">
|
||||
{members.map((m) => (
|
||||
<label
|
||||
key={m.id}
|
||||
className="flex items-center gap-1.5 rounded-full border border-neutral-300 px-2.5 py-1 text-xs dark:border-neutral-700"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedMembers.has(m.id)}
|
||||
onChange={() => toggleItemMember(item.id, m.id)}
|
||||
/>
|
||||
{m.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
|
||||
<button
|
||||
onClick={addItem}
|
||||
className="w-full rounded-lg border border-dashed border-neutral-300 py-2 text-sm text-neutral-500 hover:border-neutral-400 hover:text-neutral-700 dark:border-neutral-700 dark:hover:border-neutral-500"
|
||||
>
|
||||
+ add missed item
|
||||
</button>
|
||||
|
||||
{remainingItems.length === 0 && groups.length > 0 && (
|
||||
<button className="secondary" onClick={() => onAllDone(groups)}>
|
||||
All items assigned — finish
|
||||
</button>
|
||||
)}
|
||||
<div className="rounded-xl bg-neutral-100 p-4 dark:bg-neutral-900">
|
||||
<h3 className="text-sm font-semibold">
|
||||
{partitions.length} bill{partitions.length === 1 ? '' : 's'} to create
|
||||
{excludedCount > 0 && (
|
||||
<span className="font-normal text-neutral-500"> · {excludedCount} excluded</span>
|
||||
)}
|
||||
</h3>
|
||||
<ul className="mt-2 space-y-1 text-sm text-neutral-600 dark:text-neutral-300">
|
||||
{partitions.map((p) => (
|
||||
<li key={p.memberIds.join(',')} className="flex justify-between">
|
||||
<span>
|
||||
{p.memberIds.map(memberName).join(' + ')}{' '}
|
||||
<span className="text-neutral-400">({p.items.length} item(s))</span>
|
||||
</span>
|
||||
<span className="tabular-nums">{p.total.toFixed(2)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-red-500">{error}</p>}
|
||||
|
||||
<button
|
||||
disabled={submitting || partitions.length === 0}
|
||||
onClick={submitAll}
|
||||
className="w-full rounded-xl bg-blue-600 py-3 font-semibold text-white hover:bg-blue-500 disabled:opacity-50"
|
||||
>
|
||||
{submitting ? 'Creating bills…' : `Create ${partitions.length || ''} bill(s)`}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<label className="flex flex-col gap-1 text-xs font-medium text-neutral-500 dark:text-neutral-400">
|
||||
{label}
|
||||
{children}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
/** Best-effort match of the logged-in NC user against a Cospend member
|
||||
* name, so we can preselect them as the default payer without hardcoding a
|
||||
* project-specific member id anywhere. Case-insensitive exact match first,
|
||||
* then substring containment either direction; null if nothing looks close
|
||||
* enough (caller falls back to the first member). */
|
||||
function fuzzyMatchMember(members: Member[], ncUsername: string): Member | null {
|
||||
const needle = ncUsername.trim().toLowerCase()
|
||||
if (!needle) return null
|
||||
|
||||
const exact = members.find((m) => m.name.trim().toLowerCase() === needle)
|
||||
if (exact) return exact
|
||||
|
||||
const partial = members.find((m) => {
|
||||
const name = m.name.trim().toLowerCase()
|
||||
return name.includes(needle) || needle.includes(name)
|
||||
})
|
||||
return partial ?? null
|
||||
}
|
||||
|
||||
function memberInitials(ids: Set<string>, members: Member[]): string {
|
||||
if (ids.size === members.length && members.length > 0) return 'everyone'
|
||||
return [...ids].map((id) => members.find((m) => m.id === id)?.name.slice(0, 3) ?? '?').join(',')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { CiReceipt } from 'react-icons/ci'
|
||||
import { api, UnauthorizedError } from '../api'
|
||||
|
||||
interface Props {
|
||||
/** Rendered once a session is confirmed. */
|
||||
children: (ctx: { ncUserId: string; logout: () => void }) => React.ReactNode
|
||||
}
|
||||
|
||||
type Status =
|
||||
| { name: 'checking' }
|
||||
| { name: 'loggedOut' }
|
||||
| { name: 'starting' }
|
||||
| { name: 'polling'; flowId: string }
|
||||
| { name: 'error'; message: string }
|
||||
| { name: 'loggedIn'; ncUserId: string }
|
||||
|
||||
const POLL_INTERVAL_MS = 1500
|
||||
|
||||
export function LoginGate({ children }: Props) {
|
||||
const [status, setStatus] = useState<Status>({ name: 'checking' })
|
||||
const openedWindow = useRef<Window | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
api
|
||||
.getMe()
|
||||
.then(({ nc_user_id }) => setStatus({ name: 'loggedIn', ncUserId: nc_user_id }))
|
||||
.catch((e) => {
|
||||
if (e instanceof UnauthorizedError) setStatus({ name: 'loggedOut' })
|
||||
else setStatus({ name: 'error', message: e instanceof Error ? e.message : String(e) })
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (status.name !== 'polling') return
|
||||
const flowId = status.flowId
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
const result = await api.authPoll(flowId)
|
||||
if (result.status === 'done' && result.nc_user_id) {
|
||||
openedWindow.current?.close()
|
||||
setStatus({ name: 'loggedIn', ncUserId: result.nc_user_id })
|
||||
} else if (result.status === 'expired') {
|
||||
setStatus({ name: 'error', message: 'Login timed out - try again.' })
|
||||
}
|
||||
} catch (e) {
|
||||
setStatus({ name: 'error', message: e instanceof Error ? e.message : String(e) })
|
||||
}
|
||||
}, POLL_INTERVAL_MS)
|
||||
return () => clearInterval(interval)
|
||||
}, [status])
|
||||
|
||||
async function login() {
|
||||
setStatus({ name: 'starting' })
|
||||
try {
|
||||
const { flow_id, login_url } = await api.authStart()
|
||||
openedWindow.current = window.open(login_url, '_blank')
|
||||
setStatus({ name: 'polling', flowId: flow_id })
|
||||
} catch (e) {
|
||||
setStatus({ name: 'error', message: e instanceof Error ? e.message : String(e) })
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
api.logout().finally(() => setStatus({ name: 'loggedOut' }))
|
||||
}
|
||||
|
||||
if (status.name === 'loggedIn') {
|
||||
return <>{children({ ncUserId: status.ncUserId, logout })}</>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-[70vh] flex-col items-center justify-center px-4 text-center">
|
||||
<CiReceipt className="h-16 w-16 text-blue-600 dark:text-blue-400" />
|
||||
<h1 className="mt-2 text-3xl font-bold tracking-tight">wgBill</h1>
|
||||
|
||||
{status.name === 'checking' && (
|
||||
<p className="mt-4 text-neutral-500 dark:text-neutral-400">Checking login…</p>
|
||||
)}
|
||||
|
||||
{(status.name === 'loggedOut' || status.name === 'starting') && (
|
||||
<>
|
||||
<p className="mt-2 text-neutral-500 dark:text-neutral-400">
|
||||
Log in with your Nextcloud account to get started.
|
||||
</p>
|
||||
<button
|
||||
disabled={status.name === 'starting'}
|
||||
onClick={login}
|
||||
className="mt-6 w-full max-w-xs rounded-xl bg-blue-600 px-6 py-3 font-semibold text-white shadow-sm transition hover:bg-blue-500 disabled:opacity-50 sm:w-auto"
|
||||
>
|
||||
{status.name === 'starting' ? 'Starting…' : 'Log in with Nextcloud'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status.name === 'polling' && (
|
||||
<p className="mt-4 text-neutral-500 dark:text-neutral-400">
|
||||
Complete the login in the tab that just opened, then come back here.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{status.name === 'error' && (
|
||||
<>
|
||||
<p className="mt-4 text-red-500">{status.message}</p>
|
||||
<button
|
||||
onClick={login}
|
||||
className="mt-6 w-full max-w-xs rounded-xl bg-blue-600 px-6 py-3 font-semibold text-white shadow-sm transition hover:bg-blue-500 sm:w-auto"
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { api } from '../api'
|
||||
import type { Item } from '../types'
|
||||
|
||||
interface Props {
|
||||
receiptId: string
|
||||
initialItems: Item[]
|
||||
initialStoreName: string | null
|
||||
initialDate: string
|
||||
onConfirmed: (items: Item[], storeName: string, date: string) => void
|
||||
}
|
||||
|
||||
export function ReviewStep({
|
||||
receiptId,
|
||||
initialItems,
|
||||
initialStoreName,
|
||||
initialDate,
|
||||
onConfirmed,
|
||||
}: Props) {
|
||||
const [items, setItems] = useState<Item[]>(initialItems)
|
||||
const [storeName, setStoreName] = useState(initialStoreName ?? '')
|
||||
const [date, setDate] = useState(initialDate)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
function updateItem(id: string, patch: Partial<Item>) {
|
||||
setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)))
|
||||
}
|
||||
|
||||
function removeItem(id: string) {
|
||||
setItems((prev) => prev.filter((it) => it.id !== id))
|
||||
}
|
||||
|
||||
function addItem() {
|
||||
setItems((prev) => [
|
||||
...prev,
|
||||
{ id: crypto.randomUUID(), label: '', price: 0, bbox: null },
|
||||
])
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
try {
|
||||
await api.updateItems(receiptId, items)
|
||||
await api.updateMeta(receiptId, { store_name: storeName, date })
|
||||
onConfirmed(items, storeName, date)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const total = items.reduce((sum, it) => sum + (Number(it.price) || 0), 0)
|
||||
|
||||
return (
|
||||
<div className="step review-step">
|
||||
<h2>Check the extracted items</h2>
|
||||
<p className="hint">Fix anything the receipt reader got wrong before splitting.</p>
|
||||
|
||||
<div className="meta-row">
|
||||
<label>
|
||||
Store
|
||||
<input
|
||||
value={storeName}
|
||||
placeholder="(unreadable - add it)"
|
||||
onChange={(e) => setStoreName(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Date
|
||||
<input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<ul className="item-list">
|
||||
{items.map((item) => (
|
||||
<li key={item.id} className="item-row">
|
||||
<input
|
||||
value={item.label}
|
||||
placeholder="item"
|
||||
onChange={(e) => updateItem(item.id, { label: e.target.value })}
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={item.price}
|
||||
onChange={(e) => updateItem(item.id, { price: Number(e.target.value) })}
|
||||
/>
|
||||
<button className="icon-btn" onClick={() => removeItem(item.id)} aria-label="remove item">
|
||||
✕
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button className="secondary" onClick={addItem}>
|
||||
+ add missed item
|
||||
</button>
|
||||
<p className="total">Total: {total.toFixed(2)}</p>
|
||||
{error && <p className="error">{error}</p>}
|
||||
<button disabled={saving || items.length === 0} onClick={confirm}>
|
||||
{saving ? 'Saving…' : 'Looks good, continue'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,26 +7,37 @@ interface Props {
|
||||
|
||||
export function SummaryStep({ groups, onRestart }: Props) {
|
||||
return (
|
||||
<div className="step summary-step">
|
||||
<h2>Done 🎉</h2>
|
||||
<ul className="summary-list">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Done 🎉</h2>
|
||||
<ul className="mt-4 space-y-2">
|
||||
{groups.map((g) => (
|
||||
<li key={g.id}>
|
||||
<strong>{g.name}</strong>
|
||||
<li
|
||||
key={g.id}
|
||||
className="rounded-lg border border-neutral-200 px-4 py-3 text-sm dark:border-neutral-800"
|
||||
>
|
||||
{g.status === 'submitted' ? (
|
||||
<>
|
||||
{' — bill created. '}
|
||||
<a href={g.share_url ?? '#'} target="_blank" rel="noreferrer">
|
||||
view receipt
|
||||
<a
|
||||
href={g.share_url ?? '#'}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="font-medium text-blue-600 underline dark:text-blue-400"
|
||||
>
|
||||
View receipt
|
||||
</a>
|
||||
</>
|
||||
) : (
|
||||
<span className="error"> — failed: {g.error}</span>
|
||||
<span className="text-red-500">failed: {g.error}</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button onClick={onRestart}>Scan another receipt</button>
|
||||
<button
|
||||
onClick={onRestart}
|
||||
className="mt-6 w-full rounded-xl bg-blue-600 py-3 font-semibold text-white hover:bg-blue-500"
|
||||
>
|
||||
Scan another receipt
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+6
-102
@@ -1,111 +1,15 @@
|
||||
:root {
|
||||
--text: #6b6375;
|
||||
--text-h: #08060d;
|
||||
--bg: #fff;
|
||||
--border: #e5e4e7;
|
||||
--code-bg: #f4f3ec;
|
||||
--accent: #aa3bff;
|
||||
--accent-bg: rgba(170, 59, 255, 0.1);
|
||||
--accent-border: rgba(170, 59, 255, 0.5);
|
||||
--social-bg: rgba(244, 243, 236, 0.5);
|
||||
--shadow:
|
||||
rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
|
||||
@import 'tailwindcss';
|
||||
|
||||
--sans: system-ui, 'Segoe UI', Roboto, sans-serif;
|
||||
--heading: system-ui, 'Segoe UI', Roboto, sans-serif;
|
||||
--mono: ui-monospace, Consolas, monospace;
|
||||
|
||||
font: 18px/145% var(--sans);
|
||||
letter-spacing: 0.18px;
|
||||
html {
|
||||
color-scheme: light dark;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--text: #9ca3af;
|
||||
--text-h: #f3f4f6;
|
||||
--bg: #16171d;
|
||||
--border: #2e303a;
|
||||
--code-bg: #1f2028;
|
||||
--accent: #c084fc;
|
||||
--accent-bg: rgba(192, 132, 252, 0.15);
|
||||
--accent-border: rgba(192, 132, 252, 0.5);
|
||||
--social-bg: rgba(47, 48, 58, 0.5);
|
||||
--shadow:
|
||||
rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
|
||||
}
|
||||
|
||||
#social .button-icon {
|
||||
filter: invert(1) brightness(2);
|
||||
}
|
||||
}
|
||||
|
||||
#root {
|
||||
width: 1126px;
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
border-inline: 1px solid var(--border);
|
||||
min-height: 100svh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
@apply m-0 min-h-screen bg-neutral-50 font-sans text-neutral-900 antialiased dark:bg-neutral-950 dark:text-neutral-100;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2 {
|
||||
font-family: var(--heading);
|
||||
font-weight: 500;
|
||||
color: var(--text-h);
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 56px;
|
||||
letter-spacing: -1.68px;
|
||||
margin: 32px 0;
|
||||
@media (max-width: 1024px) {
|
||||
font-size: 36px;
|
||||
margin: 20px 0;
|
||||
@layer components {
|
||||
.input {
|
||||
@apply rounded-lg border border-neutral-300 bg-white px-2 py-1.5 text-sm text-neutral-900 focus:border-blue-500 focus:outline-none dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100;
|
||||
}
|
||||
}
|
||||
h2 {
|
||||
font-size: 24px;
|
||||
line-height: 118%;
|
||||
letter-spacing: -0.24px;
|
||||
margin: 0 0 8px;
|
||||
@media (max-width: 1024px) {
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
code,
|
||||
.counter {
|
||||
font-family: var(--mono);
|
||||
display: inline-flex;
|
||||
border-radius: 4px;
|
||||
color: var(--text-h);
|
||||
}
|
||||
|
||||
code {
|
||||
font-size: 15px;
|
||||
line-height: 135%;
|
||||
padding: 4px 8px;
|
||||
background: var(--code-bg);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
export type BBox = [number, number, number, number] // x, y, w, h, normalized 0-1
|
||||
|
||||
export interface Item {
|
||||
id: string
|
||||
label: string
|
||||
price: number
|
||||
bbox: BBox | null
|
||||
}
|
||||
|
||||
export interface Receipt {
|
||||
@@ -29,7 +26,6 @@ export interface CospendProject {
|
||||
export interface Group {
|
||||
id: string
|
||||
receipt_id: string
|
||||
name: string
|
||||
cospend_project_id: string
|
||||
payer_member_id: string
|
||||
member_ids: string[]
|
||||
@@ -45,12 +41,3 @@ export interface SubmitResult {
|
||||
amount: number
|
||||
bill_id: number
|
||||
}
|
||||
|
||||
/** A group draft in progress client-side, before it's persisted via POST /groups. */
|
||||
export interface GroupDraft {
|
||||
localId: string
|
||||
name: string
|
||||
payerMemberId: string | null
|
||||
memberIds: string[]
|
||||
itemIds: string[]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user