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 });
}
+155 -137
View File
@@ -1,6 +1,6 @@
'use client'; 'use client';
import { useRef, useState } from 'react'; import { useRef, useState, useEffect } from 'react';
type ParsedItem = { type ParsedItem = {
rawName: string; rawName: string;
@@ -9,9 +9,25 @@ type ParsedItem = {
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 }; 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']; const UNITS = ['st', 'kg', 'g', 'l', 'dl', 'cl', 'ml', 'förp', 'pak', 'burk', 'flaska'];
@@ -21,19 +37,23 @@ export default function ReceiptImportClient() {
const [parsing, setParsing] = useState(false); const [parsing, setParsing] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [rows, setRows] = useState<RowState[]>([]); const [rows, setRows] = useState<RowState[]>([]);
const [allProducts, setAllProducts] = useState<Product[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [savedCount, setSavedCount] = useState<number | null>(null); const [savedCount, setSavedCount] = useState<number | null>(null);
const [selectedFile, setSelectedFile] = useState<File | 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 handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
setSelectedFile(file); setSelectedFile(file);
if (file.type === 'application/pdf') { setPreview(file.type === 'application/pdf' ? 'pdf' : URL.createObjectURL(file));
setPreview('pdf');
} else {
setPreview(URL.createObjectURL(file));
}
setRows([]); setRows([]);
setError(null); setError(null);
setSavedCount(null); setSavedCount(null);
@@ -53,12 +73,51 @@ export default function ReceiptImportClient() {
} }
const items: ParsedItem[] = await res.json(); const items: ParsedItem[] = await res.json();
setRows( setRows(
items.map((item) => ({ items.map((item): RowState => {
...item, if (item.matchedProductId) {
checked: !!item.matchedProductId, return {
editQty: String(item.quantity), rawName: item.rawName,
editUnit: item.unit, 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) { } catch (err) {
setError(err instanceof Error ? err.message : 'Kunde inte tolka kvittot'); setError(err instanceof Error ? err.message : 'Kunde inte tolka kvittot');
@@ -71,25 +130,55 @@ export default function ReceiptImportClient() {
setRows((prev) => prev.map((r, idx) => (idx === i ? { ...r, ...patch } : r))); 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 handleSave = async () => {
const toSave = rows.filter((r) => r.checked && r.matchedProductId); const toSave = rows.filter((r) => r.checked && r.selectedProductId !== '');
if (toSave.length === 0) return; if (toSave.length === 0) return;
setSaving(true); setSaving(true);
setError(null); setError(null);
try { try {
await Promise.all( await Promise.all([
toSave.map((r) => ...toSave.map((r) =>
fetch('/api/inventory', { fetch('/api/inventory', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
productId: r.matchedProductId, productId: r.selectedProductId,
quantity: parseFloat(r.editQty) || r.quantity, quantity: parseFloat(r.editQty) || r.quantity,
unit: r.editUnit, 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); setSavedCount(toSave.length);
setRows([]); setRows([]);
setPreview(null); setPreview(null);
@@ -102,70 +191,48 @@ export default function ReceiptImportClient() {
} }
}; };
const checkedCount = rows.filter((r) => r.checked && r.matchedProductId).length; const checkedCount = rows.filter((r) => r.checked && r.selectedProductId !== '').length;
const unmatchedCount = rows.filter((r) => !r.matchedProductId).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 ( return (
<div> <div>
{/* Fil-input */}
<div <div
style={{ style={{ border: '2px dashed #ced4da', borderRadius: '10px', padding: '1.5rem', textAlign: 'center', background: '#fafafa', marginBottom: '1rem', cursor: 'pointer' }}
border: '2px dashed #ced4da',
borderRadius: '10px',
padding: '1.5rem',
textAlign: 'center',
background: '#fafafa',
marginBottom: '1rem',
cursor: 'pointer',
}}
onClick={() => fileRef.current?.click()} onClick={() => fileRef.current?.click()}
> >
<input <input ref={fileRef} type="file" accept="image/*,application/pdf" capture="environment" onChange={handleFileChange} style={{ display: 'none' }} />
ref={fileRef}
type="file"
accept="image/*,application/pdf"
capture="environment"
onChange={handleFileChange}
style={{ display: 'none' }}
/>
{preview === 'pdf' ? ( {preview === 'pdf' ? (
<div style={{ padding: '1rem', color: '#333' }}> <div style={{ padding: '1rem' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📄</div> <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📄</div>
<div style={{ fontWeight: 600 }}>{selectedFile?.name}</div> <div style={{ fontWeight: 600 }}>{selectedFile?.name}</div>
<div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>PDF-kvitto valt</div> <div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>PDF-kvitto valt</div>
</div> </div>
) : preview ? ( ) : preview ? (
// eslint-disable-next-line @next/next/no-img-element // eslint-disable-next-line @next/next/no-img-element
<img <img src={preview} alt="Kvittoförhandsgranskning" style={{ maxHeight: '300px', maxWidth: '100%', borderRadius: '6px' }} />
src={preview}
alt="Kvittoförhandsgranskning"
style={{ maxHeight: '300px', maxWidth: '100%', borderRadius: '6px' }}
/>
) : ( ) : (
<div style={{ color: '#888' }}> <div style={{ color: '#888' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📷</div> <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📷</div>
<div style={{ fontWeight: 600 }}>Fotografera eller välj kvitto</div> <div style={{ fontWeight: 600 }}>Fotografera eller välj kvitto</div>
<div style={{ fontSize: '0.85rem', marginTop: '0.25rem' }}> <div style={{ fontSize: '0.85rem', marginTop: '0.25rem' }}>Klicka för att välja bild (JPEG, PNG, WebP) eller PDF</div>
Klicka för att välja bild (JPEG, PNG, WebP) eller PDF
</div>
</div> </div>
)} )}
</div> </div>
{preview && rows.length === 0 && ( {preview && rows.length === 0 && (
<button <button onClick={handleParse} disabled={parsing} style={primaryBtn(parsing)}>
onClick={handleParse} {parsing ? '⏳ Läser kvitto...' : '🔍 Läs kvitto'}
disabled={parsing}
style={primaryBtn(parsing)}
>
{parsing ? '⏳ Tolkar kvitto via AI...' : '🔍 Tolka kvitto'}
</button> </button>
)} )}
{error && ( {error && (
<p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}> <p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}>{error}</p>
{error}
</p>
)} )}
{savedCount !== null && ( {savedCount !== null && (
@@ -174,93 +241,53 @@ export default function ReceiptImportClient() {
</p> </p>
)} )}
{/* Parsade rader */}
{rows.length > 0 && ( {rows.length > 0 && (
<div style={{ marginTop: '1.25rem' }}> <div style={{ marginTop: '1.25rem' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '0.5rem' }}> <div style={{ marginBottom: '0.75rem', display: 'flex', gap: '1rem', alignItems: 'baseline', flexWrap: 'wrap' }}>
<h2 style={{ margin: 0, fontSize: '1.05rem' }}> <h2 style={{ margin: 0, fontSize: '1.05rem' }}>Identifierade varor ({rows.length})</h2>
Identifierade varor ({rows.length}) <span style={{ fontSize: '0.8rem', color: '#888' }}>Grön = känd koppling · Orange = förslag · Välj manuellt om inget förslag</span>
</h2>
{unmatchedCount > 0 && (
<span style={{ fontSize: '0.8rem', color: '#e67e22' }}>
{unmatchedCount} {unmatchedCount === 1 ? 'vara' : 'varor'} saknas i produktdatabasen
</span>
)}
</div> </div>
<div style={{ display: 'grid', gap: '0.5rem', marginBottom: '1rem' }}> <div style={{ display: 'grid', gap: '0.5rem', marginBottom: '1rem' }}>
{rows.map((row, i) => { {rows.map((row, i) => {
const matched = !!row.matchedProductId; const label = sourceLabel(row.matchSource);
return ( return (
<div <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' }}>
key={i} <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', marginBottom: '0.5rem', flexWrap: 'wrap' }}>
style={{ <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' }} />
display: 'grid', <span style={{ fontWeight: 500 }}>{row.rawName}</span>
gridTemplateColumns: '36px 1fr 80px 90px', {label && (
gap: '0.5rem', <span style={{ fontSize: '0.75rem', color: label.color, border: `1px solid ${label.color}`, borderRadius: '4px', padding: '1px 6px' }}>{label.text}</span>
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> </div>
<input <div style={{ display: 'grid', gridTemplateColumns: '1fr 80px 90px', gap: '0.5rem', alignItems: 'center' }}>
type="number" <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' }}>
min="0" <option value=""> Välj produkt </option>
step="0.01" {allProducts.map((p) => (
value={row.editQty} <option key={p.id} value={p.id}>{p.canonicalName ?? p.name}</option>
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>
/> <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 <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' }}>
value={row.editUnit} {UNITS.map((u) => <option key={u} value={u}>{u}</option>)}
onChange={(e) => updateRow(i, { editUnit: e.target.value })} </select>
style={{ padding: '0.3rem 0.5rem', border: '1px solid #ced4da', borderRadius: '4px', fontSize: '0.9rem' }} </div>
> {row.selectedProductId !== '' && row.matchSource !== 'alias' && (
{UNITS.map((u) => <option key={u} value={u}>{u}</option>)} <label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', marginTop: '0.5rem', fontSize: '0.82rem', color: '#555', cursor: 'pointer' }}>
</select> <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> </div>
<div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}> <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
<button <button onClick={handleSave} disabled={saving || checkedCount === 0} style={primaryBtn(saving || checkedCount === 0)}>
onClick={handleSave}
disabled={saving || checkedCount === 0}
style={primaryBtn(saving || checkedCount === 0)}
>
{saving ? 'Sparar...' : `Lägg till ${checkedCount} ${checkedCount === 1 ? 'vara' : 'varor'} i inventariet`} {saving ? 'Sparar...' : `Lägg till ${checkedCount} ${checkedCount === 1 ? 'vara' : 'varor'} i inventariet`}
</button> </button>
<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' }}>
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 Börja om
</button> </button>
</div> </div>
@@ -271,14 +298,5 @@ export default function ReceiptImportClient() {
} }
function primaryBtn(disabled: boolean): React.CSSProperties { function primaryBtn(disabled: boolean): React.CSSProperties {
return { 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' };
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',
};
} }