feat: implement receipt alias functionality with CRUD operations and integrate with receipt import

This commit is contained in:
Nils-Johan Gynther
2026-04-16 21:06:16 +02:00
parent b8744f625b
commit af88a0dc81
11 changed files with 492 additions and 303 deletions
@@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from 'next/server';
const API_BASE =
process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
export async function GET() {
const res = await fetch(`${API_BASE}/api/receipt-aliases`, { cache: 'no-store' });
const text = await res.text();
return new NextResponse(text, {
status: res.status,
headers: { 'Content-Type': 'application/json' },
});
}
export async function POST(request: NextRequest) {
const body = await request.json();
const res = await fetch(`${API_BASE}/api/receipt-aliases`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const text = await res.text();
return new NextResponse(text, {
status: res.status,
headers: { 'Content-Type': 'application/json' },
});
}
export async function DELETE(request: NextRequest) {
const id = request.nextUrl.searchParams.get('id');
const res = await fetch(`${API_BASE}/api/receipt-aliases/${id}`, {
method: 'DELETE',
});
return new NextResponse(null, { status: res.status });
}
+301 -283
View File
@@ -1,284 +1,302 @@
'use client';
import { useRef, useState } from 'react';
type ParsedItem = {
rawName: string;
quantity: number;
unit: string;
price?: number | null;
matchedProductId?: number;
matchedProductName?: string;
};
type RowState = ParsedItem & { checked: boolean; editQty: string; editUnit: string };
const UNITS = ['st', 'kg', 'g', 'l', 'dl', 'cl', 'ml', 'förp', 'pak', 'burk', 'flaska'];
export default function ReceiptImportClient() {
const fileRef = useRef<HTMLInputElement>(null);
const [preview, setPreview] = useState<string | null>(null);
const [parsing, setParsing] = useState(false);
const [saving, setSaving] = useState(false);
const [rows, setRows] = useState<RowState[]>([]);
const [error, setError] = useState<string | null>(null);
const [savedCount, setSavedCount] = useState<number | null>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setSelectedFile(file);
if (file.type === 'application/pdf') {
setPreview('pdf');
} else {
setPreview(URL.createObjectURL(file));
}
setRows([]);
setError(null);
setSavedCount(null);
};
const handleParse = async () => {
if (!selectedFile) return;
setParsing(true);
setError(null);
try {
const fd = new FormData();
fd.append('file', selectedFile);
const res = await fetch('/api/receipt-import-proxy', { method: 'POST', body: fd });
if (!res.ok) {
const e = await res.json().catch(() => ({ message: 'Okänt fel' }));
throw new Error(e.message ?? 'Servern svarade med fel');
}
const items: ParsedItem[] = await res.json();
setRows(
items.map((item) => ({
...item,
checked: !!item.matchedProductId,
editQty: String(item.quantity),
editUnit: item.unit,
})),
);
} catch (err) {
setError(err instanceof Error ? err.message : 'Kunde inte tolka kvittot');
} finally {
setParsing(false);
}
};
const updateRow = (i: number, patch: Partial<RowState>) => {
setRows((prev) => prev.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));
};
const handleSave = async () => {
const toSave = rows.filter((r) => r.checked && r.matchedProductId);
if (toSave.length === 0) return;
setSaving(true);
setError(null);
try {
await Promise.all(
toSave.map((r) =>
fetch('/api/inventory', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
productId: r.matchedProductId,
quantity: parseFloat(r.editQty) || r.quantity,
unit: r.editUnit,
}),
}),
),
);
setSavedCount(toSave.length);
setRows([]);
setPreview(null);
setSelectedFile(null);
if (fileRef.current) fileRef.current.value = '';
} catch {
setError('Något gick fel vid sparning. Försök igen.');
} finally {
setSaving(false);
}
};
const checkedCount = rows.filter((r) => r.checked && r.matchedProductId).length;
const unmatchedCount = rows.filter((r) => !r.matchedProductId).length;
return (
<div>
{/* Fil-input */}
<div
style={{
border: '2px dashed #ced4da',
borderRadius: '10px',
padding: '1.5rem',
textAlign: 'center',
background: '#fafafa',
marginBottom: '1rem',
cursor: 'pointer',
}}
onClick={() => fileRef.current?.click()}
>
<input
ref={fileRef}
type="file"
accept="image/*,application/pdf"
capture="environment"
onChange={handleFileChange}
style={{ display: 'none' }}
/>
{preview === 'pdf' ? (
<div style={{ padding: '1rem', color: '#333' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📄</div>
<div style={{ fontWeight: 600 }}>{selectedFile?.name}</div>
<div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>PDF-kvitto valt</div>
</div>
) : preview ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={preview}
alt="Kvittoförhandsgranskning"
style={{ maxHeight: '300px', maxWidth: '100%', borderRadius: '6px' }}
/>
) : (
<div style={{ color: '#888' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📷</div>
<div style={{ fontWeight: 600 }}>Fotografera eller välj kvitto</div>
<div style={{ fontSize: '0.85rem', marginTop: '0.25rem' }}>
Klicka för att välja bild (JPEG, PNG, WebP) eller PDF
</div>
</div>
)}
</div>
{preview && rows.length === 0 && (
<button
onClick={handleParse}
disabled={parsing}
style={primaryBtn(parsing)}
>
{parsing ? '⏳ Tolkar kvitto via AI...' : '🔍 Tolka kvitto'}
</button>
)}
{error && (
<p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}>
{error}
</p>
)}
{savedCount !== null && (
<p style={{ color: '#27ae60', background: '#edfdf4', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem', fontWeight: 600 }}>
{savedCount} {savedCount === 1 ? 'vara lades till' : 'varor lades till'} i inventariet.
</p>
)}
{/* Parsade rader */}
{rows.length > 0 && (
<div style={{ marginTop: '1.25rem' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '0.5rem' }}>
<h2 style={{ margin: 0, fontSize: '1.05rem' }}>
Identifierade varor ({rows.length})
</h2>
{unmatchedCount > 0 && (
<span style={{ fontSize: '0.8rem', color: '#e67e22' }}>
{unmatchedCount} {unmatchedCount === 1 ? 'vara' : 'varor'} saknas i produktdatabasen
</span>
)}
</div>
<div style={{ display: 'grid', gap: '0.5rem', marginBottom: '1rem' }}>
{rows.map((row, i) => {
const matched = !!row.matchedProductId;
return (
<div
key={i}
style={{
display: 'grid',
gridTemplateColumns: '36px 1fr 80px 90px',
gap: '0.5rem',
alignItems: 'center',
padding: '0.6rem 0.75rem',
border: `1px solid ${matched ? '#dee2e6' : '#f5cba7'}`,
borderRadius: '6px',
background: matched ? '#fff' : '#fef9f5',
opacity: row.checked || !matched ? 1 : 0.7,
}}
>
<input
type="checkbox"
checked={row.checked}
disabled={!matched}
onChange={(e) => updateRow(i, { checked: e.target.checked })}
style={{ width: '18px', height: '18px', cursor: matched ? 'pointer' : 'not-allowed' }}
title={!matched ? 'Produkten finns inte i databasen — lägg till den i admin först' : ''}
/>
<div>
<div style={{ fontWeight: 500, fontSize: '0.9rem' }}>
{row.matchedProductName ?? row.rawName}
</div>
{row.matchedProductName && row.matchedProductName.toLowerCase() !== row.rawName.toLowerCase() && (
<div style={{ fontSize: '0.75rem', color: '#888' }}>
Kvitto: {row.rawName}
</div>
)}
{!matched && (
<div style={{ fontSize: '0.75rem', color: '#e67e22' }}>
Ingen matchning {row.rawName}
</div>
)}
</div>
<input
type="number"
min="0"
step="0.01"
value={row.editQty}
onChange={(e) => updateRow(i, { editQty: e.target.value })}
style={{ padding: '0.3rem 0.5rem', border: '1px solid #ced4da', borderRadius: '4px', width: '100%', fontSize: '0.9rem' }}
/>
<select
value={row.editUnit}
onChange={(e) => updateRow(i, { editUnit: e.target.value })}
style={{ padding: '0.3rem 0.5rem', border: '1px solid #ced4da', borderRadius: '4px', fontSize: '0.9rem' }}
>
{UNITS.map((u) => <option key={u} value={u}>{u}</option>)}
</select>
</div>
);
})}
</div>
<div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
<button
onClick={handleSave}
disabled={saving || checkedCount === 0}
style={primaryBtn(saving || checkedCount === 0)}
>
{saving ? 'Sparar...' : `Lägg till ${checkedCount} ${checkedCount === 1 ? 'vara' : 'varor'} i inventariet`}
</button>
<button
onClick={() => { setRows([]); setPreview(null); setSelectedFile(null); if (fileRef.current) fileRef.current.value = ''; }}
style={{ padding: '0.5rem 1rem', background: '#f0f0f0', border: '1px solid #ccc', borderRadius: '6px', cursor: 'pointer', fontSize: '0.9rem' }}
>
Börja om
</button>
</div>
</div>
)}
</div>
);
}
function primaryBtn(disabled: boolean): React.CSSProperties {
return {
padding: '0.6rem 1.25rem',
background: disabled ? '#aaa' : '#0070f3',
color: '#fff',
border: 'none',
borderRadius: '6px',
cursor: disabled ? 'not-allowed' : 'pointer',
fontWeight: 600,
fontSize: '0.95rem',
};
'use client';
import { useRef, useState, useEffect } from 'react';
type ParsedItem = {
rawName: string;
quantity: number;
unit: string;
price?: number | null;
matchedProductId?: number;
matchedProductName?: string;
suggestedProductId?: number;
suggestedProductName?: string;
};
type Product = { id: number; name: string; canonicalName: string | null };
type RowState = {
rawName: string;
quantity: number;
unit: string;
price?: number | null;
selectedProductId: number | '';
selectedProductName: string;
checked: boolean;
saveAlias: boolean;
editQty: string;
editUnit: string;
matchSource: 'alias' | 'suggestion' | 'manual' | 'none';
};
const UNITS = ['st', 'kg', 'g', 'l', 'dl', 'cl', 'ml', 'förp', 'pak', 'burk', 'flaska'];
export default function ReceiptImportClient() {
const fileRef = useRef<HTMLInputElement>(null);
const [preview, setPreview] = useState<string | null>(null);
const [parsing, setParsing] = useState(false);
const [saving, setSaving] = useState(false);
const [rows, setRows] = useState<RowState[]>([]);
const [allProducts, setAllProducts] = useState<Product[]>([]);
const [error, setError] = useState<string | null>(null);
const [savedCount, setSavedCount] = useState<number | null>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
useEffect(() => {
fetch('/api/products')
.then((r) => r.json())
.then((data) => { if (Array.isArray(data)) setAllProducts(data); })
.catch(() => {});
}, []);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setSelectedFile(file);
setPreview(file.type === 'application/pdf' ? 'pdf' : URL.createObjectURL(file));
setRows([]);
setError(null);
setSavedCount(null);
};
const handleParse = async () => {
if (!selectedFile) return;
setParsing(true);
setError(null);
try {
const fd = new FormData();
fd.append('file', selectedFile);
const res = await fetch('/api/receipt-import-proxy', { method: 'POST', body: fd });
if (!res.ok) {
const e = await res.json().catch(() => ({ message: 'Okänt fel' }));
throw new Error(e.message ?? 'Servern svarade med fel');
}
const items: ParsedItem[] = await res.json();
setRows(
items.map((item): RowState => {
if (item.matchedProductId) {
return {
rawName: item.rawName,
quantity: item.quantity,
unit: item.unit,
price: item.price,
selectedProductId: item.matchedProductId,
selectedProductName: item.matchedProductName ?? '',
checked: true,
saveAlias: false,
editQty: String(item.quantity),
editUnit: item.unit,
matchSource: 'alias',
};
}
if (item.suggestedProductId) {
return {
rawName: item.rawName,
quantity: item.quantity,
unit: item.unit,
price: item.price,
selectedProductId: item.suggestedProductId,
selectedProductName: item.suggestedProductName ?? '',
checked: false,
saveAlias: false,
editQty: String(item.quantity),
editUnit: item.unit,
matchSource: 'suggestion',
};
}
return {
rawName: item.rawName,
quantity: item.quantity,
unit: item.unit,
price: item.price,
selectedProductId: '',
selectedProductName: '',
checked: false,
saveAlias: false,
editQty: String(item.quantity),
editUnit: item.unit,
matchSource: 'none',
};
}),
);
} catch (err) {
setError(err instanceof Error ? err.message : 'Kunde inte tolka kvittot');
} finally {
setParsing(false);
}
};
const updateRow = (i: number, patch: Partial<RowState>) => {
setRows((prev) => prev.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));
};
const handleProductSelect = (i: number, productId: string) => {
if (!productId) {
updateRow(i, { selectedProductId: '', selectedProductName: '', checked: false, matchSource: 'none' });
return;
}
const prod = allProducts.find((p) => p.id === Number(productId));
if (prod) {
updateRow(i, {
selectedProductId: prod.id,
selectedProductName: prod.canonicalName ?? prod.name,
checked: true,
matchSource: 'manual',
saveAlias: true,
});
}
};
const handleSave = async () => {
const toSave = rows.filter((r) => r.checked && r.selectedProductId !== '');
if (toSave.length === 0) return;
setSaving(true);
setError(null);
try {
await Promise.all([
...toSave.map((r) =>
fetch('/api/inventory', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
productId: r.selectedProductId,
quantity: parseFloat(r.editQty) || r.quantity,
unit: r.editUnit,
brand: r.rawName,
}),
}),
),
...toSave
.filter((r) => r.saveAlias && r.selectedProductId !== '')
.map((r) =>
fetch('/api/receipt-alias-proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
receiptName: r.rawName,
productId: r.selectedProductId,
}),
}),
),
]);
setSavedCount(toSave.length);
setRows([]);
setPreview(null);
setSelectedFile(null);
if (fileRef.current) fileRef.current.value = '';
} catch {
setError('Något gick fel vid sparning. Försök igen.');
} finally {
setSaving(false);
}
};
const checkedCount = rows.filter((r) => r.checked && r.selectedProductId !== '').length;
const sourceLabel = (src: RowState['matchSource']) => {
if (src === 'alias') return { text: 'Känd vara', color: '#27ae60' };
if (src === 'suggestion') return { text: 'Förslag', color: '#e67e22' };
if (src === 'manual') return { text: 'Manuellt vald', color: '#0070f3' };
return null;
};
return (
<div>
<div
style={{ border: '2px dashed #ced4da', borderRadius: '10px', padding: '1.5rem', textAlign: 'center', background: '#fafafa', marginBottom: '1rem', cursor: 'pointer' }}
onClick={() => fileRef.current?.click()}
>
<input ref={fileRef} type="file" accept="image/*,application/pdf" capture="environment" onChange={handleFileChange} style={{ display: 'none' }} />
{preview === 'pdf' ? (
<div style={{ padding: '1rem' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📄</div>
<div style={{ fontWeight: 600 }}>{selectedFile?.name}</div>
<div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>PDF-kvitto valt</div>
</div>
) : preview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={preview} alt="Kvittoförhandsgranskning" style={{ maxHeight: '300px', maxWidth: '100%', borderRadius: '6px' }} />
) : (
<div style={{ color: '#888' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📷</div>
<div style={{ fontWeight: 600 }}>Fotografera eller välj kvitto</div>
<div style={{ fontSize: '0.85rem', marginTop: '0.25rem' }}>Klicka för att välja bild (JPEG, PNG, WebP) eller PDF</div>
</div>
)}
</div>
{preview && rows.length === 0 && (
<button onClick={handleParse} disabled={parsing} style={primaryBtn(parsing)}>
{parsing ? '⏳ Läser kvitto...' : '🔍 Läs kvitto'}
</button>
)}
{error && (
<p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}>{error}</p>
)}
{savedCount !== null && (
<p style={{ color: '#27ae60', background: '#edfdf4', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem', fontWeight: 600 }}>
{savedCount} {savedCount === 1 ? 'vara lades till' : 'varor lades till'} i inventariet.
</p>
)}
{rows.length > 0 && (
<div style={{ marginTop: '1.25rem' }}>
<div style={{ marginBottom: '0.75rem', display: 'flex', gap: '1rem', alignItems: 'baseline', flexWrap: 'wrap' }}>
<h2 style={{ margin: 0, fontSize: '1.05rem' }}>Identifierade varor ({rows.length})</h2>
<span style={{ fontSize: '0.8rem', color: '#888' }}>Grön = känd koppling · Orange = förslag · Välj manuellt om inget förslag</span>
</div>
<div style={{ display: 'grid', gap: '0.5rem', marginBottom: '1rem' }}>
{rows.map((row, i) => {
const label = sourceLabel(row.matchSource);
return (
<div key={i} style={{ padding: '0.75rem 1rem', border: `1px solid ${row.matchSource === 'alias' ? '#a8d5b5' : row.matchSource === 'suggestion' ? '#f5cba7' : '#dee2e6'}`, borderRadius: '8px', background: row.matchSource === 'alias' ? '#f0faf4' : row.matchSource === 'suggestion' ? '#fef9f5' : '#fff' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', marginBottom: '0.5rem', flexWrap: 'wrap' }}>
<input type="checkbox" checked={row.checked} disabled={row.selectedProductId === ''} onChange={(e) => updateRow(i, { checked: e.target.checked })} style={{ width: '18px', height: '18px', cursor: row.selectedProductId !== '' ? 'pointer' : 'not-allowed' }} />
<span style={{ fontWeight: 500 }}>{row.rawName}</span>
{label && (
<span style={{ fontSize: '0.75rem', color: label.color, border: `1px solid ${label.color}`, borderRadius: '4px', padding: '1px 6px' }}>{label.text}</span>
)}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 80px 90px', gap: '0.5rem', alignItems: 'center' }}>
<select value={row.selectedProductId} onChange={(e) => handleProductSelect(i, e.target.value)} style={{ padding: '0.35rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.9rem' }}>
<option value=""> Välj produkt </option>
{allProducts.map((p) => (
<option key={p.id} value={p.id}>{p.canonicalName ?? p.name}</option>
))}
</select>
<input type="number" min="0" step="0.01" value={row.editQty} onChange={(e) => updateRow(i, { editQty: e.target.value })} style={{ padding: '0.35rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.9rem' }} />
<select value={row.editUnit} onChange={(e) => updateRow(i, { editUnit: e.target.value })} style={{ padding: '0.35rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.9rem' }}>
{UNITS.map((u) => <option key={u} value={u}>{u}</option>)}
</select>
</div>
{row.selectedProductId !== '' && row.matchSource !== 'alias' && (
<label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', marginTop: '0.5rem', fontSize: '0.82rem', color: '#555', cursor: 'pointer' }}>
<input type="checkbox" checked={row.saveAlias} onChange={(e) => updateRow(i, { saveAlias: e.target.checked })} />
Kom ihåg kopplingen nästa gång matchas &quot;{row.rawName}&quot; automatiskt
</label>
)}
</div>
);
})}
</div>
<div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
<button onClick={handleSave} disabled={saving || checkedCount === 0} style={primaryBtn(saving || checkedCount === 0)}>
{saving ? 'Sparar...' : `Lägg till ${checkedCount} ${checkedCount === 1 ? 'vara' : 'varor'} i inventariet`}
</button>
<button onClick={() => { setRows([]); setPreview(null); setSelectedFile(null); if (fileRef.current) fileRef.current.value = ''; }} style={{ padding: '0.5rem 1rem', background: '#f0f0f0', border: '1px solid #ccc', borderRadius: '6px', cursor: 'pointer', fontSize: '0.9rem' }}>
Börja om
</button>
</div>
</div>
)}
</div>
);
}
function primaryBtn(disabled: boolean): React.CSSProperties {
return { padding: '0.6rem 1.25rem', background: disabled ? '#aaa' : '#0070f3', color: '#fff', border: 'none', borderRadius: '6px', cursor: disabled ? 'not-allowed' : 'pointer', fontWeight: 600, fontSize: '0.95rem' };
}