Refactor to use ClientSchedule on client

Use the ClientSchedule data structure for deserialising and tracking
edit state on the client instead of trying to directly deal with the
ApiSchedule type which is not build for ease of edits or rendering.
This commit is contained in:
Hornwitser 2025-06-14 19:22:53 +02:00
parent ce9f758f84
commit bb450fd583
15 changed files with 488 additions and 1297 deletions

View file

@ -1,9 +1,6 @@
<template>
<div v-if="schedule.deleted">
Error: Unexpected deleted schedule.
</div>
<div v-else>
<Timetable :schedule="schedulePreview" :eventSlotFilter :shiftSlotFilter />
<div>
<Timetable :schedule :eventSlotFilter :shiftSlotFilter />
<table>
<thead>
<tr>
@ -23,7 +20,7 @@
v-for="ss in shiftSlots"
:key='ss.slot?.id ?? ss.start.toMillis()'
:class='{
removed: ss.type === "slot" && removed.has(ss.id),
removed: ss.slot?.deleted || ss.shift?.deleted,
gap: ss.type === "gap",
}'
>
@ -39,21 +36,22 @@
>
</td>
<td>
<input
type="text"
v-model="newShiftName"
>
<input
type="text"
v-model="newShiftName"
>
</td>
<td></td>
<td>
<select
v-model="newShiftRole"
v-model="newShiftRoleId"
>
<option
v-for="role in schedule.roles?.filter(r => !r.deleted)"
v-for="role in schedule.roles.values()"
:key="role.id"
:value="role.id"
:selected="role.id === newShiftRole"
:disabled="role.deleted"
:selected="role.id === newShiftRoleId"
>{{ role.name }}</option>
</select>
</td>
@ -96,20 +94,21 @@
<input
type="text"
:value="ss.name"
@input="editShiftSlot(ss, { name: ($event as any).target.value })"
@input="editShift(ss, { name: ($event as any).target.value })"
>
</td>
<td>{{ status(ss) }}</td>
<td>
<select
:value="ss.roleId"
@change="editShiftSlot(ss, { roleId: parseInt(($event as any).target.value) })"
:value="ss.role.id"
@change="editShift(ss, { role: schedule.roles.get(parseInt(($event as any).target.value)) })"
>
<option
v-for="role in schedule.roles?.filter(r => !r.deleted)"
v-for="role in schedule.roles.values()"
:key="role.id"
:value="role.id"
:selected="role.id === ss.roleId"
:disabled="role.deleted"
:selected="role.id === ss.role.id"
>{{ role.name }}</option>
</select>
</td>
@ -122,12 +121,12 @@
</td>
<td>
<button
:disabled="removed.has(ss.id)"
:disabled="ss.deleted"
type="button"
@click="delShiftSlot(ss)"
@click="editShiftSlot(ss, { deleted: true })"
>Remove</button>
<button
v-if="changes.some(c => c.id === ss.id)"
v-if="schedule.isModifiedShiftSlot(ss.slot.id)"
type="button"
@click="revertShiftSlot(ss.id)"
>Revert</button>
@ -187,63 +186,37 @@
<td>{{ ss.end.diff(ss.start).toFormat('hh:mm') }}</td>
<td>{{ ss.name }}</td>
<td>{{ status(ss) }}</td>
<td>{{ ss.roleId }}</td>
<td>{{ ss.role.id }}</td>
<td><AssignedCrew :modelValue="ss.assigned" :edit="false" /></td>
</template>
</tr>
</template>
</tbody>
</table>
<p v-if="changes.length">
Changes are not save yet.
<button
type="button"
@click="saveShiftSlots"
>Save Changes</button>
</p>
<details>
<summary>Debug</summary>
<b>ShiftSlot changes</b>
<ol>
<li v-for="change in changes">
<pre><code>{{ JSON.stringify((({ shift, slot, ...data }) => data)(change as any), undefined, " ") }}</code></pre>
</li>
</ol>
<b>Shift changes</b>
<ol>
<li v-for="change in shiftChanges">
<pre><code>{{ JSON.stringify((({ shift, slot, ...data }) => data)(change as any), undefined, " ") }}</code></pre>
</li>
</ol>
</details>
</div>
</template>
<script lang="ts" setup>
import { DateTime, Duration } from 'luxon';
import type { ApiSchedule, ApiScheduleEventSlot, ApiScheduleShift, ApiScheduleShiftSlot } from '~/shared/types/api';
import { applyUpdatesToArray } from '~/shared/utils/update';
import { enumerate, pairs } from '~/shared/utils/functions';
import type { Entity } from '~/shared/types/common';
import { DateTime, Duration } from '~/shared/utils/luxon';
import { enumerate, pairs, toId } from '~/shared/utils/functions';
import type { Id } from '~/shared/types/common';
const props = defineProps<{
edit?: boolean,
roleId?: number,
eventSlotFilter?: (slot: ApiScheduleEventSlot) => boolean,
shiftSlotFilter?: (slot: ApiScheduleShiftSlot) => boolean,
roleId?: Id,
eventSlotFilter?: (slot: ClientScheduleEventSlot) => boolean,
shiftSlotFilter?: (slot: ClientScheduleShiftSlot) => boolean,
}>();
interface ShiftSlot {
type: "slot",
id: number,
updatedAt: string,
deleted?: boolean,
shift?: Extract<ApiScheduleShift, { deleted?: false }>,
slot?: ApiScheduleShiftSlot,
origRole: number,
id: Id,
deleted: boolean,
shift: ClientScheduleShift,
slot: ClientScheduleShiftSlot,
name: string,
roleId: number,
assigned: number[],
role: ClientScheduleRole,
assigned: Set<Id>,
start: DateTime,
end: DateTime,
}
@ -254,191 +227,25 @@ interface Gap {
shift?: undefined,
slot?: undefined,
name?: undefined,
roleId?: number,
role?: undefined,
start: DateTime,
end: DateTime,
}
function status(shiftSlot: ShiftSlot) {
if (schedule.value.deleted) {
throw new Error("Unexpected deleted schedule");
}
if (
!shiftSlot.shift
|| shiftSlot.shift.name !== shiftSlot.name
) {
const shift = schedule.value.shifts?.find(shift => !shift.deleted && shift.name === shiftSlot.name);
const shift = [...schedule.value.shifts.values()].find(shift => !shift.deleted && shift.name === shiftSlot.name);
return shift ? "L" : "N";
}
return shiftSlot.shift.slots.length === 1 ? "" : shiftSlot.shift.slots.length;
}
// Filter out set records where a del record exists for the same id.
function filterSetOps<T extends Entity>(changes: T[]) {
const deleteIds = new Set(changes.filter(c => c.deleted).map(c => c.id));
return changes.filter(c => c.deleted || !deleteIds.has(c.id));
}
function findShift(
shiftSlot: ShiftSlot,
changes: ApiScheduleShift[],
schedule: ApiSchedule,
) {
if (schedule.deleted) {
throw new Error("Unexpected deleted schedule");
}
let setShift = changes.filter(
c => !c.deleted,
).find(
c => (
c.name === shiftSlot.name
&& c.roleId === shiftSlot.roleId
)
);
if (
!setShift
&& shiftSlot.shift
&& shiftSlot.shift.name === shiftSlot.name
) {
setShift = shiftSlot.shift;
}
if (!setShift) {
setShift = schedule.shifts?.filter(s => !s.deleted).find(s => s.name === shiftSlot.name);
}
let delShift;
if (shiftSlot.shift) {
delShift = changes.filter(c => !c.deleted).find(
c => c.name === shiftSlot.shift!.name
);
if (!delShift) {
delShift = schedule.shifts?.filter(s => !s.deleted).find(s => s.name === shiftSlot.shift!.name);
}
}
return { setShift, delShift };
}
function mergeSlot(
shift: Extract<ApiScheduleShift, { deleted?: false }>,
shiftSlot: ShiftSlot,
): Extract<ApiScheduleShift, { deleted?: false }> {
if (schedule.value.deleted) {
throw new Error("Unexpected deleted schedule");
}
const oldSlot = shift.slots.find(s => s.id === shiftSlot.id);
const nextId = Math.max(0, ...schedule.value.shifts?.filter(s => !s.deleted).flatMap(s => s.slots.map(slot => slot.id)) ?? []) + 1;
const start = shiftSlot.start.toUTC().toISO({ suppressSeconds: true })!;
const end = shiftSlot.end.toUTC().toISO({ suppressSeconds: true })!;
const assigned = shiftSlot.assigned.length ? shiftSlot.assigned : undefined;
if (shift.roleId !== shiftSlot.roleId) {
console.warn(`Attempt to add slot id=${shiftSlot.id} roleId=${shiftSlot.roleId} to shift id=${shift.id} roleId=${shift.roleId}`);
}
// Edit slot in-place if possible
if (oldSlot && oldSlot.id === shiftSlot.id) {
return {
...shift,
slots: shift.slots.map(s => s.id !== oldSlot.id ? s : { ...s, assigned, start, end, }),
};
}
// Else remove old slot if it exist and insert a new one
return {
...shift,
slots: [...(oldSlot ? shift.slots.filter(s => s.id !== oldSlot.id) : shift.slots), {
id: oldSlot ? oldSlot.id : nextId,
assigned,
start,
end,
}],
};
}
const shiftChanges = computed(() => {
let eventChanges: Extract<ApiScheduleShift, { deleted?: false }>[] = [];
for (const change of filterSetOps(changes.value)) {
if (!change.deleted) {
let { setShift, delShift } = findShift(change, eventChanges, schedule.value);
if (delShift && delShift !== setShift) {
eventChanges = removeSlot(eventChanges, delShift, change);
}
if (!setShift) {
setShift = {
id: Math.floor(Math.random() * -1000), // XXX This wont work.
updatedAt: "",
name: change.name,
roleId: change.roleId,
slots: [],
};
}
setShift = {
...setShift,
roleId: change.roleId,
}
eventChanges = replaceChange(mergeSlot(setShift, change), eventChanges);
} else if (change.deleted) {
let { delShift } = findShift(change, eventChanges, schedule.value);
if (delShift) {
eventChanges = removeSlot(eventChanges, delShift, change);
}
}
}
return eventChanges;
});
const schedulePreview = computed(() => {
if (schedule.value.deleted) {
throw new Error("Unexpected deleted schedule");
}
const shifts = [...schedule.value.shifts ?? []]
applyUpdatesToArray(shiftChanges.value, shifts);
return {
...schedule.value,
shifts,
};
});
function removeSlot(
eventChanges: Extract<ApiScheduleShift, { deleted?: false }>[],
shift: Extract<ApiScheduleShift, { deleted?: false }>,
shiftSlot: ShiftSlot,
) {
let oldSlot = shift.slots.find(s => s.id === shiftSlot.id);
if (oldSlot) {
eventChanges = replaceChange({
...shift,
slots: shift.slots.filter(s => s.id !== oldSlot.id)
}, eventChanges);
}
return eventChanges;
return shiftSlot.shift.slots.size === 1 ? "" : shiftSlot.shift.slots.size;
}
const accountStore = useAccountStore();
const schedule = await useSchedule();
const changes = ref<ShiftSlot[]>([]);
const removed = computed(() => new Set(changes.value.filter(c => c.deleted).map(c => c.id)));
function replaceChange<T extends Entity>(
change: T,
changes: T[],
) {
const index = changes.findIndex(item => (
item.deleted === change.deleted && item.id === change.id
));
const copy = [...changes];
if (index !== -1)
copy.splice(index, 1, change);
else
copy.push(change);
return copy;
}
function revertChange<T extends Entity>(id: number, changes: T[]) {
return changes.filter(change => change.id !== id);
}
const oneDayMs = 24 * 60 * 60 * 1000;
function dropDay(diff: Duration) {
if (diff.toMillis() >= oneDayMs) {
@ -450,113 +257,88 @@ function dropDay(diff: Duration) {
const newShiftStart = ref("");
const newShiftDuration = ref("01:00");
const newShiftEnd = computed({
get: () => (
DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: "en-US" })
.plus(Duration.fromISOTime(newShiftDuration.value, { locale: "en-US" }))
.toFormat("HH:mm")
),
get: () => {
try {
return DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: accountStore.activeLocale })
.plus(Duration.fromISOTime(newShiftDuration.value, { locale: accountStore.activeLocale }))
.toFormat("HH:mm")
} catch (err) {
return "";
}
},
set: (value: string) => {
const start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: "en-US" });
const start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: accountStore.activeLocale });
const end = endFromTime(start, value);
newShiftDuration.value = dropDay(end.diff(start)).toFormat("hh:mm");
},
});
const newShiftRole = ref(props.roleId);
const newShiftRoleId = ref(props.roleId);
watch(() => props.roleId, () => {
newShiftRole.value = props.roleId;
newShiftRoleId.value = props.roleId;
});
function endFromTime(start: DateTime, time: string) {
let end = start.startOf("day").plus(Duration.fromISOTime(time, { locale: "en-US" }));
let end = start.startOf("day").plus(Duration.fromISOTime(time, { locale: accountStore.activeLocale }));
if (end.toMillis() <= start.toMillis()) {
end = end.plus({ days: 1 });
}
return end;
}
function durationFromTime(time: string) {
let duration = Duration.fromISOTime(time, { locale: "en-US" });
let duration = Duration.fromISOTime(time, { locale: accountStore.activeLocale });
if (duration.toMillis() === 0) {
duration = Duration.fromMillis(oneDayMs, { locale: "en-US" });
duration = Duration.fromMillis(oneDayMs, { locale: accountStore.activeLocale });
}
return duration;
}
const newShiftName = ref("");
function editShift(
shiftSlot: ShiftSlot,
edits: Parameters<ClientSchedule["editShift"]>[1],
) {
schedule.value.editShift(shiftSlot.shift, edits);
}
function editShiftSlot(
shiftSlot: ShiftSlot,
edits: {
deleted?: boolean,
start?: string,
end?: string,
duration?: string,
name?: string,
roleId?: number,
assigned?: number[],
assigned?: Set<Id>,
}
) {
const computedEdits: Parameters<ClientSchedule["editShiftSlot"]>[1] = {
deleted: edits.deleted,
assigned: edits.assigned,
};
if (edits.start) {
const start = DateTime.fromISO(edits.start, { zone: accountStore.activeTimezone, locale: "en-US" });
shiftSlot = {
...shiftSlot,
start,
end: start.plus(shiftSlot.end.diff(shiftSlot.start)),
};
const start = DateTime.fromISO(edits.start, { zone: accountStore.activeTimezone, locale: accountStore.activeLocale });
computedEdits.start = start;
computedEdits.end = start.plus(shiftSlot.slot.end.diff(shiftSlot.slot.start));
}
if (edits.end !== undefined) {
shiftSlot = {
...shiftSlot,
end: endFromTime(shiftSlot.start, edits.end),
};
computedEdits.end = endFromTime(shiftSlot.start, edits.end);
}
if (edits.duration !== undefined) {
shiftSlot = {
...shiftSlot,
end: shiftSlot.start.plus(durationFromTime(edits.duration)),
};
computedEdits.end = shiftSlot.start.plus(durationFromTime(edits.duration));
}
if (edits.name !== undefined) {
shiftSlot = {
...shiftSlot,
name: edits.name,
};
}
if (edits.roleId !== undefined) {
let changesCopy = changes.value;
for (const slot of shiftSlots.value) {
if (slot.type === "slot" && slot.shift?.name === shiftSlot.name) {
changesCopy = replaceChange({
...slot,
roleId: edits.roleId,
}, changesCopy);
}
}
changesCopy = replaceChange({
...shiftSlot,
roleId: edits.roleId,
}, changesCopy);
changes.value = changesCopy;
return;
}
if (edits.assigned !== undefined) {
shiftSlot = {
...shiftSlot,
assigned: edits.assigned,
};
}
changes.value = replaceChange(shiftSlot, changes.value);
schedule.value.editShiftSlot(shiftSlot.slot, computedEdits);
}
function delShiftSlot(shiftSlot: ShiftSlot) {
const change = {
...shiftSlot,
deleted: true,
};
changes.value = replaceChange(change, changes.value);
}
function revertShiftSlot(id: number) {
changes.value = revertChange(id, changes.value);
function revertShiftSlot(id: Id) {
schedule.value.restoreShiftSlot(id);
}
function newShiftSlot(options: { start?: DateTime, end?: DateTime } = {}) {
const name = newShiftName.value;
const roleId = newShiftRole.value;
if (!roleId) {
const nameId = toId(name);
const shift = [...schedule.value.shifts.values()].find(shift => toId(shift.name) === nameId);
if (!shift) {
alert("Invalid shift");
return;
}
const role = schedule.value.roles.get(newShiftRoleId.value!);
if (!role) {
alert("Invalid role");
return;
}
@ -574,42 +356,23 @@ function newShiftSlot(options: { start?: DateTime, end?: DateTime } = {}) {
end = options.end;
start = options.end.minus(duration);
} else {
start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: "en-US" });
start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: accountStore.activeLocale });
end = endFromTime(start, newShiftEnd.value);
}
if (!start.isValid || !end.isValid) {
alert("Invalid start and/or end time");
return;
}
const change: ShiftSlot = {
type: "slot",
updatedAt: "",
id: Math.floor(Math.random() * -1000), // XXX this wont work.
name,
origRole: roleId,
roleId,
assigned: [],
const slot = new ClientScheduleShiftSlot(
schedule.value.nextClientId--,
false,
shift.id,
start,
end,
};
new Set(),
);
schedule.value.setShiftSlot(slot);
newShiftName.value = "";
changes.value = replaceChange(change, changes.value);
}
async function saveShiftSlots() {
try {
await $fetch("/api/schedule", {
method: "PATCH",
body: {
id: 111,
updatedAt: "",
shifts: shiftChanges.value
} satisfies ApiSchedule,
});
changes.value = [];
} catch (err: any) {
console.error(err);
alert(err?.data?.message ?? err.message);
}
}
const oneHourMs = 60 * 60 * 1000;
@ -623,33 +386,29 @@ function gapFormat(gap: Gap) {
}
const shiftSlots = computed(() => {
if (schedule.value.deleted) {
throw new Error("Unexpected deleted schedule");
}
const data: (ShiftSlot | Gap)[] = [];
for (const shift of schedule.value.shifts ?? []) {
if (shift.deleted || props.roleId !== undefined && shift.roleId !== props.roleId)
for (const shift of schedule.value.shifts.values()) {
if (props.roleId !== undefined && shift.role.id !== props.roleId)
continue;
for (const slot of shift.slots) {
for (const slot of shift.slots.values()) {
if (props.shiftSlotFilter && !props.shiftSlotFilter(slot))
continue;
data.push({
type: "slot",
id: slot.id,
updatedAt: "",
deleted: slot.deleted || shift.deleted,
shift,
slot,
name: shift.name,
roleId: shift.roleId,
assigned: slot.assigned ?? [],
origRole: shift.roleId,
start: DateTime.fromISO(slot.start, { zone: accountStore.activeTimezone, locale: "en-US" }),
end: DateTime.fromISO(slot.end, { zone: accountStore.activeTimezone, locale: "en-US" }),
role: shift.role,
assigned: slot.assigned,
start: slot.start,
end: slot.end,
});
}
}
applyUpdatesToArray(changes.value.filter(c => !c.deleted), data as ShiftSlot[]);
data.sort((a, b) => a.start.toMillis() - b.start.toMillis() || a.end.toMillis() - b.end.toMillis());
const byTime = (a: DateTime, b: DateTime) => a.toMillis() - b.toMillis();
data.sort((a, b) => byTime(a.start, b.start) || byTime(a.end, b.end));
// Insert gaps
let maxEnd = 0;
@ -659,8 +418,7 @@ const shiftSlots = computed(() => {
if (maxEnd < second.start.toMillis()) {
gaps.push([index, {
type: "gap",
roleId: props.roleId,
start: DateTime.fromMillis(maxEnd, { locale: "en-US" }),
start: DateTime.fromMillis(maxEnd, { locale: accountStore.activeLocale }),
end: second.start,
}]);
}