feat(flyer-import): add session management and retrieval endpoints
- Add new API endpoints for retrieving flyer import sessions: - GET /flyer-import/sessions/latest - Retrieve latest session for user - GET /flyer-import/sessions/:sessionId - Retrieve specific session - Implement session persistence and restoration in Flutter UI - Add toJson() methods to FlyerImportItem and FlyerImportResult for serialization - Add new FlyerImportSession domain model for local session management - Add unit test file for FlyerImportService - Update FlyerImportController with new endpoints and user ID extraction - Update FlyerImportService with session retrieval logic and response mapping - Update API paths in Flutter client - Add session restoration on widget init in FlyerImportTab
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Post,
|
||||
Request,
|
||||
UnauthorizedException,
|
||||
@@ -47,6 +50,29 @@ export class FlyerImportController {
|
||||
throw new BadRequestException('Otillåten filtyp. Använd PDF, textfil eller bild (PNG, JPEG, WebP).');
|
||||
}
|
||||
|
||||
const userId = this.getUserId(req);
|
||||
|
||||
return this.flyerImportService.parseAndMatch(file, userId);
|
||||
}
|
||||
|
||||
@Get('sessions/latest')
|
||||
@Throttle({ default: { ttl: 60_000, limit: 30 } })
|
||||
async getLatestSession(@Request() req?: any): Promise<FlyerImportResponse> {
|
||||
const userId = this.getUserId(req);
|
||||
return this.flyerImportService.getLatestSession(userId);
|
||||
}
|
||||
|
||||
@Get('sessions/:sessionId')
|
||||
@Throttle({ default: { ttl: 60_000, limit: 30 } })
|
||||
async getSession(
|
||||
@Param('sessionId', ParseIntPipe) sessionId: number,
|
||||
@Request() req?: any,
|
||||
): Promise<FlyerImportResponse> {
|
||||
const userId = this.getUserId(req);
|
||||
return this.flyerImportService.getSession(sessionId, userId);
|
||||
}
|
||||
|
||||
private getUserId(req?: any): number {
|
||||
const userId =
|
||||
typeof req?.user?.id === 'number'
|
||||
? req.user.id
|
||||
@@ -58,6 +84,6 @@ export class FlyerImportController {
|
||||
throw new UnauthorizedException('Kunde inte identifiera användaren.');
|
||||
}
|
||||
|
||||
return this.flyerImportService.parseAndMatch(file, userId);
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { FlyerImportService } from './flyer-import.service';
|
||||
|
||||
describe('FlyerImportService', () => {
|
||||
const prismaMock = {
|
||||
flyerSession: {
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const createService = () =>
|
||||
new FlyerImportService(
|
||||
prismaMock as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('getSession', () => {
|
||||
it('throws NotFoundException when session is missing', async () => {
|
||||
prismaMock.flyerSession.findFirst.mockResolvedValue(null);
|
||||
const service = createService();
|
||||
|
||||
await expect(service.getSession(123, 1)).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(prismaMock.flyerSession.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: 123, userId: 1 },
|
||||
include: { items: { orderBy: { id: 'asc' } } },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns mapped response for owned session', async () => {
|
||||
prismaMock.flyerSession.findFirst.mockResolvedValue({
|
||||
id: 42,
|
||||
items: [
|
||||
{
|
||||
id: 99,
|
||||
rawName: 'Tomat',
|
||||
normalizedName: 'tomat',
|
||||
categoryHint: 'Gronsaker',
|
||||
price: { toNumber: () => 19.9 },
|
||||
priceUnit: 'kg',
|
||||
comparisonPrice: null,
|
||||
comparisonUnit: null,
|
||||
offerText: 'Max 2 kop/hushall',
|
||||
parseConfidence: 0.9,
|
||||
parseReasons: ['ai_parsed'],
|
||||
matchedProductId: 5,
|
||||
matchedProductName: 'Tomat',
|
||||
matchedVia: 'exact',
|
||||
matchConfidence: 0.95,
|
||||
matchReasons: ['normalized_exact'],
|
||||
},
|
||||
],
|
||||
});
|
||||
const service = createService();
|
||||
|
||||
const result = await service.getSession(42, 1);
|
||||
|
||||
expect(result.sessionId).toBe(42);
|
||||
expect(result.items).toHaveLength(1);
|
||||
expect(result.items[0].flyerItemId).toBe(99);
|
||||
expect(result.items[0].matchedVia).toBe('exact');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getLatestSession', () => {
|
||||
it('returns empty response when no sessions exist', async () => {
|
||||
prismaMock.flyerSession.findFirst.mockResolvedValue(null);
|
||||
const service = createService();
|
||||
|
||||
const result = await service.getLatestSession(1);
|
||||
|
||||
expect(result.sessionId).toBeNull();
|
||||
expect(result.items).toEqual([]);
|
||||
expect(prismaMock.flyerSession.findFirst).toHaveBeenCalledWith({
|
||||
where: { userId: 1 },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { items: { orderBy: { id: 'asc' } } },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,9 @@ import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { normalizeName } from '../common/utils/normalize-name';
|
||||
@@ -51,7 +52,7 @@ type ProductLite = {
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class FlyerImportService {
|
||||
export class FlyerImportService {
|
||||
private readonly logger = new Logger(FlyerImportService.name);
|
||||
|
||||
constructor(
|
||||
@@ -61,7 +62,7 @@ export class FlyerImportService {
|
||||
private readonly normalizer: FlyerNormalizerService,
|
||||
) {}
|
||||
|
||||
async parseAndMatch(file: Express.Multer.File, userId: number): Promise<FlyerImportResponse> {
|
||||
async parseAndMatch(file: Express.Multer.File, userId: number): Promise<FlyerImportResponse> {
|
||||
const parsed = await this.parseViaInternal(file);
|
||||
|
||||
const [products, aliases] = await Promise.all([
|
||||
@@ -123,14 +124,47 @@ export class FlyerImportService {
|
||||
|
||||
const persistedItems = await this.persistSessionWithItems(userId, parsed.retailer, items);
|
||||
|
||||
return {
|
||||
sessionId: persistedItems.sessionId,
|
||||
retailer: parsed.retailer,
|
||||
parserVersion: parsed.parserVersion,
|
||||
items: persistedItems.items,
|
||||
warnings: parsed.warnings,
|
||||
};
|
||||
}
|
||||
return {
|
||||
sessionId: persistedItems.sessionId,
|
||||
retailer: parsed.retailer,
|
||||
parserVersion: parsed.parserVersion,
|
||||
items: persistedItems.items,
|
||||
warnings: parsed.warnings,
|
||||
};
|
||||
}
|
||||
|
||||
async getSession(sessionId: number, userId: number): Promise<FlyerImportResponse> {
|
||||
const session = await this.prisma.flyerSession.findFirst({
|
||||
where: { id: sessionId, userId },
|
||||
include: { items: { orderBy: { id: 'asc' } } },
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
throw new NotFoundException('Flyer-session hittades inte.');
|
||||
}
|
||||
|
||||
return this.toFlyerImportResponseFromSession(session);
|
||||
}
|
||||
|
||||
async getLatestSession(userId: number): Promise<FlyerImportResponse> {
|
||||
const latest = await this.prisma.flyerSession.findFirst({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { items: { orderBy: { id: 'asc' } } },
|
||||
});
|
||||
|
||||
if (!latest) {
|
||||
return {
|
||||
sessionId: null,
|
||||
retailer: 'willys',
|
||||
parserVersion: 'v1',
|
||||
items: [],
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
return this.toFlyerImportResponseFromSession(latest);
|
||||
}
|
||||
|
||||
private async persistSessionWithItems(
|
||||
userId: number,
|
||||
@@ -377,7 +411,7 @@ export class FlyerImportService {
|
||||
return allowed.has(cleaned) ? cleaned : cleaned;
|
||||
}
|
||||
|
||||
private async parseViaInternal(file: Express.Multer.File): Promise<FlyerParseResponse> {
|
||||
private async parseViaInternal(file: Express.Multer.File): Promise<FlyerParseResponse> {
|
||||
try {
|
||||
this.logger.debug(`Parsing flyer file: ${file.originalname}`);
|
||||
|
||||
@@ -431,5 +465,92 @@ export class FlyerImportService {
|
||||
`Fel vid tolkning av flyer: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private toFlyerImportItem(item: {
|
||||
id: number;
|
||||
rawName: string;
|
||||
normalizedName: string;
|
||||
categoryHint: string | null;
|
||||
price: Prisma.Decimal | null;
|
||||
priceUnit: string | null;
|
||||
comparisonPrice: Prisma.Decimal | null;
|
||||
comparisonUnit: string | null;
|
||||
offerText: string | null;
|
||||
parseConfidence: number;
|
||||
parseReasons: Prisma.JsonValue | null;
|
||||
matchedProductId: number | null;
|
||||
matchedProductName: string | null;
|
||||
matchedVia: string | null;
|
||||
matchConfidence: number | null;
|
||||
matchReasons: Prisma.JsonValue | null;
|
||||
}): FlyerImportItem {
|
||||
const toStringArray = (value: Prisma.JsonValue | null): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.map((entry) => String(entry));
|
||||
};
|
||||
|
||||
const normalizedMatchVia =
|
||||
item.matchedVia === 'alias' || item.matchedVia === 'exact' || item.matchedVia === 'token'
|
||||
? item.matchedVia
|
||||
: 'none';
|
||||
|
||||
const offerLimitText = this.extractOfferLimitText(item.offerText);
|
||||
const offerSignals = this.extractOfferSignals(item.offerText);
|
||||
|
||||
return {
|
||||
flyerItemId: item.id,
|
||||
rawName: item.rawName,
|
||||
normalizedName: item.normalizedName,
|
||||
category: item.categoryHint,
|
||||
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,
|
||||
comparisonUnit: this.normalizeUnit(item.comparisonUnit) ?? offerSignals.comparisonUnit,
|
||||
offerText: item.offerText,
|
||||
isOffer:
|
||||
item.price != null
|
||||
|| item.comparisonPrice != null
|
||||
|| !!item.offerText?.trim()
|
||||
|| offerSignals.hasCampaignPattern,
|
||||
offerLimitText,
|
||||
parseConfidence: item.parseConfidence,
|
||||
parseReasons: toStringArray(item.parseReasons),
|
||||
matchedProductId: item.matchedProductId,
|
||||
matchedProductName: item.matchedProductName,
|
||||
matchedVia: normalizedMatchVia,
|
||||
matchConfidence: item.matchConfidence ?? 0,
|
||||
matchReasons: toStringArray(item.matchReasons),
|
||||
};
|
||||
}
|
||||
|
||||
private toFlyerImportResponseFromSession(session: {
|
||||
id: number;
|
||||
items: Array<{
|
||||
id: number;
|
||||
rawName: string;
|
||||
normalizedName: string;
|
||||
categoryHint: string | null;
|
||||
price: Prisma.Decimal | null;
|
||||
priceUnit: string | null;
|
||||
comparisonPrice: Prisma.Decimal | null;
|
||||
comparisonUnit: string | null;
|
||||
offerText: string | null;
|
||||
parseConfidence: number;
|
||||
parseReasons: Prisma.JsonValue | null;
|
||||
matchedProductId: number | null;
|
||||
matchedProductName: string | null;
|
||||
matchedVia: string | null;
|
||||
matchConfidence: number | null;
|
||||
matchReasons: Prisma.JsonValue | null;
|
||||
}>;
|
||||
}): FlyerImportResponse {
|
||||
return {
|
||||
sessionId: session.id,
|
||||
retailer: 'willys',
|
||||
parserVersion: 'v1',
|
||||
items: session.items.map((item) => this.toFlyerImportItem(item)),
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user