Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
295
packages/api/tests/modules/cabinet/cabinet.repository.test.ts
Normal file
295
packages/api/tests/modules/cabinet/cabinet.repository.test.ts
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { mockFind, mockFindOne, mockFindOneAndUpdate, mockSave, mockCountDocuments, mockAggregate } =
|
||||
vi.hoisted(() => ({
|
||||
mockFind: vi.fn(),
|
||||
mockFindOne: vi.fn(),
|
||||
mockFindOneAndUpdate: vi.fn(),
|
||||
mockSave: vi.fn(),
|
||||
mockCountDocuments: vi.fn(),
|
||||
mockAggregate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/schemas/cabinet-item.schema.js', () => {
|
||||
const chain = () => ({
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFind,
|
||||
});
|
||||
|
||||
const findOneChain = () => ({
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFindOne,
|
||||
});
|
||||
|
||||
const updateChain = () => ({
|
||||
exec: mockFindOneAndUpdate,
|
||||
});
|
||||
|
||||
const countChain = () => ({
|
||||
exec: mockCountDocuments,
|
||||
});
|
||||
|
||||
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 findOne = vi.fn(() => findOneChain());
|
||||
static findOneAndUpdate = vi.fn(() => updateChain());
|
||||
static countDocuments = vi.fn(() => countChain());
|
||||
static aggregate = vi.fn(() => aggChain());
|
||||
}
|
||||
|
||||
return { CabinetItemModel: FakeModel };
|
||||
});
|
||||
|
||||
import { CabinetRepository } from '../../../src/modules/cabinet/cabinet.repository.js';
|
||||
|
||||
describe(CabinetRepository.name, () => {
|
||||
let repo: CabinetRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new CabinetRepository();
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('returns paginated items', async () => {
|
||||
const items = [{ _id: 'ci-1', quantity: 30 }];
|
||||
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: 'ci-2', quantity: 10 }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const cursor = Buffer.from('ci-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: `ci-${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();
|
||||
});
|
||||
|
||||
it('filters by medicineId', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { medicineId: 'med-1', limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters by status', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', {
|
||||
status: 'active' as never,
|
||||
limit: 20,
|
||||
});
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters by expiringWithin', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { expiringWithin: 30, limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('returns item by id and householdId', async () => {
|
||||
const item = { _id: 'ci-1', householdId: 'hh1', quantity: 30 };
|
||||
mockFindOne.mockResolvedValue(item);
|
||||
|
||||
const result = await repo.findById('ci-1', 'hh1');
|
||||
|
||||
expect(result).toEqual(item);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAggregateSummary', () => {
|
||||
it('returns aggregate data', async () => {
|
||||
const aggregated = [{ _id: 'med-1', totalQuantity: 60, itemCount: 2 }];
|
||||
mockAggregate.mockResolvedValue(aggregated);
|
||||
|
||||
const result = await repo.getAggregateSummary('hh1');
|
||||
|
||||
expect(result).toEqual(aggregated);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates and returns cabinet item', async () => {
|
||||
const data = {
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
medicineStrength: 500,
|
||||
medicineStrengthUnit: 'mg',
|
||||
medicineForm: 'tablet',
|
||||
quantity: 30,
|
||||
unit: 'tablet' as const,
|
||||
};
|
||||
mockSave.mockImplementation(function (this: { toObject: () => unknown }) {
|
||||
return Promise.resolve(this);
|
||||
});
|
||||
|
||||
const result = await repo.create(data, 'hh1', 'user-1');
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates and returns item', async () => {
|
||||
const updated = { _id: 'ci-1', quantity: 25 };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.update('ci-1', 'hh1', { quantity: 25 });
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
});
|
||||
|
||||
describe('adjustQuantity', () => {
|
||||
it('adjusts quantity and returns updated item', async () => {
|
||||
mockFindOne.mockResolvedValue({ _id: 'ci-1', quantity: 30, status: 'active' });
|
||||
const updated = { _id: 'ci-1', quantity: 27, status: 'active' };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.adjustQuantity('ci-1', 'hh1', -3);
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('floors quantity at 0 and sets depleted status', async () => {
|
||||
mockFindOne.mockResolvedValue({ _id: 'ci-1', quantity: 2, status: 'active' });
|
||||
const updated = { _id: 'ci-1', quantity: 0, status: 'depleted' };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.adjustQuantity('ci-1', 'hh1', -5);
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('re-activates depleted item when adding stock', async () => {
|
||||
mockFindOne.mockResolvedValue({ _id: 'ci-1', quantity: 0, status: 'depleted' });
|
||||
const updated = { _id: 'ci-1', quantity: 10, status: 'active' };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.adjustQuantity('ci-1', 'hh1', 10);
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('returns null if item not found', async () => {
|
||||
mockFindOne.mockResolvedValue(null);
|
||||
|
||||
const result = await repo.adjustQuantity('ci-missing', 'hh1', 5);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findExpiringSoon', () => {
|
||||
it('returns items expiring within N days', async () => {
|
||||
const items = [{ _id: 'ci-1', expirationDate: new Date() }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findExpiringSoon('hh1', 30);
|
||||
|
||||
expect(result).toEqual(items);
|
||||
});
|
||||
});
|
||||
|
||||
describe('countByMedicineId', () => {
|
||||
it('returns count', async () => {
|
||||
mockCountDocuments.mockResolvedValue(3);
|
||||
|
||||
const result = await repo.countByMedicineId('med-1');
|
||||
|
||||
expect(result).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('softDelete', () => {
|
||||
it('soft deletes and returns item', async () => {
|
||||
const deleted = { _id: 'ci-1', isDeleted: true };
|
||||
mockFindOneAndUpdate.mockResolvedValue(deleted);
|
||||
|
||||
const result = await repo.softDelete('ci-1', 'hh1');
|
||||
|
||||
expect(result).toEqual(deleted);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discard', () => {
|
||||
it('zeros quantity, marks depleted and deleted', async () => {
|
||||
const discarded = { _id: 'ci-1', quantity: 0, status: 'depleted', isDeleted: true };
|
||||
mockFindOneAndUpdate.mockResolvedValue(discarded);
|
||||
|
||||
const result = await repo.discard('ci-1', 'hh1');
|
||||
|
||||
expect(result).toEqual(discarded);
|
||||
});
|
||||
|
||||
it('returns null when item not found', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue(null);
|
||||
|
||||
const result = await repo.discard('ci-missing', 'hh1');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findActiveByMedicineForFEFO', () => {
|
||||
it('returns active items sorted by expiration date', async () => {
|
||||
const items = [
|
||||
{ _id: 'ci-1', quantity: 10, expirationDate: new Date('2025-06-01') },
|
||||
{ _id: 'ci-2', quantity: 20, expirationDate: new Date('2025-12-01') },
|
||||
];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findActiveByMedicineForFEFO('hh1', 'med-1');
|
||||
|
||||
expect(result).toEqual(items);
|
||||
});
|
||||
|
||||
it('returns empty array when no active items exist', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
const result = await repo.findActiveByMedicineForFEFO('hh1', 'med-1');
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
474
packages/api/tests/modules/cabinet/cabinet.routes.test.ts
Normal file
474
packages/api/tests/modules/cabinet/cabinet.routes.test.ts
Normal file
|
|
@ -0,0 +1,474 @@
|
|||
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';
|
||||
import { DosageUnit, MedicineForm, StrengthUnit, CabinetItemStatus } from '@meshitrack/shared';
|
||||
|
||||
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 {
|
||||
mockFindByHousehold,
|
||||
mockFindById,
|
||||
mockGetAggregateSummary,
|
||||
mockCreate,
|
||||
mockUpdate,
|
||||
mockAdjustQuantity,
|
||||
mockFindExpiringSoon,
|
||||
mockSoftDelete,
|
||||
mockCountByMedicineId,
|
||||
mockDiscard,
|
||||
mockFindActiveByMedicineForFEFO,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFindByHousehold: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
mockGetAggregateSummary: vi.fn(),
|
||||
mockCreate: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockAdjustQuantity: vi.fn(),
|
||||
mockFindExpiringSoon: vi.fn(),
|
||||
mockSoftDelete: vi.fn(),
|
||||
mockCountByMedicineId: vi.fn(),
|
||||
mockDiscard: vi.fn(),
|
||||
mockFindActiveByMedicineForFEFO: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/cabinet/cabinet.repository.js', () => ({
|
||||
CabinetRepository: class {
|
||||
findByHousehold = mockFindByHousehold;
|
||||
findById = mockFindById;
|
||||
getAggregateSummary = mockGetAggregateSummary;
|
||||
create = mockCreate;
|
||||
update = mockUpdate;
|
||||
adjustQuantity = mockAdjustQuantity;
|
||||
findExpiringSoon = mockFindExpiringSoon;
|
||||
softDelete = mockSoftDelete;
|
||||
countByMedicineId = mockCountByMedicineId;
|
||||
discard = mockDiscard;
|
||||
findActiveByMedicineForFEFO = mockFindActiveByMedicineForFEFO;
|
||||
},
|
||||
}));
|
||||
|
||||
const { mockMedicineFindById } = vi.hoisted(() => ({
|
||||
mockMedicineFindById: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/medicines/medicines.repository.js', () => ({
|
||||
MedicinesRepository: class {
|
||||
findById = mockMedicineFindById;
|
||||
findByHousehold = vi.fn();
|
||||
findDuplicate = vi.fn();
|
||||
create = vi.fn();
|
||||
update = vi.fn();
|
||||
softDelete = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
const { mockProductFindById } = vi.hoisted(() => ({
|
||||
mockProductFindById: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/medicine-products/medicine-products.repository.js', () => ({
|
||||
MedicineProductsRepository: class {
|
||||
findById = mockProductFindById;
|
||||
findByMedicine = vi.fn();
|
||||
create = vi.fn();
|
||||
update = vi.fn();
|
||||
softDelete = vi.fn();
|
||||
countByMedicineId = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/medicine-products/medicine-products.service.js', () => ({
|
||||
MedicineProductsService: class {
|
||||
listByMedicine = vi.fn();
|
||||
getById = vi.fn();
|
||||
create = vi.fn();
|
||||
update = vi.fn();
|
||||
delete = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/medicines/medicines.service.js', () => ({
|
||||
MedicinesService: class {
|
||||
list = vi.fn();
|
||||
getById = vi.fn();
|
||||
create = vi.fn();
|
||||
update = vi.fn();
|
||||
delete = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/cabinet-events/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('../../../src/modules/cabinet-events/cabinet-events.service.js', () => ({
|
||||
CabinetEventsService: class {
|
||||
logEvent = vi.fn();
|
||||
logEvents = vi.fn();
|
||||
listEvents = vi.fn();
|
||||
getEventsByItem = vi.fn();
|
||||
getSpendingSummary = vi.fn();
|
||||
getAvgUnitPrices = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/users/users.repository.js', () => ({
|
||||
UsersRepository: class {
|
||||
findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
},
|
||||
}));
|
||||
|
||||
import authPlugin from '../../../src/plugins/auth.plugin.js';
|
||||
import householdPlugin from '../../../src/plugins/household.plugin.js';
|
||||
import usersRoutes from '../../../src/modules/users/users.routes.js';
|
||||
import medicinesRoutes from '../../../src/modules/medicines/medicines.routes.js';
|
||||
import medicineProductsRoutes from '../../../src/modules/medicine-products/medicine-products.routes.js';
|
||||
import cabinetEventsRoutes from '../../../src/modules/cabinet-events/cabinet-events.routes.js';
|
||||
import cabinetRoutes from '../../../src/modules/cabinet/cabinet.routes.js';
|
||||
|
||||
function makeFakeCabinetItem(overrides = {}) {
|
||||
return {
|
||||
_id: 'ci-1',
|
||||
householdId: 'hh1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
medicineStrength: 500,
|
||||
medicineStrengthUnit: StrengthUnit.MG,
|
||||
medicineForm: MedicineForm.TABLET,
|
||||
quantity: 30,
|
||||
unit: DosageUnit.TABLET,
|
||||
status: CabinetItemStatus.ACTIVE,
|
||||
createdBy: 'kc-1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('cabinet.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(medicinesRoutes);
|
||||
await instance.register(medicineProductsRoutes);
|
||||
await instance.register(cabinetEventsRoutes);
|
||||
await instance.register(cabinetRoutes);
|
||||
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', () => {
|
||||
it('returns paginated list', async () => {
|
||||
const item = makeFakeCabinetItem();
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [item],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet',
|
||||
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.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('handles ObjectId and Date objects in response', async () => {
|
||||
const item = makeFakeCabinetItem({
|
||||
_id: { toString: () => 'ci-obj' },
|
||||
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
|
||||
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
|
||||
expirationDate: new Date('2026-06-01T00:00:00.000Z'),
|
||||
notes: 'Main supply',
|
||||
medicineProductId: 'prod-1',
|
||||
medicineProductBrand: 'Glucophage',
|
||||
});
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [item],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0]._id).toBe('ci-obj');
|
||||
expect(body.data[0].expirationDate).toBe('2026-06-01T00:00:00.000Z');
|
||||
expect(body.data[0].medicineProductBrand).toBe('Glucophage');
|
||||
});
|
||||
|
||||
it('handles string dates in response', async () => {
|
||||
const item = makeFakeCabinetItem({
|
||||
expirationDate: '2026-12-31T00:00:00.000Z',
|
||||
createdAt: new Date('2024-01-01T00:00:00.000Z'),
|
||||
updatedAt: new Date('2024-01-02T00:00:00.000Z'),
|
||||
});
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [item],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].expirationDate).toBe('2026-12-31T00:00:00.000Z');
|
||||
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('includes optional purchase and store fields when present', async () => {
|
||||
const item = makeFakeCabinetItem({
|
||||
concentration: 5.0,
|
||||
concentrationUnit: 'mg/mL',
|
||||
purchaseDate: new Date('2024-03-01T00:00:00.000Z'),
|
||||
unitPrice: 1.5,
|
||||
totalPrice: 45.0,
|
||||
currency: 'USD',
|
||||
storeId: 'store-1',
|
||||
storeName: 'Pharmacy Plus',
|
||||
});
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [item],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].concentration).toBe(5.0);
|
||||
expect(body.data[0].concentrationUnit).toBe('mg/mL');
|
||||
expect(body.data[0].purchaseDate).toBe('2024-03-01T00:00:00.000Z');
|
||||
expect(body.data[0].unitPrice).toBe(1.5);
|
||||
expect(body.data[0].totalPrice).toBe(45.0);
|
||||
expect(body.data[0].currency).toBe('USD');
|
||||
expect(body.data[0].storeId).toBe('store-1');
|
||||
expect(body.data[0].storeName).toBe('Pharmacy Plus');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/cabinet/summary', () => {
|
||||
it('returns aggregate summary', async () => {
|
||||
mockGetAggregateSummary.mockResolvedValue([
|
||||
{
|
||||
_id: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
medicineStrength: 500,
|
||||
medicineStrengthUnit: 'mg',
|
||||
medicineForm: 'tablet',
|
||||
totalQuantity: 60,
|
||||
unit: 'tablet',
|
||||
earliestExpiry: new Date('2026-06-01T00:00:00.000Z'),
|
||||
itemCount: 2,
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet/summary',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].totalQuantity).toBe(60);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/cabinet/expiring-soon', () => {
|
||||
it('returns items expiring within N days', async () => {
|
||||
mockFindExpiringSoon.mockResolvedValue([makeFakeCabinetItem()]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet/expiring-soon?days=30',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/cabinet/:id', () => {
|
||||
it('returns a cabinet item', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeCabinetItem());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet/ci-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().quantity).toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/cabinet', () => {
|
||||
it('creates a cabinet item', async () => {
|
||||
mockMedicineFindById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Metformin',
|
||||
strength: 500,
|
||||
strengthUnit: 'mg',
|
||||
form: 'tablet',
|
||||
});
|
||||
mockCreate.mockResolvedValue(makeFakeCabinetItem());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/cabinet',
|
||||
headers: authHeaders,
|
||||
payload: {
|
||||
medicineId: 'med-1',
|
||||
quantity: 30,
|
||||
unit: DosageUnit.TABLET,
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().medicineName).toBe('Metformin');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:householdId/cabinet/:id', () => {
|
||||
it('updates a cabinet item', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeCabinetItem());
|
||||
mockUpdate.mockResolvedValue(makeFakeCabinetItem({ quantity: 25 }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/cabinet/ci-1',
|
||||
headers: authHeaders,
|
||||
payload: { quantity: 25 },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().quantity).toBe(25);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/cabinet/:id/adjust', () => {
|
||||
it('adjusts quantity', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeCabinetItem({ quantity: 30 }));
|
||||
mockAdjustQuantity.mockResolvedValue(makeFakeCabinetItem({ quantity: 27 }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/cabinet/ci-1/adjust',
|
||||
headers: authHeaders,
|
||||
payload: { delta: -3 },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().quantity).toBe(27);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/households/:householdId/cabinet/:id', () => {
|
||||
it('soft deletes a cabinet item', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeCabinetItem());
|
||||
mockSoftDelete.mockResolvedValue(makeFakeCabinetItem({ isDeleted: true }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/hh1/cabinet/ci-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/cabinet/:id/discard', () => {
|
||||
it('discards a cabinet item', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeCabinetItem({ quantity: 20 }));
|
||||
mockDiscard.mockResolvedValue(makeFakeCabinetItem({ quantity: 0, isDeleted: true }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/cabinet/ci-1/discard',
|
||||
headers: authHeaders,
|
||||
payload: { reason: 'expired' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().quantity).toBe(0);
|
||||
});
|
||||
|
||||
it('returns 400 for missing reason', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/cabinet/ci-1/discard',
|
||||
headers: authHeaders,
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
});
|
||||
500
packages/api/tests/modules/cabinet/cabinet.service.test.ts
Normal file
500
packages/api/tests/modules/cabinet/cabinet.service.test.ts
Normal file
|
|
@ -0,0 +1,500 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { CabinetService } from '../../../src/modules/cabinet/cabinet.service.js';
|
||||
import { CabinetEventType, CabinetEventSourceType } from '@meshitrack/shared';
|
||||
|
||||
describe(CabinetService.name, () => {
|
||||
const mockCabinetRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
getAggregateSummary: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
adjustQuantity: vi.fn(),
|
||||
findExpiringSoon: vi.fn(),
|
||||
softDelete: vi.fn(),
|
||||
countByMedicineId: vi.fn(),
|
||||
discard: vi.fn(),
|
||||
findActiveByMedicineForFEFO: vi.fn(),
|
||||
};
|
||||
|
||||
const mockMedicinesRepo = {
|
||||
findById: vi.fn(),
|
||||
findByHousehold: vi.fn(),
|
||||
findDuplicate: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
softDelete: vi.fn(),
|
||||
};
|
||||
|
||||
const mockProductsRepo = {
|
||||
findById: vi.fn(),
|
||||
findByMedicine: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
softDelete: vi.fn(),
|
||||
countByMedicineId: vi.fn(),
|
||||
};
|
||||
|
||||
const mockCabinetEventsService = {
|
||||
logEvent: vi.fn(),
|
||||
logEvents: vi.fn(),
|
||||
listEvents: vi.fn(),
|
||||
getEventsByItem: vi.fn(),
|
||||
getSpendingSummary: vi.fn(),
|
||||
getAvgUnitPrices: vi.fn(),
|
||||
};
|
||||
|
||||
let service: CabinetService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new CabinetService({
|
||||
cabinetRepository: mockCabinetRepo as never,
|
||||
medicinesRepository: mockMedicinesRepo as never,
|
||||
medicineProductsRepository: mockProductsRepo as never,
|
||||
cabinetEventsService: mockCabinetEventsService as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const result = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockCabinetRepo.findByHousehold.mockResolvedValue(result);
|
||||
|
||||
const response = await service.list('hh1', { limit: 20 });
|
||||
|
||||
expect(response).toEqual(result);
|
||||
expect(mockCabinetRepo.findByHousehold).toHaveBeenCalledWith('hh1', { limit: 20 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns item when found', async () => {
|
||||
const item = { _id: 'ci-1', quantity: 30 };
|
||||
mockCabinetRepo.findById.mockResolvedValue(item);
|
||||
|
||||
const result = await service.getById('ci-1', 'hh1');
|
||||
|
||||
expect(result).toEqual(item);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.getById('ci-missing', 'hh1')).rejects.toThrow('Cabinet item not found');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSummary', () => {
|
||||
it('returns aggregated summary with formatted dates', async () => {
|
||||
const expiryDate = new Date('2026-06-01T00:00:00.000Z');
|
||||
mockCabinetRepo.getAggregateSummary.mockResolvedValue([
|
||||
{
|
||||
_id: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
medicineStrength: 500,
|
||||
medicineStrengthUnit: 'mg',
|
||||
medicineForm: 'tablet',
|
||||
totalQuantity: 60,
|
||||
unit: 'tablet',
|
||||
earliestExpiry: expiryDate,
|
||||
itemCount: 2,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.getSummary('hh1');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].medicineId).toBe('med-1');
|
||||
expect(result[0].earliestExpiry).toBe('2026-06-01T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('handles null expiry dates', async () => {
|
||||
mockCabinetRepo.getAggregateSummary.mockResolvedValue([
|
||||
{
|
||||
_id: 'med-1',
|
||||
medicineName: 'Test',
|
||||
medicineStrength: 10,
|
||||
medicineStrengthUnit: 'mg',
|
||||
medicineForm: 'tablet',
|
||||
totalQuantity: 30,
|
||||
unit: 'tablet',
|
||||
earliestExpiry: null,
|
||||
itemCount: 1,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.getSummary('hh1');
|
||||
|
||||
expect(result[0].earliestExpiry).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('addItem', () => {
|
||||
const createInput = {
|
||||
medicineId: 'med-1',
|
||||
quantity: 30,
|
||||
unit: 'tablet' as const,
|
||||
};
|
||||
|
||||
it('creates item with denormalized medicine fields', async () => {
|
||||
mockMedicinesRepo.findById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Metformin',
|
||||
strength: 500,
|
||||
strengthUnit: 'mg',
|
||||
form: 'tablet',
|
||||
});
|
||||
const created = { _id: 'ci-1', ...createInput, medicineName: 'Metformin' };
|
||||
mockCabinetRepo.create.mockResolvedValue(created);
|
||||
|
||||
const result = await service.addItem(createInput, 'hh1', 'user-1');
|
||||
|
||||
expect(result).toEqual(created);
|
||||
expect(mockCabinetRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
medicineName: 'Metformin',
|
||||
medicineStrength: 500,
|
||||
medicineStrengthUnit: 'mg',
|
||||
medicineForm: 'tablet',
|
||||
}),
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('logs PURCHASED event after creation', async () => {
|
||||
mockMedicinesRepo.findById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Metformin',
|
||||
strength: 500,
|
||||
strengthUnit: 'mg',
|
||||
form: 'tablet',
|
||||
});
|
||||
mockCabinetRepo.create.mockResolvedValue({ _id: 'ci-1' });
|
||||
|
||||
await service.addItem(createInput, 'hh1', 'user-1');
|
||||
|
||||
expect(mockCabinetEventsService.logEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
cabinetItemId: 'ci-1',
|
||||
medicineId: 'med-1',
|
||||
eventType: CabinetEventType.PURCHASED,
|
||||
quantity: 30,
|
||||
quantityBefore: 0,
|
||||
quantityAfter: 30,
|
||||
sourceType: CabinetEventSourceType.MANUAL,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when medicine not found', async () => {
|
||||
mockMedicinesRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.addItem(createInput, 'hh1', 'user-1')).rejects.toThrow(
|
||||
'Medicine not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('denormalizes product brand when medicineProductId given', async () => {
|
||||
mockMedicinesRepo.findById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Metformin',
|
||||
strength: 500,
|
||||
strengthUnit: 'mg',
|
||||
form: 'tablet',
|
||||
});
|
||||
mockProductsRepo.findById.mockResolvedValue({
|
||||
_id: 'prod-1',
|
||||
brand: 'Glucophage',
|
||||
});
|
||||
mockCabinetRepo.create.mockResolvedValue({ _id: 'ci-1' });
|
||||
|
||||
await service.addItem({ ...createInput, medicineProductId: 'prod-1' }, 'hh1', 'user-1');
|
||||
|
||||
expect(mockCabinetRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ medicineProductBrand: 'Glucophage' }),
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when product not found', async () => {
|
||||
mockMedicinesRepo.findById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Metformin',
|
||||
strength: 500,
|
||||
strengthUnit: 'mg',
|
||||
form: 'tablet',
|
||||
});
|
||||
mockProductsRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
service.addItem({ ...createInput, medicineProductId: 'prod-missing' }, 'hh1', 'user-1'),
|
||||
).rejects.toThrow('Medicine product not found');
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates and returns item', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 30,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
const updated = { _id: 'ci-1', quantity: 25 };
|
||||
mockCabinetRepo.update.mockResolvedValue(updated);
|
||||
|
||||
const result = await service.update('ci-1', 'hh1', { quantity: 25 }, 'user-1');
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('logs ADJUSTED event when quantity changes', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 30,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.update.mockResolvedValue({ _id: 'ci-1', quantity: 25 });
|
||||
|
||||
await service.update('ci-1', 'hh1', { quantity: 25 }, 'user-1');
|
||||
|
||||
expect(mockCabinetEventsService.logEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventType: CabinetEventType.ADJUSTED,
|
||||
quantity: -5,
|
||||
quantityBefore: 30,
|
||||
quantityAfter: 25,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not log event when quantity unchanged', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 30,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.update.mockResolvedValue({ _id: 'ci-1', quantity: 30 });
|
||||
|
||||
await service.update('ci-1', 'hh1', { notes: 'updated' }, 'user-1');
|
||||
|
||||
expect(mockCabinetEventsService.logEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws NotFoundError when item does not exist', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.update('ci-missing', 'hh1', { quantity: 25 }, 'user-1')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when update returns null', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 30,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.update.mockResolvedValue(null);
|
||||
|
||||
await expect(service.update('ci-1', 'hh1', { quantity: 25 }, 'user-1')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('adjustQuantity', () => {
|
||||
it('adjusts quantity and returns item', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 30,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
const updated = { _id: 'ci-1', quantity: 27 };
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue(updated);
|
||||
|
||||
const result = await service.adjustQuantity('ci-1', 'hh1', -3, 'user-1');
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('logs ADJUSTED event', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 30,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 27 });
|
||||
|
||||
await service.adjustQuantity('ci-1', 'hh1', -3, 'user-1', 'took some');
|
||||
|
||||
expect(mockCabinetEventsService.logEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventType: CabinetEventType.ADJUSTED,
|
||||
quantity: -3,
|
||||
quantityBefore: 30,
|
||||
quantityAfter: 27,
|
||||
reason: 'took some',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws BadRequestError when delta is 0', async () => {
|
||||
await expect(service.adjustQuantity('ci-1', 'hh1', 0, 'user-1')).rejects.toThrow(
|
||||
'Delta must be non-zero',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when item does not exist', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.adjustQuantity('ci-missing', 'hh1', 5, 'user-1')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when adjust returns null', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 30,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue(null);
|
||||
|
||||
await expect(service.adjustQuantity('ci-1', 'hh1', 5, 'user-1')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getExpiringSoon', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const items = [{ _id: 'ci-1' }];
|
||||
mockCabinetRepo.findExpiringSoon.mockResolvedValue(items);
|
||||
|
||||
const result = await service.getExpiringSoon('hh1', 30);
|
||||
|
||||
expect(result).toEqual(items);
|
||||
expect(mockCabinetRepo.findExpiringSoon).toHaveBeenCalledWith('hh1', 30);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('soft deletes item and logs DELETED event', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 10,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.softDelete.mockResolvedValue({ _id: 'ci-1', isDeleted: true });
|
||||
|
||||
const result = await service.delete('ci-1', 'hh1', 'user-1');
|
||||
|
||||
expect(result.isDeleted).toBe(true);
|
||||
expect(mockCabinetEventsService.logEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventType: CabinetEventType.DELETED,
|
||||
quantity: -10,
|
||||
quantityBefore: 10,
|
||||
quantityAfter: 0,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when item does not exist', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.delete('ci-missing', 'hh1', 'user-1')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when softDelete returns null', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 5,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.softDelete.mockResolvedValue(null);
|
||||
|
||||
await expect(service.delete('ci-1', 'hh1', 'user-1')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discard', () => {
|
||||
it('discards item and logs DISCARDED event', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 20,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.discard.mockResolvedValue({ _id: 'ci-1', quantity: 0, isDeleted: true });
|
||||
|
||||
const result = await service.discard('ci-1', 'hh1', 'user-1', 'expired', 'smelled off');
|
||||
|
||||
expect(result.quantity).toBe(0);
|
||||
expect(result.isDeleted).toBe(true);
|
||||
expect(mockCabinetEventsService.logEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventType: CabinetEventType.DISCARDED,
|
||||
quantity: -20,
|
||||
quantityBefore: 20,
|
||||
quantityAfter: 0,
|
||||
reason: 'expired',
|
||||
notes: 'smelled off',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws BadRequestError when quantity is zero', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 0,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
|
||||
await expect(service.discard('ci-1', 'hh1', 'user-1', 'expired')).rejects.toThrow(
|
||||
'Cannot discard an item with zero quantity',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when item does not exist', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.discard('ci-missing', 'hh1', 'user-1', 'expired')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when discard returns null', async () => {
|
||||
mockCabinetRepo.findById.mockResolvedValue({
|
||||
_id: 'ci-1',
|
||||
quantity: 10,
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Test',
|
||||
});
|
||||
mockCabinetRepo.discard.mockResolvedValue(null);
|
||||
|
||||
await expect(service.discard('ci-1', 'hh1', 'user-1', 'expired')).rejects.toThrow(
|
||||
'Cabinet item not found',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue