feat(vacay): read-only calendar sharing (#444, #667) (#1637)

* feat(vacay): read-only calendar shares on the server (#444, #667)

* feat(vacay): shared calendars card and ring overlay on desktop

* feat(vacay): share sheet and calendar rings on mobile

* test(vacay): cover the calendar share flows

* docs(vacay): document read-only calendar sharing
This commit is contained in:
Maurice
2026-07-21 13:46:38 +02:00
committed by GitHub
parent 7528706d00
commit 31f6ec1f47
129 changed files with 2593 additions and 97 deletions
+18
View File
@@ -3709,6 +3709,24 @@ function runMigrations(db: Database.Database): void {
const hasFraction = db.prepare("SELECT 1 FROM pragma_table_info('vacay_entries') WHERE name = 'fraction'").get();
if (!hasFraction) db.exec('ALTER TABLE vacay_entries ADD COLUMN fraction REAL NOT NULL DEFAULT 1');
},
// Read-only vacay calendar sharing (#444/#667): a user can let other users
// view their vacation calendar without fusing plans. owner_id is the sharing
// user, user_id the viewer; hidden lets the viewer hide the overlay without
// removing the share. Follows the person, not the plan, so it survives
// fusion and dissolution.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS 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 NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE (owner_id, user_id)
);
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_vacay_shares_user ON vacay_shares (user_id);');
},
];
if (currentVersion < migrations.length) {
+64
View File
@@ -11,6 +11,7 @@ import {
getStats as getVacayStats, updateStats as updateVacayStats,
addHolidayCalendar, updateHolidayCalendar, deleteHolidayCalendar,
getCountries as getHolidayCountries, getHolidays,
listShares, shareCalendar, removeShare, getSharedCalendars,
} from '../../services/vacayService';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
@@ -397,5 +398,68 @@ export function registerVacayTools(server: McpServer, userId: number, scopes: st
return ok({ holidays: result.data });
}
);
if (R) server.registerTool(
'list_vacay_shares',
{
description: 'List read-only calendar shares: who the current user shares their vacation calendar with, and which calendars are shared with them.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
return ok(listShares(userId));
}
);
if (W) server.registerTool(
'share_vacay_calendar',
{
description: "Share the current user's vacation calendar with another user (view only, no merge).",
inputSchema: {
targetUserId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ targetUserId }) => {
if (isDemoUser(userId)) return demoDenied();
const me = getCurrentUser(userId);
if (!me) return { content: [{ type: 'text' as const, text: 'User not found.' }], isError: true };
const result = shareCalendar(userId, me.email, targetUserId);
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
return ok({ success: true });
}
);
if (W) server.registerTool(
'unshare_vacay_calendar',
{
description: 'Remove a read-only calendar share the current user is part of (revoke as owner, or remove a calendar shared with them).',
inputSchema: {
shareId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ shareId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!removeShare(shareId, userId, undefined)) {
return { content: [{ type: 'text' as const, text: 'Share not found.' }], isError: true };
}
return ok({ success: true });
}
);
if (R) server.registerTool(
'get_shared_vacay_calendars',
{
description: 'Get the read-only vacation calendars shared with the current user for a year (entries and company holidays per sharer).',
inputSchema: {
year: z.number().int(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ year }) => {
return ok({ calendars: getSharedCalendars(userId, String(year)) });
}
);
}
}
+55
View File
@@ -11,10 +11,12 @@ import {
Put,
UseGuards,
} from '@nestjs/common';
import { vacayShareUpdateRequestSchema, type VacayShareUpdateRequest } from '@trek/shared';
import type { User } from '../../types';
import { VacayService } from './vacay.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
/**
* /api/addons/vacay — shared vacation-day planner.
@@ -235,6 +237,59 @@ export class VacayController {
return { success: true };
}
@Get('shares')
shares(@CurrentUser() user: User) {
return this.vacay.listShares(user.id);
}
@Post('shares')
@HttpCode(200)
share(
@CurrentUser() user: User,
@Body('user_id') userIdInput?: number | string,
@Headers('x-socket-id') socketId?: string,
) {
if (!userIdInput) {
throw new HttpException({ error: 'user_id required' }, 400);
}
const result = this.vacay.shareCalendar(user.id, user.email, parseInt(String(userIdInput)), socketId);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
return { success: true };
}
@Get('shares/available-users')
shareAvailableUsers(@CurrentUser() user: User) {
return { users: this.vacay.getShareAvailableUsers(user.id) };
}
@Get('shares/calendars/:year')
sharedCalendars(@CurrentUser() user: User, @Param('year') year: string) {
return { calendars: this.vacay.getSharedCalendars(user.id, year) };
}
@Put('shares/:id')
updateShare(
@CurrentUser() user: User,
@Param('id') idParam: string,
@Body(new ZodValidationPipe(vacayShareUpdateRequestSchema)) body: VacayShareUpdateRequest,
@Headers('x-socket-id') socketId?: string,
) {
if (!this.vacay.setShareHidden(parseInt(idParam), user.id, body.hidden, socketId)) {
throw new HttpException({ error: 'Share not found' }, 404);
}
return { success: true };
}
@Delete('shares/:id')
deleteShare(@CurrentUser() user: User, @Param('id') idParam: string, @Headers('x-socket-id') socketId?: string) {
if (!this.vacay.removeShare(parseInt(idParam), user.id, socketId)) {
throw new HttpException({ error: 'Share not found' }, 404);
}
return { success: true };
}
@Get('holidays/countries')
async holidayCountries() {
const result = await this.vacay.getCountries();
+24
View File
@@ -109,4 +109,28 @@ export class VacayService {
getHolidays(year: string, country: string) {
return svc.getHolidays(year, country);
}
listShares(userId: number) {
return svc.listShares(userId);
}
shareCalendar(ownerId: number, ownerEmail: string, targetUserId: number, socketId?: string) {
return svc.shareCalendar(ownerId, ownerEmail, targetUserId, socketId);
}
removeShare(shareId: number, userId: number, socketId: string | undefined): boolean {
return svc.removeShare(shareId, userId, socketId);
}
setShareHidden(shareId: number, userId: number, hidden: boolean, socketId: string | undefined): boolean {
return svc.setShareHidden(shareId, userId, hidden, socketId);
}
getShareAvailableUsers(userId: number) {
return svc.getShareAvailableUsers(userId);
}
getSharedCalendars(viewerId: number, year: string) {
return svc.getSharedCalendars(viewerId, year);
}
}
@@ -25,6 +25,7 @@ export type NotifEventType =
| 'trip_reminder'
| 'todo_due'
| 'vacay_invite'
| 'vacay_share'
| 'collection_invite'
| 'photos_shared'
| 'collab_message'
@@ -40,6 +41,7 @@ export const ALL_EVENT_TYPES: NotifEventType[] = [
'trip_reminder',
'todo_due',
'vacay_invite',
'vacay_share',
'collection_invite',
'photos_shared',
'collab_message',
@@ -93,6 +93,13 @@ const EVENT_NOTIFICATION_CONFIG: Record<string, EventNotifConfig> = {
navigateTextKey: 'notif.action.view_vacay',
navigateTarget: p => (p.planId ? `/vacay/${p.planId}` : null),
},
vacay_share: {
inAppType: 'navigate',
titleKey: 'notif.vacay_share.title',
textKey: 'notif.vacay_share.text',
navigateTextKey: 'notif.action.view_vacay',
navigateTarget: () => '/vacay',
},
collection_invite: {
inAppType: 'navigate',
titleKey: 'notif.collection_invite.title',
+207
View File
@@ -170,6 +170,22 @@ export function notifyPlanUsers(planId: number, excludeSid: string | undefined,
const members = db.prepare("SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'").all(planId) as { user_id: number }[];
members.forEach(m => userIds.push(m.user_id));
userIds.forEach(id => broadcastToUser(id, { type: event }, excludeSid));
// Pending-invite events carry nothing a read-only viewer could see; every
// other event may change entries, colors or company holidays.
if (event !== 'vacay:invite' && event !== 'vacay:declined' && event !== 'vacay:cancelled') {
notifyShareViewers(userIds, excludeSid);
}
} catch { /* websocket not available */ }
}
export function notifyShareViewers(ownerIds: number[], excludeSid?: string): void {
if (ownerIds.length === 0) return;
try {
const { broadcastToUser } = require('../websocket');
const rows = db.prepare(
`SELECT DISTINCT user_id FROM vacay_shares WHERE owner_id IN (${ownerIds.map(() => '?').join(',')})`
).all(...ownerIds) as { user_id: number }[];
rows.forEach(r => broadcastToUser(r.user_id, { type: 'vacay:shared-update' }, excludeSid));
} catch { /* websocket not available */ }
}
@@ -487,6 +503,8 @@ export function dissolvePlan(userId: number, socketId: string | undefined): void
const { broadcastToUser } = require('../websocket');
allUserIds.filter(id => id !== userId).forEach(id => broadcastToUser(id, { type: 'vacay:dissolved' }));
} catch { /* */ }
// Everyone's entries just moved back to their own plans — refresh read-only viewers.
notifyShareViewers(allUserIds, socketId);
}
// ---------------------------------------------------------------------------
@@ -506,6 +524,195 @@ export function getAvailableUsers(userId: number, planId: number) {
`).all(userId, planId);
}
// ---------------------------------------------------------------------------
// Read-only calendar shares (#444/#667)
// ---------------------------------------------------------------------------
//
// A share lets another user VIEW someone's vacation days without fusing plans:
// no edit rights, no data migration. The share follows the person (owner_id),
// not a plan, so it keeps working across fusion and dissolution — viewers see
// the owner's entries in whatever plan the owner is currently active in.
export interface VacayShare {
id: number;
owner_id: number;
user_id: number;
hidden: number;
created_at?: string;
}
/** Like getActivePlan, but never lazily creates a plan for the user. */
function peekActivePlan(userId: number): VacayPlan | undefined {
const membership = db.prepare(`
SELECT plan_id FROM vacay_plan_members WHERE user_id = ? AND status = 'accepted'
`).get(userId) as { plan_id: number } | undefined;
if (membership) {
return db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(membership.plan_id) as VacayPlan | undefined;
}
return db.prepare('SELECT * FROM vacay_plans WHERE owner_id = ?').get(userId) as VacayPlan | undefined;
}
/** Colors already taken in the viewer's own calendar (their plan's members). */
function viewerColors(viewerId: number): Set<string> {
const plan = peekActivePlan(viewerId);
if (!plan) return new Set(['#6366f1']);
const rows = db.prepare('SELECT color FROM vacay_user_colors WHERE plan_id = ?').all(plan.id) as { color: string }[];
return new Set(rows.length > 0 ? rows.map(r => r.color) : ['#6366f1']);
}
/**
* Display color for a shared calendar. Starts from the owner's own color, but
* remaps to the first free preset when it collides with the viewer's plan
* members or an earlier share — otherwise two people on the default indigo
* would be indistinguishable in the overlay.
*/
function shareDisplayColor(ownerId: number, usedColors: Set<string>): string {
const plan = peekActivePlan(ownerId);
const row = plan
? db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(ownerId, plan.id) as { color: string } | undefined
: undefined;
let color = row?.color || '#6366f1';
if (usedColors.has(color)) {
// Preset pool exhausted? Derive a stable per-owner hue instead of colliding.
color = COLORS.find(c => !usedColors.has(c)) || `hsl(${Math.round((ownerId * 137.508) % 360)} 65% 60%)`;
}
usedColors.add(color);
return color;
}
/** Users the viewer already sees in full via their active plan (owner + members). */
function viewerCoMemberIds(viewerId: number): Set<number> {
const plan = peekActivePlan(viewerId);
return new Set(plan ? getPlanUsers(plan.id).map(u => u.id) : []);
}
export function listShares(userId: number) {
// Usernames only, like the share picker — emails stay out of the share surface.
const outgoing = db.prepare(`
SELECT s.id, s.user_id, u.username
FROM vacay_shares s JOIN users u ON s.user_id = u.id
WHERE s.owner_id = ? ORDER BY s.id
`).all(userId) as { id: number; user_id: number; username: string }[];
const incomingRows = db.prepare(`
SELECT s.id, s.owner_id, s.hidden, u.username
FROM vacay_shares s JOIN users u ON s.owner_id = u.id
WHERE s.user_id = ? ORDER BY s.id
`).all(userId) as { id: number; owner_id: number; hidden: number; username: string }[];
// Shares from someone the viewer is meanwhile fused with lie dormant — the
// plan already shows that calendar in full. They resume after dissolution.
const coMembers = viewerCoMemberIds(userId);
const usedColors = viewerColors(userId);
const incoming = incomingRows.filter(s => !coMembers.has(s.owner_id)).map(s => ({
id: s.id,
owner_id: s.owner_id,
username: s.username,
color: shareDisplayColor(s.owner_id, usedColors),
hidden: !!s.hidden,
}));
return { outgoing, incoming };
}
export function shareCalendar(ownerId: number, ownerEmail: string, targetUserId: number, socketId?: string): { error?: string; status?: number } {
if (targetUserId === ownerId) return { error: 'Cannot share with yourself', status: 400 };
const targetUser = db.prepare('SELECT id FROM users WHERE id = ?').get(targetUserId);
if (!targetUser) return { error: 'User not found', status: 404 };
const existing = db.prepare('SELECT id FROM vacay_shares WHERE owner_id = ? AND user_id = ?').get(ownerId, targetUserId);
if (existing) return { error: 'Already shared', status: 400 };
// Plan members already see the whole calendar — sharing with them is moot.
if (getPlanUsers(getActivePlanId(ownerId)).find(u => u.id === targetUserId)) {
return { error: 'User is already in your calendar', status: 400 };
}
db.prepare('INSERT INTO vacay_shares (owner_id, user_id) VALUES (?, ?)').run(ownerId, targetUserId);
try {
const { broadcastToUser } = require('../websocket');
broadcastToUser(targetUserId, { type: 'vacay:share', from: { id: ownerId } });
// The owner's other devices refresh their outgoing list too.
broadcastToUser(ownerId, { type: 'vacay:share', from: { id: ownerId } }, socketId);
} catch { /* websocket not available */ }
import('../services/notificationService').then(({ send }) => {
send({ event: 'vacay_share', actorId: ownerId, scope: 'user', targetId: targetUserId, params: { actor: ownerEmail } }).catch(() => {});
});
return {};
}
export function removeShare(shareId: number, userId: number, socketId?: string): boolean {
const share = db.prepare('SELECT * FROM vacay_shares WHERE id = ?').get(shareId) as VacayShare | undefined;
// The owner revokes, the viewer removes — both may delete, nobody else.
if (!share || (share.owner_id !== userId && share.user_id !== userId)) return false;
db.prepare('DELETE FROM vacay_shares WHERE id = ?').run(shareId);
try {
const { broadcastToUser } = require('../websocket');
broadcastToUser(share.owner_id, { type: 'vacay:share-removed' }, socketId);
broadcastToUser(share.user_id, { type: 'vacay:share-removed' }, socketId);
} catch { /* websocket not available */ }
return true;
}
export function setShareHidden(shareId: number, userId: number, hidden: boolean, socketId?: string): boolean {
const share = db.prepare('SELECT * FROM vacay_shares WHERE id = ?').get(shareId) as VacayShare | undefined;
if (!share || share.user_id !== userId) return false;
db.prepare('UPDATE vacay_shares SET hidden = ? WHERE id = ?').run(hidden ? 1 : 0, shareId);
try {
// Keep the viewer's other devices in sync; nobody else is affected.
const { broadcastToUser } = require('../websocket');
broadcastToUser(userId, { type: 'vacay:shared-update' }, socketId);
} catch { /* websocket not available */ }
return true;
}
export function getShareAvailableUsers(userId: number) {
const planId = getActivePlanId(userId);
// Username only — unlike the fusion picker this lists users from other plans
// too, so exposing their emails here would widen the instance directory.
return db.prepare(`
SELECT u.id, u.username FROM users u
WHERE u.id != ?
AND u.id NOT IN (SELECT user_id FROM vacay_shares WHERE owner_id = ?)
AND u.id NOT IN (
SELECT owner_id FROM vacay_plans WHERE id = ?
UNION
SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'
)
ORDER BY u.username
`).all(userId, userId, planId, planId);
}
export function getSharedCalendars(viewerId: number, year: string) {
const shares = db.prepare(`
SELECT s.id, s.owner_id, s.hidden, u.username
FROM vacay_shares s JOIN users u ON s.owner_id = u.id
WHERE s.user_id = ? ORDER BY s.id
`).all(viewerId) as { id: number; owner_id: number; hidden: number; username: string }[];
// Same dormancy rule as listShares: fused co-members are already fully visible.
const coMembers = viewerCoMemberIds(viewerId);
const usedColors = viewerColors(viewerId);
return shares.filter(s => !coMembers.has(s.owner_id)).map(s => {
const color = shareDisplayColor(s.owner_id, usedColors);
const plan = peekActivePlan(s.owner_id);
if (!plan) {
return { share_id: s.id, owner_id: s.owner_id, owner_name: s.username, color, hidden: !!s.hidden, entries: [], companyHolidays: [] };
}
const entries = db.prepare(
'SELECT date, fraction FROM vacay_entries WHERE plan_id = ? AND user_id = ? AND date LIKE ? ORDER BY date'
).all(plan.id, s.owner_id, `${year}-%`);
// Company holidays are plan-wide context for "when is this person off";
// only exposed while the owner has the feature enabled, and dates only —
// the note text may be authored by plan members who aren't part of the share.
const companyHolidays = plan.company_holidays_enabled
? db.prepare('SELECT date FROM vacay_company_holidays WHERE plan_id = ? AND date LIKE ? ORDER BY date').all(plan.id, `${year}-%`)
: [];
return { share_id: s.id, owner_id: s.owner_id, owner_name: s.username, color, hidden: !!s.hidden, entries, companyHolidays };
});
}
// ---------------------------------------------------------------------------
// Years
// ---------------------------------------------------------------------------
+1
View File
@@ -78,6 +78,7 @@ const RESET_TABLES = [
'journey_trips',
'journeys',
// Vacay
'vacay_shares',
'vacay_entries',
'vacay_company_holidays',
'vacay_holiday_calendars',
+130
View File
@@ -538,3 +538,133 @@ describe('Vacay toggle entry for plan member', () => {
expect(res.status).toBe(200);
});
});
describe('Vacay read-only calendar shares', () => {
it('VACAY-039 — POST /shares shares the calendar with another user', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
const res = await request(app)
.post('/api/addons/vacay/shares')
.set('Cookie', authCookie(a.id))
.send({ user_id: b.id });
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
});
it('VACAY-040 — GET /shares lists the share as outgoing for A and incoming for B', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const aRes = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(a.id));
expect(aRes.status).toBe(200);
expect(aRes.body.outgoing).toHaveLength(1);
expect(aRes.body.outgoing[0].user_id).toBe(b.id);
expect(aRes.body.incoming).toHaveLength(0);
const bRes = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
expect(bRes.status).toBe(200);
expect(bRes.body.incoming).toHaveLength(1);
expect(bRes.body.incoming[0].owner_id).toBe(a.id);
expect(bRes.body.incoming[0].hidden).toBe(false);
expect(bRes.body.outgoing).toHaveLength(0);
});
it('VACAY-041 — GET /shares/calendars/:year exposes A entries and company holidays to B', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/years').set('Cookie', authCookie(a.id)).send({ year: 2025 });
await request(app).put('/api/addons/vacay/plan').set('Cookie', authCookie(a.id)).send({ company_holidays_enabled: true });
await request(app).post('/api/addons/vacay/entries/toggle').set('Cookie', authCookie(a.id)).send({ date: '2025-06-16' });
await request(app).post('/api/addons/vacay/entries/company-holiday').set('Cookie', authCookie(a.id)).send({ date: '2025-12-25', note: 'Christmas' });
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const res = await request(app)
.get('/api/addons/vacay/shares/calendars/2025')
.set('Cookie', authCookie(b.id));
expect(res.status).toBe(200);
expect(res.body.calendars).toHaveLength(1);
const cal = res.body.calendars[0];
expect(cal.owner_id).toBe(a.id);
expect(cal.entries.map((e: { date: string }) => e.date)).toContain('2025-06-16');
expect(cal.companyHolidays.map((h: { date: string }) => h.date)).toContain('2025-12-25');
});
it('VACAY-042 — PUT /shares/:id lets B hide the shared calendar', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const list = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
const shareId = list.body.incoming[0].id;
const res = await request(app)
.put(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(b.id))
.send({ hidden: true });
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
const after = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
expect(after.body.incoming[0].hidden).toBe(true);
});
it('VACAY-043 — DELETE /shares/:id lets B remove the share', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const list = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
const shareId = list.body.incoming[0].id;
const res = await request(app)
.delete(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(b.id));
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
const bAfter = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
expect(bAfter.body.incoming).toHaveLength(0);
const aAfter = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(a.id));
expect(aAfter.body.outgoing).toHaveLength(0);
});
it('VACAY-044 — PUT/DELETE on a foreign share id returns 404', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
const { user: c } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const list = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
const shareId = list.body.incoming[0].id;
const put = await request(app)
.put(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(c.id))
.send({ hidden: true });
expect(put.status).toBe(404);
const del = await request(app)
.delete(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(c.id));
expect(del.status).toBe(404);
});
it('VACAY-045 — sharing with the same user twice returns 400', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const res = await request(app)
.post('/api/addons/vacay/shares')
.set('Cookie', authCookie(a.id))
.send({ user_id: b.id });
expect(res.status).toBe(400);
expect(res.body.error).toBe('Already shared');
});
});
+119
View File
@@ -57,6 +57,9 @@ vi.mock('../../../src/services/vacayService', async (importOriginal) => {
};
});
// share_vacay_calendar fires a user notification after inserting; stub it out
vi.mock('../../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
@@ -457,6 +460,122 @@ describe('Tool: list_holidays', () => {
});
});
// ---------------------------------------------------------------------------
// list_vacay_shares
// ---------------------------------------------------------------------------
describe('Tool: list_vacay_shares', () => {
it('returns outgoing and incoming shares', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
const result = await h.client.callTool({ name: 'list_vacay_shares', arguments: {} });
const data = parseToolResult(result) as any;
expect(Array.isArray(data.outgoing)).toBe(true);
expect(Array.isArray(data.incoming)).toBe(true);
expect(data.outgoing).toHaveLength(1);
expect(data.outgoing[0].user_id).toBe(other.id);
});
});
});
// ---------------------------------------------------------------------------
// share_vacay_calendar
// ---------------------------------------------------------------------------
describe('Tool: share_vacay_calendar', () => {
it('creates a share and returns success', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
const row = testDb.prepare('SELECT id FROM vacay_shares WHERE owner_id = ? AND user_id = ?').get(user.id, other.id);
expect(row).toBeDefined();
});
});
it('errors when sharing with yourself', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: user.id } });
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// unshare_vacay_calendar
// ---------------------------------------------------------------------------
describe('Tool: unshare_vacay_calendar', () => {
it('removes an existing share and returns success', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
const shareId = (testDb.prepare('SELECT id FROM vacay_shares WHERE owner_id = ?').get(user.id) as any).id;
const result = await h.client.callTool({ name: 'unshare_vacay_calendar', arguments: { shareId } });
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
expect(testDb.prepare('SELECT id FROM vacay_shares WHERE id = ?').get(shareId)).toBeUndefined();
});
});
it('errors when the share does not exist', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'unshare_vacay_calendar', arguments: { shareId: 99999 } });
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'unshare_vacay_calendar', arguments: { shareId: 1 } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// get_shared_vacay_calendars
// ---------------------------------------------------------------------------
describe('Tool: get_shared_vacay_calendars', () => {
it('returns the sharer entries for the viewer', async () => {
const { user: owner } = createUser(testDb);
const { user: viewer } = createUser(testDb);
await withHarness(owner.id, async (h) => {
await h.client.callTool({ name: 'toggle_vacay_entry', arguments: { date: '2025-06-15' } });
await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: viewer.id } });
});
await withHarness(viewer.id, async (h) => {
const result = await h.client.callTool({ name: 'get_shared_vacay_calendars', arguments: { year: 2025 } });
const data = parseToolResult(result) as any;
expect(Array.isArray(data.calendars)).toBe(true);
expect(data.calendars).toHaveLength(1);
expect(data.calendars[0].owner_id).toBe(owner.id);
expect(data.calendars[0].entries.map((e: any) => e.date)).toContain('2025-06-15');
});
});
});
// ---------------------------------------------------------------------------
// Resources
// ---------------------------------------------------------------------------
@@ -178,4 +178,65 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 502, body: { error: 'upstream down' } }));
});
});
describe('read-only shares', () => {
it('GET /shares delegates listShares', () => {
const listShares = vi.fn().mockReturnValue({ outgoing: [{ id: 1 }], incoming: [] });
expect(makeController({ listShares }).shares(user)).toEqual({ outgoing: [{ id: 1 }], incoming: [] });
expect(listShares).toHaveBeenCalledWith(1);
});
it('400 when user_id missing on share', () => {
return thrown(() => makeController({}).share(user, undefined)).then((r) =>
expect(r).toEqual({ status: 400, body: { error: 'user_id required' } }));
});
it('maps a shareCalendar error to its status', () => {
const shareCalendar = vi.fn().mockReturnValue({ error: 'Already shared', status: 400 });
return thrown(() => makeController({ shareCalendar }).share(user, 2)).then((r) =>
expect(r).toEqual({ status: 400, body: { error: 'Already shared' } }));
});
it('shares a calendar (user_id coerced to a number, socket id forwarded)', () => {
const shareCalendar = vi.fn().mockReturnValue({});
expect(makeController({ shareCalendar }).share(user, '2', 'sock-1')).toEqual({ success: true });
expect(shareCalendar).toHaveBeenCalledWith(1, 'u@example.test', 2, 'sock-1');
});
it('GET /shares/available-users wraps the user list', () => {
const getShareAvailableUsers = vi.fn().mockReturnValue([{ id: 3 }]);
expect(makeController({ getShareAvailableUsers }).shareAvailableUsers(user)).toEqual({ users: [{ id: 3 }] });
expect(getShareAvailableUsers).toHaveBeenCalledWith(1);
});
it('GET /shares/calendars/:year wraps the calendars', () => {
const getSharedCalendars = vi.fn().mockReturnValue([{ share_id: 4 }]);
expect(makeController({ getSharedCalendars }).sharedCalendars(user, '2026')).toEqual({ calendars: [{ share_id: 4 }] });
expect(getSharedCalendars).toHaveBeenCalledWith(1, '2026');
});
it('PUT /shares/:id forwards the socket id and the hidden flag', () => {
const setShareHidden = vi.fn().mockReturnValue(true);
expect(makeController({ setShareHidden }).updateShare(user, '7', { hidden: true }, 'sock-1')).toEqual({ success: true });
expect(setShareHidden).toHaveBeenCalledWith(7, 1, true, 'sock-1');
});
it('404 on PUT when the share is not toggleable by the caller', () => {
const setShareHidden = vi.fn().mockReturnValue(false);
return thrown(() => makeController({ setShareHidden }).updateShare(user, '9', { hidden: true })).then((r) =>
expect(r).toEqual({ status: 404, body: { error: 'Share not found' } }));
});
it('DELETE /shares/:id forwards the socket id', () => {
const removeShare = vi.fn().mockReturnValue(true);
expect(makeController({ removeShare }).deleteShare(user, '7', 'sock-1')).toEqual({ success: true });
expect(removeShare).toHaveBeenCalledWith(7, 1, 'sock-1');
});
it('404 on DELETE of a foreign share', () => {
const removeShare = vi.fn().mockReturnValue(false);
return thrown(() => makeController({ removeShare }).deleteShare(user, '9')).then((r) =>
expect(r).toEqual({ status: 404, body: { error: 'Share not found' } }));
});
});
});
@@ -95,14 +95,14 @@ describe('getPreferencesMatrix', () => {
const { event_types } = getPreferencesMatrix(user.id, 'user');
expect(event_types).not.toContain('version_available');
// +1 for plugin_notification: users can mute host-mediated plugin notifications.
expect(event_types.length).toBe(11);
expect(event_types.length).toBe(12);
});
it('NPREF-005 — user scope excludes version_available for everyone including admins', () => {
const { user } = createAdmin(testDb);
const { event_types } = getPreferencesMatrix(user.id, 'admin', 'user');
expect(event_types).not.toContain('version_available');
expect(event_types.length).toBe(11);
expect(event_types.length).toBe(12);
});
it('NPREF-005b — admin scope returns only version_available', () => {
@@ -25,6 +25,8 @@ vi.mock('../../../src/config', () => ({
}));
// Mock websocket so notifyPlanUsers doesn't throw
vi.mock('../../../src/websocket', () => ({ broadcastToUser: vi.fn() }));
// shareCalendar fires a notification after inserting — keep that out of unit scope
vi.mock('../../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
@@ -53,6 +55,12 @@ import {
toggleCompanyHoliday,
getStats,
applyHolidayCalendars,
listShares,
shareCalendar,
removeShare,
setShareHidden,
getShareAvailableUsers,
getSharedCalendars,
} from '../../../src/services/vacayService';
// ── Lifecycle ─────────────────────────────────────────────────────────────────
@@ -794,3 +802,269 @@ describe('applyHolidayCalendars', () => {
expect(remaining).toHaveLength(0);
});
});
// ── Read-only calendar shares (#444/#667) ─────────────────────────────────────
describe('shareCalendar', () => {
it('VACAY-SVC-048: inserts a share row and returns no error', () => {
const { user: owner } = setupUserWithPlan();
const { user: target } = createUser(testDb);
const result = shareCalendar(owner.id, owner.email, target.id);
expect(result.error).toBeUndefined();
const row = testDb
.prepare('SELECT * FROM vacay_shares WHERE owner_id = ? AND user_id = ?')
.get(owner.id, target.id);
expect(row).toBeDefined();
});
it('VACAY-SVC-049: returns 400 when sharing with yourself', () => {
const { user: owner } = setupUserWithPlan();
const result = shareCalendar(owner.id, owner.email, owner.id);
expect(result).toEqual({ error: 'Cannot share with yourself', status: 400 });
});
it('VACAY-SVC-050: returns 404 when the target user does not exist', () => {
const { user: owner } = setupUserWithPlan();
const result = shareCalendar(owner.id, owner.email, 99999);
expect(result).toEqual({ error: 'User not found', status: 404 });
});
it('VACAY-SVC-051: returns 400 when the share already exists', () => {
const { user: owner } = setupUserWithPlan();
const { user: target } = createUser(testDb);
shareCalendar(owner.id, owner.email, target.id);
const result = shareCalendar(owner.id, owner.email, target.id);
expect(result).toEqual({ error: 'Already shared', status: 400 });
});
it('VACAY-SVC-052: returns 400 when the target is already a member of the owner plan', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: member } = createUser(testDb);
insertMember(plan.id, member.id, 'accepted');
const result = shareCalendar(owner.id, owner.email, member.id);
expect(result).toEqual({ error: 'User is already in your calendar', status: 400 });
});
});
describe('listShares', () => {
it('VACAY-SVC-053: outgoing rows carry the target user info', () => {
const { user: owner } = setupUserWithPlan();
const { user: target } = createUser(testDb);
shareCalendar(owner.id, owner.email, target.id);
const result = listShares(owner.id);
expect(result.outgoing).toHaveLength(1);
expect(result.outgoing[0]).toMatchObject({
user_id: target.id,
username: target.username,
});
expect(result.outgoing[0]).not.toHaveProperty('email');
expect(result.incoming).toEqual([]);
});
it('VACAY-SVC-054: incoming rows carry the owner info, their color and a boolean hidden flag', () => {
const { user: owner, plan } = setupUserWithPlan();
setUserColor(owner.id, plan.id, '#ef4444', undefined);
const { user: viewer } = setupUserWithPlan();
shareCalendar(owner.id, owner.email, viewer.id);
const result = listShares(viewer.id);
expect(result.outgoing).toEqual([]);
expect(result.incoming).toHaveLength(1);
expect(result.incoming[0]).toMatchObject({
owner_id: owner.id,
username: owner.username,
color: '#ef4444',
hidden: false,
});
expect(result.incoming[0]).not.toHaveProperty('email');
});
it('VACAY-SVC-055: remaps colors when two sharing owners sit on the default indigo', () => {
const { user: viewer } = setupUserWithPlan(); // viewer's own color is #6366f1
const { user: owner1 } = setupUserWithPlan(); // default #6366f1
const { user: owner2 } = setupUserWithPlan(); // default #6366f1
shareCalendar(owner1.id, owner1.email, viewer.id);
shareCalendar(owner2.id, owner2.email, viewer.id);
const { incoming } = listShares(viewer.id);
expect(incoming).toHaveLength(2);
// Both collide with the viewer's own indigo, so each gets a distinct free preset
expect(incoming[0].color).not.toBe('#6366f1');
expect(incoming[1].color).not.toBe('#6366f1');
expect(incoming[0].color).not.toBe(incoming[1].color);
});
});
describe('removeShare', () => {
it('VACAY-SVC-056: the owner can revoke their share', () => {
const { user: owner } = setupUserWithPlan();
const { user: viewer } = createUser(testDb);
shareCalendar(owner.id, owner.email, viewer.id);
const shareId = listShares(owner.id).outgoing[0].id as number;
expect(removeShare(shareId, owner.id)).toBe(true);
const row = testDb.prepare('SELECT id FROM vacay_shares WHERE id = ?').get(shareId);
expect(row).toBeUndefined();
});
it('VACAY-SVC-057: the recipient can remove a share they received', () => {
const { user: owner } = setupUserWithPlan();
const { user: viewer } = createUser(testDb);
shareCalendar(owner.id, owner.email, viewer.id);
const shareId = listShares(viewer.id).incoming[0].id;
expect(removeShare(shareId, viewer.id)).toBe(true);
});
it('VACAY-SVC-058: a third user cannot remove the share, unknown ids return false', () => {
const { user: owner } = setupUserWithPlan();
const { user: viewer } = createUser(testDb);
const { user: stranger } = createUser(testDb);
shareCalendar(owner.id, owner.email, viewer.id);
const shareId = listShares(owner.id).outgoing[0].id as number;
expect(removeShare(shareId, stranger.id)).toBe(false);
const row = testDb.prepare('SELECT id FROM vacay_shares WHERE id = ?').get(shareId);
expect(row).toBeDefined();
expect(removeShare(99999, owner.id)).toBe(false);
});
});
describe('setShareHidden', () => {
it('VACAY-SVC-059: the recipient can hide and unhide the shared calendar', () => {
const { user: owner } = setupUserWithPlan();
const { user: viewer } = createUser(testDb);
shareCalendar(owner.id, owner.email, viewer.id);
const shareId = listShares(viewer.id).incoming[0].id;
expect(setShareHidden(shareId, viewer.id, true)).toBe(true);
let row = testDb.prepare('SELECT hidden FROM vacay_shares WHERE id = ?').get(shareId) as { hidden: number };
expect(row.hidden).toBe(1);
expect(listShares(viewer.id).incoming[0].hidden).toBe(true);
expect(setShareHidden(shareId, viewer.id, false)).toBe(true);
row = testDb.prepare('SELECT hidden FROM vacay_shares WHERE id = ?').get(shareId) as { hidden: number };
expect(row.hidden).toBe(0);
});
it('VACAY-SVC-060: the owner cannot toggle the recipient hidden flag', () => {
const { user: owner } = setupUserWithPlan();
const { user: viewer } = createUser(testDb);
shareCalendar(owner.id, owner.email, viewer.id);
const shareId = listShares(owner.id).outgoing[0].id as number;
expect(setShareHidden(shareId, owner.id, true)).toBe(false);
const row = testDb.prepare('SELECT hidden FROM vacay_shares WHERE id = ?').get(shareId) as { hidden: number };
expect(row.hidden).toBe(0);
});
});
describe('getShareAvailableUsers', () => {
it('VACAY-SVC-061: excludes self, already-shared users and plan members', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: member } = createUser(testDb);
insertMember(plan.id, member.id, 'accepted');
const { user: shared } = createUser(testDb);
shareCalendar(owner.id, owner.email, shared.id);
const { user: unrelated } = createUser(testDb);
const ids = (getShareAvailableUsers(owner.id) as { id: number }[]).map(u => u.id);
expect(ids).toContain(unrelated.id);
expect(ids).not.toContain(owner.id);
expect(ids).not.toContain(member.id);
expect(ids).not.toContain(shared.id);
});
});
describe('getSharedCalendars', () => {
it('VACAY-SVC-062: returns only the owner entries of the shared plan, including fractions', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: member } = createUser(testDb);
insertMember(plan.id, member.id, 'accepted');
const { user: viewer } = setupUserWithPlan();
toggleEntry(owner.id, plan.id, '2025-06-10', 1);
toggleEntry(owner.id, plan.id, '2025-06-11', 0.5);
toggleEntry(member.id, plan.id, '2025-06-12', 1);
shareCalendar(owner.id, owner.email, viewer.id);
const calendars = getSharedCalendars(viewer.id, '2025');
expect(calendars).toHaveLength(1);
expect(calendars[0].owner_id).toBe(owner.id);
expect(calendars[0].owner_name).toBe(owner.username);
expect(calendars[0].hidden).toBe(false);
expect(calendars[0].entries).toEqual([
{ date: '2025-06-10', fraction: 1 },
{ date: '2025-06-11', fraction: 0.5 },
]);
});
it('VACAY-SVC-063: company holidays stay hidden while the owner plan has them disabled', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: viewer } = createUser(testDb);
testDb.prepare('UPDATE vacay_plans SET company_holidays_enabled = 0 WHERE id = ?').run(plan.id);
toggleCompanyHoliday(plan.id, '2025-12-24', 'Christmas Eve', undefined);
shareCalendar(owner.id, owner.email, viewer.id);
const calendars = getSharedCalendars(viewer.id, '2025');
expect(calendars[0].companyHolidays).toEqual([]);
});
it('VACAY-SVC-064: company holidays appear once the owner plan enables them', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: viewer } = createUser(testDb);
testDb.prepare('UPDATE vacay_plans SET company_holidays_enabled = 1 WHERE id = ?').run(plan.id);
toggleCompanyHoliday(plan.id, '2025-12-24', 'Christmas Eve', undefined);
shareCalendar(owner.id, owner.email, viewer.id);
const calendars = getSharedCalendars(viewer.id, '2025');
expect(calendars[0].companyHolidays).toEqual([{ date: '2025-12-24' }]);
});
it('VACAY-SVC-065: an owner without any plan yields empty arrays (no lazy creation)', () => {
const { user: owner } = createUser(testDb); // never touched vacay — no plan row
const { user: viewer } = createUser(testDb);
testDb.prepare('INSERT INTO vacay_shares (owner_id, user_id) VALUES (?, ?)').run(owner.id, viewer.id);
const calendars = getSharedCalendars(viewer.id, '2025');
expect(calendars).toHaveLength(1);
expect(calendars[0].entries).toEqual([]);
expect(calendars[0].companyHolidays).toEqual([]);
const plan = testDb.prepare('SELECT id FROM vacay_plans WHERE owner_id = ?').get(owner.id);
expect(plan).toBeUndefined();
});
it('VACAY-SVC-066: follows an owner fused into another plan', () => {
const { user: host, plan: hostPlan } = setupUserWithPlan();
const { user: owner } = createUser(testDb);
getOwnPlan(owner.id);
insertMember(hostPlan.id, owner.id, 'accepted');
const { user: viewer } = createUser(testDb);
toggleEntry(owner.id, hostPlan.id, '2025-03-03', 1);
shareCalendar(owner.id, owner.email, viewer.id);
const calendars = getSharedCalendars(viewer.id, '2025');
expect(calendars).toHaveLength(1);
expect(calendars[0].entries).toEqual([{ date: '2025-03-03', fraction: 1 }]);
});
});