Skip to content

Commit ed8bb97

Browse files
committed
feat: simplified the between dates get request, fixed bug with fetching all the posts
1 parent 1a9a992 commit ed8bb97

File tree

5 files changed

+285
-305
lines changed

5 files changed

+285
-305
lines changed

apps/frontend/src/components/launches/calendar.context.tsx

Lines changed: 72 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,10 @@ import { extend } from 'dayjs';
2222
import useCookie from 'react-use-cookie';
2323
extend(isoWeek);
2424
extend(weekOfYear);
25+
2526
export const CalendarContext = createContext({
26-
currentDay: dayjs().day() as 0 | 1 | 2 | 3 | 4 | 5 | 6,
27-
currentWeek: dayjs().week(),
28-
currentYear: dayjs().year(),
29-
currentMonth: dayjs().month(),
27+
startDate: dayjs().startOf('isoWeek').format('YYYY-MM-DD'),
28+
endDate: dayjs().endOf('isoWeek').format('YYYY-MM-DD'),
3029
customer: null as string | null,
3130
sets: [] as { name: string; id: string; content: string[] }[],
3231
signature: undefined as any,
@@ -51,10 +50,8 @@ export const CalendarContext = createContext({
5150
},
5251
display: 'week',
5352
setFilters: (filters: {
54-
currentWeek: number;
55-
currentYear: number;
56-
currentDay: 0 | 1 | 2 | 3 | 4 | 5 | 6;
57-
currentMonth: number;
53+
startDate: string;
54+
endDate: string;
5855
display: 'week' | 'month' | 'day';
5956
customer: string | null;
6057
}) => {
@@ -64,6 +61,7 @@ export const CalendarContext = createContext({
6461
/** empty **/
6562
},
6663
});
64+
6765
export interface Integrations {
6866
name: string;
6967
id: string;
@@ -85,23 +83,35 @@ export interface Integrations {
8583
id?: string;
8684
};
8785
}
88-
function getWeekNumber(date: Date) {
89-
// Copy date so don't modify original
90-
const targetDate = new Date(
91-
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
92-
);
93-
// Set to nearest Thursday: current date + 4 - current day number
94-
// Make Sunday's day number 7
95-
targetDate.setUTCDate(
96-
targetDate.getUTCDate() + 4 - (targetDate.getUTCDay() || 7)
97-
);
98-
// Get first day of year
99-
const yearStart = new Date(Date.UTC(targetDate.getUTCFullYear(), 0, 1));
100-
// Calculate full weeks to nearest Thursday
101-
return Math.ceil(
102-
((targetDate.getTime() - yearStart.getTime()) / 86400000 + 1) / 7
103-
);
86+
87+
// Helper function to get start and end dates based on display type
88+
function getDateRange(display: string, referenceDate?: string) {
89+
const date = referenceDate ? dayjs(referenceDate) : dayjs();
90+
91+
switch (display) {
92+
case 'day':
93+
return {
94+
startDate: date.format('YYYY-MM-DD'),
95+
endDate: date.format('YYYY-MM-DD'),
96+
};
97+
case 'week':
98+
return {
99+
startDate: date.startOf('isoWeek').format('YYYY-MM-DD'),
100+
endDate: date.endOf('isoWeek').format('YYYY-MM-DD'),
101+
};
102+
case 'month':
103+
return {
104+
startDate: date.startOf('month').format('YYYY-MM-DD'),
105+
endDate: date.endOf('month').format('YYYY-MM-DD'),
106+
};
107+
default:
108+
return {
109+
startDate: date.startOf('isoWeek').format('YYYY-MM-DD'),
110+
endDate: date.endOf('isoWeek').format('YYYY-MM-DD'),
111+
};
112+
}
104113
}
114+
105115
export const CalendarWeekProvider: FC<{
106116
children: ReactNode;
107117
integrations: Integrations[];
@@ -112,35 +122,45 @@ export const CalendarWeekProvider: FC<{
112122
const searchParams = useSearchParams();
113123
const [displaySaved, setDisplaySaved] = useCookie('calendar-display', 'week');
114124
const display = searchParams.get('display') || displaySaved;
125+
126+
// Initialize with current date range based on URL params or defaults
127+
const initStartDate = searchParams.get('startDate');
128+
const initEndDate = searchParams.get('endDate');
129+
const initCustomer = searchParams.get('customer');
130+
131+
const initialRange =
132+
initStartDate && initEndDate
133+
? { startDate: initStartDate, endDate: initEndDate }
134+
: getDateRange(display);
135+
115136
const [filters, setFilters] = useState({
116-
currentDay: +(searchParams.get('day') || dayjs().day()) as
117-
| 0
118-
| 1
119-
| 2
120-
| 3
121-
| 4
122-
| 5
123-
| 6,
124-
currentWeek: +(searchParams.get('week') || getWeekNumber(new Date())),
125-
currentMonth: +(searchParams.get('month') || dayjs().month()),
126-
currentYear: +(searchParams.get('year') || dayjs().year()),
127-
customer: (searchParams.get('customer') as string) || null,
137+
startDate: initialRange.startDate,
138+
endDate: initialRange.endDate,
139+
customer: initCustomer || null,
128140
display,
129141
});
142+
130143
const params = useMemo(() => {
131144
return new URLSearchParams({
132145
display: filters.display,
133-
day: filters.currentDay.toString(),
134-
week: filters.currentWeek.toString(),
135-
month: (filters.currentMonth + 1).toString(),
136-
year: filters.currentYear.toString(),
146+
startDate: filters.startDate,
147+
endDate: filters.endDate,
137148
customer: filters?.customer?.toString() || '',
138149
}).toString();
139-
}, [filters, display]);
150+
}, [filters]);
151+
140152
const loadData = useCallback(async () => {
141-
const data = (await fetch(`/posts?${params}`)).json();
153+
const modifiedParams = new URLSearchParams({
154+
display: filters.display,
155+
customer: filters?.customer?.toString() || '',
156+
startDate: dayjs(filters.startDate).startOf('day').utc().format(),
157+
endDate: dayjs(filters.endDate).endOf('day').utc().format(),
158+
}).toString();
159+
160+
const data = (await fetch(`/posts?${modifiedParams}`)).json();
142161
return data;
143162
}, [filters, params]);
163+
144164
const swr = useSWR(`/posts-${params}`, loadData, {
145165
refreshInterval: 3600000,
146166
refreshWhenOffline: false,
@@ -157,37 +177,35 @@ export const CalendarWeekProvider: FC<{
157177
}, []);
158178

159179
const { data: sets, mutate } = useSWR('sets', setList);
160-
const { data: sign} = useSWR('default-sign', defaultSign);
180+
const { data: sign } = useSWR('default-sign', defaultSign);
161181

162182
const setFiltersWrapper = useCallback(
163183
(filters: {
164-
currentDay: 0 | 1 | 2 | 3 | 4 | 5 | 6;
165-
currentWeek: number;
166-
currentYear: number;
167-
currentMonth: number;
184+
startDate: string;
185+
endDate: string;
168186
display: 'week' | 'month' | 'day';
169187
customer: string | null;
170188
}) => {
171189
setDisplaySaved(filters.display);
172190
setFilters(filters);
173191
setInternalData([]);
174192
const path = [
175-
`day=${filters.currentDay}`,
176-
`week=${filters.currentWeek}`,
177-
`month=${filters.currentMonth}`,
178-
`year=${filters.currentYear}`,
193+
`startDate=${filters.startDate}`,
194+
`endDate=${filters.endDate}`,
179195
`display=${filters.display}`,
180196
filters.customer ? `customer=${filters.customer}` : ``,
181197
].filter((f) => f);
182198
window.history.replaceState(null, '', `/launches?${path.join('&')}`);
183199
},
184200
[filters, swr.mutate]
185201
);
202+
186203
const { isLoading } = swr;
187204
const { posts, comments } = swr?.data || {
188205
posts: [],
189206
comments: [],
190207
};
208+
191209
const changeDate = useCallback(
192210
(id: string, date: dayjs.Dayjs) => {
193211
setInternalData((d) =>
@@ -204,11 +222,13 @@ export const CalendarWeekProvider: FC<{
204222
},
205223
[posts, internalData]
206224
);
225+
207226
useEffect(() => {
208227
if (posts) {
209228
setInternalData(posts);
210229
}
211230
}, [posts]);
231+
212232
return (
213233
<CalendarContext.Provider
214234
value={{
@@ -228,4 +248,5 @@ export const CalendarWeekProvider: FC<{
228248
</CalendarContext.Provider>
229249
);
230250
};
251+
231252
export const useCalendar = () => useContext(CalendarContext);

apps/frontend/src/components/launches/calendar.tsx

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,14 @@ export const hours = Array.from(
102102
);
103103
export const DayView = () => {
104104
const calendar = useCalendar();
105-
const { integrations, posts, currentYear, currentDay, currentWeek } =
106-
calendar;
105+
const { integrations, posts, startDate } = calendar;
107106

108107
// Set dayjs locale based on current language
109108
const currentLanguage = i18next.resolvedLanguage || 'en';
110109
dayjs.locale(currentLanguage);
111110

111+
const currentDay = dayjs(startDate);
112+
112113
const options = useMemo(() => {
113114
const createdPosts = posts.map((post) => ({
114115
integration: [integrations.find((i) => i.id === post.integration.id)!],
@@ -142,6 +143,7 @@ export const DayView = () => {
142143
(p) => p[0].time
143144
);
144145
}, [integrations, posts]);
146+
145147
return (
146148
<div className="flex flex-col gap-[10px] flex-1">
147149
{options.map((option) => (
@@ -165,11 +167,7 @@ export const DayView = () => {
165167
}}
166168
>
167169
<CalendarColumn
168-
getDate={dayjs()
169-
.utc()
170-
.year(currentYear)
171-
.week(currentWeek)
172-
.day(currentDay)
170+
getDate={currentDay
173171
.startOf('day')
174172
.add(option[0].time, 'minute')
175173
.local()}
@@ -182,7 +180,7 @@ export const DayView = () => {
182180
);
183181
};
184182
export const WeekView = () => {
185-
const { currentYear, currentWeek } = useCalendar();
183+
const { startDate, endDate } = useCalendar();
186184
const t = useT();
187185

188186
// Use dayjs to get localized day names
@@ -191,16 +189,17 @@ export const WeekView = () => {
191189
dayjs.locale(currentLanguage);
192190

193191
const days = [];
194-
const yearWeek = dayjs()
195-
.year(currentYear)
196-
.week(currentWeek)
197-
.startOf('week');
198-
for (let i = 1; i <= 7; i++) {
199-
const yearWeekFormat = yearWeek.add(i, 'day').format('L');
200-
days.push({ name: dayjs().day(i).format('dddd'), day: yearWeekFormat });
192+
const weekStart = dayjs(startDate);
193+
for (let i = 0; i < 7; i++) {
194+
const day = weekStart.add(i, 'day');
195+
days.push({
196+
name: day.format('dddd'),
197+
day: day.format('L'),
198+
date: day,
199+
});
201200
}
202201
return days;
203-
}, [i18next.resolvedLanguage, currentYear, currentWeek]);
202+
}, [i18next.resolvedLanguage, startDate]);
204203

205204
return (
206205
<div className="flex flex-col text-textColor flex-1">
@@ -233,16 +232,13 @@ export const WeekView = () => {
233232
<div className="p-2 pe-4 text-center items-center justify-center flex text-[14px] text-newTableText">
234233
{convertTimeFormatBasedOnLocality(hour)}
235234
</div>
236-
{days.map((day, indexDay) => (
237-
<Fragment key={`${currentYear}-${currentWeek}-${day}-${hour}`}>
235+
{localizedDays.map((day, indexDay) => (
236+
<Fragment
237+
key={`${startDate}-${day.date.format('YYYY-MM-DD')}-${hour}`}
238+
>
238239
<div className="relative">
239240
<CalendarColumn
240-
getDate={dayjs()
241-
.year(currentYear)
242-
.week(currentWeek)
243-
.day(indexDay + 1)
244-
.hour(hour)
245-
.startOf('hour')}
241+
getDate={day.date.hour(hour).startOf('hour')}
246242
/>
247243
</div>
248244
</Fragment>
@@ -255,7 +251,7 @@ export const WeekView = () => {
255251
);
256252
};
257253
export const MonthView = () => {
258-
const { currentYear, currentMonth } = useCalendar();
254+
const { startDate } = useCalendar();
259255
const t = useT();
260256

261257
// Use dayjs to get localized day names
@@ -272,18 +268,22 @@ export const MonthView = () => {
272268
}, [i18next.resolvedLanguage]);
273269

274270
const calendarDays = useMemo(() => {
271+
const monthStart = dayjs(startDate);
272+
const currentMonth = monthStart.month();
273+
const currentYear = monthStart.year();
274+
275275
const startOfMonth = dayjs(new Date(currentYear, currentMonth, 1));
276276

277277
// Calculate the day offset for Monday (isoWeekday() returns 1 for Monday)
278278
const startDayOfWeek = startOfMonth.isoWeekday(); // 1 for Monday, 7 for Sunday
279279
const daysBeforeMonth = startDayOfWeek - 1; // Days to show from the previous month
280280

281281
// Get the start date (Monday of the first week that includes this month)
282-
const startDate = startOfMonth.subtract(daysBeforeMonth, 'day');
282+
const calendarStartDate = startOfMonth.subtract(daysBeforeMonth, 'day');
283283

284284
// Create an array to hold the calendar days (6 weeks * 7 days = 42 days max)
285285
const calendarDays = [];
286-
let currentDay = startDate;
286+
let currentDay = calendarStartDate;
287287
for (let i = 0; i < 42; i++) {
288288
let label = 'current-month';
289289
if (currentDay.month() < currentMonth) label = 'previous-month';
@@ -297,7 +297,7 @@ export const MonthView = () => {
297297
currentDay = currentDay.add(1, 'day');
298298
}
299299
return calendarDays;
300-
}, [currentYear, currentMonth]);
300+
}, [startDate]);
301301

302302
return (
303303
<div className="flex flex-col text-textColor flex-1">

0 commit comments

Comments
 (0)