Use a pinia store to manage account state
All checks were successful
/ build (push) Successful in 3m29s
/ deploy (push) Successful in 47s

Refactor the existing scattered code dealing with the account state into
a pinia store.
This commit is contained in:
Hornwitser 2025-05-24 20:01:23 +02:00
parent fae8b4e2e4
commit e722876aae
12 changed files with 126 additions and 98 deletions

View file

@ -5,13 +5,13 @@
<p v-if="event.interested">
{{ event.interested }} interested
</p>
<p v-if="sessionStore.account">
<p v-if="accountStore.interestedIds">
<button
class="interested"
:class="{ active: interestedIds.has(event.id) }"
:class="{ active: accountStore.interestedIds?.has(event.id) }"
@click="toggle(event.id, event.slots.map(slot => slot.id))"
>
{{ interestedIds.has(event.id) ? "✔ interested" : "🔔 interested?" }}
{{ accountStore.interestedIds?.has(event.id) ? "✔ interested" : "🔔 interested?" }}
</button>
</p>
@ -20,13 +20,13 @@
<li v-for="slot in event.slots" :key="slot.id">
{{ formatTime(slot.start) }} - {{ formatTime(slot.end) }}
<button
v-if="sessionStore.account && event.slots.length > 1"
v-if="accountStore.interestedIds && event.slots.length > 1"
class="interested"
:disabled="interestedIds.has(event.id)"
:class="{ active: interestedIds.has(event.id) || interestedIds.has(slot.id) }"
:disabled="accountStore.interestedIds.has(event.id)"
:class="{ active: accountStore.interestedIds.has(event.id) || accountStore.interestedIds.has(slot.id) }"
@click="toggle(slot.id)"
>
{{ interestedIds.has(event.id) || interestedIds.has(slot.id) ? "✔ interested" : "🔔 interested?" }}
{{ accountStore.interestedIds.has(event.id) || accountStore.interestedIds.has(slot.id) ? "✔ interested" : "🔔 interested?" }}
</button>
<template v-if="slot.interested">
({{ slot.interested }} interested)
@ -48,33 +48,16 @@ defineProps<{
event: ScheduleEvent
}>()
const runtimeConfig = useRuntimeConfig();
const sessionStore = useSessionStore();
const interestedIds = computed(() => new Set(sessionStore.account?.interestedIds ?? []));
const timezone = computed(() => sessionStore.account?.timezone ?? runtimeConfig.public.defaultTimezone);
const accountStore = useAccountStore();
const { data: accounts } = await useAccounts();
const idToAccount = computed(() => new Map(accounts.value?.map(a => [a.id, a])));
function formatTime(time: string) {
return DateTime.fromISO(time, { zone: timezone.value }).toFormat("yyyy-LL-dd HH:mm");
return DateTime.fromISO(time, { zone: accountStore.activeTimezone }).toFormat("yyyy-LL-dd HH:mm");
}
async function toggle(id: string, slotIds?: string[]) {
let newIds = [...sessionStore.account!.interestedIds ?? []];
if (interestedIds.value.has(id)) {
newIds = newIds.filter(newId => newId !== id);
} else {
newIds.push(id);
if (slotIds) {
const filterIds = new Set(slotIds);
newIds = newIds.filter(newId => !filterIds.has(newId));
}
}
await $fetch("/api/account", {
method: "PATCH",
body: { interestedIds: newIds },
})
await sessionStore.fetch();
await accountStore.toggleInterestedId(id, slotIds);
}
</script>

View file

@ -38,7 +38,7 @@
<td>
<input
type="checkbox"
:disabled="!canEditPublic"
:disabled="!accountStore.canEditPublic"
:value="!event.crew"
:checked="!event.crew"
@change="editEvent(event, { crew: !($event as any).target.value })"
@ -75,7 +75,7 @@
<td>
<input
type="checkbox"
:disabled="!canEditPublic"
:disabled="!accountStore.canEditPublic"
v-model="newEventPublic"
>
</td>
@ -135,11 +135,10 @@ defineProps<{
}>();
const schedule = await useSchedule();
const sessionStore = useSessionStore();
const canEditPublic = computed(() => sessionStore.account?.type === "admin");
const accountStore = useAccountStore();
function canEdit(event: ScheduleEvent) {
return event.crew || canEditPublic.value;
return event.crew || accountStore.canEditPublic;
}
const changes = ref<ChangeRecord<ScheduleEvent>[]>([]);

View file

@ -8,18 +8,18 @@
<li>
<NuxtLink to="/schedule">Schedule</NuxtLink>
</li>
<li v-if="sessionStore.account?.type === 'admin' || sessionStore.account?.type === 'crew'">
<li v-if="accountStore.canEdit">
<NuxtLink to="/edit">Edit</NuxtLink>
</li>
</ul>
</nav>
<div class="account">
<template v-if="sessionStore.account">
{{ sessionStore.account.name }}
(s:{{ sessionStore.id }} a:{{ sessionStore.account.id }}{{ sessionStore.push ? " push" : null }})
{{ sessionStore.account.type }}
<template v-if="accountStore.valid">
{{ accountStore.name }}
(s:{{ sessionStore.id }} a:{{ accountStore.id }}{{ sessionStore.push ? " push" : null }})
{{ accountStore.type }}
<NuxtLink to="/account/settings">Settings</NuxtLink>
<LogOutButton v-if="sessionStore.account.type !== 'anonymous'"/>
<LogOutButton v-if="accountStore.type !== 'anonymous'"/>
</template>
<template v-else>
<NuxtLink to="/login">Log In</NuxtLink>
@ -29,6 +29,7 @@
</template>
<script lang="ts" setup>
const accountStore = useAccountStore();
const sessionStore = useSessionStore();
</script>

View file

@ -424,12 +424,8 @@ function removeSlot(eventChanges: ChangeRecord<ScheduleEvent>[], event: Schedule
return eventChanges;
}
const sessionStore = useSessionStore();
const accountStore = useAccountStore();
const schedule = await useSchedule();
const runtimeConfig = useRuntimeConfig();
const timezone = computed(
() => sessionStore.account?.timezone ?? runtimeConfig.public.defaultTimezone
);
type EventSlotChange = { op: "set" | "del", data: EventSlot } ;
@ -466,12 +462,12 @@ const newEventStart = ref("");
const newEventDuration = ref("01:00");
const newEventEnd = computed({
get: () => (
DateTime.fromISO(newEventStart.value, { zone: timezone.value })
DateTime.fromISO(newEventStart.value, { zone: accountStore.activeTimezone })
.plus(Duration.fromISOTime(newEventDuration.value))
.toFormat("HH:mm")
),
set: (value: string) => {
const start = DateTime.fromISO(newEventStart.value, { zone: timezone.value });
const start = DateTime.fromISO(newEventStart.value, { zone: accountStore.activeTimezone });
const end = endFromTime(start, value);
newEventDuration.value = dropDay(end.diff(start)).toFormat("hh:mm");
},
@ -508,7 +504,7 @@ function editEventSlot(
}
) {
if (edits.start) {
const start = DateTime.fromISO(edits.start, { zone: timezone.value });
const start = DateTime.fromISO(edits.start, { zone: accountStore.activeTimezone });
eventSlot = {
...eventSlot,
start,
@ -577,7 +573,7 @@ function newEventSlot(options: { start?: DateTime, end?: DateTime } = {}) {
end = options.end;
start = options.end.minus(duration);
} else {
start = DateTime.fromISO(newEventStart.value, { zone: timezone.value });
start = DateTime.fromISO(newEventStart.value, { zone: accountStore.activeTimezone });
end = endFromTime(start, newEventEnd.value);
}
if (!start.isValid || !end.isValid) {
@ -641,8 +637,8 @@ const eventSlots = computed(() => {
location,
assigned: slot.assigned ?? [],
origLocation: location,
start: DateTime.fromISO(slot.start, { zone: timezone.value }),
end: DateTime.fromISO(slot.end, { zone: timezone.value }),
start: DateTime.fromISO(slot.start, { zone: accountStore.activeTimezone }),
end: DateTime.fromISO(slot.end, { zone: accountStore.activeTimezone }),
});
}
}

View file

@ -394,12 +394,8 @@ function removeSlot(eventChanges: ChangeRecord<Shift>[], shift: Shift, shiftSlot
return eventChanges;
}
const sessionStore = useSessionStore();
const accountStore = useAccountStore();
const schedule = await useSchedule();
const runtimeConfig = useRuntimeConfig();
const timezone = computed(
() => sessionStore.account?.timezone ?? runtimeConfig.public.defaultTimezone
);
type ShiftSlotChange = { op: "set" | "del", data: ShiftSlot } ;
@ -436,12 +432,12 @@ const newShiftStart = ref("");
const newShiftDuration = ref("01:00");
const newShiftEnd = computed({
get: () => (
DateTime.fromISO(newShiftStart.value, { zone: timezone.value })
DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone })
.plus(Duration.fromISOTime(newShiftDuration.value))
.toFormat("HH:mm")
),
set: (value: string) => {
const start = DateTime.fromISO(newShiftStart.value, { zone: timezone.value });
const start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone });
const end = endFromTime(start, value);
newShiftDuration.value = dropDay(end.diff(start)).toFormat("hh:mm");
},
@ -478,7 +474,7 @@ function editShiftSlot(
}
) {
if (edits.start) {
const start = DateTime.fromISO(edits.start, { zone: timezone.value });
const start = DateTime.fromISO(edits.start, { zone: accountStore.activeTimezone });
shiftSlot = {
...shiftSlot,
start,
@ -558,7 +554,7 @@ function newShiftSlot(options: { start?: DateTime, end?: DateTime } = {}) {
end = options.end;
start = options.end.minus(duration);
} else {
start = DateTime.fromISO(newShiftStart.value, { zone: timezone.value });
start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone });
end = endFromTime(start, newShiftEnd.value);
}
if (!start.isValid || !end.isValid) {
@ -621,8 +617,8 @@ const shiftSlots = computed(() => {
role: shift.role,
assigned: slot.assigned ?? [],
origRole: shift.role,
start: DateTime.fromISO(slot.start, { zone: timezone.value }),
end: DateTime.fromISO(slot.end, { zone: timezone.value }),
start: DateTime.fromISO(slot.start, { zone: accountStore.activeTimezone }),
end: DateTime.fromISO(slot.end, { zone: accountStore.activeTimezone }),
});
}
}

View file

@ -503,16 +503,14 @@ const stretches = computed(() => [
)
])
const runtimeConfig = useRuntimeConfig();
const sessionStore = useSessionStore();
const debugTimezone = ref<undefined | string>();
const accountStore = useAccountStore();
const timezone = computed({
get: () => debugTimezone.value ?? sessionStore.account?.timezone ?? runtimeConfig.public.defaultTimezone,
set: (value: string) => { debugTimezone.value = value },
get: () => accountStore.activeTimezone,
set: (value: string) => { accountStore.timezone = value },
});
const elements = computed(() => tableElementsFromStretches(
stretches.value, schedule.value.events, schedule.value.locations, schedule.value.rota, schedule.value.roles, timezone.value
stretches.value, schedule.value.events, schedule.value.locations, schedule.value.rota, schedule.value.roles, accountStore.activeTimezone
));
const totalColumns = computed(() => elements.value.totalColumns);
const columnGroups = computed(() => elements.value.columnGroups);

View file

@ -1,14 +1,14 @@
export default defineNuxtRouteMiddleware(async (to, from) => {
const sessionStore = useSessionStore();
const accountStore = useAccountStore();
if (!sessionStore.account) {
if (!accountStore.valid) {
console.log("Not logged in, redirecting to /login");
return navigateTo("/login");
}
if (
to.meta.allowedAccountTypes
&& !to.meta.allowedAccountTypes.includes(sessionStore.account.type)
&& !to.meta.allowedAccountTypes.includes(accountStore.type!)
) {
throw createError({
status: 403,

View file

@ -1,14 +1,14 @@
<template>
<main>
<h1>Account Settings</h1>
<p v-if="sessionStore.account?.type !== 'anonymous'">
Name: {{ sessionStore.account?.name }}
<p v-if="accountStore.type !== 'anonymous'">
Name: {{ accountStore.name }}
</p>
<p>Access: {{ sessionStore.account?.type }}</p>
<p>Access: {{ accountStore.type }}</p>
<form @submit.prevent="changeSettings">
<label>
Timezone
<input type="text" v-model="timezone">
<input type="text" v-model="timezone" :placeholder="accountStore.defaultTimezone">
</label>
<button type="submit">
Save
@ -35,8 +35,9 @@ definePageMeta({
});
const sessionStore = useSessionStore();
const accountStore = useAccountStore();
const timezone = ref(sessionStore.account?.timezone ?? "");
const timezone = ref(accountStore.timezone ?? "");
async function changeSettings() {
try {

View file

@ -19,7 +19,7 @@
</select>
</label>
<h2>Locations</h2>
<LocationsTable :edit="isAdmin" />
<LocationsTable :edit="accountStore.canEditPublic" />
<h2>Schedule</h2>
<label>
Location Filter:
@ -77,7 +77,7 @@ definePageMeta({
const schedule = await useSchedule();
const { data: accounts } = await useAccounts();
const sessionStore = useSessionStore();
const accountStore = useAccountStore();
const route = useRoute();
const crewFilter = computed({
@ -91,14 +91,14 @@ const crewFilter = computed({
}),
});
const eventSlotFilter = computed(() => {
if (crewFilter.value === undefined || !sessionStore.account) {
if (crewFilter.value === undefined || !accountStore.valid) {
return () => true;
}
const cid = parseInt(crewFilter.value);
return (slot: TimeSlot) => slot.assigned?.some(id => id === cid) || false;
});
const shiftSlotFilter = computed(() => {
if (crewFilter.value === undefined || !sessionStore.account) {
if (crewFilter.value === undefined || !accountStore.valid) {
return () => true;
}
const cid = parseInt(crewFilter.value);
@ -126,6 +126,4 @@ const roleFilter = computed({
},
}),
});
const isAdmin = computed(() => sessionStore.account?.type === "admin")
</script>

View file

@ -5,13 +5,13 @@
<li>
<NuxtLink to="/schedule">View Schedule</NuxtLink>
</li>
<li v-if="sessionStore.account?.type === 'admin' || sessionStore.account?.type === 'crew'">
<li v-if="accountStore.canEdit">
<NuxtLink to="/edit">Edit Schedule</NuxtLink>
</li>
<li v-if="sessionStore.account">
<li v-if="accountStore.valid">
<NuxtLink to="/account/settings">Account Settings</NuxtLink>
</li>
<li v-if="!sessionStore.account">
<li v-else>
<NuxtLink to="/login">Log In / Create Account</NuxtLink>
</li>
</ul>
@ -19,5 +19,5 @@
</template>
<script lang="ts" setup>
const sessionStore = useSessionStore();
const accountStore = useAccountStore();
</script>

View file

@ -4,7 +4,7 @@
<p>
Study carefully, we only hold these events once a year.
</p>
<p v-if="!sessionStore.account">
<p v-if="!accountStore.valid">
<NuxtLink to="/login">Login</NuxtLink> or <NuxtLink to="/login#create-account">Create an account</NuxtLink>
to get notified about updates to the schedule.
</p>
@ -12,7 +12,7 @@
Check out your <NuxtLink to="/account/settings">Account Setting</NuxtLink> to set up notifications for changes to schedule.
</p>
<h2>Schedule</h2>
<label v-if="sessionStore.account">
<label v-if="accountStore.valid">
Filter:
<select
v-model="filter"
@ -26,11 +26,11 @@
:selected='filter === "my-schedule"'
>My Schedule</option>
<option
v-if="isCrew"
v-if="accountStore.isCrew"
value="assigned"
:selected='filter === "assigned"'
>Assigned to Me</option>
<optgroup v-if="isCrew && accounts" label="Crew">
<optgroup v-if="accountStore.isCrew && accounts" label="Crew">
<option
v-for="account in accounts.filter(a => a.type === 'crew' || a.type === 'admin')"
:key="account.id"
@ -57,13 +57,9 @@
<script setup lang="ts">
import type { ShiftSlot, TimeSlot } from '~/shared/types/schedule';
const sessionStore = useSessionStore();
const accountStore = useAccountStore();
const { data: accounts } = await useAccounts();
const schedule = await useSchedule();
const isCrew = computed(() => (
sessionStore.account?.type === "crew"
|| sessionStore.account?.type === "admin"
));
const route = useRoute();
const filter = computed({
@ -78,12 +74,12 @@ const filter = computed({
});
const eventSlotFilter = computed(() => {
if (filter.value === undefined || !sessionStore.account) {
if (filter.value === undefined || !accountStore.valid) {
return () => true;
}
const aid = sessionStore.account?.id;
const aid = accountStore.id;
if (filter.value === "my-schedule") {
const ids = new Set(sessionStore.account?.interestedIds);
const ids = new Set(accountStore.interestedIds);
for (const event of schedule.value.events) {
if (ids.has(event.id)) {
for (const slot of event.slots) {
@ -103,11 +99,11 @@ const eventSlotFilter = computed(() => {
return () => false;
});
const shiftSlotFilter = computed(() => {
if (filter.value === undefined || !sessionStore.account) {
if (filter.value === undefined || !accountStore.valid) {
return () => true;
}
if (filter.value === "my-schedule" || filter.value === "assigned") {
const aid = sessionStore.account?.id;
const aid = accountStore.id;
return (slot: ShiftSlot) => slot.assigned?.some(id => id === aid) || false;
}
if (filter.value.startsWith("crew-")) {

60
stores/account.ts Normal file
View file

@ -0,0 +1,60 @@
import type { Account } from "~/shared/types/account";
export const useAccountStore = defineStore("account", () => {
const runtimeConfig = useRuntimeConfig();
const sessionStore = useSessionStore();
const state = {
valid: ref<boolean>(false),
id: ref<number>(),
name: ref<string>(),
timezone: ref<string>(),
type: ref<Account["type"]>(),
interestedIds: ref<Set<string>>(),
};
watchEffect(() => {
const account = sessionStore.account;
state.valid.value = Boolean(account);
state.id.value = account?.id;
state.name.value = account?.name;
state.timezone.value = account?.timezone;
state.type.value = account?.type;
state.interestedIds.value = account?.interestedIds ? new Set(account.interestedIds) : undefined;
});
const getters = {
isCrew: computed(() => state.type.value === "crew" || state.type.value === "admin"),
canEdit: computed(() => state.type.value === "admin" || state.type.value === "crew" ),
canEditPublic: computed(() => state.type.value === "admin"),
activeTimezone: computed(() => state.timezone.value || runtimeConfig.public.defaultTimezone),
defaultTimezone: computed(() => runtimeConfig.public.defaultTimezone),
};
const actions = {
async toggleInterestedId(id: string, slotIds?: string[]) {
if (!state.interestedIds.value) {
throw Error("accountStore.toggleInterestedId: Invalid state")
}
let newIds = [...state.interestedIds.value ?? []];
if (state.interestedIds.value.has(id)) {
newIds = newIds.filter(newId => newId !== id);
} else {
newIds.push(id);
if (slotIds) {
const filterIds = new Set(slotIds);
newIds = newIds.filter(newId => !filterIds.has(newId));
}
}
await $fetch("/api/account", {
method: "PATCH",
body: { interestedIds: newIds },
})
await sessionStore.fetch();
},
};
return {
...state,
...getters,
...actions,
};
});