Phase 9
This commit is contained in:
parent
e396f5088c
commit
a1801af63b
36 changed files with 4783 additions and 31 deletions
162
packages/api/src/modules/prices/prices.repository.test.ts
Normal file
162
packages/api/src/modules/prices/prices.repository.test.ts
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { PricesRepository } from './prices.repository.js';
|
||||
|
||||
const { mockSave, MockPriceRecordModel } = vi.hoisted(() => {
|
||||
const mockSave = vi.fn();
|
||||
function MockModel(this: { save: typeof mockSave }, data: unknown) {
|
||||
Object.assign(this, data);
|
||||
this.save = mockSave;
|
||||
}
|
||||
Object.assign(MockModel, {
|
||||
findOne: vi.fn(),
|
||||
find: vi.fn(),
|
||||
findOneAndUpdate: vi.fn(),
|
||||
insertMany: vi.fn(),
|
||||
aggregate: vi.fn(),
|
||||
});
|
||||
return { mockSave, MockPriceRecordModel: MockModel };
|
||||
});
|
||||
|
||||
vi.mock('../../schemas/price-record.schema.js', () => ({
|
||||
PriceRecordModel: MockPriceRecordModel,
|
||||
}));
|
||||
|
||||
const { PriceRecordModel } = await import('../../schemas/price-record.schema.js');
|
||||
|
||||
function makeChain(result: unknown = null) {
|
||||
return {
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: vi.fn().mockResolvedValue(result),
|
||||
};
|
||||
}
|
||||
|
||||
describe(PricesRepository.name, () => {
|
||||
let repo: PricesRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new PricesRepository();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('saves and returns new document toObject', async () => {
|
||||
const data = { householdId: 'h1', productId: 'p1', productName: 'Apple', storeId: 's1', storeName: 'Store', price: 1, currency: 'USD', quantity: 1, unit: 'g', pricePerUnit: 1, date: new Date(), createdBy: 'u1' };
|
||||
mockSave.mockResolvedValue({ toObject: () => ({ ...data, _id: 'id1' }) });
|
||||
|
||||
const result = await repo.create(data);
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result._id).toBe('id1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMany', () => {
|
||||
it('inserts multiple records and returns mapped toObjects', async () => {
|
||||
const inputs = [{ price: 1 }, { price: 2 }];
|
||||
const returns = inputs.map((x, idx) => ({ ...x, _id: `id${idx}`, toObject: function() { return this; } }));
|
||||
vi.mocked(PriceRecordModel.insertMany).mockResolvedValue(returns as any);
|
||||
|
||||
const result = await repo.createMany(inputs as any);
|
||||
expect(PriceRecordModel.insertMany).toHaveBeenCalledWith(inputs);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]._id).toBe('id0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByProduct', () => {
|
||||
it('applies complex filters and pagination cursor decoding/encoding', async () => {
|
||||
const baseFilter = { householdId: 'h1', productId: 'prod1' };
|
||||
const startDate = new Date('2026-01-01').toISOString();
|
||||
const endDate = new Date('2026-01-10').toISOString();
|
||||
const cursorId = '507f1f77bcf86cd799439011';
|
||||
const cursorStr = Buffer.from(cursorId).toString('base64');
|
||||
|
||||
const mockItems = [
|
||||
{ _id: '607f1f77bcf86cd799439012', price: 10 },
|
||||
{ _id: '607f1f77bcf86cd799439013', price: 12 }
|
||||
];
|
||||
|
||||
const chain = makeChain(mockItems);
|
||||
vi.mocked(PriceRecordModel.find).mockReturnValue(chain as any);
|
||||
|
||||
const result = await repo.findByProduct('h1', 'prod1', {
|
||||
storeId: 'st1',
|
||||
startDate,
|
||||
endDate,
|
||||
cursor: cursorStr,
|
||||
limit: 2
|
||||
});
|
||||
|
||||
expect(PriceRecordModel.find).toHaveBeenCalledWith({
|
||||
householdId: 'h1',
|
||||
productId: 'prod1',
|
||||
storeId: 'st1',
|
||||
date: {
|
||||
$gte: new Date(startDate),
|
||||
$lte: new Date(endDate),
|
||||
},
|
||||
_id: { $lt: cursorId }
|
||||
});
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('correctly indicates hasMore and generates next base64 cursor', async () => {
|
||||
const mockItems = [
|
||||
{ _id: '607f1f77bcf86cd799439011', price: 10 },
|
||||
{ _id: '607f1f77bcf86cd799439012', price: 11 },
|
||||
{ _id: '607f1f77bcf86cd799439013', price: 12 }
|
||||
];
|
||||
|
||||
const chain = makeChain(mockItems);
|
||||
vi.mocked(PriceRecordModel.find).mockReturnValue(chain as any);
|
||||
|
||||
const result = await repo.findByProduct('h1', 'prod1', { limit: 2 });
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.pagination.hasMore).toBe(true);
|
||||
expect(result.pagination.cursor).toBe(Buffer.from('607f1f77bcf86cd799439012').toString('base64'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('compareStores', () => {
|
||||
it('runs group/aggregate queries ordered by deviance', async () => {
|
||||
const mockAggResult = [
|
||||
{ _id: 's1', storeName: 'Cheap', latestPrice: 10, latestPricePerUnit: 1, currency: 'USD', date: new Date() }
|
||||
];
|
||||
vi.mocked(PriceRecordModel.aggregate).mockReturnValue({
|
||||
exec: vi.fn().mockResolvedValue(mockAggResult)
|
||||
} as any);
|
||||
|
||||
const result = await repo.compareStores('h1', 'p1');
|
||||
expect(PriceRecordModel.aggregate).toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].storeId).toBe('s1');
|
||||
expect(result[0].latestPricePerUnit).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getLatestForProduct', () => {
|
||||
it('queries latest pricing document ordered by date descending', async () => {
|
||||
const chain = makeChain({ _id: 'pr1' });
|
||||
vi.mocked(PriceRecordModel.findOne).mockReturnValue(chain as any);
|
||||
|
||||
await repo.getLatestForProduct('h1', 'p1', 's1');
|
||||
expect(PriceRecordModel.findOne).toHaveBeenCalledWith({ householdId: 'h1', productId: 'p1', storeId: 's1' });
|
||||
expect(chain.sort).toHaveBeenCalledWith({ date: -1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAnalytics', () => {
|
||||
it('executes Promise.all parallel pipeline aggregations for periods, buckets, categories, and inflation', async () => {
|
||||
const mockExec = vi.fn().mockResolvedValue([]);
|
||||
vi.mocked(PriceRecordModel.aggregate).mockReturnValue({
|
||||
exec: mockExec
|
||||
} as any);
|
||||
|
||||
await repo.getAnalytics('h1');
|
||||
// 4 explicit pipeline calls should have fired in Promise.all + inflation alert
|
||||
expect(PriceRecordModel.aggregate).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
});
|
||||
});
|
||||
244
packages/api/src/modules/prices/prices.repository.ts
Normal file
244
packages/api/src/modules/prices/prices.repository.ts
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
import { PriceRecordModel } from '../../schemas/price-record.schema.js';
|
||||
import type { PriceHistoryQueryInput } from '@meshitrack/shared';
|
||||
|
||||
export interface CreatePriceRecordData {
|
||||
householdId: string;
|
||||
productId: string;
|
||||
productName: string;
|
||||
storeId: string;
|
||||
storeName: string;
|
||||
price: number;
|
||||
currency: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
pricePerUnit: number;
|
||||
date: Date;
|
||||
receiptImageUrl?: string;
|
||||
notes?: string;
|
||||
createdBy: string;
|
||||
}
|
||||
|
||||
export class PricesRepository {
|
||||
public async create(data: CreatePriceRecordData) {
|
||||
const record = new PriceRecordModel(data);
|
||||
const saved = await record.save();
|
||||
return saved.toObject();
|
||||
}
|
||||
|
||||
public async createMany(data: CreatePriceRecordData[]) {
|
||||
const records = await PriceRecordModel.insertMany(data);
|
||||
return records.map(r => r.toObject());
|
||||
}
|
||||
|
||||
public async findByProduct(
|
||||
householdId: string,
|
||||
productId: string,
|
||||
query: PriceHistoryQueryInput
|
||||
) {
|
||||
const filter: Record<string, unknown> = { householdId, productId };
|
||||
|
||||
if (query.storeId) filter['storeId'] = query.storeId;
|
||||
|
||||
if (query.startDate || query.endDate) {
|
||||
const dateFilter: Record<string, Date> = {};
|
||||
if (query.startDate) dateFilter['$gte'] = new Date(query.startDate);
|
||||
if (query.endDate) dateFilter['$lte'] = new Date(query.endDate);
|
||||
filter['date'] = dateFilter;
|
||||
}
|
||||
|
||||
if (query.cursor) {
|
||||
const id = Buffer.from(query.cursor, 'base64').toString();
|
||||
filter['_id'] = { $lt: id };
|
||||
}
|
||||
|
||||
const limit = query.limit || 20;
|
||||
const items = await PriceRecordModel.find(filter)
|
||||
.sort({ _id: -1 })
|
||||
.limit(limit + 1)
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
const hasMore = items.length > limit;
|
||||
const data = hasMore ? items.slice(0, limit) : items;
|
||||
const cursor =
|
||||
data.length > 0 ? Buffer.from(data[data.length - 1]._id.toString()).toString('base64') : null;
|
||||
|
||||
return { data, pagination: { cursor: hasMore ? cursor : null, hasMore } };
|
||||
}
|
||||
|
||||
public async compareStores(householdId: string, productId: string) {
|
||||
const results = await PriceRecordModel.aggregate([
|
||||
{ $match: { householdId, productId } },
|
||||
{ $sort: { storeId: 1, date: -1 } },
|
||||
{
|
||||
$group: {
|
||||
_id: '$storeId',
|
||||
storeName: { $first: '$storeName' },
|
||||
latestPrice: { $first: '$price' },
|
||||
latestPricePerUnit: { $first: '$pricePerUnit' },
|
||||
currency: { $first: '$currency' },
|
||||
date: { $first: '$date' },
|
||||
},
|
||||
},
|
||||
{ $sort: { latestPricePerUnit: 1 } },
|
||||
]).exec();
|
||||
|
||||
return results.map((r) => ({
|
||||
storeId: r._id as string,
|
||||
storeName: r.storeName as string,
|
||||
latestPrice: r.latestPrice as number,
|
||||
latestPricePerUnit: r.latestPricePerUnit as number,
|
||||
currency: r.currency as string,
|
||||
date: r.date as Date,
|
||||
}));
|
||||
}
|
||||
|
||||
public async getLatestForProduct(householdId: string, productId: string, storeId?: string) {
|
||||
const filter: Record<string, unknown> = { householdId, productId };
|
||||
if (storeId) filter['storeId'] = storeId;
|
||||
return PriceRecordModel.findOne(filter).sort({ date: -1 }).lean().exec();
|
||||
}
|
||||
|
||||
public async getAnalytics(householdId: string) {
|
||||
const [spendingOverTime, averageBasketByStore, spendingByCategory] = await Promise.all([
|
||||
// 1. Total Spending Over Time (by month)
|
||||
PriceRecordModel.aggregate([
|
||||
{ $match: { householdId } },
|
||||
{
|
||||
$group: {
|
||||
_id: { $dateToString: { format: '%Y-%m', date: '$date' } },
|
||||
total: { $sum: '$price' },
|
||||
},
|
||||
},
|
||||
{ $sort: { _id: 1 } },
|
||||
{ $project: { _id: 0, period: '$_id', total: 1 } },
|
||||
]).exec(),
|
||||
|
||||
// 2. Average basket by store (grouping by Day + StoreId to simulate distinct trips)
|
||||
PriceRecordModel.aggregate([
|
||||
{ $match: { householdId } },
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
storeId: '$storeId',
|
||||
day: { $dateToString: { format: '%Y-%m-%d', date: '$date' } },
|
||||
},
|
||||
storeName: { $first: '$storeName' },
|
||||
tripTotal: { $sum: '$price' },
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$_id.storeId',
|
||||
storeName: { $first: '$storeName' },
|
||||
avgTotal: { $avg: '$tripTotal' },
|
||||
tripCount: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{ $sort: { avgTotal: -1 } },
|
||||
{ $project: { _id: 0, storeId: '$_id', storeName: 1, avgTotal: 1, tripCount: 1 } },
|
||||
]).exec(),
|
||||
|
||||
// 3. Spending by Category (Requires lookup join with Products)
|
||||
PriceRecordModel.aggregate([
|
||||
{ $match: { householdId } },
|
||||
// Safeguard converting the dynamic string field to a valid ObjectId for proper joins
|
||||
{
|
||||
$addFields: {
|
||||
prodObjId: { $toObjectId: '$productId' },
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'products',
|
||||
localField: 'prodObjId',
|
||||
foreignField: '_id',
|
||||
as: 'matchedProduct',
|
||||
},
|
||||
},
|
||||
{ $unwind: { path: '$matchedProduct', preserveNullAndEmptyArrays: true } },
|
||||
{
|
||||
$group: {
|
||||
_id: { $ifNull: ['$matchedProduct.category', 'other'] },
|
||||
total: { $sum: '$price' },
|
||||
avgPerItem: { $avg: '$price' },
|
||||
},
|
||||
},
|
||||
{ $sort: { total: -1 } },
|
||||
{ $project: { _id: 0, category: '$_id', total: 1, avgPerItem: 1 } },
|
||||
]).exec(),
|
||||
]);
|
||||
|
||||
// 4. Detect product inflation alerts (>10% price rise on last purchase compared to prior one)
|
||||
const priceAlerts = await PriceRecordModel.aggregate([
|
||||
{ $match: { householdId } },
|
||||
{ $sort: { productId: 1, storeId: 1, date: -1 } },
|
||||
{
|
||||
$group: {
|
||||
_id: { productId: '$productId', storeId: '$storeId' },
|
||||
productName: { $first: '$productName' },
|
||||
storeName: { $first: '$storeName' },
|
||||
prices: { $push: '$pricePerUnit' },
|
||||
dates: { $push: '$date' },
|
||||
},
|
||||
},
|
||||
{ $match: { 'prices.1': { $exists: true } } },
|
||||
{
|
||||
$addFields: {
|
||||
currentPrice: { $arrayElemAt: ['$prices', 0] },
|
||||
previousPrice: { $arrayElemAt: ['$prices', 1] },
|
||||
alertDate: { $arrayElemAt: ['$dates', 0] },
|
||||
},
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
changePercent: {
|
||||
$multiply: [
|
||||
{ $divide: [{ $subtract: ['$currentPrice', '$previousPrice'] }, '$previousPrice'] },
|
||||
100,
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $match: { changePercent: { $gt: 10 } } },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
productId: '$_id.productId',
|
||||
storeId: '$_id.storeId',
|
||||
productName: 1,
|
||||
storeName: 1,
|
||||
previousPrice: 1,
|
||||
currentPrice: 1,
|
||||
changePercent: 1,
|
||||
date: '$alertDate',
|
||||
},
|
||||
},
|
||||
]).exec();
|
||||
|
||||
return {
|
||||
spendingOverTime: spendingOverTime as { period: string; total: number }[],
|
||||
averageBasketByStore: averageBasketByStore as {
|
||||
storeId: string;
|
||||
storeName: string;
|
||||
avgTotal: number;
|
||||
tripCount: number;
|
||||
}[],
|
||||
spendingByCategory: spendingByCategory as {
|
||||
category: string;
|
||||
total: number;
|
||||
avgPerItem: number;
|
||||
}[],
|
||||
priceAlerts: priceAlerts as {
|
||||
productId: string;
|
||||
storeId: string;
|
||||
productName: string;
|
||||
storeName: string;
|
||||
previousPrice: number;
|
||||
currentPrice: number;
|
||||
changePercent: number;
|
||||
date: Date;
|
||||
}[],
|
||||
};
|
||||
}
|
||||
}
|
||||
182
packages/api/src/modules/prices/prices.routes.test.ts
Normal file
182
packages/api/src/modules/prices/prices.routes.test.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify from 'fastify';
|
||||
import { fastifyAwilixPlugin } from '@fastify/awilix';
|
||||
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
||||
|
||||
vi.mock('jose', () => ({
|
||||
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
|
||||
jwtVerify: vi.fn().mockResolvedValue({
|
||||
payload: {
|
||||
sub: 'kc-1',
|
||||
email: 'test@example.com',
|
||||
realm_access: { roles: ['member'] },
|
||||
householdIds: ['hh1'],
|
||||
},
|
||||
protectedHeader: {},
|
||||
key: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const mockCreate = vi.fn();
|
||||
const mockCreateMany = vi.fn();
|
||||
const mockFindByProduct = vi.fn();
|
||||
const mockCompareStores = vi.fn();
|
||||
const mockGetAnalytics = vi.fn();
|
||||
|
||||
vi.mock('./prices.repository.js', () => ({
|
||||
PricesRepository: class {
|
||||
create = mockCreate;
|
||||
createMany = mockCreateMany;
|
||||
findByProduct = mockFindByProduct;
|
||||
compareStores = mockCompareStores;
|
||||
getAnalytics = mockGetAnalytics;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../products/products.repository.js', () => ({
|
||||
ProductsRepository: class {
|
||||
findById = vi.fn().mockResolvedValue({ name: 'Mock Product' });
|
||||
findByIds = vi.fn().mockResolvedValue([{ _id: 'p1', name: 'Mock Product' }]);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../stores/stores.repository.js', () => ({
|
||||
StoresRepository: class {
|
||||
findById = vi.fn().mockResolvedValue({ name: 'Mock Store' });
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../users/users.repository.js', () => ({
|
||||
UsersRepository: class {
|
||||
findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
},
|
||||
}));
|
||||
|
||||
import authPlugin from '../../plugins/auth.plugin.js';
|
||||
import householdPlugin from '../../plugins/household.plugin.js';
|
||||
import usersRoutes from '../users/users.routes.js';
|
||||
import pricesRoutes from './prices.routes.js';
|
||||
|
||||
describe('prices.routes', () => {
|
||||
let app: any;
|
||||
|
||||
async function buildTestApp() {
|
||||
const instance = Fastify({ logger: false });
|
||||
instance.setValidatorCompiler(validatorCompiler);
|
||||
instance.setSerializerCompiler(serializerCompiler);
|
||||
await instance.register(fastifyAwilixPlugin, {
|
||||
disposeOnClose: true,
|
||||
disposeOnResponse: true,
|
||||
strictBooleanEnforced: true,
|
||||
});
|
||||
await instance.register(authPlugin);
|
||||
await instance.register(householdPlugin);
|
||||
await instance.register(usersRoutes);
|
||||
await instance.register(pricesRoutes);
|
||||
await instance.ready();
|
||||
return instance;
|
||||
}
|
||||
|
||||
const authHeaders = { authorization: 'Bearer valid' };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
app = await buildTestApp();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
function makeRecord(overrides = {}) {
|
||||
return {
|
||||
_id: 'r1',
|
||||
householdId: 'hh1',
|
||||
productId: 'p1',
|
||||
productName: 'Apples',
|
||||
storeId: 's1',
|
||||
storeName: 'Store',
|
||||
price: 10,
|
||||
currency: 'USD',
|
||||
quantity: 1,
|
||||
unit: 'piece',
|
||||
pricePerUnit: 10,
|
||||
date: new Date(),
|
||||
createdBy: 'kc-1',
|
||||
createdAt: new Date(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('POST /api/v1/households/:householdId/prices', () => {
|
||||
it('records price and returns 201 response', async () => {
|
||||
mockCreate.mockResolvedValue(makeRecord());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/prices',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
productId: 'p1',
|
||||
storeId: 's1',
|
||||
price: 5.99,
|
||||
currency: 'USD',
|
||||
quantity: 1,
|
||||
unit: 'piece',
|
||||
}),
|
||||
});
|
||||
|
||||
if (res.statusCode === 500) {
|
||||
console.log('ERROR PAYLOAD:', res.payload);
|
||||
}
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().productName).toBe('Apples');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/prices/history/:productId', () => {
|
||||
it('returns a paginated envelope of historical pricing data', async () => {
|
||||
mockFindByProduct.mockResolvedValue({
|
||||
data: [makeRecord()],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/prices/history/p1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.pagination.hasMore).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/prices/analytics', () => {
|
||||
it('returns analytical metrics suite with properly formatted dates', async () => {
|
||||
mockGetAnalytics.mockResolvedValue({
|
||||
spendingOverTime: [],
|
||||
averageBasketByStore: [],
|
||||
spendingByCategory: [],
|
||||
priceAlerts: [{ productId: 'p1', productName: 'Bread', storeId: 's1', storeName: 'Store', previousPrice: 2, currentPrice: 2.5, changePercent: 25, date: new Date() }],
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/prices/analytics',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
if (res.statusCode === 500) {
|
||||
console.log('ERROR PAYLOAD:', res.payload);
|
||||
}
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.priceAlerts).toHaveLength(1);
|
||||
expect(typeof body.priceAlerts[0].date).toBe('string');
|
||||
});
|
||||
});
|
||||
});
|
||||
188
packages/api/src/modules/prices/prices.routes.ts
Normal file
188
packages/api/src/modules/prices/prices.routes.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import fp from 'fastify-plugin';
|
||||
import { asClass, Lifetime } from 'awilix';
|
||||
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
||||
import { z } from 'zod/v4';
|
||||
import {
|
||||
CreatePriceRecordSchema,
|
||||
BulkPriceRecordInputSchema,
|
||||
PriceHistoryQuerySchema,
|
||||
PriceRecordResponseSchema,
|
||||
PriceHistoryResponseSchema,
|
||||
FoodStoreComparisonResponseSchema,
|
||||
FoodSpendingAnalyticsResponseSchema,
|
||||
} from '@meshitrack/shared';
|
||||
import { PricesRepository } from './prices.repository.js';
|
||||
import { PricesService } from './prices.service.js';
|
||||
import { ProductsRepository } from '../products/products.repository.js';
|
||||
import { StoresRepository } from '../stores/stores.repository.js';
|
||||
|
||||
type AnyPriceDoc = {
|
||||
_id: string | { toString: () => string };
|
||||
householdId: string;
|
||||
productId: string;
|
||||
productName: string;
|
||||
storeId: string;
|
||||
storeName: string;
|
||||
price: number;
|
||||
currency: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
pricePerUnit: number;
|
||||
date: Date | string | { toISOString: () => string };
|
||||
receiptImageUrl?: string;
|
||||
notes?: string;
|
||||
createdBy: string;
|
||||
createdAt: Date | string | { toISOString: () => string };
|
||||
};
|
||||
|
||||
function toIso(v: Date | string | { toISOString: () => string }): string {
|
||||
if (typeof v === 'string') return v;
|
||||
return v.toISOString();
|
||||
}
|
||||
|
||||
function toPriceRecordResponse(rawDoc: unknown) {
|
||||
const doc = rawDoc as AnyPriceDoc;
|
||||
return {
|
||||
_id: typeof doc._id === 'string' ? doc._id : doc._id.toString(),
|
||||
householdId: doc.householdId,
|
||||
productId: doc.productId,
|
||||
productName: doc.productName,
|
||||
storeId: doc.storeId,
|
||||
storeName: doc.storeName,
|
||||
price: doc.price,
|
||||
currency: doc.currency,
|
||||
quantity: doc.quantity,
|
||||
unit: doc.unit,
|
||||
pricePerUnit: doc.pricePerUnit,
|
||||
date: toIso(doc.date),
|
||||
...(doc.receiptImageUrl ? { receiptImageUrl: doc.receiptImageUrl } : {}),
|
||||
...(doc.notes != null ? { notes: doc.notes } : {}),
|
||||
createdBy: doc.createdBy,
|
||||
createdAt: toIso(doc.createdAt),
|
||||
};
|
||||
}
|
||||
|
||||
declare module '@fastify/awilix' {
|
||||
interface Cradle {
|
||||
pricesRepository: PricesRepository;
|
||||
pricesService: PricesService;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
// Register DI containers
|
||||
fastify.diContainer.register({
|
||||
pricesRepository: asClass(PricesRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
pricesService: asClass(PricesService, { lifetime: Lifetime.SINGLETON }),
|
||||
productsRepository: asClass(ProductsRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
storesRepository: asClass(StoresRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
});
|
||||
|
||||
const app = fastify.withTypeProvider<ZodTypeProvider>();
|
||||
const householdParams = z.object({ householdId: z.string() });
|
||||
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/prices',
|
||||
schema: {
|
||||
params: householdParams,
|
||||
body: CreatePriceRecordSchema,
|
||||
response: { 201: PriceRecordResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('pricesService');
|
||||
const record = await service.recordPrice(
|
||||
request.body,
|
||||
request.params.householdId,
|
||||
request.user.keycloakId
|
||||
);
|
||||
return reply.status(201).send(toPriceRecordResponse(record));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/prices/bulk',
|
||||
schema: {
|
||||
params: householdParams,
|
||||
body: BulkPriceRecordInputSchema,
|
||||
response: { 201: z.array(PriceRecordResponseSchema) },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('pricesService');
|
||||
const records = await service.recordBulkPrices(
|
||||
request.body,
|
||||
request.params.householdId,
|
||||
request.user.keycloakId
|
||||
);
|
||||
return reply.status(201).send(records.map(toPriceRecordResponse));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/prices/history/:productId',
|
||||
schema: {
|
||||
params: householdParams.extend({ productId: z.string() }),
|
||||
querystring: PriceHistoryQuerySchema,
|
||||
response: { 200: PriceHistoryResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('pricesService');
|
||||
const result = await service.getPriceHistory(
|
||||
request.params.productId,
|
||||
request.params.householdId,
|
||||
request.query
|
||||
);
|
||||
return reply.send({
|
||||
data: result.data.map(toPriceRecordResponse),
|
||||
pagination: result.pagination,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/prices/compare/:productId',
|
||||
schema: {
|
||||
params: householdParams.extend({ productId: z.string() }),
|
||||
response: { 200: FoodStoreComparisonResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('pricesService');
|
||||
const results = await service.compareStores(
|
||||
request.params.productId,
|
||||
request.params.householdId
|
||||
);
|
||||
return reply.send({
|
||||
data: results.map((r) => ({
|
||||
...r,
|
||||
date: toIso(r.date),
|
||||
})),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/prices/analytics',
|
||||
schema: {
|
||||
params: householdParams,
|
||||
response: { 200: FoodSpendingAnalyticsResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('pricesService');
|
||||
const analytics = await service.getAnalytics(request.params.householdId);
|
||||
return reply.send({
|
||||
...analytics,
|
||||
priceAlerts: analytics.priceAlerts.map((a) => ({ ...a, date: toIso(a.date) })),
|
||||
});
|
||||
},
|
||||
});
|
||||
},
|
||||
{
|
||||
name: 'prices-routes',
|
||||
dependencies: ['auth-plugin'],
|
||||
}
|
||||
);
|
||||
102
packages/api/src/modules/prices/prices.service.test.ts
Normal file
102
packages/api/src/modules/prices/prices.service.test.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { PricesService } from './prices.service.js';
|
||||
import { NotFoundError } from '../../common/errors.js';
|
||||
|
||||
describe('PricesService', () => {
|
||||
let service: PricesService;
|
||||
|
||||
const mockPricesRepo = {
|
||||
create: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
findByProduct: vi.fn(),
|
||||
compareStores: vi.fn(),
|
||||
getAnalytics: vi.fn(),
|
||||
getLatestForProduct: vi.fn(),
|
||||
};
|
||||
|
||||
const mockProductsRepo = {
|
||||
findById: vi.fn(),
|
||||
findByIds: vi.fn(),
|
||||
};
|
||||
|
||||
const mockStoresRepo = {
|
||||
findById: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new PricesService({
|
||||
pricesRepository: mockPricesRepo as any,
|
||||
productsRepository: mockProductsRepo as any,
|
||||
storesRepository: mockStoresRepo as any,
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordPrice', () => {
|
||||
it('calculates unit price and persists data on existing linkages', async () => {
|
||||
mockProductsRepo.findById.mockResolvedValue({ name: 'Milk' });
|
||||
mockStoresRepo.findById.mockResolvedValue({ name: 'Target' });
|
||||
mockPricesRepo.create.mockResolvedValue({ _id: 'rec1' });
|
||||
|
||||
const result = await service.recordPrice(
|
||||
{ productId: 'p1', storeId: 's1', price: 4, quantity: 2, unit: 'ml' as any, currency: 'USD' },
|
||||
'hh1',
|
||||
'u1'
|
||||
);
|
||||
|
||||
expect(mockPricesRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
productName: 'Milk',
|
||||
storeName: 'Target',
|
||||
pricePerUnit: 2,
|
||||
})
|
||||
);
|
||||
expect(result._id).toBe('rec1');
|
||||
});
|
||||
|
||||
it('throws NotFound if product is invalid', async () => {
|
||||
mockProductsRepo.findById.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.recordPrice(
|
||||
{ productId: 'p1', storeId: 's1', price: 1, quantity: 1, unit: 'g' as any, currency: 'USD' },
|
||||
'hh1',
|
||||
'u1'
|
||||
)
|
||||
).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordBulkPrices', () => {
|
||||
it('ingests multiple mappings throwing notFound if one catalog match fails', async () => {
|
||||
mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
|
||||
mockProductsRepo.findByIds.mockResolvedValue([{ _id: 'p1', name: 'Bread' }]);
|
||||
mockPricesRepo.createMany.mockImplementation(args => args);
|
||||
|
||||
const result = await service.recordBulkPrices(
|
||||
{
|
||||
storeId: 's1',
|
||||
items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }],
|
||||
},
|
||||
'hh1',
|
||||
'u1'
|
||||
);
|
||||
|
||||
expect(mockPricesRepo.createMany).toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].productName).toBe('Bread');
|
||||
});
|
||||
});
|
||||
|
||||
describe('estimatePrice', () => {
|
||||
it('falls back to generic if requested store history is missing', async () => {
|
||||
// First call (restricted to storeId): empty
|
||||
mockPricesRepo.getLatestForProduct.mockResolvedValueOnce(null);
|
||||
// Second call (generic): matches
|
||||
mockPricesRepo.getLatestForProduct.mockResolvedValueOnce({ price: 12 });
|
||||
|
||||
const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
|
||||
expect(mockPricesRepo.getLatestForProduct).toHaveBeenCalledTimes(2);
|
||||
expect(val).toBe(12);
|
||||
});
|
||||
});
|
||||
});
|
||||
145
packages/api/src/modules/prices/prices.service.ts
Normal file
145
packages/api/src/modules/prices/prices.service.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import type { PricesRepository } from './prices.repository.js';
|
||||
import type { ProductsRepository } from '../products/products.repository.js';
|
||||
import type { StoresRepository } from '../stores/stores.repository.js';
|
||||
import type {
|
||||
CreatePriceRecordInput,
|
||||
BulkPriceRecordInput,
|
||||
PriceHistoryQueryInput,
|
||||
} from '@meshitrack/shared';
|
||||
import { NotFoundError } from '../../common/errors.js';
|
||||
|
||||
interface Deps {
|
||||
pricesRepository: PricesRepository;
|
||||
productsRepository: ProductsRepository;
|
||||
storesRepository: StoresRepository;
|
||||
}
|
||||
|
||||
export class PricesService {
|
||||
private readonly pricesRepository: PricesRepository;
|
||||
private readonly productsRepository: ProductsRepository;
|
||||
private readonly storesRepository: StoresRepository;
|
||||
|
||||
public constructor({ pricesRepository, productsRepository, storesRepository }: Deps) {
|
||||
this.pricesRepository = pricesRepository;
|
||||
this.productsRepository = productsRepository;
|
||||
this.storesRepository = storesRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates entity existence, computes pricePerUnit, and persists record
|
||||
*/
|
||||
public async recordPrice(
|
||||
data: CreatePriceRecordInput,
|
||||
householdId: string,
|
||||
userId: string
|
||||
) {
|
||||
const [product, store] = await Promise.all([
|
||||
this.productsRepository.findById(data.productId, householdId),
|
||||
this.storesRepository.findById(data.storeId, householdId),
|
||||
]);
|
||||
|
||||
if (!product) throw new NotFoundError(`Product not found: ${data.productId}`);
|
||||
if (!store) throw new NotFoundError(`Store not found: ${data.storeId}`);
|
||||
|
||||
const pricePerUnit = data.quantity > 0 ? data.price / data.quantity : data.price;
|
||||
|
||||
return this.pricesRepository.create({
|
||||
householdId,
|
||||
productId: data.productId,
|
||||
productName: product.name as string,
|
||||
storeId: data.storeId,
|
||||
storeName: store.name as string,
|
||||
price: data.price,
|
||||
currency: data.currency,
|
||||
quantity: data.quantity,
|
||||
unit: data.unit,
|
||||
pricePerUnit,
|
||||
date: data.date ? new Date(data.date) : new Date(),
|
||||
receiptImageUrl: data.receiptImageUrl,
|
||||
notes: data.notes,
|
||||
createdBy: userId,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ingests a list of purchased products in a single transaction
|
||||
*/
|
||||
public async recordBulkPrices(
|
||||
data: BulkPriceRecordInput,
|
||||
householdId: string,
|
||||
userId: string
|
||||
) {
|
||||
const store = await this.storesRepository.findById(data.storeId, householdId);
|
||||
if (!store) throw new NotFoundError(`Store not found: ${data.storeId}`);
|
||||
|
||||
const recordDate = data.date ? new Date(data.date) : new Date();
|
||||
const productIds = data.items.map((it) => it.productId);
|
||||
|
||||
const products = await this.productsRepository.findByIds(householdId, productIds);
|
||||
const productMap = new Map(products.map((p) => [p._id.toString(), p]));
|
||||
|
||||
const creationPayloads = data.items.map((item) => {
|
||||
const product = productMap.get(item.productId);
|
||||
if (!product) {
|
||||
throw new NotFoundError(`Product not found in catalog: ${item.productId}`);
|
||||
}
|
||||
|
||||
const pricePerUnit = item.quantity > 0 ? item.price / item.quantity : item.price;
|
||||
|
||||
return {
|
||||
householdId,
|
||||
productId: item.productId,
|
||||
productName: product.name as string,
|
||||
storeId: data.storeId,
|
||||
storeName: store.name as string,
|
||||
price: item.price,
|
||||
currency: 'USD', // Base fallback or pulled from household settings in future
|
||||
quantity: item.quantity,
|
||||
unit: item.unit,
|
||||
pricePerUnit,
|
||||
date: recordDate,
|
||||
notes: item.notes,
|
||||
createdBy: userId,
|
||||
};
|
||||
});
|
||||
|
||||
return this.pricesRepository.createMany(creationPayloads);
|
||||
}
|
||||
|
||||
public async getPriceHistory(
|
||||
productId: string,
|
||||
householdId: string,
|
||||
query: PriceHistoryQueryInput
|
||||
) {
|
||||
return this.pricesRepository.findByProduct(householdId, productId, query);
|
||||
}
|
||||
|
||||
public async compareStores(productId: string, householdId: string) {
|
||||
return this.pricesRepository.compareStores(householdId, productId);
|
||||
}
|
||||
|
||||
public async getAnalytics(householdId: string) {
|
||||
return this.pricesRepository.getAnalytics(householdId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the most recent price recorded for this item (optionally restricted to a store)
|
||||
* to enable quick population of estimated basket subtotals on fresh lists.
|
||||
*/
|
||||
public async estimatePrice(
|
||||
productId: string,
|
||||
householdId: string,
|
||||
storeId?: string
|
||||
): Promise<number | null> {
|
||||
const latest = await this.pricesRepository.getLatestForProduct(householdId, productId, storeId);
|
||||
if (!latest) {
|
||||
// If a specific store was requested but has no history, fall back to the generic latest across all stores
|
||||
if (storeId) {
|
||||
const genericLatest = await this.pricesRepository.getLatestForProduct(householdId, productId);
|
||||
return genericLatest ? genericLatest.price : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return latest.price;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue