Skip to content

Your favorite shift management application!

11.1 KB
Raw Blame
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftFormData } from "@/components/shift-sheet";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { parseLocalDate, toLocalDate } from "@/lib/date-utils";
import { queryKeys } from "@/lib/query-keys";
import { ApiError } from "@/lib/api-error";
import { generateTempId } from "@/lib/utils";
import { useIsCalendarAccessible } from "@/hooks/useCalendars";
import { LIVE_REFETCH_INTERVAL } from "@/lib/query-client";

// Helper to convert API response timestamps to Date objects
export function normalizeShift(
  shift: Record<string, unknown>
): ShiftWithCalendar {
  const parsedDate = toLocalDate(shift.date as string | number | Date);

  return {
    ...(shift as Omit<ShiftWithCalendar, "date" | "createdAt" | "updatedAt">),
    date: parsedDate,
    createdAt: new Date(shift.createdAt as string | number | Date),
    updatedAt: new Date(shift.updatedAt as string | number | Date),
  };
}

// API functions
async function fetchShiftsApi(
  calendarId: string
): Promise<ShiftWithCalendar[]> {
  const params = new URLSearchParams({ calendarId });
  const response = await fetch(`/api/shifts?${params}`);

  if (!response.ok) {
    throw new ApiError(`Failed to fetch shifts: ${response.statusText}`, response.status);
  }

  const data = await response.json();
  return data.map(normalizeShift);
}

async function createShiftApi(
  calendarId: string,
  formData: ShiftFormData
): Promise<ShiftWithCalendar> {
  const response = await fetch("/api/shifts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ ...formData, calendarId }),
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.error || "Failed to create shift");
  }

  const data = await response.json();
  return normalizeShift(data);
}

async function deleteShiftApi(id: string): Promise<void> {
  const response = await fetch(`/api/shifts/${id}`, {
    method: "DELETE",
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.error || "Failed to delete shift");
  }
}

async function updateShiftApi(
  id: string,
  formData: ShiftFormData
): Promise<ShiftWithCalendar> {
  const response = await fetch(`/api/shifts/${id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(formData),
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.error || "Failed to update shift");
  }

  const data = await response.json();
  return normalizeShift(data);
}

// Context type for optimistic updates
interface CreateShiftContext {
  previous: ShiftWithCalendar[] | undefined;
}

interface DeleteShiftContext {
  previous: ShiftWithCalendar[] | undefined;
}

interface UpdateShiftContext {
  previous: ShiftWithCalendar[] | undefined;
}

export function useShifts(calendarId: string | undefined) {
  const t = useTranslations();
  const queryClient = useQueryClient();

  const accessible = useIsCalendarAccessible(calendarId);

  // Data fetching with React Query
  const {
    data: shifts = [],
    isLoading,
    isFetched,
  } = useQuery({
    queryKey: queryKeys.shifts.byCalendar(calendarId!),
    queryFn: () => fetchShiftsApi(calendarId!),
    enabled: accessible,
    refetchInterval: LIVE_REFETCH_INTERVAL,
  });

  // Create mutation with optimistic update
  const createMutation = useMutation<
    ShiftWithCalendar,
    Error,
    ShiftFormData,
    CreateShiftContext
  >({
    mutationFn: (formData) => createShiftApi(calendarId!, formData),
    onMutate: async (formData) => {
      // Cancel outgoing refetches
      await queryClient.cancelQueries({
        queryKey: queryKeys.shifts.byCalendar(calendarId!),
      });

      // Snapshot previous value
      const previous = queryClient.getQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId!)
      );

      // Create optimistic shift
      const optimisticShift: ShiftWithCalendar = {
        id: `temp-${generateTempId()}`,
        date: parseLocalDate(formData.date),
        startTime: formData.startTime,
        endTime: formData.endTime,
        segments: formData.segments ?? [],
        title: formData.title,
        color: formData.color || "#3b82f6",
        notes: formData.notes || null,
        isAllDay: formData.isAllDay || false,
        presetId: formData.presetId || null,
        customFields: formData.customFields ?? {},
        calendarId: calendarId!,
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      // Optimistically update cache
      queryClient.setQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId!),
        (old = []) => [...old, optimisticShift]
      );

      return { previous };
    },
    onError: (err, formData, context) => {
      // Rollback on error
      if (context?.previous) {
        queryClient.setQueryData(
          queryKeys.shifts.byCalendar(calendarId!),
          context.previous
        );
      }
      console.error("Failed to create shift:", err);
      toast.error(
        err instanceof Error
          ? err.message
          : t("common.createError", { item: t("shift.shift_one") })
      );
    },
    onSuccess: () => {
      toast.success(t("common.created", { item: t("shift.shift_one") }));
    },
    onSettled: () => {
      // Refetch to get real data from server
      queryClient.invalidateQueries({
        queryKey: queryKeys.shifts.byCalendar(calendarId!),
      });
    },
  });

  // Delete mutation with optimistic update
  const deleteMutation = useMutation<void, Error, string, DeleteShiftContext>({
    mutationFn: (id) => deleteShiftApi(id),
    onMutate: async (id) => {
      await queryClient.cancelQueries({
        queryKey: queryKeys.shifts.byCalendar(calendarId!),
      });

      const previous = queryClient.getQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId!)
      );

      // Optimistically remove
      queryClient.setQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId!),
        (old = []) => old.filter((s) => s.id !== id)
      );

      return { previous };
    },
    onError: (err, id, context) => {
      if (context?.previous) {
        queryClient.setQueryData(
          queryKeys.shifts.byCalendar(calendarId!),
          context.previous
        );
      }
      console.error("Failed to delete shift:", err);
      toast.error(
        err instanceof Error
          ? err.message
          : t("common.deleteError", { item: t("shift.shift_one") })
      );
    },
    onSuccess: () => {
      toast.success(t("common.deleted", { item: t("shift.shift_one") }));
    },
    onSettled: () => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.shifts.byCalendar(calendarId!),
      });
    },
  });

  // Update mutation with optimistic update
  const updateMutation = useMutation<
    ShiftWithCalendar,
    Error,
    { id: string; formData: ShiftFormData },
    UpdateShiftContext
  >({
    mutationFn: ({ id, formData }) => updateShiftApi(id, formData),
    onMutate: async ({ id, formData }) => {
      await queryClient.cancelQueries({
        queryKey: queryKeys.shifts.byCalendar(calendarId!),
      });

      const previous = queryClient.getQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId!)
      );

      // Optimistically update the shift
      queryClient.setQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId!),
        (old = []) =>
          old.map((s) =>
            s.id === id
              ? {
                ...s,
                date: parseLocalDate(formData.date),
                startTime: formData.startTime,
                endTime: formData.endTime,
                segments: formData.segments ?? [],
                title: formData.title,
                color: formData.color || s.color,
                notes: formData.notes || null,
                isAllDay: formData.isAllDay || false,
                // The edit form never carries presetId — keep the shift's existing value
                presetId: formData.presetId ?? s.presetId,
                customFields: formData.customFields ?? s.customFields,
                updatedAt: new Date(),
              }
              : s
          )
      );

      return { previous };
    },
    onError: (err, variables, context) => {
      if (context?.previous) {
        queryClient.setQueryData(
          queryKeys.shifts.byCalendar(calendarId!),
          context.previous
        );
      }
      console.error("Failed to update shift:", err);
      toast.error(
        err instanceof Error
          ? err.message
          : t("common.updateError", { item: t("shift.shift_one") })
      );
    },
    onSuccess: () => {
      toast.success(t("common.updated", { item: t("shift.shift_one") }));
    },
    onSettled: () => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.shifts.byCalendar(calendarId!),
      });
    },
  });

  // Return API-compatible interface
  return {
    shifts,
    setShifts: (
      newShifts:
        | ShiftWithCalendar[]
        | ((prev: ShiftWithCalendar[]) => ShiftWithCalendar[])
    ) => {
      if (!calendarId) return;
      queryClient.setQueryData(
        queryKeys.shifts.byCalendar(calendarId),
        newShifts
      );
    },
    loading: isLoading,
    hasLoadedOnce: isFetched,
    createShift: async (shift: ShiftFormData) => {
      if (!calendarId) {
        throw new Error("Calendar ID is required to create a shift");
      }
      return createMutation.mutateAsync(shift);
    },
    deleteShift: async (shiftId: string) => {
      if (!calendarId) {
        throw new Error("Calendar ID is required to delete a shift");
      }
      // Check if shift is externally synced (read-only)
      const cachedShifts = queryClient.getQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId)
      );
      const shift = cachedShifts?.find((s) => s.id === shiftId);
      if (shift?.syncedFromExternal) {
        throw new Error(
          t("common.deleteError", { item: t("shift.shift_one") })
        );
      }
      return deleteMutation.mutateAsync(shiftId);
    },
    updateShift: async (shiftId: string, formData: ShiftFormData) => {
      if (!calendarId) {
        throw new Error("Calendar ID is required to update a shift");
      }
      // Check if shift is externally synced (read-only)
      const cachedShifts = queryClient.getQueryData<ShiftWithCalendar[]>(
        queryKeys.shifts.byCalendar(calendarId)
      );
      const shift = cachedShifts?.find((s) => s.id === shiftId);
      if (shift?.syncedFromExternal) {
        throw new Error(
          t("common.updateError", { item: t("shift.shift_one") })
        );
      }
      return updateMutation.mutateAsync({ id: shiftId, formData });
    },
    refetchShifts: () => {
      if (!calendarId) return;
      queryClient.invalidateQueries({
        queryKey: queryKeys.shifts.byCalendar(calendarId),
      });
    },
  };
}