mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(vacay): leave days follow a moved trip as a whole block and never land on blocked days
Moving a trip's start shifted the owner's vacay entries one row at a time, checking each target against rows that were about to move themselves. A block shifted by less than its own length kept its first days behind and pushed the rest onto the weekend, even with weekends blocked. The shift now decides every day before writing: a day whose target is a blocked weekend or a whole company holiday is dropped, as is one whose target already holds leave that is not moving; a half company holiday leaves half a day. The rest move in the direction of travel inside one transaction. The plan is the one the owner is active in, so a member of a fused plan gets their days moved too, and a trip edit no longer creates a vacay plan for an owner who has none. Open vacay views are notified after the trip update commits. The pure vacay helpers moved to vacay.helpers.ts and the trip window tests to their own suite, so both files stay inside their size budgets. Refs #2604
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
import { dateAdd } from '../dialect/sql-functions';
|
||||
import type { VacayEntries } from '../entities/VacayEntries.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
@@ -18,13 +17,6 @@ export interface VacayEntryWithPersonRow {
|
||||
person_color: string;
|
||||
}
|
||||
|
||||
/** SQLite's `date(<col>, '+N days')` — the same calendar-day arithmetic `dateAdd` spells in SQL (§13), computed in JS for {@link VacayEntriesRepository.shiftForOwnerWindow}'s collision pre-check. Verified against SQLite's own `date()` modifier: both walk the proleptic Gregorian calendar by whole days, so they agree on every input (the same reasoning R9's VC4 date-diff verification gives). */
|
||||
function shiftIsoDate(isoDate: string, days: number): string {
|
||||
const d = new Date(`${isoDate}T00:00:00Z`);
|
||||
d.setUTCDate(d.getUTCDate() + days);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export class VacayEntriesRepository extends TrekRepository<VacayEntries> {
|
||||
/**
|
||||
* VC1 — `SELECT COALESCE(SUM(CASE WHEN kind = 'comp' THEN 0 ELSE fraction
|
||||
@@ -79,40 +71,28 @@ export class VacayEntriesRepository extends TrekRepository<VacayEntries> {
|
||||
}
|
||||
|
||||
/**
|
||||
* VC5 (`shiftOwnerEntriesForTripWindow`) — `UPDATE OR IGNORE vacay_entries
|
||||
* SET date = date(date, ? || ' days') WHERE plan_id = ? AND user_id = ? AND
|
||||
* date BETWEEN ? AND ?`. SQLite's per-statement `OR IGNORE`
|
||||
* conflict-resolution clause applies to UPDATE as well as INSERT, but
|
||||
* neither Kysely's `UpdateQueryBuilder` (only `.modifyEnd()`, which appends
|
||||
* AFTER the whole statement, not after the `UPDATE` keyword) nor MikroORM's
|
||||
* `nativeUpdate` exposes it — a genuine builder gap, not a helper this
|
||||
* plan's R9 anticipated (R9's own VC5 note only covers the date
|
||||
* EXPRESSION, via the existing `dateAdd`, not this conflict-resolution
|
||||
* clause). Reproduced as a read-then-conditionally-write loop instead:
|
||||
* read every candidate row, and for each one whose shifted date would
|
||||
* collide with an existing `(user, plan, date)` row, skip it — `OR
|
||||
* IGNORE`'s own per-row behavior, exactly — otherwise write it with
|
||||
* `dateAdd` (still the SQL-computed value, per R9). Low-volume,
|
||||
* request-scoped (a trip's own leave entries on a date-window move, never
|
||||
* a hot path), so the per-row round trip is not a concern.
|
||||
* VC5 (`shiftOwnerEntriesForTripWindow`): `SELECT id, date, fraction FROM
|
||||
* vacay_entries WHERE plan_id = ? AND user_id = ? AND date BETWEEN ? AND ?
|
||||
* ORDER BY date`: the leave days a trip window move carries along, and the
|
||||
* ones already standing on its targets. The service decides each row's fate
|
||||
* and writes it with {@link moveEntry} or {@link deleteById} (#2604).
|
||||
*/
|
||||
async shiftForOwnerWindow(planId: number, userId: number, start: string, end: string, offset: number): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
// M1 (task-7-review.md): legacy's single `UPDATE OR IGNORE` walks rows in
|
||||
// rowid order; without an explicit orderBy here, SQLite returns rows in
|
||||
// (user, plan, date) index order instead, so the per-row collision check
|
||||
// above skips different rows than legacy did on consecutive days inserted
|
||||
// out of id order.
|
||||
async listForOwnerWindow(
|
||||
planId: number,
|
||||
userId: number,
|
||||
start: string,
|
||||
end: string,
|
||||
): Promise<{ id: number; date: string; fraction: number }[]> {
|
||||
const rows = await this.find(
|
||||
{ plan: planId, user: userId, date: { $gte: start, $lte: end } },
|
||||
{ fields: ['id', 'date'], orderBy: { id: 'asc' } },
|
||||
{ fields: ['id', 'date', 'fraction'], orderBy: { date: 'asc' } },
|
||||
);
|
||||
for (const row of rows) {
|
||||
const shiftedDate = shiftIsoDate(row.date, offset);
|
||||
const collision = await this.findOne({ plan: planId, user: userId, date: shiftedDate }, { fields: ['id'] });
|
||||
if (collision) continue;
|
||||
await this.nativeUpdate({ id: row.id }, { date: dateAdd(platform, 'date', offset) });
|
||||
}
|
||||
return rows.map((row) => ({ id: row.id, date: row.date, fraction: row.fraction }));
|
||||
}
|
||||
|
||||
/** VC5: `UPDATE vacay_entries SET date = ?, fraction = ? WHERE id = ?`, one moved day of `shiftOwnerEntriesForTripWindow`. */
|
||||
async moveEntry(id: number, date: string, fraction: number): Promise<void> {
|
||||
await this.nativeUpdate({ id }, { date, fraction });
|
||||
}
|
||||
|
||||
/** VC24/VC30/VC121 — `DELETE FROM vacay_entries WHERE plan_id = ? AND date = ?` (`applyHolidayCalendars`'s auto-clear, and `makeRoomForCompanyHoliday`'s whole-holiday clear, reached from `updatePlan`'s company-holiday enable and `toggleCompanyHoliday`). */
|
||||
|
||||
@@ -522,6 +522,7 @@ export class TripsService {
|
||||
// The row, the leave entries that follow its dates and the rebuilt day grid are
|
||||
// one write: a failure halfway used to leave a trip whose days missed its dates.
|
||||
let removedDays: DayGridRemoval[] = [];
|
||||
let vacayId: number | undefined; // the vacay plan whose leave days moved along (#2604)
|
||||
await this.uow.transactional(async () => {
|
||||
// Before the row: the rebase reads the outgoing currency off it (#1543).
|
||||
if (rebase) await this.budget.applyCurrencyRebase(tripId, rebase);
|
||||
@@ -542,7 +543,7 @@ export class TripsService {
|
||||
});
|
||||
|
||||
if (trip.start_date && trip.end_date && newStart && newStart !== trip.start_date)
|
||||
await this.vacay.shiftOwnerEntriesForTripWindow(trip.user_id, trip.start_date, trip.end_date, newStart);
|
||||
vacayId = await this.vacay.shiftOwnerEntriesForTripWindow(trip.user_id, trip.start_date, trip.end_date, newStart);
|
||||
|
||||
if (regenerate) {
|
||||
// Accommodations have no absolute date columns, so their pre-change dates must be
|
||||
@@ -565,6 +566,7 @@ export class TripsService {
|
||||
}
|
||||
}
|
||||
});
|
||||
if (vacayId !== undefined) await this.vacay.notifyPlanUsers(vacayId, undefined);
|
||||
|
||||
const changes: Record<string, unknown> = {};
|
||||
if (title && title !== trip.title) changes.title = title;
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Pure half of the vacay domain (no DB access), moved out of vacay.service.ts
|
||||
* so the service keeps to its size budget.
|
||||
*/
|
||||
|
||||
/** Coerce an arbitrary input to a supported entry fraction: half (0.5) or full (1). */
|
||||
export function normalizeFraction(value: unknown): number {
|
||||
return Number(value) === 0.5 ? 0.5 : 1;
|
||||
}
|
||||
|
||||
/** Coerce an arbitrary input to a supported leave type: comp/flex or vacation (#1074). */
|
||||
export function normalizeKind(value: unknown): 'vacation' | 'comp' {
|
||||
return value === 'comp' ? 'comp' : 'vacation';
|
||||
}
|
||||
|
||||
/**
|
||||
* Same semantics as the client's isWeekend guard (holidays.ts): UTC weekday,
|
||||
* weekend_days falls back to Sat/Sun when the column is NULL or empty.
|
||||
*/
|
||||
export function isBlockedWeekend(
|
||||
plan: { block_weekends: number | null; weekend_days: string | null },
|
||||
date: string,
|
||||
): boolean {
|
||||
if (!plan.block_weekends) return false;
|
||||
const days = plan.weekend_days ? String(plan.weekend_days).split(',').map(Number) : [0, 6];
|
||||
return days.includes(new Date(date + 'T00:00:00Z').getUTCDay());
|
||||
}
|
||||
|
||||
export const pad2 = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/** Days a month has in every year — February caps at 28 so no boundary lands on a date a common year lacks. */
|
||||
export function daysAlwaysInMonth(month: number): number {
|
||||
if (month === 2) return 28;
|
||||
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
||||
}
|
||||
|
||||
/** Coerce an arbitrary input to a supported leave-year type (#737). */
|
||||
export function normalizeYearType(value: unknown): 'calendar' | 'fiscal' | 'anniversary' {
|
||||
return value === 'fiscal' || value === 'anniversary' ? value : 'calendar';
|
||||
}
|
||||
|
||||
/**
|
||||
* The calendar year a window's last day falls in. `end` is exclusive, so a window
|
||||
* ending on Jan 1 (the calendar default) stops inside the previous year.
|
||||
*/
|
||||
export function windowEndYear(end: string): number {
|
||||
const y = Number.parseInt(end.slice(0, 4), 10);
|
||||
return end.endsWith('-01-01') ? y - 1 : y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a date or datetime string the way SQLite's `julianday()` does — the
|
||||
* numeric components taken at face value as UTC, never the host's local
|
||||
* timezone. `Date.parse` only does this for a bare `YYYY-MM-DD`; a datetime
|
||||
* string with no zone suffix (`2025-06-12T23:30`) is local time per the ES
|
||||
* spec, which drifted from `julianday`'s always-UTC reading by whatever the
|
||||
* server's offset is (M2, task-7-review.md). Unparseable input returns `NaN`.
|
||||
*/
|
||||
export function parseAsUtcMillis(value: string): number {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(value);
|
||||
if (!m) return Number.NaN;
|
||||
const [, y, mo, d, h, mi, s] = m;
|
||||
return Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h ?? 0), Number(mi ?? 0), Number(s ?? 0));
|
||||
}
|
||||
|
||||
/** A `YYYY-MM-DD` date moved by whole calendar days, in UTC. */
|
||||
export function shiftIsoDate(isoDate: string, days: number): string {
|
||||
const d = new Date(`${isoDate}T00:00:00Z`);
|
||||
d.setUTCDate(d.getUTCDate() + days);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
@@ -28,6 +28,10 @@ import { VacayUserSettings as VacayUserSettingsEntity } from '../../db/entities/
|
||||
import type { VacayUserSettingsRepository } from '../../db/repositories/VacayUserSettings.repository';
|
||||
import { SchoolHolidayRegions } from '../../db/entities/SchoolHolidayRegions.entity';
|
||||
import type { SchoolHolidayRegionsRepository } from '../../db/repositories/SchoolHolidayRegions.repository';
|
||||
import {
|
||||
daysAlwaysInMonth, isBlockedWeekend, normalizeFraction, normalizeKind, normalizeYearType, pad2, parseAsUtcMillis,
|
||||
shiftIsoDate, windowEndYear,
|
||||
} from './vacay.helpers';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@@ -141,67 +145,6 @@ const COLORS = [
|
||||
'#10b981', '#0ea5e9', '#64748b', '#be185d', '#0d9488',
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure helpers (no DB access)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Coerce an arbitrary input to a supported entry fraction: half (0.5) or full (1). */
|
||||
function normalizeFraction(value: unknown): number {
|
||||
return Number(value) === 0.5 ? 0.5 : 1;
|
||||
}
|
||||
|
||||
/** Coerce an arbitrary input to a supported leave type: comp/flex or vacation (#1074). */
|
||||
function normalizeKind(value: unknown): 'vacation' | 'comp' {
|
||||
return value === 'comp' ? 'comp' : 'vacation';
|
||||
}
|
||||
|
||||
/**
|
||||
* Same semantics as the client's isWeekend guard (holidays.ts): UTC weekday,
|
||||
* weekend_days falls back to Sat/Sun when the column is NULL or empty.
|
||||
*/
|
||||
function isBlockedWeekend(plan: Pick<VacayPlan, 'block_weekends' | 'weekend_days'>, date: string): boolean {
|
||||
if (!plan.block_weekends) return false;
|
||||
const days = plan.weekend_days ? String(plan.weekend_days).split(',').map(Number) : [0, 6];
|
||||
return days.includes(new Date(date + 'T00:00:00Z').getUTCDay());
|
||||
}
|
||||
|
||||
const pad2 = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/** Days a month has in every year — February caps at 28 so no boundary lands on a date a common year lacks. */
|
||||
function daysAlwaysInMonth(month: number): number {
|
||||
if (month === 2) return 28;
|
||||
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
||||
}
|
||||
|
||||
/** Coerce an arbitrary input to a supported leave-year type (#737). */
|
||||
function normalizeYearType(value: unknown): 'calendar' | 'fiscal' | 'anniversary' {
|
||||
return value === 'fiscal' || value === 'anniversary' ? value : 'calendar';
|
||||
}
|
||||
|
||||
/**
|
||||
* The calendar year a window's last day falls in. `end` is exclusive, so a window
|
||||
* ending on Jan 1 (the calendar default) stops inside the previous year.
|
||||
*/
|
||||
function windowEndYear(end: string): number {
|
||||
const y = Number.parseInt(end.slice(0, 4), 10);
|
||||
return end.endsWith('-01-01') ? y - 1 : y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a date or datetime string the way SQLite's `julianday()` does — the
|
||||
* numeric components taken at face value as UTC, never the host's local
|
||||
* timezone. `Date.parse` only does this for a bare `YYYY-MM-DD`; a datetime
|
||||
* string with no zone suffix (`2025-06-12T23:30`) is local time per the ES
|
||||
* spec, which drifted from `julianday`'s always-UTC reading by whatever the
|
||||
* server's offset is (M2, task-7-review.md). Unparseable input returns `NaN`.
|
||||
*/
|
||||
function parseAsUtcMillis(value: string): number {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(value);
|
||||
if (!m) return Number.NaN;
|
||||
const [, y, mo, d, h, mi, s] = m;
|
||||
return Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h ?? 0), Number(mi ?? 0), Number(s ?? 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Vacay domain service — owns the vacay SQL, now through the ten vacay
|
||||
* repositories (+ `SchoolHolidayRegionsRepository`'s cross-domain read,
|
||||
@@ -405,12 +348,22 @@ export class VacayService {
|
||||
return (await this.getActivePlan(userId)).id;
|
||||
}
|
||||
|
||||
/**
|
||||
* A trip's new start carries its owner's leave days along by the same offset
|
||||
* (#983), in whatever plan the owner is active in, a fused one included. Each
|
||||
* day either moves or is dropped: a target on a blocked weekend or a whole
|
||||
* company holiday is no leave day, and a target already holding leave that
|
||||
* stays put is leave already. A half company holiday leaves half a day, as in
|
||||
* toggleEntry. Public holidays come from an outside API and are not checked
|
||||
* inside the trip's transaction. Returns the plan whose entries changed, so
|
||||
* the caller can notify its users once the transaction is committed (#2604).
|
||||
*/
|
||||
async shiftOwnerEntriesForTripWindow(
|
||||
ownerId: number,
|
||||
oldStart: string,
|
||||
oldEnd: string,
|
||||
newStart: string
|
||||
): Promise<void> {
|
||||
): Promise<number | undefined> {
|
||||
// VC4 (R9's verified restructured shape): `CAST(julianday(?) - julianday(?)
|
||||
// AS INTEGER)` on two BOUND VALUES is plain JS date-diff arithmetic —
|
||||
// verified against the SQL on 5 date pairs incl. a leap-year boundary and a
|
||||
@@ -422,11 +375,45 @@ export class VacayService {
|
||||
// same as legacy, instead of writing a NaN date and 500ing after the trip
|
||||
// row is already committed.
|
||||
const offset = Math.trunc((parseAsUtcMillis(newStart) - parseAsUtcMillis(oldStart)) / 86400000);
|
||||
if (!Number.isFinite(offset) || offset === 0) return;
|
||||
if (!Number.isFinite(offset) || offset === 0) return undefined;
|
||||
|
||||
const plan = await this.getOwnPlan(ownerId);
|
||||
// A trip edit never creates a plan: without one there is no leave to move.
|
||||
const plan = await this.peekActivePlan(ownerId);
|
||||
if (!plan) return undefined;
|
||||
|
||||
await this.entries.shiftForOwnerWindow(plan.id, ownerId, oldStart, oldEnd, offset);
|
||||
return await this.uow.transactional(async () => {
|
||||
const moving = await this.entries.listForOwnerWindow(plan.id, ownerId, oldStart, oldEnd);
|
||||
if (moving.length === 0) return undefined;
|
||||
const movingIds = new Set(moving.map(row => row.id));
|
||||
const firstTarget = shiftIsoDate(moving[0].date, offset);
|
||||
const lastTarget = shiftIsoDate(moving[moving.length - 1].date, offset);
|
||||
const standing = new Set(
|
||||
(await this.entries.listForOwnerWindow(plan.id, ownerId, firstTarget, lastTarget))
|
||||
.filter(row => !movingIds.has(row.id))
|
||||
.map(row => row.date),
|
||||
);
|
||||
const companyHolidays = plan.company_holidays_enabled
|
||||
? await this.companyHolidays.listDatesForRange(plan.id, firstTarget, shiftIsoDate(lastTarget, 1))
|
||||
: [];
|
||||
const companyFractions = new Map(companyHolidays.map(h => [h.date, h.fraction] as const));
|
||||
|
||||
const moves: { id: number; date: string; fraction: number }[] = [];
|
||||
for (const row of moving) {
|
||||
const date = shiftIsoDate(row.date, offset);
|
||||
const company = companyFractions.get(date);
|
||||
if (standing.has(date) || isBlockedWeekend(plan, date) || (company !== undefined && company >= 1)) {
|
||||
await this.entries.deleteById(row.id);
|
||||
} else {
|
||||
moves.push({ id: row.id, date, fraction: company !== undefined && row.fraction > 0.5 ? 0.5 : row.fraction });
|
||||
}
|
||||
}
|
||||
// Rows move in the direction of travel, so each target is already free of
|
||||
// the moving row that held it when the next one arrives: (user, plan, date)
|
||||
// is unique.
|
||||
if (offset > 0) moves.reverse();
|
||||
for (const move of moves) await this.entries.moveEntry(move.id, move.date, move.fraction);
|
||||
return plan.id;
|
||||
});
|
||||
}
|
||||
|
||||
async getPlanUsers(planId: number): Promise<VacayUser[]> {
|
||||
|
||||
Reference in New Issue
Block a user