Phase 9
This commit is contained in:
parent
e396f5088c
commit
a1801af63b
36 changed files with 4783 additions and 31 deletions
|
|
@ -27,6 +27,7 @@
|
|||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/swagger": "^9.7.0",
|
||||
"@fastify/swagger-ui": "^5.2.5",
|
||||
"@fastify/websocket": "^11.2.0",
|
||||
"@meshitrack/shared": "*",
|
||||
"awilix": "^13.0.3",
|
||||
"fastify": "^5.8.4",
|
||||
|
|
|
|||
|
|
@ -44,6 +44,9 @@ import freshnessRulesRoutes from './modules/freshness-rules/freshness-rules.rout
|
|||
import productsRoutes from './modules/products/products.routes.js';
|
||||
import mealPlansRoutes from './modules/meal-plans/meal-plans.routes.js';
|
||||
import nutritionTargetsRoutes from './modules/nutrition-targets/nutrition-target.routes.js';
|
||||
import websocket from '@fastify/websocket';
|
||||
import pricesRoutes from './modules/prices/prices.routes.js';
|
||||
import shoppingListsRoutes from './modules/shopping-lists/shopping-lists.routes.js';
|
||||
|
||||
export async function buildApp(opts: { logger?: boolean | object } = {}) {
|
||||
const app = Fastify({
|
||||
|
|
@ -109,6 +112,9 @@ export async function buildApp(opts: { logger?: boolean | object } = {}) {
|
|||
await app.register(authPlugin);
|
||||
await app.register(householdPlugin);
|
||||
|
||||
// WebSocket Plugin for persistent synchronizations
|
||||
await app.register(websocket);
|
||||
|
||||
// Route modules
|
||||
await app.register(healthRoutes);
|
||||
await app.register(usersRoutes);
|
||||
|
|
@ -129,6 +135,8 @@ export async function buildApp(opts: { logger?: boolean | object } = {}) {
|
|||
await app.register(freshnessRulesRoutes);
|
||||
await app.register(mealPlansRoutes);
|
||||
await app.register(nutritionTargetsRoutes);
|
||||
await app.register(pricesRoutes);
|
||||
await app.register(shoppingListsRoutes);
|
||||
|
||||
// Global error handler
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
|
|
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { ShoppingListsRepository } from './shopping-lists.repository.js';
|
||||
|
||||
const { mockSave, MockShoppingListModel } = 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(),
|
||||
findOneAndDelete: vi.fn(),
|
||||
});
|
||||
return { mockSave, MockShoppingListModel: MockModel };
|
||||
});
|
||||
|
||||
vi.mock('../../schemas/shopping-list.schema.js', () => ({
|
||||
ShoppingListModel: MockShoppingListModel,
|
||||
}));
|
||||
|
||||
const { ShoppingListModel } = await import('../../schemas/shopping-list.schema.js');
|
||||
|
||||
function makeChain(result: unknown = null) {
|
||||
return {
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: vi.fn().mockResolvedValue(result),
|
||||
};
|
||||
}
|
||||
|
||||
describe(ShoppingListsRepository.name, () => {
|
||||
let repo: ShoppingListsRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new ShoppingListsRepository();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('saves new shopping list model and returns simple object', async () => {
|
||||
const doc = { _id: 'list1', name: 'Test List' };
|
||||
mockSave.mockResolvedValue({ toObject: () => doc });
|
||||
|
||||
const result = await repo.create({ name: 'Test List', householdId: 'h1', createdBy: 'u1', status: 'active' });
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result._id).toBe('list1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('queries lists for household ordered newest first', async () => {
|
||||
const chain = makeChain([]);
|
||||
vi.mocked(ShoppingListModel.find).mockReturnValue(chain as any);
|
||||
|
||||
await repo.list('h1');
|
||||
expect(ShoppingListModel.find).toHaveBeenCalledWith({ householdId: 'h1' });
|
||||
expect(chain.sort).toHaveBeenCalledWith({ createdAt: -1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('queries distinct document by ID and householdId', async () => {
|
||||
const chain = makeChain({ _id: 'list1' });
|
||||
vi.mocked(ShoppingListModel.findOne).mockReturnValue(chain as any);
|
||||
|
||||
const result = await repo.findById('list1', 'h1');
|
||||
expect(ShoppingListModel.findOne).toHaveBeenCalledWith({ _id: 'list1', householdId: 'h1' });
|
||||
expect(result?._id).toBe('list1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findActiveByHousehold', () => {
|
||||
it('queries specifically active/shopping lists sorted by update recency', async () => {
|
||||
const chain = makeChain([]);
|
||||
vi.mocked(ShoppingListModel.find).mockReturnValue(chain as any);
|
||||
|
||||
await repo.findActiveByHousehold('h1');
|
||||
expect(ShoppingListModel.find).toHaveBeenCalledWith({
|
||||
householdId: 'h1',
|
||||
status: { $in: ['active', 'shopping'] }
|
||||
});
|
||||
expect(chain.sort).toHaveBeenCalledWith({ updatedAt: -1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('sets top level list variables atomically', async () => {
|
||||
const chain = makeChain({});
|
||||
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
|
||||
|
||||
await repo.update('list1', 'h1', { name: 'New Name' });
|
||||
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'list1', householdId: 'h1' },
|
||||
{ $set: { name: 'New Name' } },
|
||||
{ new: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('executes findOneAndDelete targeting target IDs', async () => {
|
||||
const chain = makeChain({});
|
||||
vi.mocked(ShoppingListModel.findOneAndDelete).mockReturnValue(chain as any);
|
||||
|
||||
await repo.delete('list1', 'h1');
|
||||
expect(ShoppingListModel.findOneAndDelete).toHaveBeenCalledWith({ _id: 'list1', householdId: 'h1' });
|
||||
});
|
||||
});
|
||||
|
||||
// --- Atomic Subdocument Array Actions Tests ---
|
||||
|
||||
describe('addItem', () => {
|
||||
it('executes $push operator targeting list subdocuments', async () => {
|
||||
const chain = makeChain({});
|
||||
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
|
||||
|
||||
const mockItem = { id: 'itm1', quantity: 1, unit: 'g', checked: false, addedToPantry: false };
|
||||
await repo.addItem('list1', 'h1', mockItem as any);
|
||||
|
||||
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'list1', householdId: 'h1' },
|
||||
{ $push: { items: mockItem } },
|
||||
{ new: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateItem', () => {
|
||||
it('maps partial payload to flattened positional $ keys', async () => {
|
||||
const chain = makeChain({});
|
||||
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
|
||||
|
||||
await repo.updateItem('list1', 'h1', 'itm1', { checked: true, actualPrice: 5.5 });
|
||||
|
||||
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'list1', householdId: 'h1', 'items.id': 'itm1' },
|
||||
{
|
||||
$set: {
|
||||
'items.$.checked': true,
|
||||
'items.$.actualPrice': 5.5
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeItem', () => {
|
||||
it('executes $pull operator matching inner item tracking id', async () => {
|
||||
const chain = makeChain({});
|
||||
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
|
||||
|
||||
await repo.removeItem('list1', 'h1', 'itm1');
|
||||
|
||||
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'list1', householdId: 'h1' },
|
||||
{ $pull: { items: { id: 'itm1' } } },
|
||||
{ new: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
import { ShoppingListModel } from '../../schemas/shopping-list.schema.js';
|
||||
import type {
|
||||
CreateShoppingListInput,
|
||||
UpdateShoppingListInput,
|
||||
ShoppingItem,
|
||||
} from '@meshitrack/shared';
|
||||
|
||||
export class ShoppingListsRepository {
|
||||
public async create(data: CreateShoppingListInput & { householdId: string; createdBy: string; status: string }) {
|
||||
const list = new ShoppingListModel(data);
|
||||
const saved = await list.save();
|
||||
return saved.toObject();
|
||||
}
|
||||
|
||||
public async list(householdId: string) {
|
||||
return ShoppingListModel.find({ householdId })
|
||||
.sort({ createdAt: -1 })
|
||||
.lean()
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async findById(id: string, householdId: string) {
|
||||
return ShoppingListModel.findOne({ _id: id, householdId }).lean().exec();
|
||||
}
|
||||
|
||||
public async findActiveByHousehold(householdId: string) {
|
||||
return ShoppingListModel.find({ householdId, status: { $in: ['active', 'shopping'] } })
|
||||
.sort({ updatedAt: -1 })
|
||||
.lean()
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async update(id: string, householdId: string, data: UpdateShoppingListInput) {
|
||||
return ShoppingListModel.findOneAndUpdate(
|
||||
{ _id: id, householdId },
|
||||
{ $set: data },
|
||||
{ new: true }
|
||||
).lean().exec();
|
||||
}
|
||||
|
||||
public async delete(id: string, householdId: string) {
|
||||
return ShoppingListModel.findOneAndDelete({ _id: id, householdId }).lean().exec();
|
||||
}
|
||||
|
||||
// --- Granular Atomic Subdocument Actions ---
|
||||
|
||||
public async addItem(id: string, householdId: string, item: ShoppingItem) {
|
||||
return ShoppingListModel.findOneAndUpdate(
|
||||
{ _id: id, householdId },
|
||||
{ $push: { items: item } },
|
||||
{ new: true }
|
||||
).lean().exec();
|
||||
}
|
||||
|
||||
public async updateItem(
|
||||
id: string,
|
||||
householdId: string,
|
||||
itemId: string,
|
||||
updates: Partial<ShoppingItem>
|
||||
) {
|
||||
const setUpdates: Record<string, unknown> = {};
|
||||
for (const [key, val] of Object.entries(updates)) {
|
||||
// Flatten parameters mapping them precisely to the positional positional matched index
|
||||
setUpdates[`items.$.${key}`] = val;
|
||||
}
|
||||
|
||||
return ShoppingListModel.findOneAndUpdate(
|
||||
{ _id: id, householdId, 'items.id': itemId },
|
||||
{ $set: setUpdates },
|
||||
{ new: true }
|
||||
).lean().exec();
|
||||
}
|
||||
|
||||
public async removeItem(id: string, householdId: string, itemId: string) {
|
||||
return ShoppingListModel.findOneAndUpdate(
|
||||
{ _id: id, householdId },
|
||||
{ $pull: { items: { id: itemId } } },
|
||||
{ new: true }
|
||||
).lean().exec();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,211 @@
|
|||
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 mockList = vi.fn();
|
||||
const mockFindById = vi.fn();
|
||||
const mockCreate = vi.fn();
|
||||
const mockUpdate = vi.fn();
|
||||
const mockDelete = vi.fn();
|
||||
const mockAddItem = vi.fn();
|
||||
const mockUpdateItem = vi.fn();
|
||||
const mockRemoveItem = vi.fn();
|
||||
|
||||
vi.mock('./shopping-lists.repository.js', () => ({
|
||||
ShoppingListsRepository: class {
|
||||
list = mockList;
|
||||
findById = mockFindById;
|
||||
create = mockCreate;
|
||||
update = mockUpdate;
|
||||
delete = mockDelete;
|
||||
addItem = mockAddItem;
|
||||
updateItem = mockUpdateItem;
|
||||
removeItem = mockRemoveItem;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../meal-plans/shopping-gap.service.js', () => ({
|
||||
ShoppingGapService: class {
|
||||
calculateGap = vi.fn().mockResolvedValue({ missingItems: [] });
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../pantry/pantry.service.js', () => ({
|
||||
PantryService: class {
|
||||
create = vi.fn().mockResolvedValue({ _id: 'pant1' });
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../products/products.repository.js', () => ({
|
||||
ProductsRepository: class {
|
||||
findById = vi.fn().mockResolvedValue({ category: 'dairy' });
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../prices/prices.service.js', () => ({
|
||||
PricesService: class {
|
||||
estimatePrice = vi.fn().mockResolvedValue(5.0);
|
||||
recordPrice = vi.fn().mockResolvedValue({});
|
||||
compareStores = vi.fn().mockResolvedValue([]);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../meal-plans/meal-plans.repository.js', () => ({
|
||||
MealPlanRepository: class {
|
||||
findById = vi.fn().mockResolvedValue({ _id: 'mp1', weekStartDate: new Date() });
|
||||
update = vi.fn().mockResolvedValue({});
|
||||
},
|
||||
}));
|
||||
|
||||
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 shoppingListsRoutes from './shopping-lists.routes.js';
|
||||
|
||||
describe('shopping-lists.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(shoppingListsRoutes);
|
||||
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 makeShoppingList(overrides = {}) {
|
||||
return {
|
||||
_id: 'list1',
|
||||
householdId: 'hh1',
|
||||
name: 'Weekly Checklist',
|
||||
items: [],
|
||||
status: 'active',
|
||||
createdBy: 'kc-1',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('GET /api/v1/households/:householdId/shopping-lists', () => {
|
||||
it('returns all lists belonging to household', async () => {
|
||||
mockList.mockResolvedValue([makeShoppingList()]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/shopping-lists',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/shopping-lists', () => {
|
||||
it('persists metadata and returns 201 response', async () => {
|
||||
mockCreate.mockImplementation(arg => Promise.resolve({ ...arg, _id: 'newListA', createdAt: new Date(), updatedAt: new Date() }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/shopping-lists',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Costco Run',
|
||||
items: []
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().name).toBe('Costco Run');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/shopping-lists/:id/items', () => {
|
||||
it('adds new checklist subdocument item generating tracking UUIDs', async () => {
|
||||
mockFindById.mockResolvedValue(makeShoppingList());
|
||||
const updated = makeShoppingList({
|
||||
items: [{ id: 'itemuuid123', productId: 'p1', quantity: 1, unit: 'piece', checked: false, addedToPantry: false }]
|
||||
});
|
||||
mockAddItem.mockResolvedValue(updated);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/shopping-lists/list1/items',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
productId: 'p1',
|
||||
quantity: 1,
|
||||
unit: 'piece'
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.items).toHaveLength(1);
|
||||
expect(body.items[0].productId).toBe('p1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/shopping-lists/:id/sync-to-pantry', () => {
|
||||
it('executes batch synchronized promotions resulting in completed summaries', async () => {
|
||||
const populatedList = makeShoppingList({
|
||||
items: [{ id: 'itemA', productId: 'p1', checked: true, addedToPantry: false, quantity: 1, unit: 'piece' }]
|
||||
});
|
||||
mockFindById.mockResolvedValue(populatedList);
|
||||
mockUpdateItem.mockResolvedValue({});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/shopping-lists/list1/sync-to-pantry',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.addedCount).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
376
packages/api/src/modules/shopping-lists/shopping-lists.routes.ts
Normal file
376
packages/api/src/modules/shopping-lists/shopping-lists.routes.ts
Normal file
|
|
@ -0,0 +1,376 @@
|
|||
import fp from 'fastify-plugin';
|
||||
import { asClass, Lifetime } from 'awilix';
|
||||
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
||||
import { z } from 'zod/v4';
|
||||
import type { WebSocket } from 'ws';
|
||||
import {
|
||||
CreateShoppingListSchema,
|
||||
UpdateShoppingListSchema,
|
||||
AddShoppingItemSchema,
|
||||
UpdateShoppingItemSchema,
|
||||
ShoppingListResponseSchema,
|
||||
ShoppingListSyncToPantryResponseSchema,
|
||||
BasketStoreComparisonResponseSchema,
|
||||
} from '@meshitrack/shared';
|
||||
import { ShoppingListsRepository } from './shopping-lists.repository.js';
|
||||
import { ShoppingListsService } from './shopping-lists.service.js';
|
||||
import { ShoppingGapService } from '../meal-plans/shopping-gap.service.js';
|
||||
import { PantryService } from '../pantry/pantry.service.js';
|
||||
import { ProductsRepository } from '../products/products.repository.js';
|
||||
import { PricesService } from '../prices/prices.service.js';
|
||||
import { MealPlanRepository } from '../meal-plans/meal-plans.repository.js';
|
||||
import { PantryRepository } from '../pantry/pantry.repository.js';
|
||||
import { RecipesRepository } from '../recipes/recipes.repository.js';
|
||||
import { StoresRepository } from '../stores/stores.repository.js';
|
||||
import { PricesRepository } from '../prices/prices.repository.js';
|
||||
|
||||
// Memory track for live concurrent websocket clients per active list session
|
||||
const activeListSockets = new Map<string, Set<WebSocket>>();
|
||||
|
||||
function broadcastToList(listId: string, excludeSocket: WebSocket, message: any) {
|
||||
const set = activeListSockets.get(listId);
|
||||
if (!set) return;
|
||||
const payload = JSON.stringify(message);
|
||||
for (const socket of set) {
|
||||
if (socket !== excludeSocket && socket.readyState === 1 /* OPEN */) {
|
||||
socket.send(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare module '@fastify/awilix' {
|
||||
interface Cradle {
|
||||
shoppingListsRepository: ShoppingListsRepository;
|
||||
shoppingListsService: ShoppingListsService;
|
||||
}
|
||||
}
|
||||
|
||||
function serializeList(doc: any) {
|
||||
return {
|
||||
...doc,
|
||||
_id: doc._id.toString(),
|
||||
createdAt: doc.createdAt?.toISOString(),
|
||||
updatedAt: doc.updatedAt?.toISOString(),
|
||||
completedAt: doc.completedAt?.toISOString(),
|
||||
items: doc.items.map((it: any) => ({
|
||||
...it,
|
||||
checkedAt: it.checkedAt?.toISOString(),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
// Register Awilix classes
|
||||
fastify.diContainer.register({
|
||||
shoppingListsRepository: asClass(ShoppingListsRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
shoppingListsService: asClass(ShoppingListsService, { lifetime: Lifetime.SINGLETON }),
|
||||
|
||||
// Cross-domain requirements to service the list workflow orchestrations
|
||||
shoppingGapService: asClass(ShoppingGapService, { lifetime: Lifetime.SINGLETON }),
|
||||
pantryService: asClass(PantryService, { lifetime: Lifetime.SINGLETON }),
|
||||
pantryRepository: asClass(PantryRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
productsRepository: asClass(ProductsRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
pricesService: asClass(PricesService, { lifetime: Lifetime.SINGLETON }),
|
||||
pricesRepository: asClass(PricesRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
mealPlanRepository: asClass(MealPlanRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
recipesRepository: asClass(RecipesRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
storesRepository: asClass(StoresRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
});
|
||||
|
||||
const app = fastify.withTypeProvider<ZodTypeProvider>();
|
||||
const householdParams = z.object({ householdId: z.string() });
|
||||
const listIdParams = householdParams.extend({ id: z.string() });
|
||||
|
||||
// 1. Standard List CRUD
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/shopping-lists',
|
||||
schema: {
|
||||
params: householdParams,
|
||||
response: { 200: z.array(ShoppingListResponseSchema) },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const lists = await service.list(request.params.householdId);
|
||||
return reply.send(lists.map(serializeList));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/shopping-lists',
|
||||
schema: {
|
||||
params: householdParams,
|
||||
body: CreateShoppingListSchema,
|
||||
response: { 201: ShoppingListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const list = await service.create(
|
||||
request.body,
|
||||
request.params.householdId,
|
||||
request.user.keycloakId
|
||||
);
|
||||
return reply.status(201).send(serializeList(list));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id',
|
||||
schema: {
|
||||
params: listIdParams,
|
||||
response: { 200: ShoppingListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const list = await service.getById(request.params.id, request.params.householdId);
|
||||
return reply.send(serializeList(list));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id',
|
||||
schema: {
|
||||
params: listIdParams,
|
||||
body: UpdateShoppingListSchema,
|
||||
response: { 200: ShoppingListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const list = await service.update(
|
||||
request.params.id,
|
||||
request.params.householdId,
|
||||
request.body
|
||||
);
|
||||
return reply.send(serializeList(list));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id',
|
||||
schema: {
|
||||
params: listIdParams,
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
await service.delete(request.params.id, request.params.householdId);
|
||||
return reply.status(204).send();
|
||||
},
|
||||
});
|
||||
|
||||
// 2. Nested Item Modifications
|
||||
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id/items',
|
||||
schema: {
|
||||
params: listIdParams,
|
||||
body: AddShoppingItemSchema,
|
||||
response: { 201: ShoppingListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const { list, addedItem } = await service.addItem(
|
||||
request.params.id,
|
||||
request.params.householdId,
|
||||
request.body
|
||||
);
|
||||
|
||||
// Emit real-time update notification to existing connected viewers
|
||||
broadcastToList(request.params.id, null as any, {
|
||||
type: 'ITEM_ADDED',
|
||||
item: { ...addedItem, checkedAt: undefined },
|
||||
});
|
||||
|
||||
return reply.status(201).send(serializeList(list));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id/items/:itemId',
|
||||
schema: {
|
||||
params: listIdParams.extend({ itemId: z.string() }),
|
||||
body: UpdateShoppingItemSchema,
|
||||
response: { 200: ShoppingListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const updatedList = await service.updateItem(
|
||||
request.params.id,
|
||||
request.params.householdId,
|
||||
request.params.itemId,
|
||||
request.body,
|
||||
request.user.keycloakId
|
||||
);
|
||||
|
||||
// Broadcast the precise item differential state update to sibling websocket listeners
|
||||
const matchedItem = updatedList.items.find((i) => i.id === request.params.itemId);
|
||||
if (matchedItem) {
|
||||
broadcastToList(request.params.id, null as any, {
|
||||
type: 'ITEM_UPDATED',
|
||||
itemId: request.params.itemId,
|
||||
updates: {
|
||||
...request.body,
|
||||
checkedAt: matchedItem.checkedAt?.toISOString(),
|
||||
checkedBy: matchedItem.checkedBy,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return reply.send(serializeList(updatedList));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id/items/:itemId',
|
||||
schema: {
|
||||
params: listIdParams.extend({ itemId: z.string() }),
|
||||
response: { 200: ShoppingListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const list = await service.removeItem(
|
||||
request.params.id,
|
||||
request.params.householdId,
|
||||
request.params.itemId
|
||||
);
|
||||
|
||||
broadcastToList(request.params.id, null as any, {
|
||||
type: 'ITEM_REMOVED',
|
||||
itemId: request.params.itemId,
|
||||
});
|
||||
|
||||
return reply.send(serializeList(list));
|
||||
},
|
||||
});
|
||||
|
||||
// 3. Domain Workflow Hooks
|
||||
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/from-meal-plan/:mealPlanId',
|
||||
schema: {
|
||||
params: householdParams.extend({ mealPlanId: z.string() }),
|
||||
response: { 201: ShoppingListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const list = await service.createFromMealPlan(
|
||||
request.params.mealPlanId,
|
||||
request.params.householdId,
|
||||
request.user.keycloakId
|
||||
);
|
||||
return reply.status(201).send(serializeList(list));
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id/sync-to-pantry',
|
||||
schema: {
|
||||
params: listIdParams,
|
||||
response: { 200: ShoppingListSyncToPantryResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const results = await service.syncCheckedToPantry(
|
||||
request.params.id,
|
||||
request.params.householdId,
|
||||
request.user.keycloakId
|
||||
);
|
||||
return reply.send(results);
|
||||
},
|
||||
});
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id/stores',
|
||||
schema: {
|
||||
params: listIdParams,
|
||||
response: { 200: BasketStoreComparisonResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const comparison = await service.getStoreComparison(
|
||||
request.params.id,
|
||||
request.params.householdId
|
||||
);
|
||||
return reply.send(comparison);
|
||||
},
|
||||
});
|
||||
|
||||
// 4. Persist Collaborative WebSocket Handshakes
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/shopping-lists/:id/sync',
|
||||
websocket: true,
|
||||
handler: (socket, request) => {
|
||||
const listId = request.params.id;
|
||||
|
||||
// Setup connection context
|
||||
if (!activeListSockets.has(listId)) {
|
||||
activeListSockets.set(listId, new Set());
|
||||
}
|
||||
activeListSockets.get(listId)!.add(socket);
|
||||
|
||||
request.log.info({ listId }, 'Active client joined shopping list sync channel');
|
||||
|
||||
socket.on('message', async (messageBuffer) => {
|
||||
try {
|
||||
const payload = JSON.parse(messageBuffer.toString());
|
||||
|
||||
// Handlers for inbound events e.g. real-time toggle checks from frontends
|
||||
if (payload.type === 'TOGGLE_ITEM') {
|
||||
const service = fastify.diContainer.resolve('shoppingListsService');
|
||||
const updatedList = await service.updateItem(
|
||||
listId,
|
||||
request.params.householdId,
|
||||
payload.itemId,
|
||||
{ checked: payload.checked },
|
||||
request.user.keycloakId
|
||||
);
|
||||
|
||||
const matched = updatedList.items.find(it => it.id === payload.itemId);
|
||||
|
||||
// Echo back differential confirmation to everyone else on the floor
|
||||
broadcastToList(listId, socket, {
|
||||
type: 'ITEM_UPDATED',
|
||||
itemId: payload.itemId,
|
||||
updates: {
|
||||
checked: payload.checked,
|
||||
checkedAt: matched?.checkedAt?.toISOString(),
|
||||
checkedBy: matched?.checkedBy,
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
request.log.error(err, 'WebSocket message sync processing error');
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
const set = activeListSockets.get(listId);
|
||||
if (set) {
|
||||
set.delete(socket);
|
||||
if (set.size === 0) {
|
||||
activeListSockets.delete(listId);
|
||||
}
|
||||
}
|
||||
request.log.info({ listId }, 'Client severed sync handshake connection');
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
name: 'shopping-lists-routes',
|
||||
dependencies: ['auth-plugin'],
|
||||
}
|
||||
);
|
||||
|
|
@ -0,0 +1,224 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { ShoppingListsService } from './shopping-lists.service.js';
|
||||
import { NotFoundError } from '../../common/errors.js';
|
||||
|
||||
describe('ShoppingListsService', () => {
|
||||
let service: ShoppingListsService;
|
||||
|
||||
const mockListsRepo = {
|
||||
list: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
addItem: vi.fn(),
|
||||
updateItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
};
|
||||
|
||||
const mockGapService = {
|
||||
calculateGap: vi.fn(),
|
||||
};
|
||||
|
||||
const mockPantryService = {
|
||||
create: vi.fn(),
|
||||
};
|
||||
|
||||
const mockProductsRepo = {
|
||||
findById: vi.fn(),
|
||||
};
|
||||
|
||||
const mockPricesService = {
|
||||
estimatePrice: vi.fn(),
|
||||
recordPrice: vi.fn(),
|
||||
compareStores: vi.fn(),
|
||||
};
|
||||
|
||||
const mockMealPlanRepo = {
|
||||
findById: vi.fn(),
|
||||
update: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new ShoppingListsService({
|
||||
shoppingListsRepository: mockListsRepo as any,
|
||||
shoppingGapService: mockGapService as any,
|
||||
pantryService: mockPantryService as any,
|
||||
productsRepository: mockProductsRepo as any,
|
||||
pricesService: mockPricesService as any,
|
||||
mealPlanRepository: mockMealPlanRepo as any,
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('populates initial estimates and auto-generates internal tracking UUIDs', async () => {
|
||||
mockProductsRepo.findById.mockResolvedValue({ category: 'produce' });
|
||||
mockPricesService.estimatePrice.mockResolvedValue(5);
|
||||
mockListsRepo.create.mockImplementation(arg => arg);
|
||||
|
||||
const result = await service.create(
|
||||
{
|
||||
name: 'Weekly run',
|
||||
items: [{ productId: 'p1', quantity: 1, unit: 'g' as any }],
|
||||
},
|
||||
'hh1',
|
||||
'u1'
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(1);
|
||||
expect(result.items[0].id).toBeDefined();
|
||||
expect(result.items[0].estimatedPrice).toBe(5);
|
||||
expect(result.totalEstimatedCost).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addItem', () => {
|
||||
it('hydrates single product pricing and pushes to list repository', async () => {
|
||||
mockListsRepo.findById.mockResolvedValue({ _id: 'list1' });
|
||||
mockProductsRepo.findById.mockResolvedValue({ category: 'meat' });
|
||||
mockPricesService.estimatePrice.mockResolvedValue(10);
|
||||
mockListsRepo.addItem.mockResolvedValue({ _id: 'list1' });
|
||||
|
||||
const res = await service.addItem('list1', 'hh1', {
|
||||
productId: 'prodA',
|
||||
quantity: 1,
|
||||
unit: 'g' as any,
|
||||
});
|
||||
|
||||
expect(mockListsRepo.addItem).toHaveBeenCalledWith(
|
||||
'list1',
|
||||
'hh1',
|
||||
expect.objectContaining({
|
||||
productId: 'prodA',
|
||||
estimatedPrice: 10,
|
||||
category: 'meat',
|
||||
})
|
||||
);
|
||||
expect(res.addedItem.id).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateItem', () => {
|
||||
it('injects correct checked timestamps on check-off state mutations', async () => {
|
||||
mockListsRepo.updateItem.mockResolvedValue({});
|
||||
|
||||
await service.updateItem('list1', 'hh1', 'itemA', { checked: true }, 'userIdX');
|
||||
|
||||
expect(mockListsRepo.updateItem).toHaveBeenCalledWith(
|
||||
'list1',
|
||||
'hh1',
|
||||
'itemA',
|
||||
expect.objectContaining({
|
||||
checked: true,
|
||||
checkedBy: 'userIdX',
|
||||
checkedAt: expect.any(Date),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createFromMealPlan', () => {
|
||||
it('runs shopping gap report and populates distinct grocery array linked back to source plan', async () => {
|
||||
mockMealPlanRepo.findById.mockResolvedValue({ _id: 'mp1', weekStartDate: '2026-05-18' });
|
||||
mockGapService.calculateGap.mockResolvedValue({
|
||||
missingItems: [
|
||||
{ productId: 'gapProd', missingQuantity: 5, unit: 'g', category: 'dairy' }
|
||||
]
|
||||
});
|
||||
mockPricesService.estimatePrice.mockResolvedValue(2);
|
||||
mockListsRepo.create.mockResolvedValue({ _id: 'newList1' });
|
||||
|
||||
const res = await service.createFromMealPlan('mp1', 'hh1', 'userIdZ');
|
||||
|
||||
expect(mockGapService.calculateGap).toHaveBeenCalledWith('hh1', 'mp1');
|
||||
expect(mockListsRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
mealPlanId: 'mp1',
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
productId: 'gapProd',
|
||||
quantity: 5,
|
||||
estimatedPrice: 2,
|
||||
})
|
||||
]
|
||||
})
|
||||
);
|
||||
// Assert link-back invocation
|
||||
expect(mockMealPlanRepo.update).toHaveBeenCalledWith('mp1', 'hh1', {
|
||||
shoppingListId: 'newList1',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('syncCheckedToPantry', () => {
|
||||
it('iterates checked items, creating pantry items and recording actual prices in ledger', async () => {
|
||||
const mockList = {
|
||||
_id: 'list1',
|
||||
preferredStoreId: 'storeA',
|
||||
items: [
|
||||
{
|
||||
id: 'itmA',
|
||||
productId: 'p1',
|
||||
checked: true,
|
||||
addedToPantry: false,
|
||||
quantity: 2,
|
||||
unit: 'g',
|
||||
actualPrice: 15.50,
|
||||
}
|
||||
]
|
||||
};
|
||||
mockListsRepo.findById.mockResolvedValue(mockList);
|
||||
|
||||
const summary = await service.syncCheckedToPantry('list1', 'hh1', 'userAlpha');
|
||||
|
||||
// 1. Verify pantry promotion
|
||||
expect(mockPantryService.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
productId: 'p1',
|
||||
quantity: 2,
|
||||
purchasePrice: 15.50,
|
||||
storeId: 'storeA',
|
||||
}),
|
||||
'hh1',
|
||||
'userAlpha'
|
||||
);
|
||||
|
||||
// 2. Verify point-in-time ledger price logging
|
||||
expect(mockPricesService.recordPrice).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
productId: 'p1',
|
||||
price: 15.50,
|
||||
storeId: 'storeA',
|
||||
}),
|
||||
'hh1',
|
||||
'userAlpha'
|
||||
);
|
||||
|
||||
// 3. Verify completion bit toggled in list subdocument
|
||||
expect(mockListsRepo.updateItem).toHaveBeenCalledWith('list1', 'hh1', 'itmA', {
|
||||
addedToPantry: true,
|
||||
});
|
||||
|
||||
expect(summary.addedCount).toBe(1);
|
||||
expect(summary.pricesLogged).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStoreComparison', () => {
|
||||
it('collates individual store deviation lists to rank optimized single store trips', async () => {
|
||||
mockListsRepo.findById.mockResolvedValue({
|
||||
items: [{ productId: 'p1' }]
|
||||
});
|
||||
mockPricesService.compareStores.mockResolvedValue([
|
||||
{ storeId: 'sA', storeName: 'Walmart', latestPrice: 10 },
|
||||
{ storeId: 'sB', storeName: 'Whole Foods', latestPrice: 18 },
|
||||
]);
|
||||
|
||||
const comparison = await service.getStoreComparison('list1', 'hh1');
|
||||
expect(comparison.singleStoreOptions).toHaveLength(2);
|
||||
expect(comparison.singleStoreOptions[0].storeName).toBe('Walmart');
|
||||
expect(comparison.singleStoreOptions[0].estimatedTotal).toBe(10);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,356 @@
|
|||
import type { ShoppingListsRepository } from './shopping-lists.repository.js';
|
||||
import type { ShoppingGapService } from '../meal-plans/shopping-gap.service.js';
|
||||
import type { PantryService } from '../pantry/pantry.service.js';
|
||||
import type { ProductsRepository } from '../products/products.repository.js';
|
||||
import type { PricesService } from '../prices/prices.service.js';
|
||||
import type { MealPlanRepository } from '../meal-plans/meal-plans.repository.js';
|
||||
import type {
|
||||
CreateShoppingListInput,
|
||||
UpdateShoppingListInput,
|
||||
AddShoppingItemInput,
|
||||
UpdateShoppingItemInput,
|
||||
ShoppingListStatus,
|
||||
ShoppingItem,
|
||||
} from '@meshitrack/shared';
|
||||
import { ShoppingListSourceType } from '@meshitrack/shared';
|
||||
import { StorageLocation, ServingUnit } from '@meshitrack/shared';
|
||||
import { NotFoundError } from '../../common/errors.js';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
interface Deps {
|
||||
shoppingListsRepository: ShoppingListsRepository;
|
||||
shoppingGapService: ShoppingGapService;
|
||||
pantryService: PantryService;
|
||||
productsRepository: ProductsRepository;
|
||||
pricesService: PricesService;
|
||||
mealPlanRepository: MealPlanRepository;
|
||||
}
|
||||
|
||||
export class ShoppingListsService {
|
||||
private readonly shoppingListsRepository: ShoppingListsRepository;
|
||||
private readonly shoppingGapService: ShoppingGapService;
|
||||
private readonly pantryService: PantryService;
|
||||
private readonly productsRepository: ProductsRepository;
|
||||
private readonly pricesService: PricesService;
|
||||
private readonly mealPlanRepository: MealPlanRepository;
|
||||
|
||||
public constructor({
|
||||
shoppingListsRepository,
|
||||
shoppingGapService,
|
||||
pantryService,
|
||||
productsRepository,
|
||||
pricesService,
|
||||
mealPlanRepository,
|
||||
}: Deps) {
|
||||
this.shoppingListsRepository = shoppingListsRepository;
|
||||
this.shoppingGapService = shoppingGapService;
|
||||
this.pantryService = pantryService;
|
||||
this.productsRepository = productsRepository;
|
||||
this.pricesService = pricesService;
|
||||
this.mealPlanRepository = mealPlanRepository;
|
||||
}
|
||||
|
||||
public async list(householdId: string) {
|
||||
return this.shoppingListsRepository.list(householdId);
|
||||
}
|
||||
|
||||
public async getById(id: string, householdId: string) {
|
||||
const list = await this.shoppingListsRepository.findById(id, householdId);
|
||||
if (!list) throw new NotFoundError('Shopping list not found');
|
||||
return list;
|
||||
}
|
||||
|
||||
public async create(data: CreateShoppingListInput, householdId: string, userId: string) {
|
||||
// Optionally calculate estimates for pre-populated items
|
||||
const hydratedItems: ShoppingItem[] = [];
|
||||
let runningTotal = 0;
|
||||
|
||||
for (const it of data.items || []) {
|
||||
const itemId = uuidv4();
|
||||
let estimatedPrice: number | undefined;
|
||||
let category: string | undefined = it.category;
|
||||
|
||||
if (it.productId) {
|
||||
const [p, est] = await Promise.all([
|
||||
this.productsRepository.findById(it.productId, householdId),
|
||||
this.pricesService.estimatePrice(it.productId, householdId, data.preferredStoreId),
|
||||
]);
|
||||
if (p) category = category || p.category;
|
||||
if (est) {
|
||||
estimatedPrice = est;
|
||||
runningTotal += est;
|
||||
}
|
||||
}
|
||||
|
||||
hydratedItems.push({
|
||||
id: itemId,
|
||||
productId: it.productId,
|
||||
customName: it.customName,
|
||||
quantity: it.quantity,
|
||||
unit: it.unit,
|
||||
checked: false,
|
||||
addedToPantry: false,
|
||||
notes: it.notes,
|
||||
estimatedPrice,
|
||||
category: category as any,
|
||||
});
|
||||
}
|
||||
|
||||
return this.shoppingListsRepository.create({
|
||||
...data,
|
||||
items: hydratedItems,
|
||||
householdId,
|
||||
createdBy: userId,
|
||||
status: 'active',
|
||||
totalEstimatedCost: runningTotal > 0 ? Math.round(runningTotal * 100) / 100 : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
public async update(id: string, householdId: string, data: UpdateShoppingListInput) {
|
||||
const list = await this.getById(id, householdId);
|
||||
const updated = await this.shoppingListsRepository.update(id, householdId, data);
|
||||
if (!updated) throw new NotFoundError('Shopping list not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async delete(id: string, householdId: string) {
|
||||
await this.getById(id, householdId);
|
||||
return this.shoppingListsRepository.delete(id, householdId);
|
||||
}
|
||||
|
||||
// --- Live Item Actions ---
|
||||
|
||||
public async addItem(id: string, householdId: string, data: AddShoppingItemInput) {
|
||||
await this.getById(id, householdId);
|
||||
|
||||
let estimatedPrice: number | undefined;
|
||||
let category: string | undefined = data.category;
|
||||
|
||||
if (data.productId) {
|
||||
const [p, est] = await Promise.all([
|
||||
this.productsRepository.findById(data.productId, householdId),
|
||||
this.pricesService.estimatePrice(data.productId, householdId),
|
||||
]);
|
||||
if (p) category = category || p.category;
|
||||
if (est) estimatedPrice = est;
|
||||
}
|
||||
|
||||
const newItem: ShoppingItem = {
|
||||
id: uuidv4(),
|
||||
productId: data.productId,
|
||||
customName: data.customName,
|
||||
quantity: data.quantity,
|
||||
unit: data.unit,
|
||||
checked: false,
|
||||
addedToPantry: false,
|
||||
notes: data.notes,
|
||||
estimatedPrice,
|
||||
category: category as any,
|
||||
};
|
||||
|
||||
const updated = await this.shoppingListsRepository.addItem(id, householdId, newItem);
|
||||
if (!updated) throw new NotFoundError('Shopping list not found');
|
||||
return { list: updated, addedItem: newItem };
|
||||
}
|
||||
|
||||
public async updateItem(
|
||||
id: string,
|
||||
householdId: string,
|
||||
itemId: string,
|
||||
data: UpdateShoppingItemInput,
|
||||
userId: string
|
||||
) {
|
||||
const updates: Partial<ShoppingItem> = { ...data };
|
||||
|
||||
if (data.checked !== undefined) {
|
||||
updates.checkedAt = data.checked ? new Date() : undefined;
|
||||
updates.checkedBy = data.checked ? userId : undefined;
|
||||
}
|
||||
|
||||
const updated = await this.shoppingListsRepository.updateItem(id, householdId, itemId, updates);
|
||||
if (!updated) throw new NotFoundError('Shopping item or list not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async removeItem(id: string, householdId: string, itemId: string) {
|
||||
const updated = await this.shoppingListsRepository.removeItem(id, householdId, itemId);
|
||||
if (!updated) throw new NotFoundError('Shopping list not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
// --- Workflow Methods ---
|
||||
|
||||
/**
|
||||
* Analyzes missing ingredients for a meal plan and pre-builds a targeted list.
|
||||
*/
|
||||
public async createFromMealPlan(mealPlanId: string, householdId: string, userId: string) {
|
||||
const plan = await this.mealPlanRepository.findById(mealPlanId, householdId);
|
||||
if (!plan) throw new NotFoundError('Meal plan not found');
|
||||
|
||||
const report = await this.shoppingGapService.calculateGap(householdId, mealPlanId);
|
||||
|
||||
const listItems: ShoppingItem[] = [];
|
||||
let runningTotal = 0;
|
||||
|
||||
for (const gap of report.missingItems) {
|
||||
const estPrice = await this.pricesService.estimatePrice(gap.productId, householdId);
|
||||
if (estPrice) runningTotal += estPrice;
|
||||
|
||||
listItems.push({
|
||||
id: uuidv4(),
|
||||
productId: gap.productId,
|
||||
quantity: gap.missingQuantity,
|
||||
unit: gap.unit as ServingUnit,
|
||||
checked: false,
|
||||
addedToPantry: false,
|
||||
category: gap.category as any,
|
||||
estimatedPrice: estPrice || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const dateStr = new Date((plan as any).weekStartDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
const name = `Groceries for Week of ${dateStr}`;
|
||||
|
||||
const newList = await this.shoppingListsRepository.create({
|
||||
name,
|
||||
items: listItems,
|
||||
householdId,
|
||||
createdBy: userId,
|
||||
status: 'active',
|
||||
createdFrom: {
|
||||
type: ShoppingListSourceType.MEAL_PLAN,
|
||||
referenceId: mealPlanId,
|
||||
},
|
||||
mealPlanId,
|
||||
totalEstimatedCost: runningTotal > 0 ? Math.round(runningTotal * 100) / 100 : undefined,
|
||||
});
|
||||
|
||||
// Re-link backing meal plan to its generated list for simplified visual tracking
|
||||
await this.mealPlanRepository.update(mealPlanId, householdId, {
|
||||
shoppingListId: newList._id.toString(),
|
||||
});
|
||||
|
||||
return newList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrates all checked grocery items into active pantry items and records final purchase prices.
|
||||
*/
|
||||
public async syncCheckedToPantry(id: string, householdId: string, userId: string) {
|
||||
const list = await this.getById(id, householdId);
|
||||
|
||||
let addedCount = 0;
|
||||
let pricesLogged = 0;
|
||||
|
||||
const pendingItems = list.items.filter((it) => it.checked && !it.addedToPantry && it.productId);
|
||||
|
||||
for (const item of pendingItems) {
|
||||
if (!item.productId) continue;
|
||||
|
||||
// 1. Promote item to active pantry
|
||||
await this.pantryService.create(
|
||||
{
|
||||
productId: item.productId,
|
||||
storageLocation: StorageLocation.PANTRY, // Generic fallback location
|
||||
quantity: item.quantity,
|
||||
unit: item.unit as ServingUnit,
|
||||
purchasePrice: item.actualPrice || undefined,
|
||||
storeId: item.storeId || list.preferredStoreId || undefined,
|
||||
notes: item.notes,
|
||||
},
|
||||
householdId,
|
||||
userId
|
||||
);
|
||||
addedCount++;
|
||||
|
||||
// 2. Log final point-in-time pricing ledger entry if user input final price
|
||||
if (item.actualPrice !== undefined && item.actualPrice > 0) {
|
||||
const storeId = item.storeId || list.preferredStoreId;
|
||||
if (storeId) {
|
||||
await this.pricesService.recordPrice(
|
||||
{
|
||||
productId: item.productId,
|
||||
storeId,
|
||||
price: item.actualPrice,
|
||||
quantity: item.quantity,
|
||||
unit: item.unit as ServingUnit,
|
||||
currency: 'USD',
|
||||
},
|
||||
householdId,
|
||||
userId
|
||||
);
|
||||
pricesLogged++;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Set item flag avoiding future sync duplications
|
||||
await this.shoppingListsRepository.updateItem(id, householdId, item.id, {
|
||||
addedToPantry: true,
|
||||
});
|
||||
}
|
||||
|
||||
return { addedCount, pricesLogged };
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyzes price history to identify the cheapest store option for this basket.
|
||||
*/
|
||||
public async getStoreComparison(id: string, householdId: string) {
|
||||
const list = await this.getById(id, householdId);
|
||||
const validItems = list.items.filter((it) => it.productId);
|
||||
|
||||
// 1. Collate all recent pricing permutations for all products in this basket
|
||||
const storePricesMap = new Map<string, Map<string, number>>(); // storeId -> Map<productId, latestPrice>
|
||||
const storeNamesMap = new Map<string, string>();
|
||||
const allProductIds = validItems.map((it) => it.productId!);
|
||||
|
||||
for (const productId of allProductIds) {
|
||||
const options = await this.pricesService.compareStores(productId, householdId);
|
||||
for (const opt of options) {
|
||||
storeNamesMap.set(opt.storeId, opt.storeName);
|
||||
if (!storePricesMap.has(opt.storeId)) {
|
||||
storePricesMap.set(opt.storeId, new Map());
|
||||
}
|
||||
storePricesMap.get(opt.storeId)!.set(productId, opt.latestPrice);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Compile comparative totals per store option
|
||||
const singleStoreOptions: Array<{
|
||||
storeId: string;
|
||||
storeName: string;
|
||||
estimatedTotal: number;
|
||||
itemsCovered: number;
|
||||
itemsMissing: string[];
|
||||
}> = [];
|
||||
|
||||
for (const [storeId, priceMap] of storePricesMap.entries()) {
|
||||
let sum = 0;
|
||||
let count = 0;
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const item of validItems) {
|
||||
const p = priceMap.get(item.productId!);
|
||||
if (p !== undefined) {
|
||||
sum += p; // Simple unit scaling could be factored in, using simple latest price sum here
|
||||
count++;
|
||||
} else {
|
||||
missing.push(item.productId!);
|
||||
}
|
||||
}
|
||||
|
||||
singleStoreOptions.push({
|
||||
storeId,
|
||||
storeName: storeNamesMap.get(storeId) || 'Store',
|
||||
estimatedTotal: Math.round(sum * 100) / 100,
|
||||
itemsCovered: count,
|
||||
itemsMissing: missing,
|
||||
});
|
||||
}
|
||||
|
||||
// Sort to surface the cheapest/fullest single store options first
|
||||
singleStoreOptions.sort((a, b) => b.itemsCovered - a.itemsCovered || a.estimatedTotal - b.estimatedTotal);
|
||||
|
||||
return { singleStoreOptions };
|
||||
}
|
||||
}
|
||||
31
packages/api/src/schemas/price-record.schema.ts
Normal file
31
packages/api/src/schemas/price-record.schema.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import mongoose from 'mongoose';
|
||||
|
||||
const priceRecordSchema = new mongoose.Schema(
|
||||
{
|
||||
householdId: { type: String, required: true },
|
||||
productId: { type: String, required: true },
|
||||
productName: { type: String, required: true },
|
||||
storeId: { type: String, required: true },
|
||||
storeName: { type: String, required: true },
|
||||
price: { type: Number, required: true },
|
||||
currency: { type: String, required: true },
|
||||
quantity: { type: Number, required: true },
|
||||
unit: { type: String, required: true },
|
||||
pricePerUnit: { type: Number, required: true },
|
||||
date: { type: Date, required: true },
|
||||
receiptImageUrl: { type: String },
|
||||
notes: { type: String },
|
||||
createdBy: { type: String, required: true },
|
||||
},
|
||||
{ timestamps: { createdAt: true, updatedAt: false } }
|
||||
);
|
||||
|
||||
// Performance Indexes for Lookup Speed and Aggregations
|
||||
priceRecordSchema.index({ householdId: 1, productId: 1, storeId: 1, date: -1 });
|
||||
priceRecordSchema.index({ householdId: 1, productId: 1, date: -1 });
|
||||
priceRecordSchema.index({ householdId: 1, storeId: 1, date: -1 });
|
||||
|
||||
export const PriceRecordModel = mongoose.model('PriceRecord', priceRecordSchema);
|
||||
export type PriceRecordDocument = mongoose.InferSchemaType<typeof priceRecordSchema> & {
|
||||
_id: mongoose.Types.ObjectId;
|
||||
};
|
||||
54
packages/api/src/schemas/shopping-list.schema.ts
Normal file
54
packages/api/src/schemas/shopping-list.schema.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import mongoose from 'mongoose';
|
||||
|
||||
const shoppingItemSchema = new mongoose.Schema(
|
||||
{
|
||||
id: { type: String, required: true }, // Client or server generated tracking UUID
|
||||
productId: { type: String },
|
||||
customName: { type: String },
|
||||
quantity: { type: Number, required: true },
|
||||
unit: { type: String, required: true },
|
||||
checked: { type: Boolean, required: true, default: false },
|
||||
checkedAt: { type: Date },
|
||||
checkedBy: { type: String },
|
||||
estimatedPrice: { type: Number },
|
||||
actualPrice: { type: Number },
|
||||
storeId: { type: String },
|
||||
notes: { type: String },
|
||||
category: { type: String },
|
||||
addedToPantry: { type: Boolean, required: true, default: false },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const shoppingListSchema = new mongoose.Schema(
|
||||
{
|
||||
householdId: { type: String, required: true },
|
||||
name: { type: String, required: true },
|
||||
items: { type: [shoppingItemSchema], required: true, default: [] },
|
||||
status: { type: String, required: true }, // values from ShoppingListStatus
|
||||
createdFrom: {
|
||||
type: {
|
||||
type: { type: String, required: true }, // values from ShoppingListSourceType
|
||||
referenceId: { type: String },
|
||||
},
|
||||
required: false,
|
||||
_id: false,
|
||||
},
|
||||
mealPlanId: { type: String },
|
||||
totalEstimatedCost: { type: Number },
|
||||
preferredStoreId: { type: String },
|
||||
completedAt: { type: Date },
|
||||
createdBy: { type: String, required: true },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
shoppingListSchema.index({ householdId: 1, status: 1 });
|
||||
shoppingListSchema.index({ householdId: 1, createdAt: -1 });
|
||||
|
||||
export const ShoppingListModel = mongoose.model('ShoppingList', shoppingListSchema);
|
||||
export type ShoppingListDocument = mongoose.InferSchemaType<typeof shoppingListSchema> & {
|
||||
_id: mongoose.Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
|
@ -9,3 +9,4 @@ export * from './product.enums.js';
|
|||
export * from './recipe.enums.js';
|
||||
export * from './pantry.enums.js';
|
||||
export * from './meal-plan.enums.js';
|
||||
export * from './shopping-list.enums.js';
|
||||
|
|
|
|||
17
packages/shared/src/enums/shopping-list.enums.test.ts
Normal file
17
packages/shared/src/enums/shopping-list.enums.test.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import { ShoppingListStatus, ShoppingListSourceType } from './shopping-list.enums.js';
|
||||
|
||||
describe('ShoppingList Enums', () => {
|
||||
it('should have correct ShoppingListStatus values', () => {
|
||||
expect(ShoppingListStatus.ACTIVE).toBe('active');
|
||||
expect(ShoppingListStatus.SHOPPING).toBe('shopping');
|
||||
expect(ShoppingListStatus.COMPLETED).toBe('completed');
|
||||
expect(ShoppingListStatus.ARCHIVED).toBe('archived');
|
||||
});
|
||||
|
||||
it('should have correct ShoppingListSourceType values', () => {
|
||||
expect(ShoppingListSourceType.MEAL_PLAN).toBe('meal_plan');
|
||||
expect(ShoppingListSourceType.MANUAL).toBe('manual');
|
||||
expect(ShoppingListSourceType.PANTRY_RESTOCK).toBe('pantry_restock');
|
||||
});
|
||||
});
|
||||
18
packages/shared/src/enums/shopping-list.enums.ts
Normal file
18
packages/shared/src/enums/shopping-list.enums.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
/**
|
||||
* State progression for grocery shopping lists
|
||||
*/
|
||||
export enum ShoppingListStatus {
|
||||
ACTIVE = 'active',
|
||||
SHOPPING = 'shopping',
|
||||
COMPLETED = 'completed',
|
||||
ARCHIVED = 'archived',
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies the genesis of a generated shopping list
|
||||
*/
|
||||
export enum ShoppingListSourceType {
|
||||
MEAL_PLAN = 'meal_plan',
|
||||
MANUAL = 'manual',
|
||||
PANTRY_RESTOCK = 'pantry_restock',
|
||||
}
|
||||
|
|
@ -17,3 +17,5 @@ export * from './pantry.js';
|
|||
export * from './meal-plan.js';
|
||||
export * from './nutrition-target.js';
|
||||
export * from './freshness.js';
|
||||
export * from './price-record.js';
|
||||
export * from './shopping-list.js';
|
||||
|
|
|
|||
23
packages/shared/src/types/price-record.ts
Normal file
23
packages/shared/src/types/price-record.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import type { ServingUnit } from '../enums/product.enums.js';
|
||||
|
||||
/**
|
||||
* Historical transaction capturing store product pricing
|
||||
*/
|
||||
export interface PriceRecord {
|
||||
id: string;
|
||||
householdId: string;
|
||||
productId: string;
|
||||
productName: string; // Denormalized for quick display
|
||||
storeId: string;
|
||||
storeName: string; // Denormalized for quick display
|
||||
price: number;
|
||||
currency: string;
|
||||
quantity: number;
|
||||
unit: ServingUnit;
|
||||
pricePerUnit: number; // price / quantity (computed/normalized value)
|
||||
date: Date;
|
||||
receiptImageUrl?: string;
|
||||
notes?: string;
|
||||
createdBy: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
49
packages/shared/src/types/shopping-list.ts
Normal file
49
packages/shared/src/types/shopping-list.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import type { ServingUnit, ProductCategory } from '../enums/product.enums.js';
|
||||
import type { ShoppingListStatus, ShoppingListSourceType } from '../enums/shopping-list.enums.js';
|
||||
|
||||
/**
|
||||
* Captures a targeted purchasable item within a shopping checklist
|
||||
*/
|
||||
export interface ShoppingItem {
|
||||
id: string; // Random reference token for live sync transactions
|
||||
productId?: string; // Reference to general inventory product
|
||||
customName?: string; // Arbitrary string label for custom ad-hoc additions
|
||||
quantity: number;
|
||||
unit: ServingUnit;
|
||||
checked: boolean;
|
||||
checkedAt?: Date;
|
||||
checkedBy?: string;
|
||||
estimatedPrice?: number; // Guessed via historical lookup
|
||||
actualPrice?: number; // Final value input by active shopper
|
||||
storeId?: string; // Local target retail outlet
|
||||
notes?: string;
|
||||
category?: ProductCategory; // Logical aisle group
|
||||
addedToPantry: boolean; // Tracking bit for pantry inventory migrations
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes generating origins for auto-lists
|
||||
*/
|
||||
export interface ShoppingListSource {
|
||||
type: ShoppingListSourceType;
|
||||
referenceId?: string; // ID pointing to generating instance (e.g. MealPlan ID)
|
||||
}
|
||||
|
||||
/**
|
||||
* Structured grocery list managing household inventory provisioning
|
||||
*/
|
||||
export interface ShoppingList {
|
||||
id: string;
|
||||
householdId: string;
|
||||
name: string;
|
||||
items: ShoppingItem[];
|
||||
status: ShoppingListStatus;
|
||||
createdFrom?: ShoppingListSource;
|
||||
mealPlanId?: string; // Explicit quick reference pointer if derived from plan
|
||||
totalEstimatedCost?: number; // Summed pre-checkout estimates
|
||||
preferredStoreId?: string;
|
||||
completedAt?: Date;
|
||||
createdBy: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
|
@ -15,3 +15,5 @@ export * from './nutrition-target.schemas.js';
|
|||
export * from './recipe.schemas.js';
|
||||
export * from './pantry.schemas.js';
|
||||
export * from './freshness-rule.schemas.js';
|
||||
export * from './price-record.schemas.js';
|
||||
export * from './shopping-list.schemas.js';
|
||||
|
|
|
|||
56
packages/shared/src/validation/price-record.schemas.test.ts
Normal file
56
packages/shared/src/validation/price-record.schemas.test.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import { CreatePriceRecordSchema, BulkPriceRecordInputSchema } from './price-record.schemas.js';
|
||||
import { ServingUnit } from '../enums/product.enums.js';
|
||||
|
||||
describe('PriceRecord Schemas', () => {
|
||||
describe('CreatePriceRecordSchema', () => {
|
||||
it('should validate a valid payload', () => {
|
||||
const payload = {
|
||||
productId: 'prod-1',
|
||||
storeId: 'store-1',
|
||||
price: 4.99,
|
||||
currency: 'USD',
|
||||
quantity: 500,
|
||||
unit: ServingUnit.GRAMS,
|
||||
notes: 'On sale',
|
||||
};
|
||||
const result = CreatePriceRecordSchema.safeParse(payload);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject negative prices', () => {
|
||||
const payload = {
|
||||
productId: 'prod-1',
|
||||
storeId: 'store-1',
|
||||
price: -1.5,
|
||||
quantity: 500,
|
||||
unit: ServingUnit.GRAMS,
|
||||
};
|
||||
const result = CreatePriceRecordSchema.safeParse(payload);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BulkPriceRecordInputSchema', () => {
|
||||
it('should validate valid bulk inputs', () => {
|
||||
const payload = {
|
||||
storeId: 'store-2',
|
||||
items: [
|
||||
{ productId: 'p1', price: 2.5, quantity: 1, unit: ServingUnit.PIECES },
|
||||
{ productId: 'p2', price: 3.0, quantity: 100, unit: ServingUnit.MILLILITERS },
|
||||
],
|
||||
};
|
||||
const result = BulkPriceRecordInputSchema.safeParse(payload);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should require at least one item', () => {
|
||||
const payload = {
|
||||
storeId: 'store-2',
|
||||
items: [],
|
||||
};
|
||||
const result = BulkPriceRecordInputSchema.safeParse(payload);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
118
packages/shared/src/validation/price-record.schemas.ts
Normal file
118
packages/shared/src/validation/price-record.schemas.ts
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import { z } from 'zod/v4';
|
||||
import { ServingUnit } from '../enums/product.enums.js';
|
||||
|
||||
export const CreatePriceRecordSchema = z.object({
|
||||
productId: z.string().min(1),
|
||||
storeId: z.string().min(1),
|
||||
price: z.number().positive(),
|
||||
currency: z.string().min(1).max(10).default('USD'),
|
||||
quantity: z.number().positive(),
|
||||
unit: z.nativeEnum(ServingUnit),
|
||||
date: z.iso.datetime().optional(),
|
||||
notes: z.string().max(1000).trim().optional(),
|
||||
receiptImageUrl: z.string().url().optional(),
|
||||
});
|
||||
|
||||
export const BulkPriceRecordInputSchema = z.object({
|
||||
storeId: z.string().min(1),
|
||||
date: z.iso.datetime().optional(),
|
||||
items: z.array(
|
||||
z.object({
|
||||
productId: z.string().min(1),
|
||||
price: z.number().positive(),
|
||||
quantity: z.number().positive(),
|
||||
unit: z.nativeEnum(ServingUnit),
|
||||
notes: z.string().max(1000).trim().optional(),
|
||||
})
|
||||
).min(1),
|
||||
});
|
||||
|
||||
export const PriceHistoryQuerySchema = z.object({
|
||||
storeId: z.string().optional(),
|
||||
startDate: z.iso.datetime().optional(),
|
||||
endDate: z.iso.datetime().optional(),
|
||||
cursor: z.string().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20),
|
||||
});
|
||||
|
||||
export const PriceRecordResponseSchema = z.object({
|
||||
_id: z.string(),
|
||||
householdId: z.string(),
|
||||
productId: z.string(),
|
||||
productName: z.string(),
|
||||
storeId: z.string(),
|
||||
storeName: z.string(),
|
||||
price: z.number(),
|
||||
currency: z.string(),
|
||||
quantity: z.number(),
|
||||
unit: z.nativeEnum(ServingUnit),
|
||||
pricePerUnit: z.number(),
|
||||
date: z.string(),
|
||||
receiptImageUrl: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
createdBy: z.string(),
|
||||
createdAt: z.string(),
|
||||
});
|
||||
|
||||
export const StorePriceComparisonSchema = z.object({
|
||||
storeId: z.string(),
|
||||
storeName: z.string(),
|
||||
latestPrice: z.number(),
|
||||
latestPricePerUnit: z.number(),
|
||||
currency: z.string(),
|
||||
date: z.string(),
|
||||
});
|
||||
|
||||
export const PriceAnalyticsResponseSchema = z.object({
|
||||
averageBasketByStore: z.array(
|
||||
z.object({
|
||||
storeId: z.string(),
|
||||
storeName: z.string(),
|
||||
avgTotal: z.number(),
|
||||
tripCount: z.number(),
|
||||
})
|
||||
),
|
||||
priceAlerts: z.array(
|
||||
z.object({
|
||||
productId: z.string(),
|
||||
productName: z.string(),
|
||||
storeId: z.string(),
|
||||
storeName: z.string(),
|
||||
previousPrice: z.number(),
|
||||
currentPrice: z.number(),
|
||||
changePercent: z.number(),
|
||||
date: z.string(),
|
||||
})
|
||||
),
|
||||
spendingOverTime: z.array(
|
||||
z.object({
|
||||
period: z.string(),
|
||||
total: z.number(),
|
||||
})
|
||||
),
|
||||
spendingByCategory: z.array(
|
||||
z.object({
|
||||
category: z.string(),
|
||||
total: z.number(),
|
||||
avgPerItem: z.number(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export const PriceHistoryResponseSchema = z.object({
|
||||
data: z.array(PriceRecordResponseSchema),
|
||||
pagination: z.object({
|
||||
cursor: z.string().nullable(),
|
||||
hasMore: z.boolean(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const FoodStoreComparisonResponseSchema = z.object({
|
||||
data: z.array(StorePriceComparisonSchema),
|
||||
});
|
||||
|
||||
export const FoodSpendingAnalyticsResponseSchema = PriceAnalyticsResponseSchema;
|
||||
|
||||
export type CreatePriceRecordInput = z.infer<typeof CreatePriceRecordSchema>;
|
||||
export type BulkPriceRecordInput = z.infer<typeof BulkPriceRecordInputSchema>;
|
||||
export type PriceHistoryQueryInput = z.infer<typeof PriceHistoryQuerySchema>;
|
||||
66
packages/shared/src/validation/shopping-list.schemas.test.ts
Normal file
66
packages/shared/src/validation/shopping-list.schemas.test.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
CreateShoppingListSchema,
|
||||
AddShoppingItemSchema,
|
||||
UpdateShoppingItemSchema,
|
||||
} from './shopping-list.schemas.js';
|
||||
import { ServingUnit } from '../enums/product.enums.js';
|
||||
|
||||
describe('ShoppingList Schemas', () => {
|
||||
describe('CreateShoppingListSchema', () => {
|
||||
it('should accept lists with items', () => {
|
||||
const payload = {
|
||||
name: 'Weekly run',
|
||||
items: [
|
||||
{ productId: 'p1', quantity: 2, unit: ServingUnit.PIECES },
|
||||
{ customName: 'Apples', quantity: 10, unit: ServingUnit.PIECES },
|
||||
],
|
||||
};
|
||||
const result = CreateShoppingListSchema.safeParse(payload);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should default to empty items array', () => {
|
||||
const payload = { name: 'Mini list' };
|
||||
const result = CreateShoppingListSchema.safeParse(payload);
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.items).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('AddShoppingItemSchema', () => {
|
||||
it('should pass with a productId', () => {
|
||||
const payload = { productId: 'prod-123', quantity: 1, unit: ServingUnit.MILLILITERS };
|
||||
const result = AddShoppingItemSchema.safeParse(payload);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should pass with a customName', () => {
|
||||
const payload = { customName: 'Fresh fish', quantity: 1.5, unit: ServingUnit.GRAMS };
|
||||
const result = AddShoppingItemSchema.safeParse(payload);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should fail if both are omitted', () => {
|
||||
const payload = { quantity: 5, unit: ServingUnit.PIECES };
|
||||
const result = AddShoppingItemSchema.safeParse(payload);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UpdateShoppingItemSchema', () => {
|
||||
it('should accept partial updates', () => {
|
||||
const payload = { checked: true, actualPrice: 2.99 };
|
||||
const result = UpdateShoppingItemSchema.safeParse(payload);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject negative prices on checkoff', () => {
|
||||
const payload = { actualPrice: -0.5 };
|
||||
const result = UpdateShoppingItemSchema.safeParse(payload);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
122
packages/shared/src/validation/shopping-list.schemas.ts
Normal file
122
packages/shared/src/validation/shopping-list.schemas.ts
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import { z } from 'zod/v4';
|
||||
import { ServingUnit, ProductCategory } from '../enums/product.enums.js';
|
||||
import { ShoppingListStatus, ShoppingListSourceType } from '../enums/shopping-list.enums.js';
|
||||
|
||||
export const ShoppingItemSchema = z.object({
|
||||
id: z.string(),
|
||||
productId: z.string().optional(),
|
||||
customName: z.string().optional(),
|
||||
quantity: z.number().positive(),
|
||||
unit: z.nativeEnum(ServingUnit),
|
||||
checked: z.boolean().default(false),
|
||||
checkedAt: z.iso.datetime().optional(),
|
||||
checkedBy: z.string().optional(),
|
||||
estimatedPrice: z.number().optional(),
|
||||
actualPrice: z.number().optional(),
|
||||
storeId: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
category: z.nativeEnum(ProductCategory).optional(),
|
||||
addedToPantry: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export const CreateShoppingListSchema = z.object({
|
||||
name: z.string().min(1).max(100).trim(),
|
||||
preferredStoreId: z.string().optional(),
|
||||
items: z.array(
|
||||
z.object({
|
||||
productId: z.string().optional(),
|
||||
customName: z.string().optional(),
|
||||
quantity: z.number().positive(),
|
||||
unit: z.nativeEnum(ServingUnit),
|
||||
notes: z.string().optional(),
|
||||
category: z.nativeEnum(ProductCategory).optional(),
|
||||
})
|
||||
).optional().default([]),
|
||||
});
|
||||
|
||||
export const UpdateShoppingListSchema = z.object({
|
||||
name: z.string().min(1).max(100).trim().optional(),
|
||||
status: z.nativeEnum(ShoppingListStatus).optional(),
|
||||
preferredStoreId: z.string().optional(),
|
||||
items: z.array(ShoppingItemSchema).optional(),
|
||||
});
|
||||
|
||||
export const AddShoppingItemSchema = z.object({
|
||||
productId: z.string().optional(),
|
||||
customName: z.string().optional(),
|
||||
quantity: z.number().positive(),
|
||||
unit: z.nativeEnum(ServingUnit),
|
||||
notes: z.string().max(500).trim().optional(),
|
||||
category: z.nativeEnum(ProductCategory).optional(),
|
||||
}).refine(
|
||||
(data) => data.productId || data.customName,
|
||||
{ message: 'Must provide either a productId or customName' }
|
||||
);
|
||||
|
||||
export const UpdateShoppingItemSchema = z.object({
|
||||
quantity: z.number().positive().optional(),
|
||||
unit: z.nativeEnum(ServingUnit).optional(),
|
||||
checked: z.boolean().optional(),
|
||||
actualPrice: z.number().nonnegative().optional(),
|
||||
storeId: z.string().optional(),
|
||||
notes: z.string().max(500).trim().optional(),
|
||||
});
|
||||
|
||||
export const ShoppingListResponseSchema = z.object({
|
||||
_id: z.string(),
|
||||
householdId: z.string(),
|
||||
name: z.string(),
|
||||
status: z.nativeEnum(ShoppingListStatus),
|
||||
items: z.array(ShoppingItemSchema),
|
||||
createdFrom: z.object({
|
||||
type: z.nativeEnum(ShoppingListSourceType),
|
||||
referenceId: z.string().optional(),
|
||||
}).optional(),
|
||||
mealPlanId: z.string().optional(),
|
||||
totalEstimatedCost: z.number().optional(),
|
||||
preferredStoreId: z.string().optional(),
|
||||
completedAt: z.string().optional(),
|
||||
createdBy: z.string(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
});
|
||||
|
||||
export const ShoppingListListResponseSchema = z.object({
|
||||
data: z.array(ShoppingListResponseSchema),
|
||||
});
|
||||
|
||||
export const StoreComparisonResultSchema = z.object({
|
||||
singleStoreOptions: z.array(
|
||||
z.object({
|
||||
storeId: z.string(),
|
||||
storeName: z.string(),
|
||||
estimatedTotal: z.number(),
|
||||
itemsCovered: z.number(),
|
||||
itemsMissing: z.array(z.string()),
|
||||
})
|
||||
),
|
||||
splitStoreOption: z.object({
|
||||
stores: z.array(
|
||||
z.object({
|
||||
storeId: z.string(),
|
||||
storeName: z.string(),
|
||||
items: z.array(z.string()),
|
||||
subtotal: z.number(),
|
||||
})
|
||||
),
|
||||
estimatedTotal: z.number(),
|
||||
savingsVsBestSingleStore: z.number(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
export const BasketStoreComparisonResponseSchema = StoreComparisonResultSchema;
|
||||
|
||||
export const ShoppingListSyncToPantryResponseSchema = z.object({
|
||||
addedCount: z.number(),
|
||||
pricesLogged: z.number(),
|
||||
});
|
||||
|
||||
export type CreateShoppingListInput = z.infer<typeof CreateShoppingListSchema>;
|
||||
export type UpdateShoppingListInput = z.infer<typeof UpdateShoppingListSchema>;
|
||||
export type AddShoppingItemInput = z.infer<typeof AddShoppingItemSchema>;
|
||||
export type UpdateShoppingItemInput = z.infer<typeof UpdateShoppingItemSchema>;
|
||||
|
|
@ -19,6 +19,7 @@
|
|||
"next-auth": "^5.0.0-beta.30",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"recharts": "^3.8.1",
|
||||
"swr": "^2.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
463
packages/web/src/app/(dashboard)/shopping-lists/[id]/page.tsx
Normal file
463
packages/web/src/app/(dashboard)/shopping-lists/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,463 @@
|
|||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useApi } from '@/lib/useApi';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { SetPageHeader } from '@/components/layout/SetPageHeader';
|
||||
import { Card, Button, Icon, Pill } from '@/components/ui';
|
||||
import {
|
||||
getShoppingList,
|
||||
addShoppingItem,
|
||||
updateShoppingItem,
|
||||
removeShoppingItem,
|
||||
syncToPantry,
|
||||
getBasketStoreComparison,
|
||||
updateShoppingList,
|
||||
} from '@/services/shopping-lists';
|
||||
import { listProducts } from '@/services/products';
|
||||
import { useShoppingListSync } from '@/lib/useShoppingListSync';
|
||||
|
||||
export default function ShoppingListDetailsPage() {
|
||||
const { householdId, isLoading: isAuthLoading } = useApi();
|
||||
const { id: listId } = useParams() as { id: string };
|
||||
const router = useRouter();
|
||||
|
||||
// List state
|
||||
const [list, setList] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
// Side panel States
|
||||
const [storeOptions, setStoreOptions] = useState<any[]>([]);
|
||||
const [isStoreLoading, setIsStoreLoading] = useState(false);
|
||||
|
||||
// Form states for Add Item
|
||||
const [products, setProducts] = useState<any[]>([]);
|
||||
const [selectedProductId, setSelectedProductId] = useState('');
|
||||
const [customItemName, setCustomItemName] = useState('');
|
||||
const [qty, setQty] = useState(1);
|
||||
const [unit, setUnit] = useState('g');
|
||||
const [notes, setNotes] = useState('');
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
|
||||
// Load core list context
|
||||
const fetchList = useCallback(async () => {
|
||||
if (!householdId || !listId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await getShoppingList(householdId, listId);
|
||||
setList(data);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Shopping list not found');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [householdId, listId]);
|
||||
|
||||
// Run price comparisons
|
||||
const fetchComparisons = useCallback(async () => {
|
||||
if (!householdId || !listId) return;
|
||||
setIsStoreLoading(true);
|
||||
try {
|
||||
const comparison = await getBasketStoreComparison(householdId, listId);
|
||||
setStoreOptions(comparison.singleStoreOptions || []);
|
||||
} catch (err) {
|
||||
console.error('Comparison load fail', err);
|
||||
} finally {
|
||||
setIsStoreLoading(false);
|
||||
}
|
||||
}, [householdId, listId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchList();
|
||||
}, [fetchList]);
|
||||
|
||||
// Pre-load household products for predictive inputs
|
||||
useEffect(() => {
|
||||
if (!householdId) return;
|
||||
listProducts(householdId).then(res => setProducts(res.data)).catch(console.error);
|
||||
}, [householdId]);
|
||||
|
||||
// Handle WS Remote Event Broadcasts
|
||||
const handleRemoteSync = useCallback((msg: any) => {
|
||||
console.log('🔔 Remote state delta payload:', msg);
|
||||
if (msg.type === 'ITEM_UPDATED') {
|
||||
setList((prev: any) => {
|
||||
if (!prev) return prev;
|
||||
return {
|
||||
...prev,
|
||||
items: prev.items.map((it: any) =>
|
||||
it.id === msg.itemId ? { ...it, ...msg.updates } : it
|
||||
),
|
||||
};
|
||||
});
|
||||
} else if (msg.type === 'ITEM_ADDED') {
|
||||
setList((prev: any) => {
|
||||
if (!prev) return prev;
|
||||
return { ...prev, items: [...prev.items, msg.item] };
|
||||
});
|
||||
} else if (msg.type === 'ITEM_REMOVED') {
|
||||
setList((prev: any) => {
|
||||
if (!prev) return prev;
|
||||
return { ...prev, items: prev.items.filter((it: any) => it.id !== msg.itemId) };
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Inject Real-Time Hooks
|
||||
const { isConnected, toggleItemCheck } = useShoppingListSync(
|
||||
householdId || '',
|
||||
listId,
|
||||
handleRemoteSync
|
||||
);
|
||||
|
||||
// 1. Perform Live Interactivity (Toggle Checks)
|
||||
const handleToggleCheck = async (itemId: string, currentChecked: boolean) => {
|
||||
const nextChecked = !currentChecked;
|
||||
|
||||
// Optimistic Client Update for ultimate snappy responsiveness
|
||||
setList((prev: any) => ({
|
||||
...prev,
|
||||
items: prev.items.map((it: any) => it.id === itemId ? { ...it, checked: nextChecked } : it)
|
||||
}));
|
||||
|
||||
// Emit to WS Channel (broadcasts immediately to all other clients)
|
||||
toggleItemCheck(itemId, nextChecked);
|
||||
|
||||
// Persist standard Rest fallback ensuring safety
|
||||
if (householdId) {
|
||||
try {
|
||||
await updateShoppingItem(householdId, listId, itemId, { checked: nextChecked });
|
||||
} catch (err) {
|
||||
console.error('Persistent toggle sync fail', err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Handle Item Mutations
|
||||
const handleAddItem = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!householdId) return;
|
||||
setIsAdding(true);
|
||||
try {
|
||||
const updated = await addShoppingItem(householdId, listId, {
|
||||
productId: selectedProductId || undefined,
|
||||
customName: !selectedProductId ? customItemName.trim() : undefined,
|
||||
quantity: qty,
|
||||
unit: unit as any,
|
||||
notes: notes.trim() || undefined,
|
||||
});
|
||||
|
||||
setList(updated);
|
||||
// Clear inputs
|
||||
setSelectedProductId('');
|
||||
setCustomItemName('');
|
||||
setQty(1);
|
||||
setNotes('');
|
||||
} catch (err: any) {
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setIsAdding(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteItem = async (itemId: string) => {
|
||||
if (!householdId) return;
|
||||
try {
|
||||
const updated = await removeShoppingItem(householdId, listId, itemId);
|
||||
setList(updated);
|
||||
} catch (err: any) {
|
||||
console.error(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
// 3. Execute Final Checkout / Pantry Sync
|
||||
const handleSyncToPantry = async () => {
|
||||
if (!householdId) return;
|
||||
const readyItems = list.items.filter((i: any) => i.checked && !i.addedToPantry);
|
||||
if (readyItems.length === 0) return;
|
||||
|
||||
if (!confirm(`Import ${readyItems.length} checked ingredients directly into active Pantry stock?`)) return;
|
||||
|
||||
try {
|
||||
const res = await syncToPantry(householdId, listId);
|
||||
alert(`Success! Provisioned ${res.addedCount} items into Pantry stock.`);
|
||||
|
||||
// Mark list as completed automatically if all are done
|
||||
const allChecked = list.items.every((i: any) => i.checked || i.addedToPantry);
|
||||
if (allChecked) {
|
||||
await updateShoppingList(householdId, listId, { status: 'completed' as any });
|
||||
}
|
||||
|
||||
fetchList();
|
||||
} catch (err: any) {
|
||||
alert('Migration sync error: ' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
// Collate items categorized for satisfying view
|
||||
const categorizedItems = useMemo(() => {
|
||||
if (!list) return {};
|
||||
const groups: Record<string, any[]> = {};
|
||||
list.items.forEach((it: any) => {
|
||||
const cat = it.category || 'Other / Misc';
|
||||
if (!groups[cat]) groups[cat] = [];
|
||||
groups[cat].push(it);
|
||||
});
|
||||
return groups;
|
||||
}, [list]);
|
||||
|
||||
if (isAuthLoading || loading) return <div style={{ padding: 40 }}>Hydrating session checklist...</div>;
|
||||
if (error || !list) return <div style={{ padding: 40, color: 'var(--danger)' }}>Error: {error}</div>;
|
||||
|
||||
const itemsPendingSync = list.items.filter((i: any) => i.checked && !i.addedToPantry).length;
|
||||
const checkedCount = list.items.filter((i: any) => i.checked).length;
|
||||
const totalCount = list.items.length;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SetPageHeader
|
||||
title={list.name}
|
||||
subtitle="Perform live checkout check-offs synchronously across multiple household devices."
|
||||
/>
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 13, padding: '0 32px', marginTop: -12, marginBottom: 12, maxWidth: 1400, margin: '-12px auto 12px' }}>
|
||||
<Pill tone={list.status === 'completed' ? 'ok' : 'info'}>{list.status}</Pill>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-muted)' }}>
|
||||
<div style={{
|
||||
width: 8, height: 8, borderRadius: '50%',
|
||||
background: isConnected ? 'var(--success, #10b981)' : 'var(--danger, #ef4444)',
|
||||
boxShadow: isConnected ? '0 0 8px var(--success)' : 'none',
|
||||
}} />
|
||||
{isConnected ? 'Live Sync Channel Operational' : 'Connecting Sync...'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '28px 32px 64px', maxWidth: 1400, margin: '0 auto' }}>
|
||||
|
||||
{/* Top Action Strip */}
|
||||
<div style={{ display: 'flex', gap: 12, marginBottom: 24, justifyContent: 'space-between', flexWrap: 'wrap' }}>
|
||||
<Button variant="ghost" onClick={() => router.push('/shopping-lists')}>
|
||||
<Icon name="chevronLeft" style={{ marginRight: 6, width: 16 }} /> Back to Hub
|
||||
</Button>
|
||||
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<Button variant="ghost" onClick={fetchComparisons}>
|
||||
<Icon name="trend" style={{ marginRight: 6, width: 16 }} /> Check Lowest Store Options
|
||||
</Button>
|
||||
{itemsPendingSync > 0 && (
|
||||
<Button onClick={handleSyncToPantry} style={{ background: 'var(--success)', borderColor: 'var(--success)', color: '#fff' }}>
|
||||
<Icon name="box" style={{ marginRight: 6, width: 16 }} /> Sync {itemsPendingSync} items to Pantry
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Workspace Split Grid */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 32, alignItems: 'start' }}>
|
||||
|
||||
{/* Left: Categorized Checklist Grid */}
|
||||
<div>
|
||||
{totalCount === 0 ? (
|
||||
<Card style={{ padding: 40, textAlign: 'center', background: 'var(--bg-elev)', border: '1px dashed var(--border)' }}>
|
||||
<Icon name="list" style={{ width: 40, color: 'var(--ink-muted)', marginBottom: 16 }} />
|
||||
<h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>Checklist is Empty</h4>
|
||||
<p style={{ fontSize: 13, color: 'var(--ink-muted)' }}>Add missing ingredients using the pane on the right.</p>
|
||||
</Card>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
|
||||
{Object.entries(categorizedItems).map(([cat, items]: [string, any]) => (
|
||||
<div key={cat}>
|
||||
<h4 style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12, borderBottom: '1px solid var(--border)', paddingBottom: 6 }}>
|
||||
{cat}
|
||||
</h4>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{items.map((it: any) => (
|
||||
<div
|
||||
key={it.id}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 14,
|
||||
padding: '12px 16px', background: 'var(--bg-elev)',
|
||||
border: '1px solid var(--border)', borderRadius: 'var(--r-md)',
|
||||
transition: 'all 0.15s',
|
||||
opacity: it.checked ? 0.65 : 1,
|
||||
textDecoration: it.checked ? 'line-through' : 'none',
|
||||
}}
|
||||
>
|
||||
{/* Checkbox circle */}
|
||||
<button
|
||||
onClick={() => handleToggleCheck(it.id, it.checked)}
|
||||
style={{
|
||||
width: 22, height: 22, borderRadius: '50%',
|
||||
border: `2px solid ${it.checked ? 'var(--success, #10b981)' : 'var(--border-hover)'}`,
|
||||
background: it.checked ? 'var(--success, #10b981)' : 'transparent',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
cursor: 'pointer', flexShrink: 0, padding: 0,
|
||||
}}
|
||||
>
|
||||
{it.checked && <Icon name="check" style={{ width: 12, color: '#fff' }} />}
|
||||
</button>
|
||||
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 14, color: it.checked ? 'var(--ink-muted)' : 'var(--ink)' }}>
|
||||
{it.productId ? products.find(p => p._id === it.productId)?.name || 'Ingredient Loading...' : it.customName}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--ink-muted)', display: 'flex', gap: 10, marginTop: 2 }}>
|
||||
<span>Qty: {it.quantity} {it.unit}</span>
|
||||
{it.notes && <span>• Note: {it.notes}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Estimated Price Tag */}
|
||||
{it.estimatedPrice && !it.checked && (
|
||||
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-muted)', background: 'var(--bg)', padding: '4px 8px', borderRadius: 'var(--r-sm)' }}>
|
||||
~${it.estimatedPrice.toFixed(2)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Migrated Badge */}
|
||||
{it.addedToPantry && (
|
||||
<Pill tone="ok">
|
||||
<Icon name="box" style={{ width: 10, marginRight: 4 }} /> Pantry
|
||||
</Pill>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => handleDeleteItem(it.id)}
|
||||
style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 6, color: 'var(--ink-muted)', opacity: 0.5 }}
|
||||
>
|
||||
<Icon name="trash" style={{ width: 14 }} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right Side Panel: Context Inputs */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
|
||||
|
||||
{/* Pane A: Add New Item */}
|
||||
<Card style={{ padding: 20 }}>
|
||||
<h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Icon name="plus" style={{ width: 16 }} /> Add Grocery Item
|
||||
</h4>
|
||||
<form onSubmit={handleAddItem} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
|
||||
<div>
|
||||
<label style={labelStyle}>Link Product Catalog</label>
|
||||
<select
|
||||
value={selectedProductId}
|
||||
onChange={(e) => {
|
||||
setSelectedProductId(e.target.value);
|
||||
if (e.target.value) setCustomItemName('');
|
||||
}}
|
||||
style={selectStyle}
|
||||
>
|
||||
<option value="">-- Create Manual Custom Input --</option>
|
||||
{products.map(p => <option key={p._id} value={p._id}>{p.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{!selectedProductId && (
|
||||
<div>
|
||||
<label style={labelStyle}>Custom Custom Name</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="e.g., Generic Flour"
|
||||
value={customItemName}
|
||||
onChange={e => setCustomItemName(e.target.value)}
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<div>
|
||||
<label style={labelStyle}>Quantity</label>
|
||||
<input
|
||||
type="number"
|
||||
required
|
||||
min="0.01"
|
||||
step="any"
|
||||
value={qty}
|
||||
onChange={e => setQty(parseFloat(e.target.value) || 0)}
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label style={labelStyle}>Unit</label>
|
||||
<select value={unit} onChange={e => setUnit(e.target.value)} style={selectStyle}>
|
||||
<option value="g">Grams</option>
|
||||
<option value="ml">Milliliters</option>
|
||||
<option value="piece">Pieces</option>
|
||||
<option value="slice">Slices</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label style={labelStyle}>Notes</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Brand preference, etc."
|
||||
value={notes}
|
||||
onChange={e => setNotes(e.target.value)}
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={isAdding} style={{ width: '100%' }}>
|
||||
{isAdding ? 'Appending...' : 'Add to List'}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
{/* Pane B: Real-Time Store Optimizer */}
|
||||
{storeOptions.length > 0 && (
|
||||
<Card style={{ padding: 20 }}>
|
||||
<h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Icon name="trend" style={{ width: 16, color: 'var(--brand)' }} /> Lowest Store Basket Rank
|
||||
</h4>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{storeOptions.map((opt, idx) => (
|
||||
<div key={opt.storeId} style={{ padding: 12, background: 'var(--bg)', border: idx === 0 ? '1px solid var(--success)' : '1px solid var(--border)', borderRadius: 'var(--r-md)' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 13 }}>{opt.storeName}</span>
|
||||
<span style={{ fontSize: 14, fontWeight: 700, color: idx === 0 ? 'var(--success)' : 'var(--ink)' }}>${opt.estimatedTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-muted)', marginTop: 4 }}>
|
||||
<span>Covered: {opt.itemsCovered}/{totalCount} products</span>
|
||||
{idx === 0 && <span style={{ color: 'var(--success)', fontWeight: 600 }}>Cheapest Single Trip</span>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const labelStyle: React.CSSProperties = {
|
||||
display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--ink-muted)',
|
||||
textTransform: 'uppercase', letterSpacing: '0.03em', marginBottom: 6,
|
||||
};
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
width: '100%', padding: '8px 12px', borderRadius: 'var(--r-md)',
|
||||
background: 'var(--bg)', border: '1px solid var(--border)', color: 'var(--ink)',
|
||||
fontSize: 13, outline: 'none',
|
||||
};
|
||||
|
||||
const selectStyle: React.CSSProperties = {
|
||||
width: '100%', padding: '8px 12px', borderRadius: 'var(--r-md)',
|
||||
background: 'var(--bg)', border: '1px solid var(--border)', color: 'var(--ink)',
|
||||
fontSize: 13, outline: 'none', height: 36,
|
||||
};
|
||||
369
packages/web/src/app/(dashboard)/shopping-lists/page.tsx
Normal file
369
packages/web/src/app/(dashboard)/shopping-lists/page.tsx
Normal file
|
|
@ -0,0 +1,369 @@
|
|||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useApi } from '@/lib/useApi';
|
||||
import { SetPageHeader } from '@/components/layout/SetPageHeader';
|
||||
import { Card, Button, Icon, Pill } from '@/components/ui';
|
||||
import { getShoppingLists, createShoppingList } from '@/services/shopping-lists';
|
||||
import { listMealPlans } from '@/services/meal-plans';
|
||||
import { generateFromMealPlan } from '@/services/shopping-lists';
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function ShoppingListsPage() {
|
||||
const { householdId, isLoading } = useApi();
|
||||
const [lists, setLists] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
// Modal States
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
const [isGapModalOpen, setIsGapModalOpen] = useState(false);
|
||||
|
||||
// Form States
|
||||
const [newListName, setNewListName] = useState('');
|
||||
const [recentMealPlans, setRecentMealPlans] = useState<any[]>([]);
|
||||
const [mealPlanLoading, setMealPlanLoading] = useState(false);
|
||||
|
||||
const fetchLists = useCallback(async () => {
|
||||
if (!householdId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await getShoppingLists(householdId);
|
||||
// Sort by active status first, then newest first
|
||||
data.sort((a, b) => {
|
||||
if (a.status === 'active' && b.status !== 'active') return -1;
|
||||
if (a.status !== 'active' && b.status === 'active') return 1;
|
||||
return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
});
|
||||
setLists(data);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to load shopping lists');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [householdId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchLists();
|
||||
}, [fetchLists]);
|
||||
|
||||
const handleCreateList = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newListName.trim() || !householdId) return;
|
||||
try {
|
||||
const res = await createShoppingList(householdId, {
|
||||
name: newListName.trim(),
|
||||
items: [],
|
||||
});
|
||||
setNewListName('');
|
||||
setIsCreateModalOpen(false);
|
||||
// Redirect or update list
|
||||
setLists((prev) => [res, ...prev]);
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to create list');
|
||||
}
|
||||
};
|
||||
|
||||
const openGapModal = async () => {
|
||||
setIsGapModalOpen(true);
|
||||
if (!householdId) return;
|
||||
setMealPlanLoading(true);
|
||||
try {
|
||||
const plans = await listMealPlans(householdId);
|
||||
setRecentMealPlans(plans.data || []);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setMealPlanLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGenerateFromPlan = async (mealPlanId: string) => {
|
||||
if (!householdId) return;
|
||||
try {
|
||||
const res = await generateFromMealPlan(householdId, mealPlanId);
|
||||
setIsGapModalOpen(false);
|
||||
setLists((prev) => [res, ...prev]);
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to generate groceries from meal plan');
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) return <SetPageHeader title="Groceries" subtitle="Analyze needs and track baskets" />;
|
||||
if (!householdId) return <div style={{ padding: 32 }}>Please join a household.</div>;
|
||||
|
||||
const activeLists = lists.filter(l => l.status === 'active' || l.status === 'shopping');
|
||||
const completedLists = lists.filter(l => l.status === 'completed' || l.status === 'archived');
|
||||
|
||||
// Derive stats
|
||||
const totalActiveCost = activeLists.reduce((sum, l) => sum + (l.totalEstimatedCost || 0), 0);
|
||||
const totalPendingItems = activeLists.reduce((sum, l) => sum + l.items.filter((i: any) => !i.checked).length, 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SetPageHeader title="Grocery & Shopping" subtitle="Streamline your checklist, check gaps, and compare costs." />
|
||||
|
||||
<div style={{ padding: '28px 32px 64px', maxWidth: 1300, margin: '0 auto' }}>
|
||||
{/* 1. Beautiful Stats Band */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 20, marginBottom: 32 }}>
|
||||
<MetricCard
|
||||
icon="store"
|
||||
title="Active Lists"
|
||||
value={String(activeLists.length)}
|
||||
subtitle="Ready to shop"
|
||||
color="var(--brand)"
|
||||
/>
|
||||
<MetricCard
|
||||
icon="list"
|
||||
title="Pending Items"
|
||||
value={String(totalPendingItems)}
|
||||
subtitle="Across all active trips"
|
||||
color="var(--warning, #f59e0b)"
|
||||
/>
|
||||
<MetricCard
|
||||
icon="tag"
|
||||
title="Est. Total Value"
|
||||
value={`$${totalActiveCost.toFixed(2)}`}
|
||||
subtitle="Estimated current cart"
|
||||
color="var(--success, #10b981)"
|
||||
/>
|
||||
<MetricCard
|
||||
icon="trend"
|
||||
title="Spending Trend"
|
||||
value="Analyics"
|
||||
subtitle="Visualize price fluctuations"
|
||||
color="var(--ink-muted)"
|
||||
link="/shopping-lists/prices"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 2. Action Row */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, flexWrap: 'wrap', gap: 16 }}>
|
||||
<h3 style={{ fontSize: 18, fontWeight: 600, color: 'var(--ink)' }}>Checklists & Baskets</h3>
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<Button variant="ghost" onClick={openGapModal}>
|
||||
<Icon name="zap" style={{ marginRight: 6, width: 16 }} />
|
||||
Generate from Meal Plan
|
||||
</Button>
|
||||
<Button onClick={() => setIsCreateModalOpen(true)}>
|
||||
<Icon name="plus" style={{ marginRight: 6, width: 16 }} />
|
||||
New Shopping List
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <div style={{ color: 'var(--danger)', padding: 16, background: 'var(--danger-soft)', borderRadius: 'var(--r-md)', marginBottom: 24 }}>{error}</div>}
|
||||
|
||||
{/* 3. Lists Grid */}
|
||||
{loading ? (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 20 }}>
|
||||
{[1, 2, 3].map(i => <div key={i} style={{ height: 180, borderRadius: 'var(--r-lg)', border: '1px solid var(--border)', background: 'var(--bg-elev)', opacity: 0.4 }} />)}
|
||||
</div>
|
||||
) : activeLists.length === 0 && completedLists.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '80px 24px', background: 'var(--bg-elev)', border: '1px dashed var(--border)', borderRadius: 'var(--r-lg)' }}>
|
||||
<Icon name="store" style={{ width: 48, height: 48, color: 'var(--ink-muted)', marginBottom: 16 }} />
|
||||
<h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 8 }}>No Shopping Lists Found</h4>
|
||||
<p style={{ color: 'var(--ink-muted)', fontSize: 14, marginBottom: 24, maxWidth: 400, margin: '0 auto 24px' }}>
|
||||
Create an empty manual checklist, or dynamically auto-generate missing ingredients directly from your meal plan!
|
||||
</p>
|
||||
<Button onClick={() => setIsCreateModalOpen(true)}>Create First List</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Active Section */}
|
||||
{activeLists.length > 0 && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 20, marginBottom: 40 }}>
|
||||
{activeLists.map((list) => (
|
||||
<ShoppingListCard key={list._id} list={list} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Past Section */}
|
||||
{completedLists.length > 0 && (
|
||||
<>
|
||||
<h4 style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 16 }}>Completed Runs</h4>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 20 }}>
|
||||
{completedLists.map((list) => (
|
||||
<ShoppingListCard key={list._id} list={list} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Creation Modal Dialog Overlay */}
|
||||
{isCreateModalOpen && (
|
||||
<div style={overlayStyle} onClick={() => setIsCreateModalOpen(false)}>
|
||||
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
||||
<h3 style={{ fontSize: 18, fontWeight: 600, marginBottom: 16 }}>Create Shopping List</h3>
|
||||
<form onSubmit={handleCreateList}>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--ink-muted)', marginBottom: 6 }}>Checklist Name</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="e.g., Weekly Costco Run"
|
||||
value={newListName}
|
||||
onChange={(e) => setNewListName(e.target.value)}
|
||||
style={inputStyle}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
|
||||
<Button type="button" variant="ghost" onClick={() => setIsCreateModalOpen(false)}>Cancel</Button>
|
||||
<Button type="submit">Create</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Meal Plan Gap Generator Modal */}
|
||||
{isGapModalOpen && (
|
||||
<div style={overlayStyle} onClick={() => setIsGapModalOpen(false)}>
|
||||
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
||||
<h3 style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>Scan Meal Plan Gaps</h3>
|
||||
<p style={{ fontSize: 13, color: 'var(--ink-muted)', marginBottom: 20 }}>
|
||||
Select a scheduled weekly plan. We will cross-reference your recipe ingredient requirements vs active pantry inventory to auto-generate your grocery shortages!
|
||||
</p>
|
||||
|
||||
{mealPlanLoading ? (
|
||||
<div style={{ textAlign: 'center', padding: 20 }}>Loading schedules...</div>
|
||||
) : recentMealPlans.length === 0 ? (
|
||||
<div style={{ padding: 16, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 8, textAlign: 'center', fontSize: 14, color: 'var(--ink-muted)' }}>
|
||||
No meal plans configured. Build a plan first!
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 300, overflowY: 'auto', marginBottom: 20 }}>
|
||||
{recentMealPlans.slice(0, 5).map((plan) => {
|
||||
const dateStr = new Date(plan.weekStartDate).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
|
||||
return (
|
||||
<button
|
||||
key={plan._id}
|
||||
onClick={() => handleGenerateFromPlan(plan._id)}
|
||||
style={planRowStyle}
|
||||
>
|
||||
<div style={{ textAlign: 'left' }}>
|
||||
<div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 14 }}>Week of {dateStr}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>Status: <span style={{ textTransform: 'capitalize' }}>{plan.status}</span></div>
|
||||
</div>
|
||||
<Icon name="chevronRight" style={{ width: 16, color: 'var(--ink-muted)' }} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<Button variant="ghost" onClick={() => setIsGapModalOpen(false)}>Close</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ icon, title, value, subtitle, color, link }: any) {
|
||||
const content = (
|
||||
<Card style={{ padding: 20, height: '100%', display: 'flex', alignItems: 'center', gap: 16, position: 'relative', overflow: 'hidden', cursor: link ? 'pointer' : 'default' }}>
|
||||
<div style={{ width: 48, height: 48, borderRadius: '50%', background: `${color}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<Icon name={icon} style={{ width: 22, height: 22, color }} />
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '0.02em' }}>{title}</div>
|
||||
<div style={{ fontSize: 24, fontWeight: 700, color: 'var(--ink)', margin: '2px 0' }}>{value}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--ink-muted)', display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
{subtitle}
|
||||
{link && <Icon name="chevronRight" style={{ width: 12 }} />}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
return link ? <Link href={link} style={{ textDecoration: 'none' }}>{content}</Link> : content;
|
||||
}
|
||||
|
||||
function ShoppingListCard({ list }: { list: any }) {
|
||||
const total = list.items.length;
|
||||
const checked = list.items.filter((i: any) => i.checked).length;
|
||||
const progress = total > 0 ? Math.round((checked / total) * 100) : 0;
|
||||
const date = new Date(list.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
||||
|
||||
const isActive = list.status === 'active' || list.status === 'shopping';
|
||||
|
||||
return (
|
||||
<Link href={`/shopping-lists/${list._id}`} style={{ textDecoration: 'none' }}>
|
||||
<Card style={{
|
||||
padding: 20,
|
||||
transition: 'all 0.2s ease',
|
||||
border: isActive ? '1px solid var(--border-hover, #444)' : '1px solid var(--border)',
|
||||
position: 'relative',
|
||||
background: isActive ? 'rgba(255,255,255,0.02)' : 'var(--bg-elev)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 12,
|
||||
cursor: 'pointer',
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
|
||||
<div>
|
||||
<h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', margin: 0, lineHeight: 1.3 }}>{list.name}</h4>
|
||||
<span style={{ fontSize: 11, color: 'var(--ink-muted)', display: 'inline-block', marginTop: 4 }}>Created {date}</span>
|
||||
</div>
|
||||
<Pill tone={list.status === 'active' ? 'info' : list.status === 'shopping' ? 'warn' : 'ghost'}>
|
||||
{list.status === 'shopping' ? 'Live' : list.status}
|
||||
</Pill>
|
||||
</div>
|
||||
|
||||
<div style={{ fontSize: 13, color: 'var(--ink-muted)', display: 'flex', gap: 16, alignItems: 'center' }}>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<Icon name="list" style={{ width: 14 }} /> {checked}/{total} items
|
||||
</span>
|
||||
{list.totalEstimatedCost && (
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 4, fontWeight: 600, color: 'var(--ink)' }}>
|
||||
${list.totalEstimatedCost.toFixed(2)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Custom Progress Bar */}
|
||||
<div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-muted)', marginBottom: 4 }}>
|
||||
<span>Progress</span>
|
||||
<span>{progress}%</span>
|
||||
</div>
|
||||
<div style={{ height: 6, background: 'var(--border)', borderRadius: 3, overflow: 'hidden' }}>
|
||||
<div style={{ height: '100%', width: `${progress}%`, background: progress === 100 ? 'var(--success, #10b981)' : 'var(--brand)', borderRadius: 3, transition: 'width 0.4s cubic-bezier(0.4, 0, 0.2, 1)' }} />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
const overlayStyle: React.CSSProperties = {
|
||||
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
|
||||
background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(6px)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999,
|
||||
padding: 16,
|
||||
};
|
||||
|
||||
const modalStyle: React.CSSProperties = {
|
||||
background: 'var(--bg-elev)', border: '1px solid var(--border)',
|
||||
borderRadius: 'var(--r-lg)', padding: 24, width: '100%', maxWidth: 460,
|
||||
boxShadow: '0 20px 40px rgba(0,0,0,0.3)',
|
||||
};
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
width: '100%', padding: '10px 14px', borderRadius: 'var(--r-md)',
|
||||
background: 'var(--bg)', border: '1px solid var(--border)', color: 'var(--ink)',
|
||||
fontSize: 14, outline: 'none',
|
||||
};
|
||||
|
||||
const planRowStyle: React.CSSProperties = {
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center',
|
||||
padding: '12px 16px', background: 'var(--bg)', border: '1px solid var(--border)',
|
||||
borderRadius: 'var(--r-md)', width: '100%', cursor: 'pointer', transition: 'all 0.15s',
|
||||
};
|
||||
197
packages/web/src/app/(dashboard)/shopping-lists/prices/page.tsx
Normal file
197
packages/web/src/app/(dashboard)/shopping-lists/prices/page.tsx
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useApi } from '@/lib/useApi';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { SetPageHeader } from '@/components/layout/SetPageHeader';
|
||||
import { Card, Button, Icon, Pill } from '@/components/ui';
|
||||
import { getPriceAnalytics } from '@/services/prices';
|
||||
import {
|
||||
ResponsiveContainer,
|
||||
LineChart,
|
||||
Line,
|
||||
BarChart,
|
||||
Bar,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
Cell,
|
||||
} from 'recharts';
|
||||
|
||||
export default function PricesAnalyticsPage() {
|
||||
const { householdId, isLoading } = useApi();
|
||||
const router = useRouter();
|
||||
const [data, setData] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const loadAnalytics = useCallback(async () => {
|
||||
if (!householdId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await getPriceAnalytics(householdId);
|
||||
setData(result);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to load analytics');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [householdId]);
|
||||
|
||||
useEffect(() => {
|
||||
loadAnalytics();
|
||||
}, [loadAnalytics]);
|
||||
|
||||
if (isLoading || loading) return <div style={{ padding: 40 }}>Synthesizing financial graphs...</div>;
|
||||
if (error || !data) return <div style={{ padding: 40, color: 'var(--danger)' }}>Error: {error}</div>;
|
||||
|
||||
const COLORS = ['var(--brand)', 'var(--success)', 'var(--warning)', '#a855f7', '#ec4899', '#3b82f6'];
|
||||
|
||||
return (
|
||||
<>
|
||||
<SetPageHeader
|
||||
title="Inflation & Spend Metrics"
|
||||
subtitle="Interactive real-time visualization of your historical grocery ledger ledger"
|
||||
/>
|
||||
|
||||
<div style={{ padding: '28px 32px 64px', maxWidth: 1400, margin: '0 auto' }}>
|
||||
|
||||
<div style={{ marginBottom: 24 }}>
|
||||
<Button variant="ghost" onClick={() => router.push('/shopping-lists')}>
|
||||
<Icon name="chevronLeft" style={{ marginRight: 6, width: 16 }} /> Back to Checklists
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 1. Immediate Red Alert Banner: Inflation Markup >10% */}
|
||||
{data.priceAlerts.length > 0 && (
|
||||
<div style={{
|
||||
background: 'rgba(239, 68, 68, 0.08)',
|
||||
border: '1px solid rgba(239, 68, 68, 0.3)',
|
||||
borderRadius: 'var(--r-lg)',
|
||||
padding: 20, marginBottom: 32,
|
||||
display: 'flex', gap: 16, alignItems: 'flex-start'
|
||||
}}>
|
||||
<div style={{
|
||||
width: 40, height: 40, borderRadius: '50%',
|
||||
background: 'var(--danger)', display: 'flex',
|
||||
alignItems: 'center', justifyContent: 'center', flexShrink: 0
|
||||
}}>
|
||||
<Icon name="alert" style={{ width: 20, color: '#fff' }} />
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>Significant Inflation Markers Detected</h4>
|
||||
<p style={{ fontSize: 13, color: 'var(--ink-muted)', marginBottom: 16 }}>The following item markups exceeded the baseline 10% deviation thresholds compared to their trailing averages:</p>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
|
||||
{data.priceAlerts.map((alert: any, idx: number) => (
|
||||
<div key={idx} style={{ padding: 12, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink)' }}>{alert.productName}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>At {alert.storeName}</div>
|
||||
</div>
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<div style={{ color: 'var(--danger)', fontWeight: 700, fontSize: 14 }}>+{alert.changePercent.toFixed(0)}%</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>${alert.previousPrice} ➔ ${alert.currentPrice}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 2. Grid Layout for Interactive Charts */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(500px, 1fr))', gap: 28, marginBottom: 32 }}>
|
||||
|
||||
{/* Time Series Spend Trend */}
|
||||
<Card style={{ padding: 24 }}>
|
||||
<h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 20 }}>Monthly Spending Velocities</h4>
|
||||
<div style={{ height: 300 }}>
|
||||
{data.spendingOverTime.length === 0 ? (
|
||||
<div style={emptyStyle}>No historical spend records found.</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={data.spendingOverTime} margin={{ top: 5, right: 10, left: -20, bottom: 5 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
|
||||
<XAxis dataKey="period" stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
|
||||
<YAxis stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
|
||||
<Tooltip contentStyle={tooltipStyle} />
|
||||
<Line type="monotone" dataKey="total" stroke="var(--brand)" strokeWidth={3} activeDot={{ r: 6 }} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Category Distribution */}
|
||||
<Card style={{ padding: 24 }}>
|
||||
<h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 20 }}>Spending Distrubution by Category</h4>
|
||||
<div style={{ height: 300 }}>
|
||||
{data.spendingByCategory.length === 0 ? (
|
||||
<div style={emptyStyle}>No categorized allocations recorded yet.</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={data.spendingByCategory} margin={{ top: 5, right: 10, left: -20, bottom: 5 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
|
||||
<XAxis dataKey="category" stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
|
||||
<YAxis stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
|
||||
<Tooltip contentStyle={tooltipStyle} />
|
||||
<Bar dataKey="total" radius={[4, 4, 0, 0]}>
|
||||
{data.spendingByCategory.map((entry: any, index: number) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 3. Average Basket Comparisons (Grid of Stores) */}
|
||||
<Card style={{ padding: 24 }}>
|
||||
<h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 20 }}>Average Complete Basket Totals per Store</h4>
|
||||
{data.averageBasketByStore.length === 0 ? (
|
||||
<div style={emptyStyle}>Create multiple shopping trips to visualize basket trends.</div>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 20 }}>
|
||||
{data.averageBasketByStore.sort((a:any, b:any) => a.avgTotal - b.avgTotal).map((store: any, idx: number) => (
|
||||
<div key={store.storeId} style={{
|
||||
padding: 20, background: 'var(--bg-elev)',
|
||||
border: idx === 0 ? '1px solid var(--success)' : '1px solid var(--border)',
|
||||
borderRadius: 'var(--r-md)', position: 'relative', overflow: 'hidden'
|
||||
}}>
|
||||
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-muted)', textTransform: 'uppercase', marginBottom: 8 }}>{store.storeName}</div>
|
||||
<div style={{ fontSize: 28, fontWeight: 700, color: idx === 0 ? 'var(--success)' : 'var(--ink)' }}>${store.avgTotal.toFixed(2)}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 4 }}>Based on {store.tripCount} simulated checkouts</div>
|
||||
{idx === 0 && (
|
||||
<div style={{
|
||||
position: 'absolute', top: 0, right: 0,
|
||||
background: 'var(--success)', color: '#fff',
|
||||
fontSize: 9, padding: '4px 8px', borderBottomLeftRadius: 'var(--r-sm)',
|
||||
fontWeight: 700, textTransform: 'uppercase'
|
||||
}}>Best Value</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const emptyStyle: React.CSSProperties = {
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
height: '100%', color: 'var(--ink-muted)', fontSize: 13, border: '1px dashed var(--border)',
|
||||
borderRadius: 'var(--r-md)'
|
||||
};
|
||||
|
||||
const tooltipStyle: React.CSSProperties = {
|
||||
background: '#1f2937', border: '1px solid #374151', borderRadius: 8,
|
||||
color: '#fff', fontSize: 12,
|
||||
};
|
||||
102
packages/web/src/lib/useShoppingListSync.ts
Normal file
102
packages/web/src/lib/useShoppingListSync.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { getShoppingListSyncSocketUrl } from '@/services/shopping-lists';
|
||||
|
||||
export interface SyncUpdateMessage {
|
||||
type: 'ITEM_ADDED' | 'ITEM_UPDATED' | 'ITEM_REMOVED';
|
||||
itemId?: string;
|
||||
item?: any;
|
||||
updates?: any;
|
||||
}
|
||||
|
||||
export function useShoppingListSync(
|
||||
householdId: string,
|
||||
listId: string,
|
||||
onRemoteChange: (msg: SyncUpdateMessage) => void
|
||||
) {
|
||||
const socketRef = useRef<WebSocket | null>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const reconnectAttemptsRef = useRef(0);
|
||||
|
||||
const connect = useCallback(() => {
|
||||
if (!householdId || !listId) return;
|
||||
|
||||
// Close previous socket if active
|
||||
if (socketRef.current) {
|
||||
socketRef.current.close();
|
||||
}
|
||||
|
||||
try {
|
||||
const url = getShoppingListSyncSocketUrl(householdId, listId);
|
||||
const ws = new WebSocket(url);
|
||||
socketRef.current = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
setIsConnected(true);
|
||||
setError(null);
|
||||
reconnectAttemptsRef.current = 0;
|
||||
console.log(`🛒 Connected to shopping list real-time sync: ${listId}`);
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const payload: SyncUpdateMessage = JSON.parse(event.data);
|
||||
onRemoteChange(payload);
|
||||
} catch (err) {
|
||||
console.error('Failed parsing real-time grocery payload', err);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
setError('Connection interrupt');
|
||||
};
|
||||
|
||||
ws.onclose = (event) => {
|
||||
setIsConnected(false);
|
||||
console.log(`🔌 Sync severed: ${event.reason || 'Disconnected'}`);
|
||||
|
||||
// Simple linear backoff reconnect
|
||||
if (reconnectAttemptsRef.current < 5) {
|
||||
reconnectAttemptsRef.current += 1;
|
||||
const delay = Math.min(1000 * reconnectAttemptsRef.current, 5000);
|
||||
setTimeout(() => {
|
||||
console.log(`🔄 Attempting sync handshake reconnect (${reconnectAttemptsRef.current}/5)...`);
|
||||
connect();
|
||||
}, delay);
|
||||
}
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Fatal WebSocket initialization', err);
|
||||
setError('Sync failed to initialize');
|
||||
}
|
||||
}, [householdId, listId, onRemoteChange]);
|
||||
|
||||
useEffect(() => {
|
||||
connect();
|
||||
return () => {
|
||||
if (socketRef.current) {
|
||||
// Clear hook handlers to prevent state leakage during dismount
|
||||
socketRef.current.onclose = null;
|
||||
socketRef.current.close();
|
||||
}
|
||||
};
|
||||
}, [connect]);
|
||||
|
||||
const toggleItemCheck = useCallback((itemId: string, checked: boolean) => {
|
||||
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
|
||||
socketRef.current.send(
|
||||
JSON.stringify({
|
||||
type: 'TOGGLE_ITEM',
|
||||
itemId,
|
||||
checked,
|
||||
})
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
isConnected,
|
||||
error,
|
||||
toggleItemCheck,
|
||||
};
|
||||
}
|
||||
|
|
@ -11,6 +11,10 @@ class ApiClient {
|
|||
return this._accessToken !== null;
|
||||
}
|
||||
|
||||
public get baseUrl(): string {
|
||||
return BASE_URL;
|
||||
}
|
||||
|
||||
private getHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
|
|
|
|||
71
packages/web/src/services/prices.ts
Normal file
71
packages/web/src/services/prices.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { apiClient } from './api-client';
|
||||
import type { z } from 'zod/v4';
|
||||
import type {
|
||||
PriceRecordResponseSchema,
|
||||
PriceHistoryResponseSchema,
|
||||
FoodStoreComparisonResponseSchema,
|
||||
FoodSpendingAnalyticsResponseSchema,
|
||||
CreatePriceRecordSchema,
|
||||
BulkPriceRecordInputSchema,
|
||||
} from '@meshitrack/shared';
|
||||
|
||||
type PriceRecordResponse = z.infer<typeof PriceRecordResponseSchema>;
|
||||
type PriceHistoryResponse = z.infer<typeof PriceHistoryResponseSchema>;
|
||||
type FoodStoreComparisonResponse = z.infer<typeof FoodStoreComparisonResponseSchema>;
|
||||
type FoodSpendingAnalyticsResponse = z.infer<typeof FoodSpendingAnalyticsResponseSchema>;
|
||||
type CreatePriceRecordInput = z.infer<typeof CreatePriceRecordSchema>;
|
||||
type BulkPriceRecordInput = z.infer<typeof BulkPriceRecordInputSchema>;
|
||||
|
||||
export async function recordPrice(
|
||||
householdId: string,
|
||||
data: CreatePriceRecordInput
|
||||
): Promise<PriceRecordResponse> {
|
||||
return apiClient.post<PriceRecordResponse>(`/households/${householdId}/prices`, data);
|
||||
}
|
||||
|
||||
export async function recordBulkPrices(
|
||||
householdId: string,
|
||||
data: BulkPriceRecordInput
|
||||
): Promise<PriceRecordResponse[]> {
|
||||
return apiClient.post<PriceRecordResponse[]>(`/households/${householdId}/prices/bulk`, data);
|
||||
}
|
||||
|
||||
export async function getPriceHistory(
|
||||
householdId: string,
|
||||
productId: string,
|
||||
query?: {
|
||||
storeId?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
cursor?: string;
|
||||
limit?: number;
|
||||
}
|
||||
): Promise<PriceHistoryResponse> {
|
||||
const params = new URLSearchParams();
|
||||
if (query?.storeId) params.set('storeId', query.storeId);
|
||||
if (query?.startDate) params.set('startDate', query.startDate);
|
||||
if (query?.endDate) params.set('endDate', query.endDate);
|
||||
if (query?.cursor) params.set('cursor', query.cursor);
|
||||
if (query?.limit) params.set('limit', String(query.limit));
|
||||
const qs = params.toString();
|
||||
return apiClient.get<PriceHistoryResponse>(
|
||||
`/households/${householdId}/prices/history/${productId}${qs ? `?${qs}` : ''}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function compareStores(
|
||||
householdId: string,
|
||||
productId: string
|
||||
): Promise<FoodStoreComparisonResponse> {
|
||||
return apiClient.get<FoodStoreComparisonResponse>(
|
||||
`/households/${householdId}/prices/compare/${productId}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function getPriceAnalytics(
|
||||
householdId: string
|
||||
): Promise<FoodSpendingAnalyticsResponse> {
|
||||
return apiClient.get<FoodSpendingAnalyticsResponse>(
|
||||
`/households/${householdId}/prices/analytics`
|
||||
);
|
||||
}
|
||||
119
packages/web/src/services/shopping-lists.ts
Normal file
119
packages/web/src/services/shopping-lists.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { apiClient } from './api-client';
|
||||
import type { z } from 'zod/v4';
|
||||
import type {
|
||||
ShoppingListResponseSchema,
|
||||
CreateShoppingListSchema,
|
||||
UpdateShoppingListSchema,
|
||||
AddShoppingItemSchema,
|
||||
UpdateShoppingItemSchema,
|
||||
ShoppingListSyncToPantryResponseSchema,
|
||||
BasketStoreComparisonResponseSchema,
|
||||
} from '@meshitrack/shared';
|
||||
|
||||
type ShoppingListResponse = z.infer<typeof ShoppingListResponseSchema>;
|
||||
type CreateShoppingListInput = z.infer<typeof CreateShoppingListSchema>;
|
||||
type UpdateShoppingListInput = z.infer<typeof UpdateShoppingListSchema>;
|
||||
type AddShoppingItemInput = z.infer<typeof AddShoppingItemSchema>;
|
||||
type UpdateShoppingItemInput = z.infer<typeof UpdateShoppingItemSchema>;
|
||||
type ShoppingListSyncToPantryResponse = z.infer<typeof ShoppingListSyncToPantryResponseSchema>;
|
||||
type BasketStoreComparisonResponse = z.infer<typeof BasketStoreComparisonResponseSchema>;
|
||||
|
||||
export async function getShoppingLists(householdId: string): Promise<ShoppingListResponse[]> {
|
||||
return apiClient.get<ShoppingListResponse[]>(`/households/${householdId}/shopping-lists`);
|
||||
}
|
||||
|
||||
export async function getShoppingList(householdId: string, id: string): Promise<ShoppingListResponse> {
|
||||
return apiClient.get<ShoppingListResponse>(`/households/${householdId}/shopping-lists/${id}`);
|
||||
}
|
||||
|
||||
export async function createShoppingList(
|
||||
householdId: string,
|
||||
data: CreateShoppingListInput
|
||||
): Promise<ShoppingListResponse> {
|
||||
return apiClient.post<ShoppingListResponse>(`/households/${householdId}/shopping-lists`, data);
|
||||
}
|
||||
|
||||
export async function updateShoppingList(
|
||||
householdId: string,
|
||||
id: string,
|
||||
data: UpdateShoppingListInput
|
||||
): Promise<ShoppingListResponse> {
|
||||
return apiClient.patch<ShoppingListResponse>(`/households/${householdId}/shopping-lists/${id}`, data);
|
||||
}
|
||||
|
||||
export async function deleteShoppingList(householdId: string, id: string): Promise<void> {
|
||||
return apiClient.delete<void>(`/households/${householdId}/shopping-lists/${id}`);
|
||||
}
|
||||
|
||||
// -- Nested Item Operations --
|
||||
|
||||
export async function addShoppingItem(
|
||||
householdId: string,
|
||||
id: string,
|
||||
data: AddShoppingItemInput
|
||||
): Promise<ShoppingListResponse> {
|
||||
return apiClient.post<ShoppingListResponse>(`/households/${householdId}/shopping-lists/${id}/items`, data);
|
||||
}
|
||||
|
||||
export async function updateShoppingItem(
|
||||
householdId: string,
|
||||
id: string,
|
||||
itemId: string,
|
||||
data: UpdateShoppingItemInput
|
||||
): Promise<ShoppingListResponse> {
|
||||
return apiClient.patch<ShoppingListResponse>(
|
||||
`/households/${householdId}/shopping-lists/${id}/items/${itemId}`,
|
||||
data
|
||||
);
|
||||
}
|
||||
|
||||
export async function removeShoppingItem(
|
||||
householdId: string,
|
||||
id: string,
|
||||
itemId: string
|
||||
): Promise<ShoppingListResponse> {
|
||||
return apiClient.delete<ShoppingListResponse>(
|
||||
`/households/${householdId}/shopping-lists/${id}/items/${itemId}`
|
||||
);
|
||||
}
|
||||
|
||||
// -- Workflows --
|
||||
|
||||
export async function generateFromMealPlan(
|
||||
householdId: string,
|
||||
mealPlanId: string
|
||||
): Promise<ShoppingListResponse> {
|
||||
return apiClient.post<ShoppingListResponse>(
|
||||
`/households/${householdId}/shopping-lists/from-meal-plan/${mealPlanId}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function syncToPantry(
|
||||
householdId: string,
|
||||
id: string
|
||||
): Promise<ShoppingListSyncToPantryResponse> {
|
||||
return apiClient.post<ShoppingListSyncToPantryResponse>(
|
||||
`/households/${householdId}/shopping-lists/${id}/sync-to-pantry`
|
||||
);
|
||||
}
|
||||
|
||||
export async function getBasketStoreComparison(
|
||||
householdId: string,
|
||||
id: string
|
||||
): Promise<BasketStoreComparisonResponse> {
|
||||
return apiClient.get<BasketStoreComparisonResponse>(
|
||||
`/households/${householdId}/shopping-lists/${id}/stores`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates direct WebSocket path for collaborative checklist syncing.
|
||||
*/
|
||||
export function getShoppingListSyncSocketUrl(householdId: string, id: string): string {
|
||||
// Derive WS protocol based on configured API baseURL protocol (defaulting to unsafe ws for localhost)
|
||||
const baseUrl = apiClient.baseUrl || '';
|
||||
const isSecure = baseUrl.startsWith('https');
|
||||
const cleanHost = baseUrl.replace(/^https?:\/\//, '');
|
||||
const protocol = isSecure ? 'wss' : 'ws';
|
||||
return `${protocol}://${cleanHost}/households/${householdId}/shopping-lists/${id}/sync`;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue