feat(shopping-list): add shopping list feature with flyer integration
This commit introduces a comprehensive shopping list feature with the following key changes: Backend: - Added ShoppingListItem model with relations to User, Product, and Category - Added new fields to FlyerSession for source file metadata - Added categoryId field to FlyerItem model - Implemented session source file retrieval endpoint - Added endpoint for updating flyer session items with category assignment - Added endpoint for planning flyer selections to shopping list - Implemented backfillCategoriesMine for AI-assisted category assignment - Added ShoppingListModule and integrated with FlyerSelectionModule Frontend: - Added ShoppingListScreen and navigation route - Implemented API paths and client methods for shopping list operations - Added category tree loading for shopping list item creation - Integrated shopping list functionality in flyer import tab - Added category backfill trigger in inventory screen - Updated FlyerImportItem model with categoryId support - Added methods for updating flyer session items and retrieving source files Database: - Added new Prisma migration for flyer source metadata and shopping list items - Updated schema with new relations and indexes The shopping list feature allows users to: 1. Plan flyer selections directly to their shopping list 2. View and manage their shopping list items 3. Update flyer session items with proper categorization 4. Retrieve original flyer source files 5. Automatically backfill categories for uncategorized products
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
@@ -105,6 +106,7 @@ export class FlyerImportService {
|
||||
rawName: item.rawName,
|
||||
normalizedName: item.normalizedName,
|
||||
category: item.category,
|
||||
categoryId: null,
|
||||
price,
|
||||
priceUnit,
|
||||
comparisonPrice,
|
||||
@@ -122,21 +124,151 @@ export class FlyerImportService {
|
||||
};
|
||||
});
|
||||
|
||||
const persistedItems = await this.persistSessionWithItems(userId, parsed.retailer, items);
|
||||
const persistedItems = await this.persistSessionWithItems(userId, parsed.retailer, items, file);
|
||||
|
||||
return {
|
||||
sessionId: persistedItems.sessionId,
|
||||
retailer: parsed.retailer,
|
||||
parserVersion: parsed.parserVersion,
|
||||
sourceAvailable: true,
|
||||
sourceFileName: file.originalname ?? null,
|
||||
sourceMimeType: file.mimetype ?? null,
|
||||
sourceFileSize: file.size ?? null,
|
||||
items: persistedItems.items,
|
||||
warnings: parsed.warnings,
|
||||
};
|
||||
}
|
||||
|
||||
async getSessionSource(sessionId: number, userId: number): Promise<{
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
contentLength: number;
|
||||
data: Buffer;
|
||||
}> {
|
||||
const session = await this.prisma.flyerSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: {
|
||||
userId: true,
|
||||
sourceFileName: true,
|
||||
sourceMimeType: true,
|
||||
sourceFileSize: true,
|
||||
sourceData: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
throw new NotFoundException('Flyer-session hittades inte.');
|
||||
}
|
||||
if (session.userId !== userId) {
|
||||
throw new ForbiddenException('Du saknar åtkomst till denna session.');
|
||||
}
|
||||
if (!session.sourceData || !session.sourceFileName || !session.sourceMimeType) {
|
||||
throw new NotFoundException('Källfil saknas för denna flyer-session.');
|
||||
}
|
||||
|
||||
const data = Buffer.from(session.sourceData);
|
||||
return {
|
||||
fileName: session.sourceFileName,
|
||||
mimeType: session.sourceMimeType,
|
||||
contentLength: session.sourceFileSize ?? data.length,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
async updateSessionItem(
|
||||
sessionId: number,
|
||||
itemId: number,
|
||||
userId: number,
|
||||
payload: { rawName?: string; categoryId?: number | null },
|
||||
): Promise<FlyerImportItem> {
|
||||
const session = await this.prisma.flyerSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
if (!session) {
|
||||
throw new NotFoundException('Flyer-session hittades inte.');
|
||||
}
|
||||
if (session.userId !== userId) {
|
||||
throw new ForbiddenException('Du saknar åtkomst till denna session.');
|
||||
}
|
||||
|
||||
const item = await this.prisma.flyerItem.findUnique({
|
||||
where: { id: itemId },
|
||||
select: { id: true, sessionId: true, rawName: true },
|
||||
});
|
||||
if (!item || item.sessionId !== sessionId) {
|
||||
throw new NotFoundException('Flyer-rad hittades inte i sessionen.');
|
||||
}
|
||||
|
||||
const updateData: Prisma.FlyerItemUncheckedUpdateInput = {};
|
||||
|
||||
if (typeof payload.rawName === 'string') {
|
||||
const trimmed = payload.rawName.trim();
|
||||
if (!trimmed) {
|
||||
throw new BadRequestException('Namn får inte vara tomt.');
|
||||
}
|
||||
updateData.rawName = trimmed;
|
||||
updateData.normalizedName = normalizeName(trimmed) || normalizeName(item.rawName);
|
||||
}
|
||||
|
||||
if (payload.categoryId !== undefined) {
|
||||
if (payload.categoryId === null) {
|
||||
updateData.categoryId = null;
|
||||
updateData.categoryHint = null;
|
||||
} else {
|
||||
const path = await this.resolveCategoryPath(payload.categoryId);
|
||||
updateData.categoryId = payload.categoryId;
|
||||
updateData.categoryHint = path;
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
throw new BadRequestException('Inga giltiga fält att uppdatera.');
|
||||
}
|
||||
|
||||
const updated = await this.prisma.flyerItem.update({
|
||||
where: { id: itemId },
|
||||
data: updateData,
|
||||
include: {
|
||||
categoryRef: {
|
||||
include: {
|
||||
parent: {
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return this.toFlyerImportItem(updated as any);
|
||||
}
|
||||
|
||||
async getSession(sessionId: number, userId: number): Promise<FlyerImportResponse> {
|
||||
const session = await this.prisma.flyerSession.findFirst({
|
||||
where: { id: sessionId, userId },
|
||||
include: { items: { orderBy: { id: 'asc' } } },
|
||||
select: {
|
||||
id: true,
|
||||
sourceFileName: true,
|
||||
sourceMimeType: true,
|
||||
sourceFileSize: true,
|
||||
sourceStorageKey: true,
|
||||
items: {
|
||||
include: {
|
||||
categoryRef: {
|
||||
include: {
|
||||
parent: {
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
@@ -150,37 +282,67 @@ export class FlyerImportService {
|
||||
const latest = await this.prisma.flyerSession.findFirst({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { items: { orderBy: { id: 'asc' } } },
|
||||
select: {
|
||||
id: true,
|
||||
sourceFileName: true,
|
||||
sourceMimeType: true,
|
||||
sourceFileSize: true,
|
||||
sourceStorageKey: true,
|
||||
items: {
|
||||
include: {
|
||||
categoryRef: {
|
||||
include: {
|
||||
parent: {
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!latest) {
|
||||
return {
|
||||
sessionId: null,
|
||||
retailer: 'willys',
|
||||
parserVersion: 'v1',
|
||||
items: [],
|
||||
warnings: [],
|
||||
};
|
||||
return {
|
||||
sessionId: null,
|
||||
retailer: 'willys',
|
||||
parserVersion: 'v1',
|
||||
sourceAvailable: false,
|
||||
sourceFileName: null,
|
||||
sourceMimeType: null,
|
||||
sourceFileSize: null,
|
||||
items: [],
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
return this.toFlyerImportResponseFromSession(latest);
|
||||
}
|
||||
|
||||
private async persistSessionWithItems(
|
||||
userId: number,
|
||||
retailer: 'willys',
|
||||
items: FlyerImportItem[],
|
||||
): Promise<{ sessionId: number; items: FlyerImportItem[] }> {
|
||||
private async persistSessionWithItems(
|
||||
userId: number,
|
||||
retailer: 'willys',
|
||||
items: FlyerImportItem[],
|
||||
file: Express.Multer.File,
|
||||
): Promise<{ sessionId: number; items: FlyerImportItem[] }> {
|
||||
const weekKey = this.toWeekKey(new Date());
|
||||
|
||||
const session = await this.prisma.flyerSession.create({
|
||||
data: {
|
||||
userId,
|
||||
retailer,
|
||||
weekKey,
|
||||
status: 'draft',
|
||||
},
|
||||
select: { id: true },
|
||||
weekKey,
|
||||
status: 'draft',
|
||||
sourceFileName: file.originalname ?? null,
|
||||
sourceMimeType: file.mimetype ?? null,
|
||||
sourceFileSize: file.size ?? file.buffer.length,
|
||||
sourceStorageKey: this.buildSourceStorageKey(userId, weekKey),
|
||||
sourceData: Buffer.from(file.buffer),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const savedItems: FlyerImportItem[] = [];
|
||||
@@ -188,10 +350,11 @@ export class FlyerImportService {
|
||||
const created = await this.prisma.flyerItem.create({
|
||||
data: {
|
||||
sessionId: session.id,
|
||||
rawName: item.rawName,
|
||||
normalizedName: item.normalizedName,
|
||||
categoryHint: item.category,
|
||||
price: item.price != null ? new Prisma.Decimal(item.price) : null,
|
||||
rawName: item.rawName,
|
||||
normalizedName: item.normalizedName,
|
||||
categoryHint: item.category,
|
||||
categoryId: item.categoryId,
|
||||
price: item.price != null ? new Prisma.Decimal(item.price) : null,
|
||||
priceUnit: item.priceUnit,
|
||||
comparisonPrice:
|
||||
item.comparisonPrice != null ? new Prisma.Decimal(item.comparisonPrice) : null,
|
||||
@@ -472,6 +635,16 @@ export class FlyerImportService {
|
||||
rawName: string;
|
||||
normalizedName: string;
|
||||
categoryHint: string | null;
|
||||
categoryId: number | null;
|
||||
categoryRef?: {
|
||||
name: string;
|
||||
parent?: {
|
||||
name: string;
|
||||
parent?: {
|
||||
name: string;
|
||||
} | null;
|
||||
} | null;
|
||||
} | null;
|
||||
price: Prisma.Decimal | null;
|
||||
priceUnit: string | null;
|
||||
comparisonPrice: Prisma.Decimal | null;
|
||||
@@ -495,6 +668,8 @@ export class FlyerImportService {
|
||||
? item.matchedVia
|
||||
: 'none';
|
||||
|
||||
const categoryPath = this.buildCategoryPath(item.categoryRef) ?? item.categoryHint;
|
||||
|
||||
const offerLimitText = this.extractOfferLimitText(item.offerText);
|
||||
const offerSignals = this.extractOfferSignals(item.offerText);
|
||||
|
||||
@@ -502,7 +677,8 @@ export class FlyerImportService {
|
||||
flyerItemId: item.id,
|
||||
rawName: item.rawName,
|
||||
normalizedName: item.normalizedName,
|
||||
category: item.categoryHint,
|
||||
category: categoryPath,
|
||||
categoryId: item.categoryId,
|
||||
price: item.price != null ? item.price.toNumber() : offerSignals.price,
|
||||
priceUnit: this.normalizeUnit(item.priceUnit) ?? offerSignals.priceUnit,
|
||||
comparisonPrice: item.comparisonPrice != null ? item.comparisonPrice.toNumber() : offerSignals.comparisonPrice,
|
||||
@@ -524,13 +700,44 @@ export class FlyerImportService {
|
||||
};
|
||||
}
|
||||
|
||||
private buildCategoryPath(categoryRef?: {
|
||||
name: string;
|
||||
parent?: {
|
||||
name: string;
|
||||
parent?: { name: string } | null;
|
||||
} | null;
|
||||
} | null): string | null {
|
||||
if (!categoryRef) return null;
|
||||
const names: string[] = [];
|
||||
let current: { name: string; parent?: any } | null = categoryRef;
|
||||
while (current) {
|
||||
names.unshift(current.name);
|
||||
current = current.parent ?? null;
|
||||
}
|
||||
return names.length > 0 ? names.join(' > ') : null;
|
||||
}
|
||||
|
||||
private toFlyerImportResponseFromSession(session: {
|
||||
id: number;
|
||||
sourceFileName?: string | null;
|
||||
sourceMimeType?: string | null;
|
||||
sourceFileSize?: number | null;
|
||||
sourceStorageKey?: string | null;
|
||||
items: Array<{
|
||||
id: number;
|
||||
rawName: string;
|
||||
normalizedName: string;
|
||||
categoryHint: string | null;
|
||||
categoryId: number | null;
|
||||
categoryRef?: {
|
||||
name: string;
|
||||
parent?: {
|
||||
name: string;
|
||||
parent?: {
|
||||
name: string;
|
||||
} | null;
|
||||
} | null;
|
||||
} | null;
|
||||
price: Prisma.Decimal | null;
|
||||
priceUnit: string | null;
|
||||
comparisonPrice: Prisma.Decimal | null;
|
||||
@@ -549,8 +756,41 @@ export class FlyerImportService {
|
||||
sessionId: session.id,
|
||||
retailer: 'willys',
|
||||
parserVersion: 'v1',
|
||||
sourceAvailable: !!session.sourceStorageKey,
|
||||
sourceFileName: session.sourceFileName ?? null,
|
||||
sourceMimeType: session.sourceMimeType ?? null,
|
||||
sourceFileSize: session.sourceFileSize ?? null,
|
||||
items: session.items.map((item) => this.toFlyerImportItem(item)),
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
private async resolveCategoryPath(categoryId: number): Promise<string> {
|
||||
const category = await this.prisma.category.findUnique({
|
||||
where: { id: categoryId },
|
||||
include: {
|
||||
parent: {
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!category) {
|
||||
throw new BadRequestException(`Kategori med id ${categoryId} hittades inte.`);
|
||||
}
|
||||
|
||||
const names: string[] = [];
|
||||
let current: { name: string; parent: any } | null = category as any;
|
||||
while (current) {
|
||||
names.unshift(current.name);
|
||||
current = current.parent;
|
||||
}
|
||||
return names.join(' > ');
|
||||
}
|
||||
|
||||
private buildSourceStorageKey(userId: number, weekKey: string): string {
|
||||
return `flyer/${userId}/${weekKey}/${Date.now()}`;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user