fixing the time between UTC and timezone from New York
This commit is contained in:
+229
-132
@@ -4,51 +4,112 @@ import { getWeekSchedule } from "@api/scheduleApi";
|
||||
import { PageHeader } from "@components/PageHeader";
|
||||
import type { BackendPreference } from "@/types/backend";
|
||||
import type { Schedule } from "@/types/schedule";
|
||||
import type { DayOfWeek } from "@/types/users";
|
||||
import { useCompaniesStore } from "../store/companiesStore";
|
||||
import styles from "./SchedulePage.module.scss";
|
||||
import { useCompaniesStore } from "../store/companiesStore";
|
||||
|
||||
type SchedulePageProps = {
|
||||
backendPreference: BackendPreference;
|
||||
};
|
||||
|
||||
const weekDays: DayOfWeek[] = [
|
||||
"sunday",
|
||||
"monday",
|
||||
"tuesday",
|
||||
"wednesday",
|
||||
"thursday",
|
||||
"friday",
|
||||
"saturday",
|
||||
const businessTimeZone = "America/New_York";
|
||||
|
||||
const weekdayLabels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
|
||||
const companyColorPalette = [
|
||||
"#2563eb",
|
||||
"#dc2626",
|
||||
"#16a34a",
|
||||
"#9333ea",
|
||||
"#ea580c",
|
||||
"#0891b2",
|
||||
"#be123c",
|
||||
"#4f46e5",
|
||||
"#65a30d",
|
||||
"#c026d3",
|
||||
"#0e7490",
|
||||
"#9d174d",
|
||||
];
|
||||
|
||||
function formatDay(day: DayOfWeek): string {
|
||||
return day.charAt(0).toUpperCase() + day.slice(1);
|
||||
function getCompanyColor(company: string | undefined): string {
|
||||
if (!company) {
|
||||
return "#64748b";
|
||||
}
|
||||
|
||||
const hash = [...company].reduce((total, char) => total + char.charCodeAt(0), 0);
|
||||
return companyColorPalette[hash % companyColorPalette.length];
|
||||
}
|
||||
|
||||
function getWeekStart(date: Date): Date {
|
||||
const weekStart = new Date(date);
|
||||
weekStart.setHours(0, 0, 0, 0);
|
||||
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
|
||||
return weekStart;
|
||||
function normalizeBackendTimestamp(value: string): string {
|
||||
const hasTimezone = /[Zz]$/.test(value) || /[+-]\d{2}:\d{2}$/.test(value);
|
||||
const baseValue = hasTimezone ? value : `${value}Z`;
|
||||
return baseValue.replace(/(\.\d{3})\d+/, "$1");
|
||||
}
|
||||
|
||||
function addDays(date: Date, days: number): Date {
|
||||
const nextDate = new Date(date);
|
||||
nextDate.setDate(nextDate.getDate() + days);
|
||||
return nextDate;
|
||||
function parseBackendDateAsUTC(value: string): Date {
|
||||
return new Date(normalizeBackendTimestamp(value));
|
||||
}
|
||||
|
||||
function formatDate(value: Date): string {
|
||||
return value.toLocaleDateString([], {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
});
|
||||
function getBusinessDateKey(date: Date): string {
|
||||
return date.toLocaleDateString("en-CA", { timeZone: businessTimeZone });
|
||||
}
|
||||
|
||||
function formatShortDate(value: Date): string {
|
||||
return value.toLocaleDateString([], { month: "short", day: "numeric" });
|
||||
function getBusinessWeekdayIndex(date: Date): number {
|
||||
const weekday = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: businessTimeZone,
|
||||
weekday: "short",
|
||||
}).format(date);
|
||||
const mapping: Record<string, number> = {
|
||||
Sun: 0,
|
||||
Mon: 1,
|
||||
Tue: 2,
|
||||
Wed: 3,
|
||||
Thu: 4,
|
||||
Fri: 5,
|
||||
Sat: 6,
|
||||
};
|
||||
return mapping[weekday] ?? 0;
|
||||
}
|
||||
|
||||
function addDaysToDateKey(dateKey: string, days: number): string {
|
||||
const [year, month, day] = dateKey.split("-").map(Number);
|
||||
const date = new Date(Date.UTC(year, month - 1, day));
|
||||
date.setUTCDate(date.getUTCDate() + days);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function getBusinessMonthStartKey(date: Date): string {
|
||||
const businessKey = getBusinessDateKey(date);
|
||||
return `${businessKey.slice(0, 7)}-01`;
|
||||
}
|
||||
|
||||
function getBusinessWeekdayIndexForKey(dateKey: string): number {
|
||||
const [year, month, day] = dateKey.split("-").map(Number);
|
||||
const date = new Date(Date.UTC(year, month - 1, day, 12, 0, 0));
|
||||
return getBusinessWeekdayIndex(date);
|
||||
}
|
||||
|
||||
function getCalendarGridStartKey(monthStartKey: string): string {
|
||||
const weekday = getBusinessWeekdayIndexForKey(monthStartKey);
|
||||
return addDaysToDateKey(monthStartKey, -weekday);
|
||||
}
|
||||
|
||||
function formatMonthLabel(monthStartKey: string): string {
|
||||
const [year, month] = monthStartKey.split("-").map(Number);
|
||||
const monthNames = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
return `${monthNames[month - 1]} ${year}`;
|
||||
}
|
||||
|
||||
function formatTime(value: string | null): string {
|
||||
@@ -56,7 +117,11 @@ function formatTime(value: string | null): string {
|
||||
return "Not registered";
|
||||
}
|
||||
|
||||
return new Date(value).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
return parseBackendDateAsUTC(value).toLocaleTimeString("en-US", {
|
||||
timeZone: businessTimeZone,
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export function SchedulePage({ backendPreference }: SchedulePageProps) {
|
||||
@@ -64,64 +129,71 @@ export function SchedulePage({ backendPreference }: SchedulePageProps) {
|
||||
const [error, setError] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [selectedCompany, setSelectedCompany] = useState("");
|
||||
const [selectedWeekStart, setSelectedWeekStart] = useState(() => getWeekStart(new Date()));
|
||||
const [selectedMonthStartKey, setSelectedMonthStartKey] = useState(() =>
|
||||
getBusinessMonthStartKey(new Date()),
|
||||
);
|
||||
const companyNames = useCompaniesStore((state) => state.companyNames);
|
||||
const companiesError = useCompaniesStore((state) => state.error);
|
||||
const loadCompanies = useCompaniesStore((state) => state.loadCompanies);
|
||||
|
||||
const selectedWeekEnd = useMemo(() => addDays(selectedWeekStart, 6), [selectedWeekStart]);
|
||||
const selectedWeekEndExclusive = useMemo(
|
||||
() => addDays(selectedWeekStart, 7),
|
||||
[selectedWeekStart],
|
||||
);
|
||||
const selectedWeekDays = useMemo(
|
||||
() => weekDays.map((day, index) => ({ day, date: addDays(selectedWeekStart, index) })),
|
||||
[selectedWeekStart],
|
||||
const todayKey = useMemo(() => getBusinessDateKey(new Date()), []);
|
||||
const calendarStartKey = useMemo(
|
||||
() => getCalendarGridStartKey(selectedMonthStartKey),
|
||||
[selectedMonthStartKey],
|
||||
);
|
||||
|
||||
const schedulesByDay = useMemo(() => {
|
||||
return schedules.reduce<Record<DayOfWeek, Schedule[]>>(
|
||||
(accumulator, schedule) => {
|
||||
if (selectedCompany && schedule.company !== selectedCompany) {
|
||||
return accumulator;
|
||||
}
|
||||
const calendarDays = useMemo(() => {
|
||||
return Array.from({ length: 42 }, (_, index) => {
|
||||
const dateKey = addDaysToDateKey(calendarStartKey, index);
|
||||
const isCurrentMonth = dateKey.slice(0, 7) === selectedMonthStartKey.slice(0, 7);
|
||||
const isToday = dateKey === todayKey;
|
||||
const dayNumber = Number(dateKey.slice(8, 10));
|
||||
return { dateKey, isCurrentMonth, isToday, dayNumber };
|
||||
});
|
||||
}, [calendarStartKey, selectedMonthStartKey, todayKey]);
|
||||
|
||||
if (!schedule.enter_time) {
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
const enterDate = new Date(schedule.enter_time);
|
||||
|
||||
if (
|
||||
Number.isNaN(enterDate.getTime()) ||
|
||||
enterDate < selectedWeekStart ||
|
||||
enterDate >= selectedWeekEndExclusive
|
||||
) {
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
const day = weekDays[enterDate.getDay()];
|
||||
accumulator[day] = [...accumulator[day], schedule];
|
||||
const schedulesByDateKey = useMemo(() => {
|
||||
return schedules.reduce<Record<string, Schedule[]>>((accumulator, schedule) => {
|
||||
if (selectedCompany && schedule.company !== selectedCompany) {
|
||||
return accumulator;
|
||||
},
|
||||
{
|
||||
sunday: [],
|
||||
monday: [],
|
||||
tuesday: [],
|
||||
wednesday: [],
|
||||
thursday: [],
|
||||
friday: [],
|
||||
saturday: [],
|
||||
},
|
||||
);
|
||||
}, [schedules, selectedCompany, selectedWeekEndExclusive, selectedWeekStart]);
|
||||
}
|
||||
|
||||
function showPreviousWeek() {
|
||||
setSelectedWeekStart((currentWeekStart) => addDays(currentWeekStart, -7));
|
||||
if (!schedule.enter_time) {
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
const enterDate = parseBackendDateAsUTC(schedule.enter_time);
|
||||
|
||||
if (Number.isNaN(enterDate.getTime())) {
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
const businessDateKey = getBusinessDateKey(enterDate);
|
||||
accumulator[businessDateKey] = [...(accumulator[businessDateKey] ?? []), schedule];
|
||||
return accumulator;
|
||||
}, {});
|
||||
}, [schedules, selectedCompany]);
|
||||
|
||||
function showPreviousMonth() {
|
||||
setSelectedMonthStartKey((currentKey) => {
|
||||
const [y, m] = currentKey.split("-").map(Number);
|
||||
const d = new Date(Date.UTC(y, m - 1, 1));
|
||||
d.setUTCMonth(d.getUTCMonth() - 1);
|
||||
return d.toISOString().slice(0, 10);
|
||||
});
|
||||
}
|
||||
|
||||
function showNextWeek() {
|
||||
setSelectedWeekStart((currentWeekStart) => addDays(currentWeekStart, 7));
|
||||
function showNextMonth() {
|
||||
setSelectedMonthStartKey((currentKey) => {
|
||||
const [y, m] = currentKey.split("-").map(Number);
|
||||
const d = new Date(Date.UTC(y, m - 1, 1));
|
||||
d.setUTCMonth(d.getUTCMonth() + 1);
|
||||
return d.toISOString().slice(0, 10);
|
||||
});
|
||||
}
|
||||
|
||||
function showToday() {
|
||||
setSelectedMonthStartKey(getBusinessMonthStartKey(new Date()));
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -166,69 +238,94 @@ export function SchedulePage({ backendPreference }: SchedulePageProps) {
|
||||
}, [companyNames, selectedCompany]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={styles.schedulePage}>
|
||||
<PageHeader
|
||||
title="Schedule"
|
||||
description="Weekly scheduler calendar starts on Sunday and ends on Saturday so you can see who is working each day."
|
||||
description="Monthly calendar shows who is working each day. Week starts on Sunday."
|
||||
/>
|
||||
{error ? <p className={styles.error}>{error}</p> : null}
|
||||
{companiesError ? <p className={styles.error}>{companiesError}</p> : null}
|
||||
{isLoading ? <p className={styles.muted}>Loading schedule...</p> : null}
|
||||
<div className={styles.scheduleToolbar}>
|
||||
<div className={styles.weekNavigator} aria-label="Select schedule week">
|
||||
<button type="button" onClick={showPreviousWeek} aria-label="Previous week">
|
||||
<FaChevronLeft aria-hidden="true" />
|
||||
</button>
|
||||
<h2>
|
||||
Week from {formatDate(selectedWeekStart)} to {formatDate(selectedWeekEnd)}
|
||||
</h2>
|
||||
<button type="button" onClick={showNextWeek} aria-label="Next week">
|
||||
<FaChevronRight aria-hidden="true" />
|
||||
</button>
|
||||
<label className={styles.companyFilter}>
|
||||
<select
|
||||
value={selectedCompany}
|
||||
onChange={(event) => setSelectedCompany(event.target.value)}
|
||||
>
|
||||
<option value="">All companies</option>
|
||||
{companyNames.map((company) => (
|
||||
<option key={company} value={company}>
|
||||
{company}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className={styles.calendarShell} aria-label="Monthly schedule calendar">
|
||||
<div className={styles.calendarHeader}>
|
||||
<div className={styles.monthTitle}>
|
||||
<h2>{formatMonthLabel(selectedMonthStartKey)}</h2>
|
||||
</div>
|
||||
<div className={styles.headerActions}>
|
||||
<div className={styles.navGroup}>
|
||||
<button type="button" onClick={showPreviousMonth} aria-label="Previous month">
|
||||
<FaChevronLeft aria-hidden="true" />
|
||||
</button>
|
||||
<button type="button" className={styles.todayButton} onClick={showToday}>
|
||||
Today
|
||||
</button>
|
||||
<button type="button" onClick={showNextMonth} aria-label="Next month">
|
||||
<FaChevronRight aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<label className={styles.companyFilter}>
|
||||
<select
|
||||
value={selectedCompany}
|
||||
onChange={(event) => setSelectedCompany(event.target.value)}
|
||||
>
|
||||
<option value="">All companies</option>
|
||||
{companyNames.map((company) => (
|
||||
<option key={company} value={company}>
|
||||
{company}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<section className={styles.calendar} aria-label="Weekly schedule from Sunday to Saturday">
|
||||
{selectedWeekDays.map(({ day, date }) => (
|
||||
<article className={styles.dayCard} key={day}>
|
||||
<h3>
|
||||
{formatDay(day)}
|
||||
<span>{formatShortDate(date)}</span>
|
||||
</h3>
|
||||
<div className={styles.shiftList}>
|
||||
{schedulesByDay[day].length > 0 ? (
|
||||
schedulesByDay[day].map((schedule) => (
|
||||
<div className={styles.shift} key={schedule.id}>
|
||||
<strong>
|
||||
{schedule.user
|
||||
? `${schedule.user.name} ${schedule.user.last_name}`
|
||||
: "Unknown user"}
|
||||
</strong>
|
||||
<span>{schedule.company ?? "No company"}</span>
|
||||
<span>
|
||||
{formatTime(schedule.enter_time)} - {formatTime(schedule.out_time)}
|
||||
<div className={styles.calendarWeekdays} aria-hidden="true">
|
||||
{weekdayLabels.map((label) => (
|
||||
<div key={label} className={styles.weekdayLabel}>
|
||||
{label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.calendarScroll}>
|
||||
<div className={styles.calendarGrid}>
|
||||
{calendarDays.map(({ dateKey, isCurrentMonth, isToday, dayNumber }) => {
|
||||
const daySchedules = schedulesByDateKey[dateKey] ?? [];
|
||||
return (
|
||||
<div
|
||||
key={dateKey}
|
||||
className={`${styles.calendarDay} ${isCurrentMonth ? "" : styles.outsideMonth} ${isToday ? styles.todayCell : ""}`}
|
||||
>
|
||||
<div className={styles.dayHeader}>
|
||||
<span className={`${styles.dayNumber} ${isToday ? styles.todayBadge : ""}`}>
|
||||
{dayNumber}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<p className={styles.muted}>No shifts scheduled</p>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</>
|
||||
<div className={styles.eventList}>
|
||||
{daySchedules.length > 0 ? (
|
||||
daySchedules.map((schedule) => (
|
||||
<div
|
||||
className={styles.event}
|
||||
key={schedule.id}
|
||||
style={{ ["--company-color" as string]: getCompanyColor(schedule.company) }}
|
||||
title={`${schedule.user ? `${schedule.user.name} ${schedule.user.last_name}` : "Unknown user"} ${formatTime(schedule.enter_time)} - ${formatTime(schedule.out_time)}`}
|
||||
>
|
||||
<span className={styles.eventTitle}>
|
||||
{schedule.user ? `${schedule.user.name} ${schedule.user.last_name}` : "Unknown user"}
|
||||
</span>
|
||||
<span className={styles.eventMeta}>
|
||||
<span className={styles.companyDot} /> {schedule.company ?? "No company"} · {formatTime(schedule.enter_time)} - {formatTime(schedule.out_time)}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<span className={styles.emptyDay} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user