mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
chore: move vacay backend to proper DI
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* Vacay module e2e — exercises the migrated /api/addons/vacay endpoints through
|
||||
* the real JwtAuthGuard against a temp SQLite db. vacayService is mocked; this
|
||||
* focuses on auth, status codes (POSTs stay 200) and a couple of validation/403
|
||||
* bodies.
|
||||
* the real JwtAuthGuard against a temp SQLite db. DI-native: VacayService runs
|
||||
* its real SQL over the temp db (no legacy service mock); only the websocket
|
||||
* and notification side channels stay mocked. Focuses on auth, status codes
|
||||
* (POSTs stay 200), the Zod-pipe 400 envelope and a 403 body.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import request from 'supertest';
|
||||
@@ -18,34 +19,70 @@ const { db } = vi.hoisted(() => {
|
||||
tmp.exec('PRAGMA journal_mode = WAL');
|
||||
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
||||
// The vacay tables VacayService's real SQL touches (trimmed from src/db/schema.ts,
|
||||
// with the fraction/kind columns the migrations add to vacay_entries).
|
||||
tmp.exec(`CREATE TABLE vacay_plans (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
block_weekends INTEGER DEFAULT 1, holidays_enabled INTEGER DEFAULT 0, holidays_region TEXT DEFAULT '',
|
||||
school_holidays_enabled INTEGER DEFAULT 0, company_holidays_enabled INTEGER DEFAULT 1,
|
||||
carry_over_enabled INTEGER DEFAULT 1, weekend_days TEXT, week_start INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(owner_id));`);
|
||||
tmp.exec(`CREATE TABLE vacay_plan_members (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
status TEXT DEFAULT 'pending', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(plan_id, user_id));`);
|
||||
tmp.exec(`CREATE TABLE vacay_user_colors (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
|
||||
color TEXT DEFAULT '#6366f1', UNIQUE(user_id, plan_id));`);
|
||||
tmp.exec(`CREATE TABLE vacay_years (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
|
||||
year INTEGER NOT NULL, UNIQUE(plan_id, year));`);
|
||||
tmp.exec(`CREATE TABLE vacay_user_years (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
|
||||
year INTEGER NOT NULL, vacation_days INTEGER DEFAULT 30, carried_over INTEGER DEFAULT 0,
|
||||
UNIQUE(user_id, plan_id, year));`);
|
||||
tmp.exec(`CREATE TABLE vacay_entries (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
date TEXT NOT NULL, note TEXT DEFAULT '',
|
||||
fraction REAL NOT NULL DEFAULT 1, kind TEXT NOT NULL DEFAULT 'vacation',
|
||||
UNIQUE(user_id, plan_id, date));`);
|
||||
tmp.exec(`CREATE TABLE vacay_company_holidays (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
|
||||
date TEXT NOT NULL, note TEXT DEFAULT '', UNIQUE(plan_id, date));`);
|
||||
tmp.exec(`CREATE TABLE vacay_holiday_calendars (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
|
||||
type TEXT NOT NULL DEFAULT 'public_holiday', region TEXT NOT NULL, label TEXT,
|
||||
color TEXT NOT NULL DEFAULT '#fecaca', sort_order INTEGER NOT NULL DEFAULT 0);`);
|
||||
tmp.exec(`CREATE TABLE vacay_shares (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
hidden INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(owner_id, user_id));`);
|
||||
tmp.exec(`CREATE TABLE vacay_user_settings (
|
||||
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
year_type TEXT NOT NULL DEFAULT 'calendar', year_start_month INTEGER NOT NULL DEFAULT 1,
|
||||
year_start_day INTEGER NOT NULL DEFAULT 1, hire_date TEXT);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn() }));
|
||||
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
const { svc } = vi.hoisted(() => ({
|
||||
svc: {
|
||||
getPlanData: vi.fn(), getActivePlanId: vi.fn(), getActivePlan: vi.fn(), updatePlan: vi.fn(),
|
||||
addHolidayCalendar: vi.fn(), updateHolidayCalendar: vi.fn(), deleteHolidayCalendar: vi.fn(),
|
||||
getPlanUsers: vi.fn(), setUserColor: vi.fn(), sendInvite: vi.fn(), acceptInvite: vi.fn(),
|
||||
declineInvite: vi.fn(), cancelInvite: vi.fn(), dissolvePlan: vi.fn(), getAvailableUsers: vi.fn(),
|
||||
listYears: vi.fn(), addYear: vi.fn(), deleteYear: vi.fn(), getEntries: vi.fn(),
|
||||
toggleEntry: vi.fn(), toggleCompanyHoliday: vi.fn(), getStats: vi.fn(), updateStats: vi.fn(),
|
||||
getCountries: vi.fn(), getHolidays: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/vacayService', () => svc);
|
||||
|
||||
import { DatabaseModule } from '../../src/nest/database/database.module';
|
||||
import { VacayModule } from '../../src/nest/vacay/vacay.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { broadcastToUser } from '../../src/websocket';
|
||||
|
||||
describe('Vacay e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [VacayModule] }).compile();
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, VacayModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
@@ -60,11 +97,6 @@ describe('Vacay e2e (real auth guard + temp SQLite)', () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
svc.getActivePlanId.mockReturnValue(10);
|
||||
svc.getActivePlan.mockReturnValue({ id: 10 });
|
||||
svc.getPlanUsers.mockReturnValue([{ id: 1 }]);
|
||||
svc.getPlanData.mockReturnValue({ plan: { id: 10 } });
|
||||
svc.toggleEntry.mockReturnValue({ action: 'added' });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -76,18 +108,21 @@ describe('Vacay e2e (real auth guard + temp SQLite)', () => {
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 plan for an authenticated user', async () => {
|
||||
it('200 plan for an authenticated user (lazily creates the plan)', async () => {
|
||||
const res = await request(server).get('/api/addons/vacay/plan').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ plan: { id: 10 } });
|
||||
expect(res.body.plan.owner_id).toBe(1);
|
||||
expect(res.body.isOwner).toBe(true);
|
||||
expect(db.prepare('SELECT id FROM vacay_plans WHERE owner_id = 1').get()).toBeDefined();
|
||||
});
|
||||
|
||||
it('200 (not 201) on POST entries/toggle, forwarding the socket id', async () => {
|
||||
const res = await request(server).post('/api/addons/vacay/entries/toggle')
|
||||
.set('Cookie', sessionCookie(1)).set('X-Socket-Id', 'sock-7').send({ date: '2026-07-01' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ action: 'added' });
|
||||
expect(svc.toggleEntry).toHaveBeenCalledWith(1, 10, '2026-07-01', undefined, undefined, 'sock-7');
|
||||
expect(res.body).toEqual({ action: 'added', fraction: 1, kind: 'vacation' });
|
||||
expect(db.prepare("SELECT id FROM vacay_entries WHERE user_id = 1 AND date = '2026-07-01'").get()).toBeDefined();
|
||||
expect(vi.mocked(broadcastToUser)).toHaveBeenCalledWith(1, { type: 'vacay:update' }, 'sock-7');
|
||||
});
|
||||
|
||||
it('400 from the Zod pipe on entries/toggle without a date', async () => {
|
||||
|
||||
@@ -16,6 +16,8 @@ import { TagsMcp } from '../../src/nest/tags/tags.mcp';
|
||||
import { TagsService } from '../../src/nest/tags/tags.service';
|
||||
import { TodoMcp } from '../../src/nest/todo/todo.mcp';
|
||||
import { TodoService } from '../../src/nest/todo/todo.service';
|
||||
import { VacayMcp } from '../../src/nest/vacay/vacay.mcp';
|
||||
import { VacayService } from '../../src/nest/vacay/vacay.service';
|
||||
|
||||
/**
|
||||
* Hand-wired counterpart of the boot-time discovery in McpRegistryService,
|
||||
@@ -35,6 +37,7 @@ export function createMcpTestRegistry(): McpRegistry {
|
||||
new DayNotesMcp(new DayNotesService(dbService)),
|
||||
new AssignmentsMcp(new AssignmentsService(dbService)),
|
||||
new CollabMcp(new CollabService(dbService)),
|
||||
new VacayMcp(new VacayService(dbService)),
|
||||
],
|
||||
{ accessPolicy: trekMcpAccessPolicy },
|
||||
);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { LlmConfigResolver } from '../../src/nest/llm-parse/llm-config.resolver'
|
||||
import { SettingsService } from '../../src/nest/settings/settings.service';
|
||||
import { FilesService } from '../../src/nest/files/files.service';
|
||||
import { CollabService } from '../../src/nest/collab/collab.service';
|
||||
import { VacayService } from '../../src/nest/vacay/vacay.service';
|
||||
|
||||
/**
|
||||
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
|
||||
@@ -37,6 +38,7 @@ export function createHostDepsFactory(dbs: DatabaseService): PluginHostDepsFacto
|
||||
dbs,
|
||||
new FilesService(dbs),
|
||||
new CollabService(dbs),
|
||||
new VacayService(dbs),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,15 +51,13 @@ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
]),
|
||||
}));
|
||||
|
||||
// Mock vacayService.getCountries to avoid real HTTP call to nager.at
|
||||
vi.mock('../../src/services/vacayService', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../src/services/vacayService')>('../../src/services/vacayService');
|
||||
return {
|
||||
...actual,
|
||||
getCountries: vi.fn().mockResolvedValue({
|
||||
data: [{ countryCode: 'DE', name: 'Germany' }, { countryCode: 'FR', name: 'France' }],
|
||||
}),
|
||||
};
|
||||
import { VacayService } from '../../src/nest/vacay/vacay.service';
|
||||
|
||||
// Stub VacayService.getCountries to avoid a real HTTP call to nager.at (the
|
||||
// legacy path-level partial mock; the service is DI-native now, so spy on the
|
||||
// prototype instead).
|
||||
vi.spyOn(VacayService.prototype, 'getCountries').mockResolvedValue({
|
||||
data: [{ countryCode: 'DE', name: 'Germany' }, { countryCode: 'FR', name: 'France' }],
|
||||
});
|
||||
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
/**
|
||||
* Unit tests for MCP vacay tools (vacay addon-gated):
|
||||
* Unit tests for MCP vacay tools (vacay addon-gated, VacayMcp — DI-discovered
|
||||
* via the hand-built test registry in tests/helpers/mcp-test-controllers.ts):
|
||||
* get_vacay_plan, update_vacay_plan, set_vacay_color,
|
||||
* list_vacay_years, add_vacay_year, delete_vacay_year,
|
||||
* get_vacay_entries, toggle_vacay_entry, toggle_company_holiday,
|
||||
* get_vacay_stats, update_vacay_stats,
|
||||
* add_holiday_calendar, update_holiday_calendar, delete_holiday_calendar,
|
||||
* list_holiday_countries, list_holidays.
|
||||
* Resources: trek://vacay/plan, trek://vacay/entries/{year}.
|
||||
* Resources: trek://vacay/plan, trek://vacay/entries/{year},
|
||||
* trek://vacay/holidays/{year} — these ride the registry too (attached inside
|
||||
* registerTools), so `withTools` must stay on even for resource reads.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
@@ -44,19 +47,6 @@ vi.mock('../../../src/services/adminService', () => ({
|
||||
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
|
||||
}));
|
||||
|
||||
// Mock async service functions that make external calls
|
||||
vi.mock('../../../src/services/vacayService', async (importOriginal) => {
|
||||
const original = await importOriginal() as Record<string, unknown>;
|
||||
return {
|
||||
...original,
|
||||
updatePlan: vi.fn().mockResolvedValue({
|
||||
plan: { id: 1, block_weekends: true, holidays_enabled: false, company_holidays_enabled: false, carry_over_enabled: false, holiday_calendars: [] },
|
||||
}),
|
||||
getCountries: vi.fn().mockResolvedValue({ data: [{ code: 'US', name: 'United States' }] }),
|
||||
getHolidays: vi.fn().mockResolvedValue({ data: [{ date: '2025-01-01', name: 'New Year' }] }),
|
||||
};
|
||||
});
|
||||
|
||||
// share_vacay_calendar fires a user notification after inserting; stub it out
|
||||
vi.mock('../../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
@@ -65,6 +55,16 @@ import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
import { VacayService } from '../../../src/nest/vacay/vacay.service';
|
||||
|
||||
// Stub the async methods that make external calls (VacayService is DI-native;
|
||||
// the registry constructs a real instance, so spy on the prototype — the
|
||||
// successor of the legacy path-level partial mock of services/vacayService).
|
||||
vi.spyOn(VacayService.prototype, 'updatePlan').mockResolvedValue({
|
||||
plan: { id: 1, block_weekends: true, holidays_enabled: false, company_holidays_enabled: false, carry_over_enabled: false, holiday_calendars: [] },
|
||||
} as never);
|
||||
vi.spyOn(VacayService.prototype, 'getCountries').mockResolvedValue({ data: [{ code: 'US', name: 'United States' }] });
|
||||
vi.spyOn(VacayService.prototype, 'getHolidays').mockResolvedValue({ data: [{ date: '2025-01-01', name: 'New Year' }] });
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
@@ -602,3 +602,14 @@ describe('Resource: trek://vacay/entries/{year}', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resource: trek://vacay/holidays/{year}', () => {
|
||||
it('returns [] while public holidays are disabled or no region is set', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withResourceHarness(user.id, async (h) => {
|
||||
const result = await h.client.readResource({ uri: 'trek://vacay/holidays/2025' });
|
||||
const data = parseResourceResult(result) as unknown[];
|
||||
expect(data).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+235
-241
File diff suppressed because it is too large
Load Diff
@@ -4,8 +4,9 @@
|
||||
* per-plugin data db is cached, a granted db:own call works through the wired
|
||||
* host, and trip broadcasts are force-namespaced to plugin:{id}:{event}.
|
||||
* DI-native domains (budget/reservations/tags/categories/todo/packing/
|
||||
* day-notes/assignments/oauth/llm-config/files) are constructor-injected stubs;
|
||||
* legacy services/* domains stay path-mocked until their own DI migration lands.
|
||||
* day-notes/assignments/oauth/llm-config/files/collab/vacay) are
|
||||
* constructor-injected stubs; legacy services/* domains stay path-mocked until
|
||||
* their own DI migration lands.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
@@ -268,12 +269,6 @@ vi.mock('../../../src/services/atlasService', () => ({
|
||||
createBucketItem: vi.fn((uid: number, data: { name: string }) => ({ id: 110, user_id: uid, name: data.name })),
|
||||
deleteBucketItem: vi.fn((_uid: number, itemId: number) => Number(itemId) !== 404),
|
||||
}));
|
||||
vi.mock('../../../src/services/vacayService', () => ({
|
||||
getPlanData: vi.fn((uid: number) => ({ plan: { id: 1, owner: uid } })),
|
||||
getActivePlanId: vi.fn(() => 77),
|
||||
toggleEntry: vi.fn((uid: number, planId: number) => ({ action: 'added', uid, planId })),
|
||||
toggleCompanyHoliday: vi.fn((planId: number) => ({ action: 'added', planId })),
|
||||
}));
|
||||
vi.mock('../../../src/services/collectionsService', () => {
|
||||
const httpError = (status: number, message: string) => { const e = new Error(message) as Error & { status: number }; e.status = status; throw e; };
|
||||
return {
|
||||
@@ -297,6 +292,14 @@ const dayNotesStub = {
|
||||
dayExists: vi.fn((dayId: number) => dayId === 3),
|
||||
} as unknown as DayNotesService;
|
||||
|
||||
// Vacay is a constructor-injected stub (same behaviors as the old path mock).
|
||||
const vacayStub = {
|
||||
getPlanData: vi.fn((uid: number) => ({ plan: { id: 1, owner: uid } })),
|
||||
getActivePlanId: vi.fn(() => 77),
|
||||
toggleEntry: vi.fn((uid: number, planId: number) => ({ action: 'added', uid, planId })),
|
||||
toggleCompanyHoliday: vi.fn((planId: number) => ({ action: 'added', planId })),
|
||||
} as unknown as VacayService;
|
||||
|
||||
import { PluginHostDepsFactory, type PluginCallRouter } from '../../../src/nest/plugins/host/plugin-host-deps.factory';
|
||||
import { getPluginDataDb, closePluginDataDb } from '../../../src/nest/plugins/host/plugin-host-state';
|
||||
import { db as mockDb } from '../../../src/db/database';
|
||||
@@ -312,12 +315,13 @@ import type { PluginOAuthService } from '../../../src/nest/plugins/plugin-oauth.
|
||||
import type { LlmConfigResolver } from '../../../src/nest/llm-parse/llm-config.resolver';
|
||||
import type { FilesService } from '../../../src/nest/files/files.service';
|
||||
import type { CollabService } from '../../../src/nest/collab/collab.service';
|
||||
import type { VacayService } from '../../../src/nest/vacay/vacay.service';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
// The factory under test, wired exactly like PluginsModule does — but with the
|
||||
// DI-native domain services replaced by the stubs above. The shim keeps the
|
||||
// ~45 historical call sites unchanged and supplies a default no-op router.
|
||||
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub);
|
||||
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub);
|
||||
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
|
||||
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user