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,14 @@
-- CreateTable
CREATE TABLE `ReceiptAlias` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`receiptName` VARCHAR(191) NOT NULL,
`productId` INTEGER NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE INDEX `ReceiptAlias_receiptName_key`(`receiptName`),
INDEX `ReceiptAlias_productId_idx`(`productId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `ReceiptAlias` ADD CONSTRAINT `ReceiptAlias_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Product`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
+9
View File
@@ -21,6 +21,7 @@ model Product {
inventoryItems InventoryItem[] inventoryItems InventoryItem[]
recipeIngredients RecipeIngredient[] recipeIngredients RecipeIngredient[]
pantryItems PantryItem[] pantryItems PantryItem[]
receiptAliases ReceiptAlias[]
} }
model InventoryItem { model InventoryItem {
@@ -95,6 +96,14 @@ model PantryItem {
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }
model ReceiptAlias {
id Int @id @default(autoincrement())
receiptName String @unique // normaliserat kvittonamn (lowercase, trim)
productId Int
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
}
model MealPlanEntry { model MealPlanEntry {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
date DateTime @db.Date date DateTime @db.Date
+2
View File
@@ -8,6 +8,7 @@ import { QuickImportModule } from './quick-import/quick-import.module';
import { PantryModule } from './pantry/pantry.module'; import { PantryModule } from './pantry/pantry.module';
import { MealPlanModule } from './meal-plan/meal-plan.module'; import { MealPlanModule } from './meal-plan/meal-plan.module';
import { ReceiptImportModule } from './receipt-import/receipt-import.module'; import { ReceiptImportModule } from './receipt-import/receipt-import.module';
import { ReceiptAliasModule } from './receipt-alias/receipt-alias.module';
@Module({ @Module({
@@ -21,6 +22,7 @@ import { ReceiptImportModule } from './receipt-import/receipt-import.module';
PantryModule, PantryModule,
MealPlanModule, MealPlanModule,
ReceiptImportModule, ReceiptImportModule,
ReceiptAliasModule,
], ],
}) })
export class AppModule {} export class AppModule {}
@@ -0,0 +1,10 @@
import { IsInt, IsString, MinLength } from 'class-validator';
export class CreateReceiptAliasDto {
@IsString()
@MinLength(1)
receiptName!: string;
@IsInt()
productId!: number;
}
@@ -0,0 +1,23 @@
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post } from '@nestjs/common';
import { ReceiptAliasService } from './receipt-alias.service';
import { CreateReceiptAliasDto } from './dto/create-receipt-alias.dto';
@Controller('receipt-aliases')
export class ReceiptAliasController {
constructor(private readonly receiptAliasService: ReceiptAliasService) {}
@Get()
findAll() {
return this.receiptAliasService.findAll();
}
@Post()
upsert(@Body() dto: CreateReceiptAliasDto) {
return this.receiptAliasService.upsert(dto);
}
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number) {
return this.receiptAliasService.remove(id);
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { ReceiptAliasController } from './receipt-alias.controller';
import { ReceiptAliasService } from './receipt-alias.service';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [PrismaModule],
controllers: [ReceiptAliasController],
providers: [ReceiptAliasService],
exports: [ReceiptAliasService],
})
export class ReceiptAliasModule {}
@@ -0,0 +1,28 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateReceiptAliasDto } from './dto/create-receipt-alias.dto';
@Injectable()
export class ReceiptAliasService {
constructor(private readonly prisma: PrismaService) {}
findAll() {
return this.prisma.receiptAlias.findMany({
include: { product: { select: { id: true, name: true, canonicalName: true } } },
orderBy: { receiptName: 'asc' },
});
}
async upsert(dto: CreateReceiptAliasDto) {
const normalized = dto.receiptName.toLowerCase().trim();
return this.prisma.receiptAlias.upsert({
where: { receiptName: normalized },
create: { receiptName: normalized, productId: dto.productId },
update: { productId: dto.productId },
});
}
remove(id: number) {
return this.prisma.receiptAlias.delete({ where: { id } });
}
}
@@ -3,6 +3,10 @@ export interface ParsedReceiptItem {
quantity: number; quantity: number;
unit: string; unit: string;
price?: number | null; price?: number | null;
// alias-match: säker, användaren slipper bekräfta
matchedProductId?: number; matchedProductId?: number;
matchedProductName?: string; matchedProductName?: string;
// ordbaserad match: förslag, kräver bekräftelse
suggestedProductId?: number;
suggestedProductName?: string;
} }
@@ -131,8 +131,16 @@ export class ReceiptImportService {
): Promise<ParsedReceiptItem[]> { ): Promise<ParsedReceiptItem[]> {
if (!response.ok) { if (!response.ok) {
const err = await response.text(); const err = await response.text();
this.logger.error(`Mistral API svarade ${response.status}: ${err}`); this.logger.error(`Mistral API svarade ${response.status} (${source}): ${err}`);
throw new ServiceUnavailableException('Mistral API returnerade ett fel — kontrollera API-nyckeln'); const hint =
response.status === 401
? 'Ogiltig API-nyckel (401)'
: response.status === 429
? 'För många förfrågningar — försök igen om en stund (429)'
: `HTTP ${response.status}`;
throw new ServiceUnavailableException(
`Mistral API returnerade ett fel: ${hint}`,
);
} }
const data = (await response.json()) as { const data = (await response.json()) as {
@@ -156,35 +164,61 @@ export class ReceiptImportService {
private async matchProducts( private async matchProducts(
items: ParsedReceiptItem[], items: ParsedReceiptItem[],
): Promise<ParsedReceiptItem[]> { ): Promise<ParsedReceiptItem[]> {
const products = await this.prisma.product.findMany({ // Hämta alias och produkter parallellt
select: { id: true, name: true, canonicalName: true }, const [aliases, products] = await Promise.all([
}); this.prisma.receiptAlias.findMany({
select: { receiptName: true, productId: true, product: { select: { id: true, name: true, canonicalName: true } } },
}),
this.prisma.product.findMany({
where: { isActive: true },
select: { id: true, name: true, canonicalName: true },
}),
]);
return items.map((item) => { return items.map((item) => {
const raw = (item.rawName ?? '').toLowerCase().trim(); const raw = (item.rawName ?? '').toLowerCase().trim();
if (!raw) return item; if (!raw) return item;
// Exakt matchning först // 1. Alias-match (säker, användaren behöver inte bekräfta)
let match = products.find((p) => { const alias = aliases.find((a) => a.receiptName === raw);
const n = (p.canonicalName ?? p.name).toLowerCase(); if (alias) {
return n === raw || p.name.toLowerCase() === raw; return {
}); ...item,
matchedProductId: alias.product.id,
// Delvis matchning matchedProductName: alias.product.canonicalName ?? alias.product.name,
if (!match) { };
match = products.find((p) => {
const n = (p.canonicalName ?? p.name).toLowerCase();
return n.includes(raw) || raw.includes(n);
});
} }
// 2. Ordbaserad matchning (förslag, kräver bekräftelse)
const suggestion = this.findWordMatch(raw, products);
return { return {
...item, ...item,
matchedProductId: match?.id, suggestedProductId: suggestion?.id,
matchedProductName: match suggestedProductName: suggestion
? (match.canonicalName ?? match.name) ? (suggestion.canonicalName ?? suggestion.name)
: undefined, : undefined,
}; };
}); });
} }
private findWordMatch(
raw: string,
products: { id: number; name: string; canonicalName: string | null }[],
): { id: number; name: string; canonicalName: string | null } | undefined {
// Dela upp kvittonamnet i ord (min 3 tecken)
const rawWords = raw.split(/[\s\-_]+/).filter((w) => w.length >= 3);
if (rawWords.length === 0) return undefined;
// Fortsätt med att hitta produkter där ett produktnamn-ord finns i kvittonamnet
// Exempel: produktord "ost" finns i kvittoord "prästost", "herrgårdsost", "brieost"
return products.find((p) => {
const productWords = (p.canonicalName ?? p.name)
.toLowerCase()
.split(/[\s\-_]+/)
.filter((w) => w.length >= 3);
return productWords.some((pw) =>
rawWords.some((rw) => rw.includes(pw) || pw.includes(rw)),
);
});
}
} }
@@ -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'; 'use client';
import { useRef, useState } from 'react'; import { useRef, useState, useEffect } from 'react';
type ParsedItem = { type ParsedItem = {
rawName: string; rawName: string;
quantity: number; quantity: number;
unit: string; unit: string;
price?: number | null; price?: number | null;
matchedProductId?: number; matchedProductId?: number;
matchedProductName?: string; matchedProductName?: string;
}; suggestedProductId?: number;
suggestedProductName?: string;
type RowState = ParsedItem & { checked: boolean; editQty: string; editUnit: string }; };
const UNITS = ['st', 'kg', 'g', 'l', 'dl', 'cl', 'ml', 'förp', 'pak', 'burk', 'flaska']; type Product = { id: number; name: string; canonicalName: string | null };
export default function ReceiptImportClient() { type RowState = {
const fileRef = useRef<HTMLInputElement>(null); rawName: string;
const [preview, setPreview] = useState<string | null>(null); quantity: number;
const [parsing, setParsing] = useState(false); unit: string;
const [saving, setSaving] = useState(false); price?: number | null;
const [rows, setRows] = useState<RowState[]>([]); selectedProductId: number | '';
const [error, setError] = useState<string | null>(null); selectedProductName: string;
const [savedCount, setSavedCount] = useState<number | null>(null); checked: boolean;
const [selectedFile, setSelectedFile] = useState<File | null>(null); saveAlias: boolean;
editQty: string;
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => { editUnit: string;
const file = e.target.files?.[0]; matchSource: 'alias' | 'suggestion' | 'manual' | 'none';
if (!file) return; };
setSelectedFile(file);
if (file.type === 'application/pdf') { const UNITS = ['st', 'kg', 'g', 'l', 'dl', 'cl', 'ml', 'förp', 'pak', 'burk', 'flaska'];
setPreview('pdf');
} else { export default function ReceiptImportClient() {
setPreview(URL.createObjectURL(file)); const fileRef = useRef<HTMLInputElement>(null);
} const [preview, setPreview] = useState<string | null>(null);
setRows([]); const [parsing, setParsing] = useState(false);
setError(null); const [saving, setSaving] = useState(false);
setSavedCount(null); const [rows, setRows] = useState<RowState[]>([]);
}; const [allProducts, setAllProducts] = useState<Product[]>([]);
const [error, setError] = useState<string | null>(null);
const handleParse = async () => { const [savedCount, setSavedCount] = useState<number | null>(null);
if (!selectedFile) return; const [selectedFile, setSelectedFile] = useState<File | null>(null);
setParsing(true);
setError(null); useEffect(() => {
try { fetch('/api/products')
const fd = new FormData(); .then((r) => r.json())
fd.append('file', selectedFile); .then((data) => { if (Array.isArray(data)) setAllProducts(data); })
const res = await fetch('/api/receipt-import-proxy', { method: 'POST', body: fd }); .catch(() => {});
if (!res.ok) { }, []);
const e = await res.json().catch(() => ({ message: 'Okänt fel' }));
throw new Error(e.message ?? 'Servern svarade med fel'); const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
} const file = e.target.files?.[0];
const items: ParsedItem[] = await res.json(); if (!file) return;
setRows( setSelectedFile(file);
items.map((item) => ({ setPreview(file.type === 'application/pdf' ? 'pdf' : URL.createObjectURL(file));
...item, setRows([]);
checked: !!item.matchedProductId, setError(null);
editQty: String(item.quantity), setSavedCount(null);
editUnit: item.unit, };
})),
); const handleParse = async () => {
} catch (err) { if (!selectedFile) return;
setError(err instanceof Error ? err.message : 'Kunde inte tolka kvittot'); setParsing(true);
} finally { setError(null);
setParsing(false); try {
} const fd = new FormData();
}; fd.append('file', selectedFile);
const res = await fetch('/api/receipt-import-proxy', { method: 'POST', body: fd });
const updateRow = (i: number, patch: Partial<RowState>) => { if (!res.ok) {
setRows((prev) => prev.map((r, idx) => (idx === i ? { ...r, ...patch } : r))); const e = await res.json().catch(() => ({ message: 'Okänt fel' }));
}; throw new Error(e.message ?? 'Servern svarade med fel');
}
const handleSave = async () => { const items: ParsedItem[] = await res.json();
const toSave = rows.filter((r) => r.checked && r.matchedProductId); setRows(
if (toSave.length === 0) return; items.map((item): RowState => {
setSaving(true); if (item.matchedProductId) {
setError(null); return {
try { rawName: item.rawName,
await Promise.all( quantity: item.quantity,
toSave.map((r) => unit: item.unit,
fetch('/api/inventory', { price: item.price,
method: 'POST', selectedProductId: item.matchedProductId,
headers: { 'Content-Type': 'application/json' }, selectedProductName: item.matchedProductName ?? '',
body: JSON.stringify({ checked: true,
productId: r.matchedProductId, saveAlias: false,
quantity: parseFloat(r.editQty) || r.quantity, editQty: String(item.quantity),
unit: r.editUnit, editUnit: item.unit,
}), matchSource: 'alias',
}), };
), }
); if (item.suggestedProductId) {
setSavedCount(toSave.length); return {
setRows([]); rawName: item.rawName,
setPreview(null); quantity: item.quantity,
setSelectedFile(null); unit: item.unit,
if (fileRef.current) fileRef.current.value = ''; price: item.price,
} catch { selectedProductId: item.suggestedProductId,
setError('Något gick fel vid sparning. Försök igen.'); selectedProductName: item.suggestedProductName ?? '',
} finally { checked: false,
setSaving(false); saveAlias: false,
} editQty: String(item.quantity),
}; editUnit: item.unit,
matchSource: 'suggestion',
const checkedCount = rows.filter((r) => r.checked && r.matchedProductId).length; };
const unmatchedCount = rows.filter((r) => !r.matchedProductId).length; }
return {
return ( rawName: item.rawName,
<div> quantity: item.quantity,
{/* Fil-input */} unit: item.unit,
<div price: item.price,
style={{ selectedProductId: '',
border: '2px dashed #ced4da', selectedProductName: '',
borderRadius: '10px', checked: false,
padding: '1.5rem', saveAlias: false,
textAlign: 'center', editQty: String(item.quantity),
background: '#fafafa', editUnit: item.unit,
marginBottom: '1rem', matchSource: 'none',
cursor: 'pointer', };
}} }),
onClick={() => fileRef.current?.click()} );
> } catch (err) {
<input setError(err instanceof Error ? err.message : 'Kunde inte tolka kvittot');
ref={fileRef} } finally {
type="file" setParsing(false);
accept="image/*,application/pdf" }
capture="environment" };
onChange={handleFileChange}
style={{ display: 'none' }} const updateRow = (i: number, patch: Partial<RowState>) => {
/> setRows((prev) => prev.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));
{preview === 'pdf' ? ( };
<div style={{ padding: '1rem', color: '#333' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📄</div> const handleProductSelect = (i: number, productId: string) => {
<div style={{ fontWeight: 600 }}>{selectedFile?.name}</div> if (!productId) {
<div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>PDF-kvitto valt</div> updateRow(i, { selectedProductId: '', selectedProductName: '', checked: false, matchSource: 'none' });
</div> return;
) : preview ? ( }
// eslint-disable-next-line @next/next/no-img-element const prod = allProducts.find((p) => p.id === Number(productId));
<img if (prod) {
src={preview} updateRow(i, {
alt="Kvittoförhandsgranskning" selectedProductId: prod.id,
style={{ maxHeight: '300px', maxWidth: '100%', borderRadius: '6px' }} selectedProductName: prod.canonicalName ?? prod.name,
/> checked: true,
) : ( matchSource: 'manual',
<div style={{ color: '#888' }}> saveAlias: true,
<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> const handleSave = async () => {
</div> const toSave = rows.filter((r) => r.checked && r.selectedProductId !== '');
)} if (toSave.length === 0) return;
</div> setSaving(true);
setError(null);
{preview && rows.length === 0 && ( try {
<button await Promise.all([
onClick={handleParse} ...toSave.map((r) =>
disabled={parsing} fetch('/api/inventory', {
style={primaryBtn(parsing)} method: 'POST',
> headers: { 'Content-Type': 'application/json' },
{parsing ? '⏳ Tolkar kvitto via AI...' : '🔍 Tolka kvitto'} body: JSON.stringify({
</button> productId: r.selectedProductId,
)} quantity: parseFloat(r.editQty) || r.quantity,
unit: r.editUnit,
{error && ( brand: r.rawName,
<p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}> }),
{error} }),
</p> ),
)} ...toSave
.filter((r) => r.saveAlias && r.selectedProductId !== '')
{savedCount !== null && ( .map((r) =>
<p style={{ color: '#27ae60', background: '#edfdf4', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem', fontWeight: 600 }}> fetch('/api/receipt-alias-proxy', {
{savedCount} {savedCount === 1 ? 'vara lades till' : 'varor lades till'} i inventariet. method: 'POST',
</p> headers: { 'Content-Type': 'application/json' },
)} body: JSON.stringify({
receiptName: r.rawName,
{/* Parsade rader */} productId: r.selectedProductId,
{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}) setSavedCount(toSave.length);
</h2> setRows([]);
{unmatchedCount > 0 && ( setPreview(null);
<span style={{ fontSize: '0.8rem', color: '#e67e22' }}> setSelectedFile(null);
{unmatchedCount} {unmatchedCount === 1 ? 'vara' : 'varor'} saknas i produktdatabasen if (fileRef.current) fileRef.current.value = '';
</span> } catch {
)} setError('Något gick fel vid sparning. Försök igen.');
</div> } finally {
setSaving(false);
<div style={{ display: 'grid', gap: '0.5rem', marginBottom: '1rem' }}> }
{rows.map((row, i) => { };
const matched = !!row.matchedProductId;
return ( const checkedCount = rows.filter((r) => r.checked && r.selectedProductId !== '').length;
<div
key={i} const sourceLabel = (src: RowState['matchSource']) => {
style={{ if (src === 'alias') return { text: 'Känd vara', color: '#27ae60' };
display: 'grid', if (src === 'suggestion') return { text: 'Förslag', color: '#e67e22' };
gridTemplateColumns: '36px 1fr 80px 90px', if (src === 'manual') return { text: 'Manuellt vald', color: '#0070f3' };
gap: '0.5rem', return null;
alignItems: 'center', };
padding: '0.6rem 0.75rem',
border: `1px solid ${matched ? '#dee2e6' : '#f5cba7'}`, return (
borderRadius: '6px', <div>
background: matched ? '#fff' : '#fef9f5', <div
opacity: row.checked || !matched ? 1 : 0.7, style={{ border: '2px dashed #ced4da', borderRadius: '10px', padding: '1.5rem', textAlign: 'center', background: '#fafafa', marginBottom: '1rem', cursor: 'pointer' }}
}} onClick={() => fileRef.current?.click()}
> >
<input <input ref={fileRef} type="file" accept="image/*,application/pdf" capture="environment" onChange={handleFileChange} style={{ display: 'none' }} />
type="checkbox" {preview === 'pdf' ? (
checked={row.checked} <div style={{ padding: '1rem' }}>
disabled={!matched} <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📄</div>
onChange={(e) => updateRow(i, { checked: e.target.checked })} <div style={{ fontWeight: 600 }}>{selectedFile?.name}</div>
style={{ width: '18px', height: '18px', cursor: matched ? 'pointer' : 'not-allowed' }} <div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>PDF-kvitto valt</div>
title={!matched ? 'Produkten finns inte i databasen — lägg till den i admin först' : ''} </div>
/> ) : preview ? (
<div> // eslint-disable-next-line @next/next/no-img-element
<div style={{ fontWeight: 500, fontSize: '0.9rem' }}> <img src={preview} alt="Kvittoförhandsgranskning" style={{ maxHeight: '300px', maxWidth: '100%', borderRadius: '6px' }} />
{row.matchedProductName ?? row.rawName} ) : (
</div> <div style={{ color: '#888' }}>
{row.matchedProductName && row.matchedProductName.toLowerCase() !== row.rawName.toLowerCase() && ( <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📷</div>
<div style={{ fontSize: '0.75rem', color: '#888' }}> <div style={{ fontWeight: 600 }}>Fotografera eller välj kvitto</div>
Kvitto: {row.rawName} <div style={{ fontSize: '0.85rem', marginTop: '0.25rem' }}>Klicka för att välja bild (JPEG, PNG, WebP) eller PDF</div>
</div> </div>
)} )}
{!matched && ( </div>
<div style={{ fontSize: '0.75rem', color: '#e67e22' }}>
Ingen matchning {row.rawName} {preview && rows.length === 0 && (
</div> <button onClick={handleParse} disabled={parsing} style={primaryBtn(parsing)}>
)} {parsing ? '⏳ Läser kvitto...' : '🔍 Läs kvitto'}
</div> </button>
<input )}
type="number"
min="0" {error && (
step="0.01" <p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}>{error}</p>
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' }} {savedCount !== null && (
/> <p style={{ color: '#27ae60', background: '#edfdf4', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem', fontWeight: 600 }}>
<select {savedCount} {savedCount === 1 ? 'vara lades till' : 'varor lades till'} i inventariet.
value={row.editUnit} </p>
onChange={(e) => updateRow(i, { editUnit: e.target.value })} )}
style={{ padding: '0.3rem 0.5rem', border: '1px solid #ced4da', borderRadius: '4px', fontSize: '0.9rem' }}
> {rows.length > 0 && (
{UNITS.map((u) => <option key={u} value={u}>{u}</option>)} <div style={{ marginTop: '1.25rem' }}>
</select> <div style={{ marginBottom: '0.75rem', display: 'flex', gap: '1rem', alignItems: 'baseline', flexWrap: 'wrap' }}>
</div> <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>
<div style={{ display: 'grid', gap: '0.5rem', marginBottom: '1rem' }}>
<div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}> {rows.map((row, i) => {
<button const label = sourceLabel(row.matchSource);
onClick={handleSave} return (
disabled={saving || checkedCount === 0} <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' }}>
style={primaryBtn(saving || checkedCount === 0)} <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' }} />
{saving ? 'Sparar...' : `Lägg till ${checkedCount} ${checkedCount === 1 ? 'vara' : 'varor'} i inventariet`} <span style={{ fontWeight: 500 }}>{row.rawName}</span>
</button> {label && (
<button <span style={{ fontSize: '0.75rem', color: label.color, border: `1px solid ${label.color}`, borderRadius: '4px', padding: '1px 6px' }}>{label.text}</span>
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' }} </div>
> <div style={{ display: 'grid', gridTemplateColumns: '1fr 80px 90px', gap: '0.5rem', alignItems: 'center' }}>
Börja om <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' }}>
</button> <option value=""> Välj produkt </option>
</div> {allProducts.map((p) => (
</div> <option key={p.id} value={p.id}>{p.canonicalName ?? p.name}</option>
)} ))}
</div> </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>)}
function primaryBtn(disabled: boolean): React.CSSProperties { </select>
return { </div>
padding: '0.6rem 1.25rem', {row.selectedProductId !== '' && row.matchSource !== 'alias' && (
background: disabled ? '#aaa' : '#0070f3', <label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', marginTop: '0.5rem', fontSize: '0.82rem', color: '#555', cursor: 'pointer' }}>
color: '#fff', <input type="checkbox" checked={row.saveAlias} onChange={(e) => updateRow(i, { saveAlias: e.target.checked })} />
border: 'none', Kom ihåg kopplingen nästa gång matchas &quot;{row.rawName}&quot; automatiskt
borderRadius: '6px', </label>
cursor: disabled ? 'not-allowed' : 'pointer', )}
fontWeight: 600, </div>
fontSize: '0.95rem', );
}; })}
</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' };
} }