92 lines
2.3 KiB
TypeScript
Executable File
92 lines
2.3 KiB
TypeScript
Executable File
import { addDays } from '@/lib/calendar';
|
|
import type { VacationPeriod } from '@/types/planner';
|
|
|
|
let tempId = -1;
|
|
|
|
/**
|
|
* Pure mirror of the backend PeriodService: add a range, merging
|
|
* overlapping/adjacent periods of the same marker. Used for optimistic UI.
|
|
*/
|
|
export function addRangeOptimistic(
|
|
periods: VacationPeriod[],
|
|
markerId: number,
|
|
start: string,
|
|
end: string,
|
|
): VacationPeriod[] {
|
|
const rest: VacationPeriod[] = [];
|
|
let mergedStart = start;
|
|
let mergedEnd = end;
|
|
|
|
for (const period of periods) {
|
|
const touches =
|
|
period.marker_id === markerId &&
|
|
period.start_date <= addDays(end, 1) &&
|
|
period.end_date >= addDays(start, -1);
|
|
|
|
if (touches) {
|
|
if (period.start_date < mergedStart) {
|
|
mergedStart = period.start_date;
|
|
}
|
|
|
|
if (period.end_date > mergedEnd) {
|
|
mergedEnd = period.end_date;
|
|
}
|
|
} else {
|
|
rest.push(period);
|
|
}
|
|
}
|
|
|
|
return [
|
|
...rest,
|
|
{
|
|
id: tempId--,
|
|
marker_id: markerId,
|
|
start_date: mergedStart,
|
|
end_date: mergedEnd,
|
|
},
|
|
];
|
|
}
|
|
|
|
/** Pure mirror of the backend toggleDay (remove / split / add). */
|
|
export function toggleDayOptimistic(
|
|
periods: VacationPeriod[],
|
|
markerId: number,
|
|
date: string,
|
|
): VacationPeriod[] {
|
|
const covering = periods.find(
|
|
(p) =>
|
|
p.marker_id === markerId &&
|
|
p.start_date <= date &&
|
|
p.end_date >= date,
|
|
);
|
|
|
|
if (!covering) {
|
|
return addRangeOptimistic(periods, markerId, date, date);
|
|
}
|
|
|
|
const rest = periods.filter((p) => p.id !== covering.id);
|
|
|
|
if (covering.start_date === date && covering.end_date === date) {
|
|
return rest;
|
|
}
|
|
|
|
if (covering.start_date === date) {
|
|
return [...rest, { ...covering, start_date: addDays(date, 1) }];
|
|
}
|
|
|
|
if (covering.end_date === date) {
|
|
return [...rest, { ...covering, end_date: addDays(date, -1) }];
|
|
}
|
|
|
|
return [
|
|
...rest,
|
|
{ ...covering, end_date: addDays(date, -1) },
|
|
{
|
|
id: tempId--,
|
|
marker_id: markerId,
|
|
start_date: addDays(date, 1),
|
|
end_date: covering.end_date,
|
|
},
|
|
];
|
|
}
|