Implement regimens

This commit is contained in:
Aerilyn Weber 2026-03-28 18:25:49 +09:00
parent 1f66fab30f
commit 9f416903ef
66 changed files with 9130 additions and 189 deletions

View file

@ -0,0 +1,396 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const { mockFind, mockSave, mockInsertMany, mockAggregate } = vi.hoisted(() => ({
mockFind: vi.fn(),
mockSave: vi.fn(),
mockInsertMany: vi.fn(),
mockAggregate: vi.fn(),
}));
vi.mock('../../schemas/cabinet-event.schema.js', () => {
const chain = () => ({
sort: vi.fn().mockReturnThis(),
limit: vi.fn().mockReturnThis(),
lean: vi.fn().mockReturnThis(),
exec: mockFind,
});
const aggChain = () => ({
exec: mockAggregate,
});
class FakeModel {
data: unknown;
constructor(data: unknown) {
this.data = data;
}
save = mockSave;
toObject() {
return this.data;
}
static find = vi.fn(() => chain());
static insertMany = mockInsertMany;
static aggregate = vi.fn(() => aggChain());
}
return { CabinetEventModel: FakeModel };
});
import { CabinetEventsRepository } from './cabinet-events.repository.js';
describe(CabinetEventsRepository.name, () => {
let repo: CabinetEventsRepository;
const baseEventData = {
householdId: 'hh1',
userId: 'user-1',
cabinetItemId: 'ci-1',
medicineId: 'med-1',
medicineName: 'Metformin',
eventType: 'purchased' as const,
quantity: 10,
quantityBefore: 0,
quantityAfter: 10,
sourceType: 'manual' as const,
};
beforeEach(() => {
vi.clearAllMocks();
repo = new CabinetEventsRepository();
});
describe('create', () => {
it('creates and returns a cabinet event', async () => {
mockSave.mockImplementation(function (this: { toObject: () => unknown }) {
return Promise.resolve(this);
});
const result = await repo.create(baseEventData);
expect(result).toEqual(baseEventData);
expect(mockSave).toHaveBeenCalled();
});
});
describe('createMany', () => {
it('inserts multiple events', async () => {
const events = [baseEventData, { ...baseEventData, quantity: 5 }];
mockInsertMany.mockResolvedValue(events);
const result = await repo.createMany(events);
expect(result).toEqual(events);
expect(mockInsertMany).toHaveBeenCalledWith(events);
});
});
describe('findByHousehold', () => {
it('returns paginated events with no filters', async () => {
const items = [{ _id: 'ev-1', quantity: 10 }];
mockFind.mockResolvedValue(items);
const result = await repo.findByHousehold('hh1', { limit: 20 });
expect(result.data).toEqual(items);
expect(result.pagination.hasMore).toBe(false);
});
it('handles cursor-based pagination', async () => {
const items = [{ _id: 'ev-2', quantity: 5 }];
mockFind.mockResolvedValue(items);
const cursor = Buffer.from('ev-1').toString('base64');
const result = await repo.findByHousehold('hh1', { cursor, limit: 20 });
expect(result.data).toEqual(items);
expect(result.pagination.hasMore).toBe(false);
});
it('sets hasMore when more items exist', async () => {
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `ev-${i}`, quantity: i }));
mockFind.mockResolvedValue(items);
const result = await repo.findByHousehold('hh1', { limit: 2 });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(true);
expect(result.pagination.cursor).toBeTruthy();
});
it('returns null cursor when no data', async () => {
mockFind.mockResolvedValue([]);
const result = await repo.findByHousehold('hh1', { limit: 20 });
expect(result.pagination.cursor).toBeNull();
expect(result.pagination.hasMore).toBe(false);
});
it('filters by medicineId', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', { medicineId: 'med-1', limit: 20 });
expect(mockFind).toHaveBeenCalled();
});
it('filters by eventType', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', { eventType: 'purchased' as never, limit: 20 });
expect(mockFind).toHaveBeenCalled();
});
it('filters by startDate only', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', {
startDate: '2024-01-01T00:00:00.000Z',
limit: 20,
});
expect(mockFind).toHaveBeenCalled();
});
it('filters by endDate only', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', {
endDate: '2024-12-31T00:00:00.000Z',
limit: 20,
});
expect(mockFind).toHaveBeenCalled();
});
it('filters by both startDate and endDate', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', {
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-12-31T00:00:00.000Z',
limit: 20,
});
expect(mockFind).toHaveBeenCalled();
});
});
describe('findByCabinetItem', () => {
it('returns paginated events for a cabinet item', async () => {
const items = [{ _id: 'ev-1', cabinetItemId: 'ci-1' }];
mockFind.mockResolvedValue(items);
const result = await repo.findByCabinetItem('hh1', 'ci-1', { limit: 20 });
expect(result.data).toEqual(items);
expect(result.pagination.hasMore).toBe(false);
});
it('handles cursor-based pagination', async () => {
const items = [{ _id: 'ev-2' }];
mockFind.mockResolvedValue(items);
const cursor = Buffer.from('ev-1').toString('base64');
const result = await repo.findByCabinetItem('hh1', 'ci-1', { cursor, limit: 20 });
expect(result.data).toEqual(items);
expect(result.pagination.hasMore).toBe(false);
});
it('sets hasMore when more items exist', async () => {
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `ev-${i}` }));
mockFind.mockResolvedValue(items);
const result = await repo.findByCabinetItem('hh1', 'ci-1', { limit: 2 });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(true);
expect(result.pagination.cursor).toBeTruthy();
});
it('returns null cursor when no data', async () => {
mockFind.mockResolvedValue([]);
const result = await repo.findByCabinetItem('hh1', 'ci-1', { limit: 20 });
expect(result.pagination.cursor).toBeNull();
expect(result.pagination.hasMore).toBe(false);
});
});
describe('getSpendingSummary', () => {
it('returns spending summary with default month period', async () => {
const byMedicine = [
{
_id: 'med-1',
medicineName: 'Metformin',
totalSpent: 100,
totalQuantity: 10,
avgUnitPrice: 10,
purchaseCount: 2,
currency: 'USD',
},
];
const byPeriod = [{ _id: '2024-01', totalSpent: 100 }];
mockAggregate
.mockResolvedValueOnce(byMedicine)
.mockResolvedValueOnce(byPeriod);
const result = await repo.getSpendingSummary('hh1', { period: 'month' });
expect(result.totalSpent).toBe(100);
expect(result.currency).toBe('USD');
expect(result.byMedicine).toHaveLength(1);
expect(result.byMedicine[0].medicineId).toBe('med-1');
expect(result.byMedicine[0].medicineName).toBe('Metformin');
expect(result.byMedicine[0].totalSpent).toBe(100);
expect(result.byMedicine[0].totalQuantity).toBe(10);
expect(result.byMedicine[0].avgUnitPrice).toBe(10);
expect(result.byMedicine[0].purchaseCount).toBe(2);
expect(result.byPeriod).toHaveLength(1);
expect(result.byPeriod[0].period).toBe('2024-01');
expect(result.byPeriod[0].totalSpent).toBe(100);
});
it('returns null currency when no medicine data', async () => {
mockAggregate
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
const result = await repo.getSpendingSummary('hh1', { period: 'month' });
expect(result.totalSpent).toBe(0);
expect(result.currency).toBeNull();
expect(result.byMedicine).toHaveLength(0);
expect(result.byPeriod).toHaveLength(0);
});
it('filters by medicineId', async () => {
mockAggregate
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
await repo.getSpendingSummary('hh1', { period: 'month', medicineId: 'med-1' });
expect(mockAggregate).toHaveBeenCalledTimes(2);
});
it('filters by startDate only', async () => {
mockAggregate
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
await repo.getSpendingSummary('hh1', {
period: 'month',
startDate: '2024-01-01T00:00:00.000Z',
});
expect(mockAggregate).toHaveBeenCalledTimes(2);
});
it('filters by endDate only', async () => {
mockAggregate
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
await repo.getSpendingSummary('hh1', {
period: 'month',
endDate: '2024-12-31T00:00:00.000Z',
});
expect(mockAggregate).toHaveBeenCalledTimes(2);
});
it('filters by both startDate and endDate', async () => {
mockAggregate
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
await repo.getSpendingSummary('hh1', {
period: 'month',
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-12-31T00:00:00.000Z',
});
expect(mockAggregate).toHaveBeenCalledTimes(2);
});
it('uses quarter date format', async () => {
mockAggregate
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
await repo.getSpendingSummary('hh1', { period: 'quarter' });
expect(mockAggregate).toHaveBeenCalledTimes(2);
});
it('uses year date format', async () => {
mockAggregate
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
await repo.getSpendingSummary('hh1', { period: 'year' });
expect(mockAggregate).toHaveBeenCalledTimes(2);
});
it('handles null currency in first medicine entry', async () => {
const byMedicine = [
{
_id: 'med-1',
medicineName: 'Metformin',
totalSpent: 50,
totalQuantity: 5,
avgUnitPrice: 10,
purchaseCount: 1,
currency: null,
},
];
mockAggregate
.mockResolvedValueOnce(byMedicine)
.mockResolvedValueOnce([]);
const result = await repo.getSpendingSummary('hh1', { period: 'month' });
expect(result.currency).toBeNull();
});
});
describe('getAvgUnitPriceByMedicine', () => {
it('returns empty map when no medicine ids provided', async () => {
const result = await repo.getAvgUnitPriceByMedicine('hh1', []);
expect(result).toEqual(new Map());
expect(mockAggregate).not.toHaveBeenCalled();
});
it('returns map of avg unit prices', async () => {
const results = [
{ _id: 'med-1', avgUnitPrice: 10.5, currency: 'USD', totalSpent: 105, totalQuantity: 10 },
{ _id: 'med-2', avgUnitPrice: 5.0, currency: 'EUR', totalSpent: 50, totalQuantity: 10 },
];
mockAggregate.mockResolvedValue(results);
const map = await repo.getAvgUnitPriceByMedicine('hh1', ['med-1', 'med-2']);
expect(map.size).toBe(2);
expect(map.get('med-1')).toEqual({ avgUnitPrice: 10.5, currency: 'USD' });
expect(map.get('med-2')).toEqual({ avgUnitPrice: 5.0, currency: 'EUR' });
});
it('handles null currency in results', async () => {
const results = [
{ _id: 'med-1', avgUnitPrice: 10, currency: null, totalSpent: 100, totalQuantity: 10 },
];
mockAggregate.mockResolvedValue(results);
const map = await repo.getAvgUnitPriceByMedicine('hh1', ['med-1']);
expect(map.get('med-1')).toEqual({ avgUnitPrice: 10, currency: null });
});
});
});

View file

@ -0,0 +1,214 @@
import { CabinetEventModel } from '../../schemas/cabinet-event.schema.js';
import type {
CabinetEventType,
CabinetEventSourceType,
CabinetEventQueryInput,
SpendingSummaryQueryInput,
} from '@meshitrack/shared';
export interface CreateCabinetEventData {
householdId: string;
userId: string;
cabinetItemId: string;
medicineId: string;
medicineName: string;
eventType: CabinetEventType;
quantity: number;
quantityBefore: number;
quantityAfter: number;
unitPrice?: number;
totalPrice?: number;
currency?: string;
storeId?: string;
storeName?: string;
sourceType: CabinetEventSourceType;
sourceId?: string;
reason?: string;
notes?: string;
}
export class CabinetEventsRepository {
public async create(data: CreateCabinetEventData) {
const event = new CabinetEventModel(data);
const saved = await event.save();
return saved.toObject();
}
public async createMany(events: CreateCabinetEventData[]) {
return CabinetEventModel.insertMany(events);
}
public async findByHousehold(householdId: string, query: CabinetEventQueryInput) {
const filter: Record<string, unknown> = { householdId };
if (query.medicineId) filter['medicineId'] = query.medicineId;
if (query.eventType) filter['eventType'] = query.eventType;
if (query.startDate || query.endDate) {
const dateFilter: Record<string, string> = {};
if (query.startDate) dateFilter['$gte'] = query.startDate;
if (query.endDate) dateFilter['$lte'] = query.endDate;
filter['createdAt'] = dateFilter;
}
if (query.cursor) {
const id = Buffer.from(query.cursor, 'base64').toString();
filter['_id'] = { $lt: id };
}
const limit = query.limit;
const items = await CabinetEventModel.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 findByCabinetItem(
householdId: string,
cabinetItemId: string,
query: { cursor?: string; limit: number },
) {
const filter: Record<string, unknown> = { householdId, cabinetItemId };
if (query.cursor) {
const id = Buffer.from(query.cursor, 'base64').toString();
filter['_id'] = { $lt: id };
}
const limit = query.limit;
const items = await CabinetEventModel.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 getSpendingSummary(householdId: string, query: SpendingSummaryQueryInput) {
const match: Record<string, unknown> = {
householdId,
eventType: 'purchased',
unitPrice: { $ne: null },
};
if (query.medicineId) match['medicineId'] = query.medicineId;
if (query.startDate || query.endDate) {
const dateFilter: Record<string, string> = {};
if (query.startDate) dateFilter['$gte'] = query.startDate;
if (query.endDate) dateFilter['$lte'] = query.endDate;
match['createdAt'] = dateFilter;
}
const dateFormat =
query.period === 'year' ? '%Y' : query.period === 'quarter' ? '%Y-Q%q' : '%Y-%m';
const [byMedicine, byPeriod] = await Promise.all([
CabinetEventModel.aggregate([
{ $match: match },
{
$group: {
_id: '$medicineId',
medicineName: { $first: '$medicineName' },
totalSpent: { $sum: { $multiply: ['$unitPrice', '$quantity'] } },
totalQuantity: { $sum: '$quantity' },
purchaseCount: { $sum: 1 },
currency: { $first: '$currency' },
},
},
{
$addFields: {
avgUnitPrice: {
$cond: [{ $gt: ['$totalQuantity', 0] }, { $divide: ['$totalSpent', '$totalQuantity'] }, 0],
},
},
},
{ $sort: { totalSpent: -1 } },
]).exec(),
CabinetEventModel.aggregate([
{ $match: match },
{
$group: {
_id: { $dateToString: { format: dateFormat, date: '$createdAt' } },
totalSpent: { $sum: { $multiply: ['$unitPrice', '$quantity'] } },
},
},
{ $sort: { _id: 1 } },
]).exec(),
]);
const totalSpent = byMedicine.reduce(
(sum: number, m: Record<string, unknown>) => sum + (m.totalSpent as number),
0,
);
const currency =
byMedicine.length > 0 ? (byMedicine[0].currency as string | null) ?? null : null;
return {
totalSpent,
currency,
byMedicine: byMedicine.map((m: Record<string, unknown>) => ({
medicineId: m._id as string,
medicineName: m.medicineName as string,
totalSpent: m.totalSpent as number,
totalQuantity: m.totalQuantity as number,
avgUnitPrice: m.avgUnitPrice as number,
purchaseCount: m.purchaseCount as number,
})),
byPeriod: byPeriod.map((p: Record<string, unknown>) => ({
period: p._id as string,
totalSpent: p.totalSpent as number,
})),
};
}
public async getAvgUnitPriceByMedicine(householdId: string, medicineIds: string[]) {
if (medicineIds.length === 0) return new Map<string, { avgUnitPrice: number; currency: string | null }>();
const results = await CabinetEventModel.aggregate([
{
$match: {
householdId,
eventType: 'purchased',
medicineId: { $in: medicineIds },
unitPrice: { $ne: null },
},
},
{
$group: {
_id: '$medicineId',
totalSpent: { $sum: { $multiply: ['$unitPrice', '$quantity'] } },
totalQuantity: { $sum: '$quantity' },
currency: { $first: '$currency' },
},
},
{
$addFields: {
avgUnitPrice: {
$cond: [{ $gt: ['$totalQuantity', 0] }, { $divide: ['$totalSpent', '$totalQuantity'] }, 0],
},
},
},
]).exec();
const map = new Map<string, { avgUnitPrice: number; currency: string | null }>();
for (const r of results) {
map.set(r._id as string, {
avgUnitPrice: r.avgUnitPrice as number,
currency: (r.currency as string | null) ?? null,
});
}
return map;
}
}

View file

@ -0,0 +1,387 @@
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',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: { alg: 'RS256' },
key: {},
}),
}));
const { mockListEvents, mockGetEventsByItem, mockGetSpendingSummary } = vi.hoisted(() => ({
mockListEvents: vi.fn(),
mockGetEventsByItem: vi.fn(),
mockGetSpendingSummary: vi.fn(),
}));
vi.mock('./cabinet-events.repository.js', () => ({
CabinetEventsRepository: class {
create = vi.fn();
createMany = vi.fn();
findByHousehold = vi.fn();
findByCabinetItem = vi.fn();
getSpendingSummary = vi.fn();
getAvgUnitPriceByMedicine = vi.fn();
},
}));
vi.mock('./cabinet-events.service.js', () => ({
CabinetEventsService: class {
logEvent = vi.fn();
logEvents = vi.fn();
listEvents = mockListEvents;
getEventsByItem = mockGetEventsByItem;
getSpendingSummary = mockGetSpendingSummary;
getAvgUnitPrices = vi.fn();
},
}));
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 cabinetEventsRoutes from './cabinet-events.routes.js';
function makeFakeEvent(overrides = {}) {
return {
_id: 'ev-1',
householdId: 'hh1',
userId: 'kc-1',
cabinetItemId: 'ci-1',
medicineId: 'med-1',
medicineName: 'Metformin',
eventType: 'purchased',
quantity: 10,
quantityBefore: 0,
quantityAfter: 10,
sourceType: 'manual',
createdAt: '2024-06-01T00:00:00.000Z',
...overrides,
};
}
describe('cabinet-events.routes', () => {
let app: Awaited<ReturnType<typeof buildTestApp>>;
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(cabinetEventsRoutes);
await instance.ready();
return instance;
}
const authHeaders = { authorization: 'Bearer valid-token' };
beforeEach(async () => {
vi.clearAllMocks();
app = await buildTestApp();
});
afterEach(async () => {
if (app) await app.close();
});
describe('GET /api/v1/households/:householdId/cabinet-events', () => {
it('returns paginated event list', async () => {
const event = makeFakeEvent();
mockListEvents.mockResolvedValue({
data: [event],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0].medicineName).toBe('Metformin');
expect(body.data[0].eventType).toBe('purchased');
expect(body.pagination.hasMore).toBe(false);
});
it('handles ObjectId and Date objects in response', async () => {
const event = makeFakeEvent({
_id: { toString: () => 'ev-obj' },
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
unitPrice: 5.5,
totalPrice: 55,
currency: 'USD',
storeId: 'store-1',
storeName: 'Pharmacy A',
sourceId: 'src-1',
reason: 'restocking',
notes: 'bulk purchase',
});
mockListEvents.mockResolvedValue({
data: [event],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0]._id).toBe('ev-obj');
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
expect(body.data[0].unitPrice).toBe(5.5);
expect(body.data[0].totalPrice).toBe(55);
expect(body.data[0].currency).toBe('USD');
expect(body.data[0].storeId).toBe('store-1');
expect(body.data[0].storeName).toBe('Pharmacy A');
expect(body.data[0].sourceId).toBe('src-1');
expect(body.data[0].reason).toBe('restocking');
expect(body.data[0].notes).toBe('bulk purchase');
});
it('handles Date instances in createdAt', async () => {
const event = makeFakeEvent({
createdAt: new Date('2024-03-15T12:00:00.000Z'),
});
mockListEvents.mockResolvedValue({
data: [event],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0].createdAt).toBe('2024-03-15T12:00:00.000Z');
});
it('omits null optional fields from response', async () => {
const event = makeFakeEvent({
unitPrice: null,
totalPrice: null,
currency: null,
storeId: null,
storeName: null,
sourceId: null,
reason: null,
notes: null,
});
mockListEvents.mockResolvedValue({
data: [event],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0].unitPrice).toBeUndefined();
expect(body.data[0].totalPrice).toBeUndefined();
expect(body.data[0].currency).toBeUndefined();
expect(body.data[0].storeId).toBeUndefined();
expect(body.data[0].storeName).toBeUndefined();
expect(body.data[0].sourceId).toBeUndefined();
expect(body.data[0].reason).toBeUndefined();
expect(body.data[0].notes).toBeUndefined();
});
it('passes query parameters to service', async () => {
mockListEvents.mockResolvedValue({
data: [],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events?medicineId=med-1&eventType=purchased&limit=10',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(mockListEvents).toHaveBeenCalledWith('hh1', expect.objectContaining({
medicineId: 'med-1',
eventType: 'purchased',
limit: 10,
}));
});
});
describe('GET /api/v1/households/:householdId/cabinet-events/by-item/:cabinetItemId', () => {
it('returns paginated events for a cabinet item', async () => {
const event = makeFakeEvent();
mockGetEventsByItem.mockResolvedValue({
data: [event],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events/by-item/ci-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0].cabinetItemId).toBe('ci-1');
expect(body.pagination.hasMore).toBe(false);
});
it('passes query parameters to service', async () => {
mockGetEventsByItem.mockResolvedValue({
data: [],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events/by-item/ci-1?limit=5&cursor=abc',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(mockGetEventsByItem).toHaveBeenCalledWith('hh1', 'ci-1', expect.objectContaining({
limit: 5,
cursor: 'abc',
}));
});
it('handles ObjectId and Date objects in by-item response', async () => {
const event = makeFakeEvent({
_id: { toString: () => 'ev-obj-2' },
createdAt: new Date('2024-05-01T00:00:00.000Z'),
});
mockGetEventsByItem.mockResolvedValue({
data: [event],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events/by-item/ci-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0]._id).toBe('ev-obj-2');
expect(body.data[0].createdAt).toBe('2024-05-01T00:00:00.000Z');
});
});
describe('GET /api/v1/households/:householdId/cabinet-events/spending-summary', () => {
it('returns spending summary', async () => {
mockGetSpendingSummary.mockResolvedValue({
totalSpent: 250,
currency: 'USD',
byMedicine: [
{
medicineId: 'med-1',
medicineName: 'Metformin',
totalSpent: 250,
totalQuantity: 25,
avgUnitPrice: 10,
purchaseCount: 5,
},
],
byPeriod: [
{ period: '2024-01', totalSpent: 100 },
{ period: '2024-02', totalSpent: 150 },
],
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events/spending-summary',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.totalSpent).toBe(250);
expect(body.currency).toBe('USD');
expect(body.byMedicine).toHaveLength(1);
expect(body.byMedicine[0].medicineId).toBe('med-1');
expect(body.byPeriod).toHaveLength(2);
});
it('passes query parameters to service', async () => {
mockGetSpendingSummary.mockResolvedValue({
totalSpent: 0,
currency: null,
byMedicine: [],
byPeriod: [],
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events/spending-summary?period=quarter&medicineId=med-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(mockGetSpendingSummary).toHaveBeenCalledWith('hh1', expect.objectContaining({
period: 'quarter',
medicineId: 'med-1',
}));
});
it('returns empty summary with null currency', async () => {
mockGetSpendingSummary.mockResolvedValue({
totalSpent: 0,
currency: null,
byMedicine: [],
byPeriod: [],
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet-events/spending-summary',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.totalSpent).toBe(0);
expect(body.currency).toBeNull();
expect(body.byMedicine).toHaveLength(0);
expect(body.byPeriod).toHaveLength(0);
});
});
});

View file

@ -0,0 +1,157 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
CabinetEventQuerySchema,
CabinetEventListResponseSchema,
SpendingSummaryQuerySchema,
SpendingSummaryResponseSchema,
} from '@meshitrack/shared';
import { CabinetEventsRepository } from './cabinet-events.repository.js';
import { CabinetEventsService } from './cabinet-events.service.js';
type AnyCabinetEventDoc = {
_id: string | { toString: () => string };
householdId: string;
userId: string;
cabinetItemId: string;
medicineId: string;
medicineName: string;
eventType: string;
quantity: number;
quantityBefore: number;
quantityAfter: number;
unitPrice?: number | null;
totalPrice?: number | null;
currency?: string | null;
storeId?: string | null;
storeName?: string | null;
sourceType: string;
sourceId?: string | null;
reason?: string | null;
notes?: string | null;
createdAt: string | Date | { toISOString: () => string };
};
function toStr(v: string | { toString: () => string }): string {
return typeof v === 'string' ? v : v.toString();
}
function toIso(v: string | Date | { toISOString: () => string }): string {
if (typeof v === 'string') return v;
if (v instanceof Date) return v.toISOString();
return v.toISOString();
}
function toCabinetEventResponse(doc: AnyCabinetEventDoc) {
return {
_id: toStr(doc._id),
householdId: doc.householdId,
userId: doc.userId,
cabinetItemId: doc.cabinetItemId,
medicineId: doc.medicineId,
medicineName: doc.medicineName,
eventType: doc.eventType,
quantity: doc.quantity,
quantityBefore: doc.quantityBefore,
quantityAfter: doc.quantityAfter,
...(doc.unitPrice != null ? { unitPrice: doc.unitPrice } : {}),
...(doc.totalPrice != null ? { totalPrice: doc.totalPrice } : {}),
...(doc.currency ? { currency: doc.currency } : {}),
...(doc.storeId ? { storeId: doc.storeId } : {}),
...(doc.storeName ? { storeName: doc.storeName } : {}),
sourceType: doc.sourceType,
...(doc.sourceId ? { sourceId: doc.sourceId } : {}),
...(doc.reason ? { reason: doc.reason } : {}),
...(doc.notes ? { notes: doc.notes } : {}),
createdAt: toIso(doc.createdAt),
};
}
declare module '@fastify/awilix' {
interface Cradle {
cabinetEventsRepository: CabinetEventsRepository;
cabinetEventsService: CabinetEventsService;
}
}
export default fp(
async (fastify) => {
fastify.diContainer.register({
cabinetEventsRepository: asClass(CabinetEventsRepository, { lifetime: Lifetime.SINGLETON }),
cabinetEventsService: asClass(CabinetEventsService, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
const householdParams = z.object({ householdId: z.string() });
// GET /api/v1/households/:householdId/cabinet-events — list events
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/cabinet-events',
schema: {
params: householdParams,
querystring: CabinetEventQuerySchema,
response: { 200: CabinetEventListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetEventsService');
const result = await service.listEvents(request.params.householdId, request.query);
return reply.send({
data: result.data.map(toCabinetEventResponse),
pagination: result.pagination,
});
},
});
// GET /api/v1/households/:householdId/cabinet-events/by-item/:cabinetItemId — events for one item
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/cabinet-events/by-item/:cabinetItemId',
schema: {
params: householdParams.extend({ cabinetItemId: z.string() }),
querystring: z.object({
cursor: z.string().optional(),
limit: z.coerce.number().int().min(1).max(100).default(20),
}),
response: { 200: CabinetEventListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetEventsService');
const result = await service.getEventsByItem(
request.params.householdId,
request.params.cabinetItemId,
request.query,
);
return reply.send({
data: result.data.map(toCabinetEventResponse),
pagination: result.pagination,
});
},
});
// GET /api/v1/households/:householdId/cabinet-events/spending-summary — spending analytics
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/cabinet-events/spending-summary',
schema: {
params: householdParams,
querystring: SpendingSummaryQuerySchema,
response: { 200: SpendingSummaryResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetEventsService');
const summary = await service.getSpendingSummary(
request.params.householdId,
request.query,
);
return reply.send(summary);
},
});
},
{
name: 'cabinet-events-routes',
dependencies: ['auth-plugin'],
},
);

View file

@ -0,0 +1,142 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { CabinetEventsService } from './cabinet-events.service.js';
describe(CabinetEventsService.name, () => {
const mockCabinetEventsRepo = {
create: vi.fn(),
createMany: vi.fn(),
findByHousehold: vi.fn(),
findByCabinetItem: vi.fn(),
getSpendingSummary: vi.fn(),
getAvgUnitPriceByMedicine: vi.fn(),
};
let service: CabinetEventsService;
const baseEventData = {
householdId: 'hh1',
userId: 'user-1',
cabinetItemId: 'ci-1',
medicineId: 'med-1',
medicineName: 'Metformin',
eventType: 'purchased' as const,
quantity: 10,
quantityBefore: 0,
quantityAfter: 10,
sourceType: 'manual' as const,
};
beforeEach(() => {
vi.clearAllMocks();
service = new CabinetEventsService({
cabinetEventsRepository: mockCabinetEventsRepo as never,
});
});
describe('logEvent', () => {
it('delegates to repository create', async () => {
const created = { _id: 'ev-1', ...baseEventData };
mockCabinetEventsRepo.create.mockResolvedValue(created);
const result = await service.logEvent(baseEventData);
expect(result).toEqual(created);
expect(mockCabinetEventsRepo.create).toHaveBeenCalledWith(baseEventData);
});
});
describe('logEvents', () => {
it('delegates to repository createMany', async () => {
const events = [baseEventData, { ...baseEventData, quantity: 5 }];
const inserted = events.map((e, i) => ({ _id: `ev-${i}`, ...e }));
mockCabinetEventsRepo.createMany.mockResolvedValue(inserted);
const result = await service.logEvents(events);
expect(result).toEqual(inserted);
expect(mockCabinetEventsRepo.createMany).toHaveBeenCalledWith(events);
});
it('returns empty array for empty input without calling repository', async () => {
const result = await service.logEvents([]);
expect(result).toEqual([]);
expect(mockCabinetEventsRepo.createMany).not.toHaveBeenCalled();
});
});
describe('listEvents', () => {
it('delegates to repository findByHousehold', async () => {
const expected = {
data: [{ _id: 'ev-1' }],
pagination: { cursor: null, hasMore: false },
};
mockCabinetEventsRepo.findByHousehold.mockResolvedValue(expected);
const query = { limit: 20 };
const result = await service.listEvents('hh1', query);
expect(result).toEqual(expected);
expect(mockCabinetEventsRepo.findByHousehold).toHaveBeenCalledWith('hh1', query);
});
});
describe('getEventsByItem', () => {
it('delegates to repository findByCabinetItem', async () => {
const expected = {
data: [{ _id: 'ev-1', cabinetItemId: 'ci-1' }],
pagination: { cursor: null, hasMore: false },
};
mockCabinetEventsRepo.findByCabinetItem.mockResolvedValue(expected);
const query = { limit: 20 };
const result = await service.getEventsByItem('hh1', 'ci-1', query);
expect(result).toEqual(expected);
expect(mockCabinetEventsRepo.findByCabinetItem).toHaveBeenCalledWith('hh1', 'ci-1', query);
});
it('passes cursor through to repository', async () => {
const expected = {
data: [],
pagination: { cursor: null, hasMore: false },
};
mockCabinetEventsRepo.findByCabinetItem.mockResolvedValue(expected);
const query = { cursor: 'abc123', limit: 10 };
await service.getEventsByItem('hh1', 'ci-1', query);
expect(mockCabinetEventsRepo.findByCabinetItem).toHaveBeenCalledWith('hh1', 'ci-1', query);
});
});
describe('getSpendingSummary', () => {
it('delegates to repository getSpendingSummary', async () => {
const expected = {
totalSpent: 100,
currency: 'USD',
byMedicine: [],
byPeriod: [],
};
mockCabinetEventsRepo.getSpendingSummary.mockResolvedValue(expected);
const query = { period: 'month' as const };
const result = await service.getSpendingSummary('hh1', query);
expect(result).toEqual(expected);
expect(mockCabinetEventsRepo.getSpendingSummary).toHaveBeenCalledWith('hh1', query);
});
});
describe('getAvgUnitPrices', () => {
it('delegates to repository getAvgUnitPriceByMedicine', async () => {
const expected = new Map([['med-1', { avgUnitPrice: 10, currency: 'USD' }]]);
mockCabinetEventsRepo.getAvgUnitPriceByMedicine.mockResolvedValue(expected);
const result = await service.getAvgUnitPrices('hh1', ['med-1']);
expect(result).toEqual(expected);
expect(mockCabinetEventsRepo.getAvgUnitPriceByMedicine).toHaveBeenCalledWith('hh1', ['med-1']);
});
});
});

View file

@ -0,0 +1,43 @@
import type { CabinetEventsRepository, CreateCabinetEventData } from './cabinet-events.repository.js';
import type { CabinetEventQueryInput, SpendingSummaryQueryInput } from '@meshitrack/shared';
interface Deps {
cabinetEventsRepository: CabinetEventsRepository;
}
export class CabinetEventsService {
private readonly cabinetEventsRepository: CabinetEventsRepository;
public constructor({ cabinetEventsRepository }: Deps) {
this.cabinetEventsRepository = cabinetEventsRepository;
}
public async logEvent(data: CreateCabinetEventData) {
return this.cabinetEventsRepository.create(data);
}
public async logEvents(events: CreateCabinetEventData[]) {
if (events.length === 0) return [];
return this.cabinetEventsRepository.createMany(events);
}
public async listEvents(householdId: string, query: CabinetEventQueryInput) {
return this.cabinetEventsRepository.findByHousehold(householdId, query);
}
public async getEventsByItem(
householdId: string,
cabinetItemId: string,
query: { cursor?: string; limit: number },
) {
return this.cabinetEventsRepository.findByCabinetItem(householdId, cabinetItemId, query);
}
public async getSpendingSummary(householdId: string, query: SpendingSummaryQueryInput) {
return this.cabinetEventsRepository.getSpendingSummary(householdId, query);
}
public async getAvgUnitPrices(householdId: string, medicineIds: string[]) {
return this.cabinetEventsRepository.getAvgUnitPriceByMedicine(householdId, medicineIds);
}
}