feat: implement receipt alias functionality with CRUD operations and integrate with receipt import
This commit is contained in:
@@ -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;
|
||||
@@ -21,6 +21,7 @@ model Product {
|
||||
inventoryItems InventoryItem[]
|
||||
recipeIngredients RecipeIngredient[]
|
||||
pantryItems PantryItem[]
|
||||
receiptAliases ReceiptAlias[]
|
||||
}
|
||||
|
||||
model InventoryItem {
|
||||
@@ -95,6 +96,14 @@ model PantryItem {
|
||||
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 {
|
||||
id Int @id @default(autoincrement())
|
||||
date DateTime @db.Date
|
||||
|
||||
@@ -8,6 +8,7 @@ import { QuickImportModule } from './quick-import/quick-import.module';
|
||||
import { PantryModule } from './pantry/pantry.module';
|
||||
import { MealPlanModule } from './meal-plan/meal-plan.module';
|
||||
import { ReceiptImportModule } from './receipt-import/receipt-import.module';
|
||||
import { ReceiptAliasModule } from './receipt-alias/receipt-alias.module';
|
||||
|
||||
|
||||
@Module({
|
||||
@@ -21,6 +22,7 @@ import { ReceiptImportModule } from './receipt-import/receipt-import.module';
|
||||
PantryModule,
|
||||
MealPlanModule,
|
||||
ReceiptImportModule,
|
||||
ReceiptAliasModule,
|
||||
],
|
||||
})
|
||||
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;
|
||||
unit: string;
|
||||
price?: number | null;
|
||||
// alias-match: säker, användaren slipper bekräfta
|
||||
matchedProductId?: number;
|
||||
matchedProductName?: string;
|
||||
// ordbaserad match: förslag, kräver bekräftelse
|
||||
suggestedProductId?: number;
|
||||
suggestedProductName?: string;
|
||||
}
|
||||
|
||||
@@ -131,8 +131,16 @@ export class ReceiptImportService {
|
||||
): Promise<ParsedReceiptItem[]> {
|
||||
if (!response.ok) {
|
||||
const err = await response.text();
|
||||
this.logger.error(`Mistral API svarade ${response.status}: ${err}`);
|
||||
throw new ServiceUnavailableException('Mistral API returnerade ett fel — kontrollera API-nyckeln');
|
||||
this.logger.error(`Mistral API svarade ${response.status} (${source}): ${err}`);
|
||||
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 {
|
||||
@@ -156,35 +164,61 @@ export class ReceiptImportService {
|
||||
private async matchProducts(
|
||||
items: ParsedReceiptItem[],
|
||||
): Promise<ParsedReceiptItem[]> {
|
||||
const products = await this.prisma.product.findMany({
|
||||
// Hämta alias och produkter parallellt
|
||||
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) => {
|
||||
const raw = (item.rawName ?? '').toLowerCase().trim();
|
||||
if (!raw) return item;
|
||||
|
||||
// Exakt matchning först
|
||||
let match = products.find((p) => {
|
||||
const n = (p.canonicalName ?? p.name).toLowerCase();
|
||||
return n === raw || p.name.toLowerCase() === raw;
|
||||
});
|
||||
|
||||
// Delvis matchning
|
||||
if (!match) {
|
||||
match = products.find((p) => {
|
||||
const n = (p.canonicalName ?? p.name).toLowerCase();
|
||||
return n.includes(raw) || raw.includes(n);
|
||||
});
|
||||
}
|
||||
|
||||
// 1. Alias-match (säker, användaren behöver inte bekräfta)
|
||||
const alias = aliases.find((a) => a.receiptName === raw);
|
||||
if (alias) {
|
||||
return {
|
||||
...item,
|
||||
matchedProductId: match?.id,
|
||||
matchedProductName: match
|
||||
? (match.canonicalName ?? match.name)
|
||||
matchedProductId: alias.product.id,
|
||||
matchedProductName: alias.product.canonicalName ?? alias.product.name,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Ordbaserad matchning (förslag, kräver bekräftelse)
|
||||
const suggestion = this.findWordMatch(raw, products);
|
||||
return {
|
||||
...item,
|
||||
suggestedProductId: suggestion?.id,
|
||||
suggestedProductName: suggestion
|
||||
? (suggestion.canonicalName ?? suggestion.name)
|
||||
: 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 });
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
'use client';
|
||||
|
||||
import { useRef, useState } from 'react';
|
||||
import { useRef, useState, useEffect } from 'react';
|
||||
|
||||
type ParsedItem = {
|
||||
rawName: string;
|
||||
@@ -9,9 +9,25 @@ type ParsedItem = {
|
||||
price?: number | null;
|
||||
matchedProductId?: number;
|
||||
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'];
|
||||
|
||||
@@ -21,19 +37,23 @@ export default function ReceiptImportClient() {
|
||||
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);
|
||||
if (file.type === 'application/pdf') {
|
||||
setPreview('pdf');
|
||||
} else {
|
||||
setPreview(URL.createObjectURL(file));
|
||||
}
|
||||
setPreview(file.type === 'application/pdf' ? 'pdf' : URL.createObjectURL(file));
|
||||
setRows([]);
|
||||
setError(null);
|
||||
setSavedCount(null);
|
||||
@@ -53,12 +73,51 @@ export default function ReceiptImportClient() {
|
||||
}
|
||||
const items: ParsedItem[] = await res.json();
|
||||
setRows(
|
||||
items.map((item) => ({
|
||||
...item,
|
||||
checked: !!item.matchedProductId,
|
||||
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');
|
||||
@@ -71,25 +130,55 @@ export default function ReceiptImportClient() {
|
||||
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.matchedProductId);
|
||||
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) =>
|
||||
await Promise.all([
|
||||
...toSave.map((r) =>
|
||||
fetch('/api/inventory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
productId: r.matchedProductId,
|
||||
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);
|
||||
@@ -102,70 +191,48 @@ export default function ReceiptImportClient() {
|
||||
}
|
||||
};
|
||||
|
||||
const checkedCount = rows.filter((r) => r.checked && r.matchedProductId).length;
|
||||
const unmatchedCount = rows.filter((r) => !r.matchedProductId).length;
|
||||
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>
|
||||
{/* Fil-input */}
|
||||
<div
|
||||
style={{
|
||||
border: '2px dashed #ced4da',
|
||||
borderRadius: '10px',
|
||||
padding: '1.5rem',
|
||||
textAlign: 'center',
|
||||
background: '#fafafa',
|
||||
marginBottom: '1rem',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
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' }}
|
||||
/>
|
||||
<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={{ 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' }}
|
||||
/>
|
||||
<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 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 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>
|
||||
<p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}>{error}</p>
|
||||
)}
|
||||
|
||||
{savedCount !== null && (
|
||||
@@ -174,93 +241,53 @@ export default function ReceiptImportClient() {
|
||||
</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 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 matched = !!row.matchedProductId;
|
||||
const label = sourceLabel(row.matchSource);
|
||||
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 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>
|
||||
<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' }}
|
||||
>
|
||||
<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 "{row.rawName}" 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)}
|
||||
>
|
||||
<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' }}
|
||||
>
|
||||
<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>
|
||||
@@ -271,14 +298,5 @@ export default function ReceiptImportClient() {
|
||||
}
|
||||
|
||||
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',
|
||||
};
|
||||
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' };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user