mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
feat(llm-parse): read a photo, as a booking or as a receipt in Costs
Whether the AI Parsing model reads images is an admin setting now, and it lands with the two features that send a photo, so it has something to control. The setting is `vision: 'auto' | 'on' | 'off'` on the addon config. On Automatic a local Ollama is asked what the model can do (`/api/show`), and a cloud provider means no; Yes and No are applied as set. The old `multimodal` flag is not read: the admin screens wrote it false on every save, so a stored false meant nothing. The per-user toggle keeps its on/off meaning and is read by the extraction now. The lookup is server-side only: capped read, validated body, never throws, cached per server and model. GET /api/llm/capabilities answers it for the signed-in caller, and both photo pickers below ask it. The booking import takes JPG, PNG and WEBP when the model reads images. The photo goes as an image to every provider (image_url, an Anthropic image block, Ollama's native chat with `images`), capped at 1600px, and skips KDE Itinerary. A scanned PDF, which used to reach the model as empty text, has its first two pages drawn by pdf-parse and sent the same way. The rest is the import as it was: background job, review, the file attached to the booking, the linked cost. On a real qwen3.5:4b a train ticket came back as bare clock times until the router gave the model every type's field meanings, and its price as an object inside a string, which read as 4900; both are handled. Costs gets Scan receipt: a dialog laid out like the booking import's takes one photo, read on the import job queue, then reviewed in the existing expense editor pre-filled with merchant, total, currency, day and lines, the photo waiting in Receipts & Invoices to be uploaded on save. No table, no migration, no category guess, no document-type detection.
This commit is contained in:
@@ -12,6 +12,7 @@ import DawarichIcon from '../../../components/shared/DawarichIcon'
|
||||
import AirTrailIcon from '../../../components/shared/AirTrailIcon'
|
||||
import { DOCUMENT_PROVIDER_ICONS } from '../../../components/shared/DocumentProviderIcons'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import { asLlmVision, LLM_VISION_MODES, type LlmVision } from '@trek/shared'
|
||||
import { MAdminButton, MAdminCard, MAdminField, MAdminInput, MAdminSecretInput } from './MAdminUi'
|
||||
|
||||
const ICON_MAP = {
|
||||
@@ -391,12 +392,14 @@ const RECOMMENDED_MODELS: { id: string; label: string; note: string; recommended
|
||||
* provider, it also lists installed Ollama models and can pull NuExtract models.
|
||||
*/
|
||||
function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const cfg = (addon.config ?? {}) as Record<string, unknown>
|
||||
const [provider, setProvider] = useState<string>((cfg.provider as string) ?? 'local')
|
||||
const [model, setModel] = useState<string>((cfg.model as string) ?? '')
|
||||
const [baseUrl, setBaseUrl] = useState<string>((cfg.baseUrl as string) ?? '')
|
||||
const [apiKey, setApiKey] = useState<string>((cfg.apiKey as string) ?? '')
|
||||
const [vision, setVision] = useState<LlmVision>(asLlmVision(cfg.vision))
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// Local-provider model management.
|
||||
@@ -458,7 +461,7 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
setSaving(true)
|
||||
try {
|
||||
// Send the masked sentinel unchanged so the server keeps the stored key.
|
||||
await adminApi.updateAddon(addon.id, { config: { provider, model: model.trim(), baseUrl: baseUrl.trim(), apiKey, multimodal: cfg.multimodal === true } })
|
||||
await adminApi.updateAddon(addon.id, { config: { provider, model: model.trim(), baseUrl: baseUrl.trim(), apiKey, vision } })
|
||||
toast.success('Saved')
|
||||
} catch {
|
||||
toast.error('Failed to save')
|
||||
@@ -546,6 +549,31 @@ function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
placeholder={provider === 'anthropic' ? 'claude-opus-4-8' : provider === 'openai' ? 'gpt-4o' : 'select or pull below'}
|
||||
/>
|
||||
|
||||
<MAdminField label={t('settings.aiParsing.multimodal')}>
|
||||
<div role="radiogroup" aria-label={t('settings.aiParsing.multimodal')} className="flex gap-[6px]">
|
||||
{LLM_VISION_MODES.map((mode) => {
|
||||
const active = vision === mode
|
||||
return (
|
||||
<button
|
||||
key={mode}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={active}
|
||||
onClick={() => setVision(mode)}
|
||||
className={`flex-1 rounded-xl border px-3 py-[10px] text-[0.8125rem] font-semibold text-m-ink ${
|
||||
active ? 'border-[color:var(--m-act)] bg-[color:var(--m-ic)]' : 'border-[color:var(--m-rowbr)]'
|
||||
}`}
|
||||
>
|
||||
{t(`admin.addons.llm.vision.${mode}`)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</MAdminField>
|
||||
<p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">
|
||||
{t(provider === 'local' ? 'admin.addons.llm.vision.hintLocal' : 'admin.addons.llm.vision.hintCloud')}
|
||||
</p>
|
||||
|
||||
{/* Local model management (Ollama) */}
|
||||
{provider === 'local' && (
|
||||
<div className="space-y-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-3">
|
||||
|
||||
@@ -13,6 +13,7 @@ import MMapArea from './map/MMapArea'
|
||||
import MPlacesBrowser from './places/MPlacesBrowser'
|
||||
import MTripTabPanel from './tabs/MTripTabPanel'
|
||||
import MTripSheets from './sheets/MTripSheets'
|
||||
import MReceiptScanButton from './tabs/MReceiptScanButton'
|
||||
import MTripLoadingSplash from './MTripLoadingSplash'
|
||||
import { usePluginDayTints, dayTintBackground } from '../../../components/Plugins/PluginDaySchedule'
|
||||
import { stageOf } from '../../../components/Roadtrip/roadtripRowModel'
|
||||
@@ -593,6 +594,7 @@ export default function MTripShell({
|
||||
{trTab === 'finanzplan' && (
|
||||
<div className="absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center gap-[7px]">
|
||||
<PrimaryPill label={t('costs.addExpense')} onClick={() => setAddExpenseSignal(s => s + 1)} />
|
||||
<MReceiptScanButton tripId={tripId} canEdit={planner.can('budget_edit', trip)} />
|
||||
<MIconBtn ariaLabel={t('budget.exportCsv')} onClick={() => setExportCostsCsvSignal(s => s + 1)} size={40} className="text-m-muted backdrop-blur-[24px] backdrop-saturate-[1.7]">
|
||||
<FileDown size={15} strokeWidth={2} />
|
||||
</MIconBtn>
|
||||
|
||||
@@ -15,7 +15,7 @@ import { splitShareLabel, useExpenseFx } from '../../../../components/Budget/exp
|
||||
import { SYMBOLS, SPLIT_COLORS, currenciesWith } from '../../../../components/Budget/BudgetPanel.constants'
|
||||
import { COST_CATEGORY_LIST, catMeta } from '../../../../components/Budget/costsCategories'
|
||||
import { localToday } from '../../../../components/Planner/today'
|
||||
import { amountPattern, calculateTicketShares, hasTicketSplit, NOTE_MAX, readTicketItems, readUserNote, splitEqualShares, writeTicketItems, type TicketItem } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import { amountPattern, calculateTicketShares, hasTicketSplit, newExpenseSeed, NOTE_MAX, readTicketItems, readUserNote, splitEqualShares, writeTicketItems, type TicketItem } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import type { ExpensePrefill } from '../../../../components/Budget/CostsPanel'
|
||||
import { payersBalanced, rebalancePayers } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import GuestBadge from '../../../../components/shared/GuestBadge'
|
||||
@@ -76,15 +76,14 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
|
||||
const [cat, setCat] = useState<string>(editing ? catMeta(editing.category).key : (prefill?.category || 'food'))
|
||||
const [catOpen, setCatOpen] = useState(false)
|
||||
const [note, setNote] = useState(() => readUserNote(editing))
|
||||
const [currency, setCurrency] = useState(editingCurrency)
|
||||
const [day, setDay] = useState(editing?.expense_date || localToday())
|
||||
const [seed] = useState(() => newExpenseSeed(prefill, base, people.map(p => p.id), localToday()))
|
||||
const [currency, setCurrency] = useState(editing ? editingCurrency : seed.currency)
|
||||
const [day, setDay] = useState(editing ? (editing.expense_date || localToday()) : seed.day)
|
||||
// Edit and prefill seeds are padded to the currency's decimals (#2175), same
|
||||
// as the desktop modal: a saved 4,90 must reopen as "4,90", not "4,9". A
|
||||
// prefill has no currency of its own and is read as `base`.
|
||||
// as the desktop modal: a saved 4,90 must reopen as "4,90", not "4,9".
|
||||
const [total, setTotal] = useState<string>(() => {
|
||||
if (editing) return editing.total_price ? amountToInputString(editing.total_price, editingCurrency) : ''
|
||||
if (prefill?.amount != null) return amountToInputString(prefill.amount, base)
|
||||
return ''
|
||||
return seed.total
|
||||
})
|
||||
const [participants, setParticipants] = useState<Set<number>>(() =>
|
||||
editing ? new Set((editing.members || []).map(m => m.user_id)) : new Set(people.map(p => p.id)))
|
||||
@@ -115,7 +114,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
|
||||
return 'equally'
|
||||
})
|
||||
|
||||
const [ticketItems, setTicketItems] = useState<TicketItem[]>(() => readTicketItems(editing))
|
||||
const [ticketItems, setTicketItems] = useState<TicketItem[]>(() => editing ? readTicketItems(editing) : seed.ticketItems)
|
||||
|
||||
const [customAmounts, setCustomAmounts] = useState<Record<number, string>>(() => {
|
||||
const m: Record<number, string> = {}
|
||||
@@ -128,7 +127,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
|
||||
})
|
||||
|
||||
const [receipts, setReceipts] = useState<BudgetItemReceipt[]>(() => editing?.receipts || [])
|
||||
const [pendingReceiptFiles, setPendingReceiptFiles] = useState<File[]>([])
|
||||
const [pendingReceiptFiles, setPendingReceiptFiles] = useState<File[]>(() => editing ? [] : seed.receiptFiles)
|
||||
const [uploadingReceipt, setUploadingReceipt] = useState(false)
|
||||
const [previewReceipts, setPreviewReceipts] = useState<{ receipts: BudgetItemReceipt[]; initialIndex: number } | null>(null)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import AirTrailImportModal from '../../../../components/Planner/AirTrailImportMo
|
||||
import TripFormModal from '../../../../components/Trips/TripFormModal'
|
||||
import TripMembersModal from '../../../../components/Trips/TripMembersModal'
|
||||
import type { ExpensePrefill } from '../../../../components/Budget/CostsPanel'
|
||||
import { expenseEditorFor } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import { useAuthStore } from '../../../../store/authStore'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
@@ -59,6 +60,7 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
|
||||
else if (req.prefill) setBookingExpense({ editing: null, prefill: req.prefill })
|
||||
}
|
||||
const costsBase = (displayCurrency || trip?.currency || 'EUR').toUpperCase()
|
||||
const expenseEditor = expenseEditorFor(bookingExpense, () => setBookingExpense(null), planner.receiptExpense, planner.clearReceiptExpense)
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -142,16 +144,17 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
|
||||
/>
|
||||
)}
|
||||
|
||||
{bookingExpense && (
|
||||
{expenseEditor && (
|
||||
<MCostSheet
|
||||
key={expenseEditor.key}
|
||||
tripId={tripId}
|
||||
base={costsBase}
|
||||
people={planner.tripMembers}
|
||||
me={meId}
|
||||
editing={bookingExpense.editing}
|
||||
prefill={bookingExpense.prefill}
|
||||
onClose={() => setBookingExpense(null)}
|
||||
onSaved={() => { setBookingExpense(null); loadBudgetItems(tripId) }}
|
||||
editing={expenseEditor.editing}
|
||||
prefill={expenseEditor.prefill}
|
||||
onClose={expenseEditor.close}
|
||||
onSaved={() => { expenseEditor.close(); loadBudgetItems(tripId) }}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { ScanLine } from 'lucide-react'
|
||||
import MIconBtn from '../../../components/MIconBtn'
|
||||
import { useReceiptScan } from '../../../../components/Budget/useReceiptScan'
|
||||
import { ReceiptScanModal } from '../../../../components/Budget/ReceiptScanModal'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
|
||||
/** The Costs header's "Scan receipt" button on a phone; the dialog and the scan are the shared ones. */
|
||||
export default function MReceiptScanButton({ tripId, canEdit }: { tripId: number; canEdit: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
const scan = useReceiptScan(tripId, canEdit)
|
||||
if (!scan.offered) return null
|
||||
return (
|
||||
<>
|
||||
<MIconBtn ariaLabel={t('costs.scan.button')} onClick={scan.open} size={40} className="text-m-muted backdrop-blur-[24px] backdrop-saturate-[1.7]">
|
||||
<ScanLine size={15} strokeWidth={2} />
|
||||
</MIconBtn>
|
||||
<ReceiptScanModal scan={scan} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user