Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
|
|
@ -0,0 +1,186 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { mockFind, mockFindOne, mockFindOneAndUpdate, mockSave } = vi.hoisted(() => ({
|
||||
mockFind: vi.fn(),
|
||||
mockFindOne: vi.fn(),
|
||||
mockFindOneAndUpdate: vi.fn(),
|
||||
mockSave: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/schemas/organizer-fill.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,
|
||||
});
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
return { OrganizerFillModel: FakeModel };
|
||||
});
|
||||
|
||||
import { OrganizerRepository } from '../../../src/modules/organizer/organizer.repository.js';
|
||||
|
||||
describe(OrganizerRepository.name, () => {
|
||||
let repo: OrganizerRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new OrganizerRepository();
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('returns paginated items', async () => {
|
||||
const items = [{ _id: 'fill-1', regimenName: 'Morning' }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', 'user-1', { limit: 20 });
|
||||
|
||||
expect(result.data).toEqual(items);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('handles cursor-based pagination', async () => {
|
||||
const items = [{ _id: 'fill-2', regimenName: 'Evening' }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const cursor = Buffer.from('fill-1').toString('base64');
|
||||
const result = await repo.findByHousehold('hh1', 'user-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: `fill-${i}`,
|
||||
regimenName: `R${i}`,
|
||||
}));
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', 'user-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.findByHousehold('hh1', 'user-1', { limit: 20 });
|
||||
|
||||
expect(result.pagination.cursor).toBeNull();
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('filters by regimenId', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', 'user-1', { regimenId: 'reg-1', limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters by status', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', 'user-1', { status: 'completed' as never, limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns cursor as null when hasMore is false even with data', async () => {
|
||||
const items = [{ _id: 'fill-1', regimenName: 'Morning' }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', 'user-1', { limit: 20 });
|
||||
|
||||
expect(result.pagination.cursor).toBeNull();
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('returns fill by id and householdId', async () => {
|
||||
const fill = { _id: 'fill-1', householdId: 'hh1', regimenName: 'Morning' };
|
||||
mockFindOne.mockResolvedValue(fill);
|
||||
|
||||
const result = await repo.findById('fill-1', 'hh1');
|
||||
|
||||
expect(result).toEqual(fill);
|
||||
});
|
||||
|
||||
it('returns null when not found', async () => {
|
||||
mockFindOne.mockResolvedValue(null);
|
||||
|
||||
const result = await repo.findById('fill-missing', 'hh1');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates and returns organizer fill', async () => {
|
||||
const data = {
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
regimenId: 'reg-1',
|
||||
regimenName: 'Morning',
|
||||
numberOfDays: 7,
|
||||
fillDate: new Date(),
|
||||
items: [],
|
||||
status: 'completed' as const,
|
||||
};
|
||||
mockSave.mockImplementation(function (this: { toObject: () => unknown }) {
|
||||
return Promise.resolve(this);
|
||||
});
|
||||
|
||||
const result = await repo.create(data as never);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateStatus', () => {
|
||||
it('updates and returns fill with new status', async () => {
|
||||
const updated = { _id: 'fill-1', status: 'reversed' };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.updateStatus('fill-1', 'hh1', 'reversed' as never);
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('returns null when fill not found', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue(null);
|
||||
|
||||
const result = await repo.updateStatus('fill-missing', 'hh1', 'reversed' as never);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
485
packages/api/tests/modules/organizer/organizer.routes.test.ts
Normal file
485
packages/api/tests/modules/organizer/organizer.routes.test.ts
Normal file
|
|
@ -0,0 +1,485 @@
|
|||
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 { OrganizerFillStatus } 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 { mockListFills, mockGetFillById, mockPreview, mockFill, mockUndoFill } = vi.hoisted(() => ({
|
||||
mockListFills: vi.fn(),
|
||||
mockGetFillById: vi.fn(),
|
||||
mockPreview: vi.fn(),
|
||||
mockFill: vi.fn(),
|
||||
mockUndoFill: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/organizer/organizer.repository.js', () => ({
|
||||
OrganizerRepository: class {
|
||||
create = vi.fn();
|
||||
update = vi.fn();
|
||||
findById = vi.fn();
|
||||
findByHousehold = vi.fn();
|
||||
updateStatus = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/organizer/organizer.service.js', () => ({
|
||||
OrganizerService: class {
|
||||
listFills = mockListFills;
|
||||
getFillById = mockGetFillById;
|
||||
preview = mockPreview;
|
||||
fill = mockFill;
|
||||
undoFill = mockUndoFill;
|
||||
},
|
||||
}));
|
||||
|
||||
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 organizerRoutes from '../../../src/modules/organizer/organizer.routes.js';
|
||||
|
||||
function makeFakeFill(overrides = {}) {
|
||||
return {
|
||||
_id: 'fill-1',
|
||||
householdId: 'hh1',
|
||||
userId: 'kc-1',
|
||||
regimenId: 'reg-1',
|
||||
regimenName: 'Daily Medications',
|
||||
numberOfDays: 7,
|
||||
fillDate: '2024-06-01T00:00:00.000Z',
|
||||
items: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
quantityNeeded: 7,
|
||||
quantityTaken: 7,
|
||||
wasShort: false,
|
||||
shortage: 0,
|
||||
deductions: [{ cabinetItemId: 'ci-1', quantityTaken: 7 }],
|
||||
},
|
||||
],
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
notes: null,
|
||||
createdAt: '2024-06-01T00:00:00.000Z',
|
||||
updatedAt: '2024-06-01T00:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFakePreview(overrides = {}) {
|
||||
return {
|
||||
regimenName: 'Daily Medications',
|
||||
numberOfDays: 7,
|
||||
items: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
quantityNeeded: 7,
|
||||
quantityAvailable: 30,
|
||||
isShort: false,
|
||||
shortage: 0,
|
||||
cabinetBreakdown: [
|
||||
{
|
||||
cabinetItemId: 'ci-1',
|
||||
expirationDate: '2025-12-31T00:00:00.000Z',
|
||||
quantityToTake: 7,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
canFillCompletely: true,
|
||||
hasShortages: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('organizer.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(organizerRoutes);
|
||||
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/organizer/fills', () => {
|
||||
it('returns paginated fill list', async () => {
|
||||
const fill = makeFakeFill();
|
||||
mockListFills.mockResolvedValue({
|
||||
data: [fill],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/organizer/fills',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].regimenName).toBe('Daily Medications');
|
||||
expect(body.data[0].status).toBe(OrganizerFillStatus.COMPLETED);
|
||||
expect(body.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('passes query parameters to service', async () => {
|
||||
mockListFills.mockResolvedValue({
|
||||
data: [],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/organizer/fills?regimenId=reg-1&status=completed&limit=10',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(mockListFills).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
'kc-1',
|
||||
expect.objectContaining({
|
||||
regimenId: 'reg-1',
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
limit: 10,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('handles ObjectId and Date serialization in fill response', async () => {
|
||||
const fill = makeFakeFill({
|
||||
_id: { toString: () => 'fill-obj' },
|
||||
fillDate: new Date('2024-06-01T00:00:00.000Z'),
|
||||
createdAt: { toISOString: () => '2024-06-01T00:00:00.000Z' },
|
||||
updatedAt: new Date('2024-06-02T00:00:00.000Z'),
|
||||
});
|
||||
mockListFills.mockResolvedValue({
|
||||
data: [fill],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/organizer/fills',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0]._id).toBe('fill-obj');
|
||||
expect(body.data[0].fillDate).toBe('2024-06-01T00:00:00.000Z');
|
||||
expect(body.data[0].createdAt).toBe('2024-06-01T00:00:00.000Z');
|
||||
expect(body.data[0].updatedAt).toBe('2024-06-02T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('omits notes from response when null', async () => {
|
||||
const fill = makeFakeFill({ notes: null });
|
||||
mockListFills.mockResolvedValue({
|
||||
data: [fill],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/organizer/fills',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].notes).toBeUndefined();
|
||||
});
|
||||
|
||||
it('includes notes in response when present', async () => {
|
||||
const fill = makeFakeFill({ notes: 'Refilled before holiday' });
|
||||
mockListFills.mockResolvedValue({
|
||||
data: [fill],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/organizer/fills',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].notes).toBe('Refilled before holiday');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/organizer/fills/:id', () => {
|
||||
it('returns single fill by id', async () => {
|
||||
const fill = makeFakeFill();
|
||||
mockGetFillById.mockResolvedValue(fill);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/organizer/fills/fill-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body._id).toBe('fill-1');
|
||||
expect(body.regimenId).toBe('reg-1');
|
||||
expect(body.items).toHaveLength(1);
|
||||
expect(body.items[0].deductions).toHaveLength(1);
|
||||
expect(body.items[0].deductions[0].cabinetItemId).toBe('ci-1');
|
||||
});
|
||||
|
||||
it('passes id and householdId to service correctly', async () => {
|
||||
const fill = makeFakeFill();
|
||||
mockGetFillById.mockResolvedValue(fill);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/organizer/fills/fill-42',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(mockGetFillById).toHaveBeenCalledWith('fill-42', 'hh1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/organizer/preview', () => {
|
||||
it('returns preview result with items and shortage info', async () => {
|
||||
const preview = makeFakePreview();
|
||||
mockPreview.mockResolvedValue(preview);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/preview',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
payload: { regimenId: 'reg-1', numberOfDays: 7 },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.regimenName).toBe('Daily Medications');
|
||||
expect(body.canFillCompletely).toBe(true);
|
||||
expect(body.hasShortages).toBe(false);
|
||||
expect(body.items).toHaveLength(1);
|
||||
expect(body.items[0].medicineName).toBe('Metformin');
|
||||
expect(body.items[0].cabinetBreakdown).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('passes regimenId and numberOfDays to service', async () => {
|
||||
const preview = makeFakePreview();
|
||||
mockPreview.mockResolvedValue(preview);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/preview',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
payload: { regimenId: 'reg-99', numberOfDays: 14 },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(mockPreview).toHaveBeenCalledWith('hh1', 'kc-1', 'reg-99', 14);
|
||||
});
|
||||
|
||||
it('returns preview with hasShortages=true and isShort items', async () => {
|
||||
const preview = makeFakePreview({
|
||||
canFillCompletely: false,
|
||||
hasShortages: true,
|
||||
items: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
quantityNeeded: 14,
|
||||
quantityAvailable: 5,
|
||||
isShort: true,
|
||||
shortage: 9,
|
||||
cabinetBreakdown: [
|
||||
{
|
||||
cabinetItemId: 'ci-1',
|
||||
expirationDate: '2025-12-31T00:00:00.000Z',
|
||||
quantityToTake: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
mockPreview.mockResolvedValue(preview);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/preview',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
payload: { regimenId: 'reg-1', numberOfDays: 14 },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.hasShortages).toBe(true);
|
||||
expect(body.canFillCompletely).toBe(false);
|
||||
expect(body.items[0].isShort).toBe(true);
|
||||
expect(body.items[0].shortage).toBe(9);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/organizer/fill', () => {
|
||||
it('creates fill and returns 201 with COMPLETED status', async () => {
|
||||
const fill = makeFakeFill({ status: OrganizerFillStatus.COMPLETED });
|
||||
mockFill.mockResolvedValue(fill);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/fill',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
payload: { regimenId: 'reg-1', numberOfDays: 7, allowPartial: false },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body._id).toBe('fill-1');
|
||||
expect(body.status).toBe(OrganizerFillStatus.COMPLETED);
|
||||
});
|
||||
|
||||
it('returns 201 with PARTIAL status when wasShort items exist', async () => {
|
||||
const fill = makeFakeFill({
|
||||
status: OrganizerFillStatus.PARTIAL,
|
||||
items: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
quantityNeeded: 14,
|
||||
quantityTaken: 5,
|
||||
wasShort: true,
|
||||
shortage: 9,
|
||||
deductions: [{ cabinetItemId: 'ci-1', quantityTaken: 5 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
mockFill.mockResolvedValue(fill);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/fill',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
payload: { regimenId: 'reg-1', numberOfDays: 14, allowPartial: true },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.status).toBe(OrganizerFillStatus.PARTIAL);
|
||||
expect(body.items[0].wasShort).toBe(true);
|
||||
expect(body.items[0].shortage).toBe(9);
|
||||
});
|
||||
|
||||
it('returns 400 on invalid body (missing regimenId)', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/fill',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
payload: { numberOfDays: 7, allowPartial: false },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('passes correct args (householdId, userId, body) to service', async () => {
|
||||
const fill = makeFakeFill();
|
||||
mockFill.mockResolvedValue(fill);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/fill',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
payload: { regimenId: 'reg-1', numberOfDays: 7, allowPartial: false, notes: 'test note' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(mockFill).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
'kc-1',
|
||||
expect.objectContaining({
|
||||
regimenId: 'reg-1',
|
||||
numberOfDays: 7,
|
||||
allowPartial: false,
|
||||
notes: 'test note',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/organizer/fills/:id/undo', () => {
|
||||
it('reverses fill and returns 200 with REVERSED status', async () => {
|
||||
const fill = makeFakeFill({ status: OrganizerFillStatus.REVERSED });
|
||||
mockUndoFill.mockResolvedValue(fill);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/fills/fill-1/undo',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body._id).toBe('fill-1');
|
||||
expect(body.status).toBe(OrganizerFillStatus.REVERSED);
|
||||
});
|
||||
|
||||
it('passes correct args to service (householdId first, then id, then userId)', async () => {
|
||||
const fill = makeFakeFill({ status: OrganizerFillStatus.REVERSED });
|
||||
mockUndoFill.mockResolvedValue(fill);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/organizer/fills/fill-42/undo',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(mockUndoFill).toHaveBeenCalledWith('hh1', 'fill-42', 'kc-1');
|
||||
});
|
||||
});
|
||||
});
|
||||
649
packages/api/tests/modules/organizer/organizer.service.test.ts
Normal file
649
packages/api/tests/modules/organizer/organizer.service.test.ts
Normal file
|
|
@ -0,0 +1,649 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import {
|
||||
CabinetEventType,
|
||||
CabinetEventSourceType,
|
||||
OrganizerFillStatus,
|
||||
DosageFrequency,
|
||||
} from '@meshitrack/shared';
|
||||
|
||||
const { mockSession } = vi.hoisted(() => ({
|
||||
mockSession: {
|
||||
startTransaction: vi.fn(),
|
||||
commitTransaction: vi.fn(),
|
||||
abortTransaction: vi.fn(),
|
||||
endSession: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('mongoose', () => {
|
||||
return { default: { startSession: vi.fn().mockResolvedValue(mockSession) } };
|
||||
});
|
||||
|
||||
import { OrganizerService } from '../../../src/modules/organizer/organizer.service.js';
|
||||
|
||||
describe(OrganizerService.name, () => {
|
||||
const mockOrganizerRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
create: vi.fn(),
|
||||
updateStatus: vi.fn(),
|
||||
};
|
||||
|
||||
const mockRegimensService = {
|
||||
list: vi.fn(),
|
||||
getById: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
getActiveByUser: vi.fn(),
|
||||
calculateBurnRates: vi.fn(),
|
||||
};
|
||||
|
||||
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 mockCabinetEventsService = {
|
||||
logEvent: vi.fn(),
|
||||
logEvents: vi.fn(),
|
||||
listEvents: vi.fn(),
|
||||
getEventsByItem: vi.fn(),
|
||||
getSpendingSummary: vi.fn(),
|
||||
getAvgUnitPrices: vi.fn(),
|
||||
};
|
||||
|
||||
let service: OrganizerService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new OrganizerService({
|
||||
organizerRepository: mockOrganizerRepo as never,
|
||||
regimensService: mockRegimensService as never,
|
||||
cabinetRepository: mockCabinetRepo as never,
|
||||
cabinetEventsService: mockCabinetEventsService as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('listFills', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const result = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockOrganizerRepo.findByHousehold.mockResolvedValue(result);
|
||||
|
||||
const response = await service.listFills('hh1', 'user-1', { limit: 20 });
|
||||
|
||||
expect(response).toEqual(result);
|
||||
expect(mockOrganizerRepo.findByHousehold).toHaveBeenCalledWith('hh1', 'user-1', {
|
||||
limit: 20,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFillById', () => {
|
||||
it('returns fill when found', async () => {
|
||||
const fill = { _id: 'fill-1', regimenName: 'Morning' };
|
||||
mockOrganizerRepo.findById.mockResolvedValue(fill);
|
||||
|
||||
const result = await service.getFillById('fill-1', 'hh1');
|
||||
|
||||
expect(result).toEqual(fill);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.getFillById('fill-missing', 'hh1')).rejects.toThrow(
|
||||
'Organizer fill not found',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('preview', () => {
|
||||
const makeRegimen = (overrides = {}) => ({
|
||||
_id: 'reg-1',
|
||||
name: 'Morning Routine',
|
||||
isActive: true,
|
||||
medications: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
dosage: 1,
|
||||
frequency: DosageFrequency.DAILY,
|
||||
customFrequencyPerDay: null,
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it('returns preview with no shortages when stock is sufficient', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 30, expirationDate: new Date('2027-01-01') },
|
||||
]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
expect(result.regimenName).toBe('Morning Routine');
|
||||
expect(result.numberOfDays).toBe(7);
|
||||
expect(result.canFillCompletely).toBe(true);
|
||||
expect(result.hasShortages).toBe(false);
|
||||
expect(result.items).toHaveLength(1);
|
||||
expect(result.items[0].medicineId).toBe('med-1');
|
||||
expect(result.items[0].quantityNeeded).toBe(7);
|
||||
expect(result.items[0].quantityAvailable).toBe(30);
|
||||
expect(result.items[0].isShort).toBe(false);
|
||||
expect(result.items[0].shortage).toBe(0);
|
||||
expect(result.items[0].cabinetBreakdown).toHaveLength(1);
|
||||
expect(result.items[0].cabinetBreakdown[0].quantityToTake).toBe(7);
|
||||
expect(result.items[0].cabinetBreakdown[0].quantityBefore).toBe(30);
|
||||
});
|
||||
|
||||
it('returns preview with shortages when stock is insufficient', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 3, expirationDate: null },
|
||||
]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
expect(result.canFillCompletely).toBe(false);
|
||||
expect(result.hasShortages).toBe(true);
|
||||
expect(result.items[0].isShort).toBe(true);
|
||||
expect(result.items[0].shortage).toBe(4);
|
||||
expect(result.items[0].quantityAvailable).toBe(3);
|
||||
});
|
||||
|
||||
it('handles FEFO allocation across multiple cabinet items', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 3, expirationDate: new Date('2026-06-01') },
|
||||
{ _id: { toString: () => 'ci-2' }, quantity: 5, expirationDate: new Date('2026-12-01') },
|
||||
]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
expect(result.canFillCompletely).toBe(true);
|
||||
expect(result.items[0].cabinetBreakdown).toHaveLength(2);
|
||||
expect(result.items[0].cabinetBreakdown[0].cabinetItemId).toBe('ci-1');
|
||||
expect(result.items[0].cabinetBreakdown[0].quantityToTake).toBe(3);
|
||||
expect(result.items[0].cabinetBreakdown[1].cabinetItemId).toBe('ci-2');
|
||||
expect(result.items[0].cabinetBreakdown[1].quantityToTake).toBe(4);
|
||||
});
|
||||
|
||||
it('skips AS_NEEDED medications', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(
|
||||
makeRegimen({
|
||||
medications: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
dosage: 1,
|
||||
frequency: DosageFrequency.AS_NEEDED,
|
||||
customFrequencyPerDay: null,
|
||||
},
|
||||
{
|
||||
medicineId: 'med-2',
|
||||
medicineName: 'Ibuprofen',
|
||||
dosage: 2,
|
||||
frequency: DosageFrequency.DAILY,
|
||||
customFrequencyPerDay: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-2' }, quantity: 20, expirationDate: null },
|
||||
]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
expect(result.items).toHaveLength(1);
|
||||
expect(result.items[0].medicineId).toBe('med-2');
|
||||
});
|
||||
|
||||
it('throws BadRequestError when regimen is not active', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen({ isActive: false }));
|
||||
|
||||
await expect(service.preview('hh1', 'user-1', 'reg-1', 7)).rejects.toThrow(
|
||||
'Regimen is not active',
|
||||
);
|
||||
});
|
||||
|
||||
it('handles null expirationDate in cabinet items', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 10, expirationDate: null },
|
||||
]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
expect(result.items[0].cabinetBreakdown[0].expirationDate).toBeNull();
|
||||
});
|
||||
|
||||
it('handles empty cabinet (no items available)', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
expect(result.canFillCompletely).toBe(false);
|
||||
expect(result.hasShortages).toBe(true);
|
||||
expect(result.items[0].quantityAvailable).toBe(0);
|
||||
expect(result.items[0].shortage).toBe(7);
|
||||
expect(result.items[0].cabinetBreakdown).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('uses customFrequencyPerDay when present', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(
|
||||
makeRegimen({
|
||||
medications: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Custom Med',
|
||||
dosage: 2,
|
||||
frequency: DosageFrequency.CUSTOM,
|
||||
customFrequencyPerDay: 3,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 100, expirationDate: null },
|
||||
]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
// dosage(2) * customFrequencyPerDay(3) * numberOfDays(7) = 42
|
||||
expect(result.items[0].quantityNeeded).toBe(42);
|
||||
});
|
||||
|
||||
it('stops taking from cabinet items once remaining is zero', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 7, expirationDate: null },
|
||||
{ _id: { toString: () => 'ci-2' }, quantity: 10, expirationDate: null },
|
||||
]);
|
||||
|
||||
const result = await service.preview('hh1', 'user-1', 'reg-1', 7);
|
||||
|
||||
// Needs 7, first item has 7 -- second item should not be touched
|
||||
expect(result.items[0].cabinetBreakdown).toHaveLength(1);
|
||||
expect(result.items[0].cabinetBreakdown[0].quantityToTake).toBe(7);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fill', () => {
|
||||
const fillInput = {
|
||||
regimenId: 'reg-1',
|
||||
numberOfDays: 7,
|
||||
allowPartial: false,
|
||||
notes: 'Weekly fill',
|
||||
};
|
||||
|
||||
const makeRegimen = () => ({
|
||||
_id: 'reg-1',
|
||||
name: 'Morning Routine',
|
||||
isActive: true,
|
||||
medications: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
dosage: 1,
|
||||
frequency: DosageFrequency.DAILY,
|
||||
customFrequencyPerDay: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
it('executes fill successfully with no shortages', async () => {
|
||||
// preview dependencies
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 30, expirationDate: new Date('2027-01-01') },
|
||||
]);
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 23 });
|
||||
mockOrganizerRepo.create.mockResolvedValue({
|
||||
_id: { toString: () => 'fill-1' },
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
regimenId: 'reg-1',
|
||||
regimenName: 'Morning Routine',
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
const result = await service.fill('hh1', 'user-1', fillInput);
|
||||
|
||||
expect(result.status).toBe(OrganizerFillStatus.COMPLETED);
|
||||
expect(mockSession.startTransaction).toHaveBeenCalled();
|
||||
expect(mockSession.commitTransaction).toHaveBeenCalled();
|
||||
expect(mockSession.endSession).toHaveBeenCalled();
|
||||
expect(mockCabinetRepo.adjustQuantity).toHaveBeenCalledWith('ci-1', 'hh1', -7);
|
||||
expect(mockCabinetEventsService.logEvents).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws BadRequestError when shortages exist and allowPartial is false', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 3, expirationDate: null },
|
||||
]);
|
||||
|
||||
await expect(service.fill('hh1', 'user-1', fillInput)).rejects.toThrow(
|
||||
'Not enough stock to fill completely',
|
||||
);
|
||||
});
|
||||
|
||||
it('allows partial fill when allowPartial is true', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 3, expirationDate: null },
|
||||
]);
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 0 });
|
||||
mockOrganizerRepo.create.mockResolvedValue({
|
||||
_id: { toString: () => 'fill-1' },
|
||||
status: OrganizerFillStatus.PARTIAL,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
const result = await service.fill('hh1', 'user-1', { ...fillInput, allowPartial: true });
|
||||
|
||||
expect(result.status).toBe(OrganizerFillStatus.PARTIAL);
|
||||
expect(mockOrganizerRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
status: OrganizerFillStatus.PARTIAL,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('creates CONSUMED events for each deduction', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 30, expirationDate: null },
|
||||
]);
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 23 });
|
||||
mockOrganizerRepo.create.mockResolvedValue({
|
||||
_id: { toString: () => 'fill-1' },
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
await service.fill('hh1', 'user-1', fillInput);
|
||||
|
||||
const events = mockCabinetEventsService.logEvents.mock.calls[0][0];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
cabinetItemId: 'ci-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
eventType: CabinetEventType.CONSUMED,
|
||||
quantity: -7,
|
||||
quantityBefore: 30,
|
||||
quantityAfter: 23,
|
||||
sourceType: CabinetEventSourceType.ORGANIZER_FILL,
|
||||
sourceId: 'fill-1',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('handles adjustQuantity returning null (skips deduction)', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 30, expirationDate: null },
|
||||
]);
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue(null);
|
||||
mockOrganizerRepo.create.mockResolvedValue({
|
||||
_id: { toString: () => 'fill-1' },
|
||||
status: OrganizerFillStatus.PARTIAL,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
const result = await service.fill('hh1', 'user-1', { ...fillInput, allowPartial: true });
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
// No events logged since adjustQuantity returned null
|
||||
const events = mockCabinetEventsService.logEvents.mock.calls[0][0];
|
||||
expect(events).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('aborts transaction and rethrows on error', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 30, expirationDate: null },
|
||||
]);
|
||||
mockCabinetRepo.adjustQuantity.mockRejectedValue(new Error('DB failure'));
|
||||
|
||||
await expect(service.fill('hh1', 'user-1', fillInput)).rejects.toThrow('DB failure');
|
||||
|
||||
expect(mockSession.abortTransaction).toHaveBeenCalled();
|
||||
expect(mockSession.endSession).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates fill with notes when provided', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 30, expirationDate: null },
|
||||
]);
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 23 });
|
||||
mockOrganizerRepo.create.mockResolvedValue({
|
||||
_id: { toString: () => 'fill-1' },
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
await service.fill('hh1', 'user-1', fillInput);
|
||||
|
||||
expect(mockOrganizerRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
notes: 'Weekly fill',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('sets COMPLETED status when no items have shortages', async () => {
|
||||
mockRegimensService.getById.mockResolvedValue(makeRegimen());
|
||||
mockCabinetRepo.findActiveByMedicineForFEFO.mockResolvedValue([
|
||||
{ _id: { toString: () => 'ci-1' }, quantity: 30, expirationDate: null },
|
||||
]);
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 23 });
|
||||
mockOrganizerRepo.create.mockResolvedValue({
|
||||
_id: { toString: () => 'fill-1' },
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
await service.fill('hh1', 'user-1', fillInput);
|
||||
|
||||
expect(mockOrganizerRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('undoFill', () => {
|
||||
const makeFill = (overrides = {}) => ({
|
||||
_id: 'fill-1',
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
status: OrganizerFillStatus.COMPLETED,
|
||||
items: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
quantityNeeded: 7,
|
||||
quantityTaken: 7,
|
||||
wasShort: false,
|
||||
shortage: 0,
|
||||
deductions: [{ cabinetItemId: 'ci-1', quantityTaken: 7 }],
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it('reverses fill and restores quantities', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(makeFill());
|
||||
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1', quantity: 23 });
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 30 });
|
||||
mockOrganizerRepo.updateStatus.mockResolvedValue({
|
||||
...makeFill(),
|
||||
status: OrganizerFillStatus.REVERSED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
const result = await service.undoFill('hh1', 'fill-1', 'user-1');
|
||||
|
||||
expect(result.status).toBe(OrganizerFillStatus.REVERSED);
|
||||
expect(mockCabinetRepo.adjustQuantity).toHaveBeenCalledWith('ci-1', 'hh1', 7);
|
||||
expect(mockOrganizerRepo.updateStatus).toHaveBeenCalledWith(
|
||||
'fill-1',
|
||||
'hh1',
|
||||
OrganizerFillStatus.REVERSED,
|
||||
);
|
||||
expect(mockSession.startTransaction).toHaveBeenCalled();
|
||||
expect(mockSession.commitTransaction).toHaveBeenCalled();
|
||||
expect(mockSession.endSession).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates RESTORED events for each deduction', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(makeFill());
|
||||
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1', quantity: 23 });
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 30 });
|
||||
mockOrganizerRepo.updateStatus.mockResolvedValue({
|
||||
...makeFill(),
|
||||
status: OrganizerFillStatus.REVERSED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
await service.undoFill('hh1', 'fill-1', 'user-1');
|
||||
|
||||
const events = mockCabinetEventsService.logEvents.mock.calls[0][0];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
cabinetItemId: 'ci-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
eventType: CabinetEventType.RESTORED,
|
||||
quantity: 7,
|
||||
quantityBefore: 23,
|
||||
quantityAfter: 30,
|
||||
sourceType: CabinetEventSourceType.ORGANIZER_UNDO,
|
||||
sourceId: 'fill-1',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws BadRequestError when fill is already reversed', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(
|
||||
makeFill({ status: OrganizerFillStatus.REVERSED }),
|
||||
);
|
||||
|
||||
await expect(service.undoFill('hh1', 'fill-1', 'user-1')).rejects.toThrow(
|
||||
'Fill has already been reversed',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when fill does not exist', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.undoFill('hh1', 'fill-missing', 'user-1')).rejects.toThrow(
|
||||
'Organizer fill not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('aborts transaction and rethrows on error', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(makeFill());
|
||||
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1', quantity: 23 });
|
||||
mockCabinetRepo.adjustQuantity.mockRejectedValue(new Error('DB failure'));
|
||||
|
||||
await expect(service.undoFill('hh1', 'fill-1', 'user-1')).rejects.toThrow('DB failure');
|
||||
|
||||
expect(mockSession.abortTransaction).toHaveBeenCalled();
|
||||
expect(mockSession.endSession).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handles cabinet item not found when restoring (uses 0 as quantityBefore)', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(makeFill());
|
||||
mockCabinetRepo.findById.mockResolvedValue(null);
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ _id: 'ci-1', quantity: 7 });
|
||||
mockOrganizerRepo.updateStatus.mockResolvedValue({
|
||||
...makeFill(),
|
||||
status: OrganizerFillStatus.REVERSED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
await service.undoFill('hh1', 'fill-1', 'user-1');
|
||||
|
||||
const events = mockCabinetEventsService.logEvents.mock.calls[0][0];
|
||||
expect(events[0].quantityBefore).toBe(0);
|
||||
expect(events[0].quantityAfter).toBe(7);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when updateStatus returns null', async () => {
|
||||
mockOrganizerRepo.findById.mockResolvedValue(makeFill({ items: [] }));
|
||||
mockOrganizerRepo.updateStatus.mockResolvedValue(null);
|
||||
|
||||
await expect(service.undoFill('hh1', 'fill-1', 'user-1')).rejects.toThrow(
|
||||
'Organizer fill not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('restores multiple deductions across items', async () => {
|
||||
const fill = makeFill({
|
||||
items: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
quantityNeeded: 7,
|
||||
quantityTaken: 7,
|
||||
wasShort: false,
|
||||
shortage: 0,
|
||||
deductions: [
|
||||
{ cabinetItemId: 'ci-1', quantityTaken: 4 },
|
||||
{ cabinetItemId: 'ci-2', quantityTaken: 3 },
|
||||
],
|
||||
},
|
||||
{
|
||||
medicineId: 'med-2',
|
||||
medicineName: 'Aspirin',
|
||||
quantityNeeded: 14,
|
||||
quantityTaken: 14,
|
||||
wasShort: false,
|
||||
shortage: 0,
|
||||
deductions: [{ cabinetItemId: 'ci-3', quantityTaken: 14 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
mockOrganizerRepo.findById.mockResolvedValue(fill);
|
||||
mockCabinetRepo.findById.mockResolvedValue({ quantity: 10 });
|
||||
mockCabinetRepo.adjustQuantity.mockResolvedValue({ quantity: 20 });
|
||||
mockOrganizerRepo.updateStatus.mockResolvedValue({
|
||||
...fill,
|
||||
status: OrganizerFillStatus.REVERSED,
|
||||
});
|
||||
mockCabinetEventsService.logEvents.mockResolvedValue([]);
|
||||
|
||||
await service.undoFill('hh1', 'fill-1', 'user-1');
|
||||
|
||||
expect(mockCabinetRepo.adjustQuantity).toHaveBeenCalledTimes(3);
|
||||
expect(mockCabinetRepo.findById).toHaveBeenCalledTimes(3);
|
||||
const events = mockCabinetEventsService.logEvents.mock.calls[0][0];
|
||||
expect(events).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue