📨 The ultimate agentic social media scheduling tool 🤖
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: change timezone
Nevo David2f671180f627
diff --git a/apps/backend/src/api/routes/public.controller.ts b/apps/backend/src/api/routes/public.controller.tsindex c009440e7..157487d45 100644--- a/apps/backend/src/api/routes/public.controller.ts+++ b/apps/backend/src/api/routes/public.controller.ts@@ -16,8 +16,7 @@ import { RealIP } from 'nestjs-real-ip';import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';import { Request, Response } from 'express';-import { makeId } from '@gitroom/nestjs-libraries/services/make.is';-import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';+import { applyTrackCookies } from '@gitroom/nestjs-libraries/track/track.cookies';import { AgentGraphInsertService } from '@gitroom/nestjs-libraries/agent/agent.graph.insert.service';import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';import { AuthService } from '@gitroom/helpers/auth/auth.service';@@ -97,8 +96,7 @@ export class PublicController {@Body()body: { fbclid?: string; tt: TrackEnum; additional: Record<string, any> }) {- const uniqueId = req?.cookies?.track || makeId(10);- const fbc = req?.cookies?._fbc || req?.cookies?.fbclid || body.fbclid;+ const { uniqueId, fbc, fbp } = applyTrackCookies(req, res, body.fbclid);this._trackService.track(uniqueId,@@ -108,36 +106,9 @@ export class PublicController {body.additional,fbc,undefined,- req?.cookies?._fbp+ fbp).catch((err) => {});- if (!req.cookies.track) {- res.cookie('track', uniqueId, {- domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),- ...(!process.env.NOT_SECURED- ? {- secure: true,- httpOnly: true,- }- : {}),- sameSite: 'none',- expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),- });- }-- if (body.fbclid && !req.cookies.fbclid) {- res.cookie('fbclid', body.fbclid, {- domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),- ...(!process.env.NOT_SECURED- ? {- secure: true,- httpOnly: true,- }- : {}),- sameSite: 'none',- expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),- });- }res.status(200).json({track: uniqueId,diff --git a/apps/backend/src/api/routes/users.controller.ts b/apps/backend/src/api/routes/users.controller.tsindex 1f0a6e39e..fccade5ba 100644--- a/apps/backend/src/api/routes/users.controller.ts+++ b/apps/backend/src/api/routes/users.controller.ts@@ -25,12 +25,13 @@ import { ApiTags } from '@nestjs/swagger';import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';import { UserDetailDto } from '@gitroom/nestjs-libraries/dtos/users/user.details.dto';import { EmailNotificationsDto } from '@gitroom/nestjs-libraries/dtos/users/email-notifications.dto';+import { TimezoneDto } from '@gitroom/nestjs-libraries/dtos/users/timezone.dto';import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';import { RealIP } from 'nestjs-real-ip';import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';-import { makeId } from '@gitroom/nestjs-libraries/services/make.is';+import { applyTrackCookies } from '@gitroom/nestjs-libraries/track/track.cookies';import {AuthorizationActions,Sections,@@ -233,6 +234,14 @@ export class UsersController {return this._userService.updateEmailNotifications(user.id, body);}+ @Post('/timezone')+ async updateTimezone(+ @GetUserFromRequest() user: User,+ @Body() body: TimezoneDto+ ) {+ return this._userService.updateTimezone(user.id, body);+ }+@Post('/api-key/rotate')@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])async rotateApiKey(@GetOrgFromRequest() organization: Organization) {@@ -412,8 +421,7 @@ export class UsersController {@Body()body: { tt: TrackEnum; fbclid: string; additional: Record<string, any> }) {- const uniqueId = req?.cookies?.track || makeId(10);- const fbc = req?.cookies?._fbc || req?.cookies?.fbclid || body.fbclid;+ const { uniqueId, fbc, fbp } = applyTrackCookies(req, res, body.fbclid);this._trackService.track(uniqueId,@@ -423,22 +431,9 @@ export class UsersController {body.additional,fbc,user,- req?.cookies?._fbp+ fbp).catch((err) => {});- if (!req.cookies.track) {- res.cookie('track', uniqueId, {- domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),- ...(!process.env.NOT_SECURED- ? {- secure: true,- httpOnly: true,- sameSite: 'none',- }- : {}),- expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),- });- }res.status(200).json({track: uniqueId,diff --git a/apps/frontend/src/app/(app)/layout.tsx b/apps/frontend/src/app/(app)/layout.tsxindex 0b8addbee..b2cf627a5 100644--- a/apps/frontend/src/app/(app)/layout.tsx+++ b/apps/frontend/src/app/(app)/layout.tsx@@ -97,7 +97,6 @@ export default async function AppLayout({ children }: { children: ReactNode }) {}><SentryComponent>- {/*<SetTimezone />*/}<HtmlComponent /><DubAnalytics /><FacebookComponent />diff --git a/apps/frontend/src/components/agents/agent.chat.tsx b/apps/frontend/src/components/agents/agent.chat.tsxindex 4f75781cd..44929f244 100644--- a/apps/frontend/src/components/agents/agent.chat.tsx+++ b/apps/frontend/src/components/agents/agent.chat.tsx@@ -35,6 +35,7 @@ import {} from '@copilotkit/runtime-client-gql';import { AddEditModal } from '@gitroom/frontend/components/new-launch/add.edit.modal';import dayjs from 'dayjs';+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import { ExistingDataContextProvider } from '@gitroom/frontend/components/launches/helpers/use.existing.data';import { useT } from '@gitroom/react/translation/get.transation.service.client';@@ -370,7 +371,7 @@ const OpenModal: FC<{}}><AddEditModal- date={dayjs.utc(integration.date)}+ date={fromUtc(integration.date)}allIntegrations={properties}integrations={properties.filter((p) => p.id === integration.integrationIddiff --git a/apps/frontend/src/components/analytics/stars.table.component.tsx b/apps/frontend/src/components/analytics/stars.table.component.tsxindex 90b81639f..cb8884d28 100644--- a/apps/frontend/src/components/analytics/stars.table.component.tsx+++ b/apps/frontend/src/components/analytics/stars.table.component.tsx@@ -10,7 +10,7 @@ import {} from 'react';import { UtcToLocalDateRender } from '@gitroom/react/helpers/utc.date.render';import { Button } from '@gitroom/react/form/button';-import dayjs from 'dayjs';+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';import Link from 'next/link';import { useRouter, useSearchParams } from 'next/navigation';import useSWR from 'swr';@@ -138,7 +138,7 @@ export const StarsTableComponent = () => {mutate();}, [searchParams]);const renderMediaLink = useCallback((date: string) => {- const local = dayjs.utc(date).local();+ const local = fromUtc(date);const weekNumber = local.isoWeek();const year = local.year();return `/launches?week=${weekNumber}&year=${year}`;diff --git a/apps/frontend/src/components/approved-apps/approved-apps.component.tsx b/apps/frontend/src/components/approved-apps/approved-apps.component.tsxindex ff8206547..ce388290d 100644--- a/apps/frontend/src/components/approved-apps/approved-apps.component.tsx+++ b/apps/frontend/src/components/approved-apps/approved-apps.component.tsx@@ -7,6 +7,7 @@ import { Button } from '@gitroom/react/form/button';import { useToaster } from '@gitroom/react/toaster/toaster';import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';import { useT } from '@gitroom/react/translation/get.transation.service.client';+import { getTimezone } from '@gitroom/frontend/components/layout/set.timezone';const useApprovedApps = () => {const fetch = useFetch();@@ -102,7 +103,9 @@ export const ApprovedAppsComponent: FC = () => {)}<div className="text-customColor18 text-[12px]">{t('authorized_on', 'Authorized on')}{' '}- {new Date(app.createdAt).toLocaleDateString()}+ {new Date(app.createdAt).toLocaleDateString(undefined, {+ timeZone: getTimezone(),+ })}</div></div></div>diff --git a/apps/frontend/src/components/billing/billing.history.component.tsx b/apps/frontend/src/components/billing/billing.history.component.tsxindex 50c232090..7dbb8c4d7 100644--- a/apps/frontend/src/components/billing/billing.history.component.tsx+++ b/apps/frontend/src/components/billing/billing.history.component.tsx@@ -2,12 +2,12 @@import React, { FC, useCallback, useMemo, useState } from 'react';import useSWR from 'swr';-import dayjs from 'dayjs';import clsx from 'clsx';import { capitalize } from 'lodash';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';import { useT } from '@gitroom/react/translation/get.transation.service.client';import { Select } from '@gitroom/react/form/select';+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';interface Invoice {id: string;@@ -57,12 +57,7 @@ const formatAmount = (amount: number, currency: string) => {};const formatDate = (unix: number | null) =>- unix- ? dayjs- .utc(unix * 1000)- .local()- .format('D MMM, YYYY')- : '';+ unix ? fromUtc(unix * 1000).format('D MMM, YYYY') : '';const ActionLink: FC<{href: string;diff --git a/apps/frontend/src/components/billing/embedded.billing.tsx b/apps/frontend/src/components/billing/embedded.billing.tsxindex 7411f77e1..ec3b1d4ed 100644--- a/apps/frontend/src/components/billing/embedded.billing.tsx+++ b/apps/frontend/src/components/billing/embedded.billing.tsx@@ -12,7 +12,7 @@ import {import { modeEmitter } from '@gitroom/frontend/components/layout/mode.component';import useCookie from 'react-use-cookie';import { Button } from '@gitroom/react/form/button';-import dayjs from 'dayjs';+import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';import { useToaster } from '@gitroom/react/toaster/toaster';import { useT } from '@gitroom/react/translation/get.transation.service.client';@@ -211,7 +211,7 @@ const PriceBreakdown: FC = () => {const dueToday = checkout?.total?.total?.amount || '$0.00';const nextBillingTotal = recurring?.dueNext?.total?.amount;const nextBillingDate = recurring?.trial?.trialEnd- ? dayjs(recurring.trial.trialEnd * 1000).format('MMMM D, YYYY')+ ? newDayjs(recurring.trial.trialEnd * 1000).format('MMMM D, YYYY'): null;const billingInterval =recurring?.interval === 'month'@@ -360,11 +360,11 @@ const AppliedCouponDisplay: FC<{if (expiresAt && typeof expiresAt === 'number') {const date = new Date(expiresAt * 1000);- return dayjs(date).format('MMMM D, YYYY');+ return newDayjs(date).format('MMMM D, YYYY');}if (expiresAt && typeof expiresAt === 'string') {- return dayjs(expiresAt).format('MMMM D, YYYY');+ return newDayjs(expiresAt).format('MMMM D, YYYY');}return null;@@ -618,7 +618,7 @@ const SubmitBar: FC<{ loading: boolean }> = ({ loading }) => {{t('billing_ending', 'ending')}{' '}<br className="hidden mobile:block" /><span className="text-textColor font-[600]">- {dayjs(+ {newDayjs(checkout.checkout.recurring?.trial?.trialEnd * 1000).format('MMMM D, YYYY')}{' '}—{' '}diff --git a/apps/frontend/src/components/billing/main.billing.component.tsx b/apps/frontend/src/components/billing/main.billing.component.tsxindex 133a9a37c..7416eb63a 100644--- a/apps/frontend/src/components/billing/main.billing.component.tsx+++ b/apps/frontend/src/components/billing/main.billing.component.tsx@@ -8,7 +8,6 @@ import { useDebouncedCallback } from 'use-debounce';import ReactLoading from '@gitroom/frontend/components/layout/loading';import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';import { useToaster } from '@gitroom/react/toaster/toaster';-import dayjs from 'dayjs';import clsx from 'clsx';import { capitalize } from 'lodash';import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';@@ -27,7 +26,7 @@ import { useTrack } from '@gitroom/react/helpers/use.track';import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';import { useT } from '@gitroom/react/translation/get.transation.service.client';import { FinishTrial } from '@gitroom/frontend/components/billing/finish.trial';-import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';import { timer } from '@gitroom/helpers/utils/timer';import { useDubClickId } from '@gitroom/frontend/components/layout/dubAnalytics';import { LogoutComponent } from '@gitroom/frontend/components/layout/logout.component';@@ -184,9 +183,7 @@ const BillingCycle: FC<{): t('billing_renews_on', 'Your plan renews on')}{' '}<bdi className="font-[600] text-newTextColor">- {newDayjs(renewal.renewsAt * 1000)- .local()- .format('D MMM, YYYY')}+ {fromUtc(renewal.renewsAt * 1000).format('D MMM, YYYY')}</bdi>{'. '}</>@@ -809,10 +806,7 @@ export const MainBillingComponent: FC<{return {label: subscription?.cancelAt? t('billing_downgrade_on', 'Downgrade on {{date}}', {- date: dayjs- .utc(subscription.cancelAt)- .local()- .format('D MMM, YYYY'),+ date: fromUtc(subscription.cancelAt).format('D MMM, YYYY'),}): t('cancel_subscription_1', 'Cancel subscription'),onClick: moveToCheckout('FREE'),@@ -886,7 +880,7 @@ export const MainBillingComponent: FC<{'Your subscription will be canceled at')}{' '}<bdi className="font-[600]">- {newDayjs(subscription.cancelAt).local().format('D MMM, YYYY')}+ {fromUtc(subscription.cancelAt).format('D MMM, YYYY')}</bdi>{'. '}{t(diff --git a/apps/frontend/src/components/launches/calendar.context.tsx b/apps/frontend/src/components/launches/calendar.context.tsxindex e28bb2a19..119598a55 100644--- a/apps/frontend/src/components/launches/calendar.context.tsx+++ b/apps/frontend/src/components/launches/calendar.context.tsx@@ -20,7 +20,10 @@ import isoWeek from 'dayjs/plugin/isoWeek';import weekOfYear from 'dayjs/plugin/weekOfYear';import { extend } from 'dayjs';import useCookie from 'react-use-cookie';-import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';+import {+ fromUtc,+ newDayjs,+} from '@gitroom/frontend/components/layout/set.timezone';import { timer } from '@gitroom/helpers/utils/timer';import { expandPostsList, expandPosts } from '@gitroom/helpers/utils/posts.list.minify';extend(isoWeek);@@ -51,6 +54,9 @@ export const CalendarContext = createContext({}[];}>,+ // the publish date of each post, in the user's timezone. Keyed by the post+ // itself, the occurrences of a recurring post share the same id+ postDates: new Map<object, dayjs.Dayjs>(),reloadCalendarView: () => {/** empty **/},@@ -388,6 +394,16 @@ export const CalendarWeekProvider: FC<{// one clock for every calendar cell, instead of a timer per cellconst currentHour = useNow('hour');+ // every calendar cell looks for its posts in the whole list, so the dates+ // are parsed once here instead of in each cell+ const postDates = useMemo(+ () =>+ new Map<object, dayjs.Dayjs>(+ internalData.map((post: Post) => [post, fromUtc(post.publishDate)])+ ),+ [internalData]+ );+return (<CalendarContext.Providervalue={{@@ -395,6 +411,7 @@ export const CalendarWeekProvider: FC<{reloadCalendarView,...filters,posts: calendarIsLoading ? [] : filterByChannels(internalData),+ postDates,loading,integrations,setFilters: setFiltersWrapper,diff --git a/apps/frontend/src/components/launches/calendar.tsx b/apps/frontend/src/components/launches/calendar.tsxindex 0854697b9..36605298b 100644--- a/apps/frontend/src/components/launches/calendar.tsx+++ b/apps/frontend/src/components/launches/calendar.tsx@@ -56,7 +56,10 @@ import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';import { useVariables } from '@gitroom/react/helpers/variable.context';import copy from 'copy-to-clipboard';import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';-import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';+import {+ fromUtc,+ newDayjs,+} from '@gitroom/frontend/components/layout/set.timezone';import { Button } from '@gitroom/react/form/button';import { ChevronUpIcon } from '@gitroom/frontend/components/ui/icons';@@ -192,9 +195,7 @@ const usePostActions = (onMutate?: () => void) => {const date = !isDuplicate? null: (await (await fetch('/posts/find-slot')).json()).date;- const publishDate = dayjs- .utc(date || data.posts[0].publishDate)- .local();+ const publishDate = fromUtc(date || data.posts[0].publishDate);const ExistingData = !isDuplicate? ExistingDataContextProvider: Fragment;@@ -393,6 +394,12 @@ const usePostActions = (onMutate?: () => void) => {return { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost };};+// A day view slot is a minute of the user's day, on the day in view+const slotDate = (startDate: string, time: number) =>+ newDayjs(startDate)+ .hour(Math.floor(time / 60))+ .minute(time % 60);+// One day view slot. Memoized, so the now line's minute tick doesn't re-render the slotsconst DaySlotColumn: FC<{ option: any[]; startDate: string }> = memo(({ option, startDate }) => {@@ -404,13 +411,7 @@ const DaySlotColumn: FC<{ option: any[]; startDate: string }> = memo(integrations: option.flatMap((p) => p.integration),}}>- <CalendarColumn- getDate={dayjs- .utc(startDate)- .startOf('day')- .add(option[0].time, 'minute')- .local()}- />+ <CalendarColumn getDate={slotDate(startDate, option[0].time)} /></CalendarContext.Provider>);}@@ -418,23 +419,36 @@ const DaySlotColumn: FC<{ option: any[]; startDate: string }> = memo(export const DayView = () => {const calendar = useCalendar();- const { integrations, posts, startDate } = calendar;+ const { integrations, posts, postDates, startDate } = calendar;// Set dayjs locale based on current languageconst currentLanguage = i18next.resolvedLanguage || 'en';dayjs.locale(currentLanguage);const options = useMemo(() => {- const createdPosts = posts.map((post) => ({- integration: [integrations.find((i) => i.id === post.integration.id)!],- image: post?.integration?.picture || '',- identifier: post?.integration?.providerIdentifier || '',- id: post?.integration?.id || '',- name: post?.integration?.name || '',- time: dayjs- .utc(post.publishDate)- .diff(dayjs.utc(post.publishDate).startOf('day'), 'minute'),- }));+ const day = newDayjs(startDate);+ // a recurring post comes with all its occurrences, only this day's make slots+ const createdPosts = posts+ .filter(+ (post) =>+ postDates.get(post).format('YYYY-MM-DD') === day.format('YYYY-MM-DD')+ )+ .map((post) => {+ const date = postDates.get(post);+ return {+ integration: [+ integrations.find((i) => i.id === post.integration.id)!,+ ],+ image: post?.integration?.picture || '',+ identifier: post?.integration?.providerIdentifier || '',+ id: post?.integration?.id || '',+ name: post?.integration?.name || '',+ time: date.hour() * 60 + date.minute(),+ };+ });+ // posting times are minutes of the UTC day, moved to the clock of the day+ // in view (on a DST change day, the ones before the change are an hour off)+ const offset = day.hour(12).utcOffset();return sortBy(Object.values(groupBy(@@ -447,7 +461,7 @@ export const DayView = () => {name: p?.name,id: p?.id,image: p?.picture,- time: t?.time,+ time: (((t?.time + offset) % 1440) + 1440) % 1440,}))),],@@ -456,27 +470,17 @@ export const DayView = () => {),(p) => p[0].time);- }, [integrations, posts]);+ }, [integrations, posts, postDates, startDate]);- // the now line goes right before the first upcoming slot+ // the now line goes right before the first upcoming slot, only on todayconst now = useNow();const nowIndex = useMemo(() => {- const upcoming = options.findIndex((option) =>- dayjs- .utc(startDate)- .startOf('day')- .add(option[0].time, 'minute')- .isAfter(now)- );- // now is between two slots of this page (the slots follow the UTC day,- // so outside UTC it can be the page next to today)- if (upcoming > 0) {- return upcoming;- }- // before the first or after the last slot, only shown on todayif (!options.length || !newDayjs(startDate).isSame(now, 'day')) {return -1;}+ const upcoming = options.findIndex((option) =>+ slotDate(startDate, option[0].time).isAfter(now)+ );return upcoming === -1 ? options.length : upcoming;}, [options, startDate, now]);@@ -493,12 +497,9 @@ export const DayView = () => {/>)}<div className="text-center text-[14px] min-h-[21px] shrink-0">- {newDayjs()- .utc()- .startOf('day')- .add(option[0].time, 'minute')- .local()- .format(isUSCitizen() ? 'hh:mm A' : 'LT')}+ {slotDate(startDate, option[0].time).format(+ isUSCitizen() ? 'hh:mm A' : 'LT'+ )}</div><divkey={option[0].time}@@ -611,9 +612,8 @@ export const MonthView = () => {const calendarDays = useMemo(() => {const monthStart = newDayjs(startDate);const currentMonth = monthStart.month();- const currentYear = monthStart.year();- const startOfMonth = newDayjs(new Date(currentYear, currentMonth, 1));+ const startOfMonth = monthStart.startOf('month');// Calculate the day offset for Monday (isoWeekday() returns 1 for Monday)const startDayOfWeek = startOfMonth.isoWeekday(); // 1 for Monday, 7 for Sunday@@ -690,7 +690,7 @@ export const ListView = () => {const groupedPosts = useMemo(() => {const groups: { [key: string]: any[] } = {};listPosts.forEach((post) => {- const dateKey = newDayjs(post.publishDate).local().format('YYYY-MM-DD');+ const dateKey = fromUtc(post.publishDate).format('YYYY-MM-DD');if (!groups[dateKey]) {groups[dateKey] = [];}@@ -729,7 +729,7 @@ export const ListView = () => {key={post.id}display="day"isBeforeNow={false}- date={newDayjs(post.publishDate)}+ date={fromUtc(post.publishDate)}state={post.state}statistics={openStatistics(post.id)}missingRelease={openMissingRelease(post.id)}@@ -778,6 +778,7 @@ export const CalendarColumn: FC<{const {integrations,posts,+ postDates,changeDate,display,reloadCalendarView,@@ -792,19 +793,20 @@ export const CalendarColumn: FC<{// Use shared post actions hookconst { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost } = usePostActions();const postList = useMemo(() => {- return posts.filter((post) => {- const pList = dayjs.utc(post.publishDate).local();- const check =- display === 'day'- ? pList.format('YYYY-MM-DD HH:mm') ===- getDate.format('YYYY-MM-DD HH:mm')- : display === 'week'- ? pList.isSameOrAfter(getDate.startOf('hour')) &&- pList.isBefore(getDate.endOf('hour'))- : pList.format('DD/MM/YYYY') === getDate.format('DD/MM/YYYY');- return check;- });- }, [posts, display, getDate]);+ if (display === 'week') {+ const start = getDate.startOf('hour').valueOf();+ const end = getDate.endOf('hour').valueOf();+ return posts.filter((post) => {+ const time = postDates.get(post).valueOf();+ return time >= start && time < end;+ });+ }+ const format = display === 'day' ? 'YYYY-MM-DD HH:mm' : 'DD/MM/YYYY';+ const cell = getDate.format(format);+ return posts.filter(+ (post) => postDates.get(post).format(format) === cell+ );+ }, [posts, postDates, display, getDate]);const [showAll, setShowAll] = useState(false);const showAllFunc = useCallback(() => {setShowAll(true);@@ -1428,7 +1430,7 @@ const CalendarItem: FC<{</div>{showTime && (<div className="text-textColor/50 text-[12px] whitespace-nowrap flex items-center">- {newDayjs(post.publishDate).local().format(isUSCitizen() ? 'hh:mm A' : 'HH:mm')}+ {fromUtc(post.publishDate).format(isUSCitizen() ? 'hh:mm A' : 'HH:mm')}</div>)}</div>diff --git a/apps/frontend/src/components/launches/continue.integration.tsx b/apps/frontend/src/components/launches/continue.integration.tsxindex dd9e404ac..8386cb405 100644--- a/apps/frontend/src/components/launches/continue.integration.tsx+++ b/apps/frontend/src/components/launches/continue.integration.tsx@@ -6,7 +6,6 @@ import { useRouter } from 'next/navigation';import { Redirect } from '@gitroom/frontend/components/layout/redirect';import { useT } from '@gitroom/react/translation/get.transation.service.client';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';-import dayjs from 'dayjs';import { continueProviderList } from '@gitroom/frontend/components/new-launch/providers/continue-provider/list';import { IntegrationContext } from '@gitroom/frontend/components/launches/helpers/use.integration';import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';@@ -105,7 +104,7 @@ export const ContinueIntegration: FC<{useEffect(() => {(async () => {- const timezone = String(dayjs.tz().utcOffset());+ const timezone = String(newDayjs().utcOffset());// Try public endpoint first (handles both public and fallback scenarios)let data = await fetch(`/integrations/social-connect/${provider}`, {diff --git a/apps/frontend/src/components/launches/generator/generator.tsx b/apps/frontend/src/components/launches/generator/generator.tsxindex 85ff61ae7..80e262ad5 100644--- a/apps/frontend/src/components/launches/generator/generator.tsx+++ b/apps/frontend/src/components/launches/generator/generator.tsx@@ -17,7 +17,7 @@ import {CalendarWeekProvider,useCalendar,} from '@gitroom/frontend/components/launches/calendar.context';-import dayjs from 'dayjs';+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';import { Select } from '@gitroom/react/form/select';import { useT } from '@gitroom/react/translation/get.transation.service.client';import { AddEditModal } from '@gitroom/frontend/components/new-launch/add.edit.modal';@@ -194,7 +194,7 @@ const FirstStep: FC = (props) => {...p,}))}mutate={reloadCalendarView}- date={dayjs.utc(load.date).local()}+ date={fromUtc(load.date)}reopenModal={() => ({})}onlyValues={messages}/>diff --git a/apps/frontend/src/components/launches/helpers/date.picker.tsx b/apps/frontend/src/components/launches/helpers/date.picker.tsxindex b1439118c..913c696b4 100644--- a/apps/frontend/src/components/launches/helpers/date.picker.tsx+++ b/apps/frontend/src/components/launches/helpers/date.picker.tsx@@ -6,7 +6,10 @@ import { useClickOutside } from '@mantine/hooks';import { Button } from '@gitroom/react/form/button';import { isUSCitizen } from './isuscitizen.utils';import { useT } from '@gitroom/react/translation/get.transation.service.client';-import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';+import {+ newDayjs,+ toPickerDate,+} from '@gitroom/frontend/components/layout/set.timezone';import {CalendarIcon,ChevronLeftIcon,@@ -66,15 +69,17 @@ export const DatePickerPanel: FC<{}> = (props) => {const { date, onChange, sheet } = props;const t = useT();- const [month, setMonth] = useState(date.toDate());+ const [month, setMonth] = useState(toPickerDate(date));+ // the pickers give machine-local dates, so their wall clock is read with+ // plain dayjs and then placed in the user's timezoneconst changeDate = useCallback((type: 'date' | 'time') => (day: Date) => {onChange(newDayjs(type === 'time'- ? date.format('YYYY-MM-DD') + ' ' + newDayjs(day).format('HH:mm:ss')- : newDayjs(day).format('YYYY-MM-DD') + ' ' + date.format('HH:mm:ss')+ ? date.format('YYYY-MM-DD') + ' ' + dayjs(day).format('HH:mm:ss')+ : dayjs(day).format('YYYY-MM-DD') + ' ' + date.format('HH:mm:ss')));},@@ -144,7 +149,7 @@ export const DatePickerPanel: FC<{setMonth(day);changeDate('date')(day);}}- value={date.toDate()}+ value={toPickerDate(date)}dayClassName={(day, modifiers) =>clsx('!w-full !max-w-[40px] !h-[40px] !leading-[40px] !rounded-[8px] !text-[14px]',@@ -152,7 +157,7 @@ export const DatePickerPanel: FC<{? '!bg-boxFocused !text-textItemFocused !font-[600] !outline-none': modifiers.outside? '!text-newTextColor/20 !font-[400]'- : dayjs(day).isSame(dayjs(), 'day')+ : dayjs(day).isSame(toPickerDate(newDayjs()), 'day')? '!text-[#FC69FF] !font-[600]': '!text-textItemBlur !font-[400]')@@ -232,7 +237,7 @@ export const DatePickerPanel: FC<{<><CalendaronChange={changeDate('date')}- value={date.toDate()}+ value={toPickerDate(date)}dayClassName={(date, modifiers) => {if (modifiers.weekend) {return '!text-customColor28';@@ -260,7 +265,7 @@ export const DatePickerPanel: FC<{input:'bg-sixth h-[40px] border border-tableBorder text-textColor rounded-[4px] outline-none',}}- defaultValue={date.toDate()}+ defaultValue={toPickerDate(date)}/></>);diff --git a/apps/frontend/src/components/launches/integration.redirect.component.tsx b/apps/frontend/src/components/launches/integration.redirect.component.tsxindex 07556ed5d..b919ef459 100644--- a/apps/frontend/src/components/launches/integration.redirect.component.tsx+++ b/apps/frontend/src/components/launches/integration.redirect.component.tsx@@ -1,14 +1,10 @@'use client';-import dayjs from 'dayjs';-import utc from 'dayjs/plugin/utc';-import timezone from 'dayjs/plugin/timezone';import { usePathname, useRouter, useSearchParams } from 'next/navigation';import { FC, useEffect } from 'react';-dayjs.extend(utc);-dayjs.extend(timezone);+import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';export const IntegrationRedirectComponent: FC = () => {- const offset = dayjs.tz().utcOffset();+ const offset = newDayjs().utcOffset();const pathname = usePathname();const searchParams = useSearchParams();const router = useRouter();diff --git a/apps/frontend/src/components/launches/menu/menu.tsx b/apps/frontend/src/components/launches/menu/menu.tsxindex d479252f0..91596bac5 100644--- a/apps/frontend/src/components/launches/menu/menu.tsx+++ b/apps/frontend/src/components/launches/menu/menu.tsx@@ -28,7 +28,7 @@ import { useRouter } from 'next/navigation';import { useVariables } from '@gitroom/react/helpers/variable.context';import { useT } from '@gitroom/react/translation/get.transation.service.client';import { AddEditModal } from '@gitroom/frontend/components/new-launch/add.edit.modal';-import dayjs from 'dayjs';+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';import { ModalWrapperComponent } from '@gitroom/frontend/components/new-launch/modal.wrapper.component';import copy from 'copy-to-clipboard';import { Input } from '@gitroom/react/form/input';@@ -284,7 +284,7 @@ export const Menu: FC<{integrations={integrations}selectedChannels={[integration.id]}// focusedChannel={integration.id}- date={dayjs.utc(date).local()}+ date={fromUtc(date)}/>),size: '80%',diff --git a/apps/frontend/src/components/launches/new.post.tsx b/apps/frontend/src/components/launches/new.post.tsxindex 359822ed0..77afcd052 100644--- a/apps/frontend/src/components/launches/new.post.tsx+++ b/apps/frontend/src/components/launches/new.post.tsx@@ -1,6 +1,6 @@import React, { useCallback } from 'react';import { useModals } from '@gitroom/frontend/components/layout/new-modal';-import dayjs from 'dayjs';+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';import { useCalendar } from '@gitroom/frontend/components/launches/calendar.context';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';import { useT } from '@gitroom/react/translation/get.transation.service.client';@@ -67,7 +67,7 @@ export const NewPost = () => {reopenModal={createAPost}mutate={reloadCalendarView}integrations={integrations}- date={dayjs.utc(date).local()}+ date={fromUtc(date)}/>),size: '80%',diff --git a/apps/frontend/src/components/launches/time.table.tsx b/apps/frontend/src/components/launches/time.table.tsxindex 3e878a525..dabf35254 100644--- a/apps/frontend/src/components/launches/time.table.tsx+++ b/apps/frontend/src/components/launches/time.table.tsx@@ -7,7 +7,6 @@ import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';import { Select } from '@gitroom/react/form/select';import { Button } from '@gitroom/react/form/button';import utc from 'dayjs/plugin/utc';-import timezone from 'dayjs/plugin/timezone';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';// @ts-ignoreimport useKeypress from 'react-use-keypress';@@ -15,7 +14,10 @@ import { useModals } from '@gitroom/frontend/components/layout/new-modal';import { sortBy } from 'lodash';import { usePreventWindowUnload } from '@gitroom/react/helpers/use.prevent.window.unload';import { useT } from '@gitroom/react/translation/get.transation.service.client';-import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';+import {+ fromUtc,+ newDayjs,+} from '@gitroom/frontend/components/layout/set.timezone';import clsx from 'clsx';import {TrashIcon,@@ -24,7 +26,6 @@ import {} from '@gitroom/frontend/components/ui/icons';dayjs.extend(utc);-dayjs.extend(timezone);const hours = [...Array(24).keys()].map((i) => ({value: i,@@ -92,7 +93,7 @@ export const TimeTable: FC<{.add(hour, 'hours').add(minute, 'minutes').diff(newDayjs().utc().startOf('day'), 'minutes') -- dayjs.tz().utcOffset();+ newDayjs().utcOffset();setCurrentTimes((prev) => [...prev,{@@ -105,12 +106,9 @@ export const TimeTable: FC<{return sortBy(currentTimes.map(({ time }) => ({value: time,- formatted: dayjs- .utc()- .startOf('day')- .add(time, 'minutes')- .local()- .format('HH:mm'),+ formatted: fromUtc(+ dayjs.utc().startOf('day').add(time, 'minutes')+ ).format('HH:mm'),})),(p) => p.value);diff --git a/apps/frontend/src/components/layout/announcement.banner.tsx b/apps/frontend/src/components/layout/announcement.banner.tsxindex 273a50d48..8f649d575 100644--- a/apps/frontend/src/components/layout/announcement.banner.tsx+++ b/apps/frontend/src/components/layout/announcement.banner.tsx@@ -8,6 +8,7 @@ import { useModals } from '@gitroom/frontend/components/layout/new-modal';import { useT } from '@gitroom/react/translation/get.transation.service.client';import { Button } from '@gitroom/react/form/button';import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';+import { getTimezone } from '@gitroom/frontend/components/layout/set.timezone';type AnnouncementColor = 'INFO' | 'WARNING' | 'ERROR';@@ -71,7 +72,9 @@ const AnnouncementDetailModal: FC<{return (<div className="flex flex-col gap-[16px] min-w-[500px]"><div className="text-newTextColor/60 text-[13px]">- {new Date(announcement.createdAt).toLocaleDateString()}+ {new Date(announcement.createdAt).toLocaleDateString(undefined, {+ timeZone: getTimezone(),+ })}</div><div className="whitespace-pre-wrap text-newTextColor">{announcement.description}diff --git a/apps/frontend/src/components/layout/set.timezone.tsx b/apps/frontend/src/components/layout/set.timezone.tsxindex ac5b74a54..98b62c480 100644--- a/apps/frontend/src/components/layout/set.timezone.tsx+++ b/apps/frontend/src/components/layout/set.timezone.tsx@@ -1,43 +1,352 @@'use client';-import dayjs, { ConfigType } from 'dayjs';-import { FC, useEffect } from 'react';-import timezone from 'dayjs/plugin/timezone';+import dayjs, { ConfigType, Dayjs, PluginFunc } from 'dayjs';import utc from 'dayjs/plugin/utc';import relativeTime from 'dayjs/plugin/relativeTime';-dayjs.extend(timezone);+// the plugin below wraps methods of these, so they are registered firstdayjs.extend(utc);dayjs.extend(relativeTime);-const { utc: originalUtc } = dayjs;+const MINUTE = 60000;+const HOUR = 3600000;+const DAY = 86400000;+const STORAGE_KEY = 'timezoneName';-export const getTimezone = () => {- if (typeof window === 'undefined') {- return dayjs.tz.guess();+const formatters = new Map<string, Intl.DateTimeFormat>();+const formatter = (timezone: string) => {+ let format = formatters.get(timezone);+ if (!format) {+ format = new Intl.DateTimeFormat('en-US', {+ timeZone: timezone,+ hourCycle: 'h23',+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ hour: 'numeric',+ minute: 'numeric',+ second: 'numeric',+ });+ formatters.set(timezone, format);}- return localStorage.getItem('timezone') || dayjs.tz.guess();+ return format;};-export const newDayjs = (config?: ConfigType) => {- return dayjs(config);+// the offset (in minutes) of a timezone at an instant+const exactOffset = (timezone: string, timestamp: number) => {+ const time = Math.floor(timestamp / 1000) * 1000;+ const parts: Record<string, number> = {};+ for (const { type, value } of formatter(timezone).formatToParts(time)) {+ parts[type] = +value;+ }+ const wall = Date.UTC(+ parts.year,+ parts.month - 1,+ parts.day,+ parts.hour % 24,+ parts.minute,+ parts.second+ );+ return Math.round((wall - time) / MINUTE);+};++// offsets only change at transitions (about twice a year), so they are cached+// per UTC day; a day with a transition is cached per hour, and an hour with+// one is computed every time+const days = new Map<string, Map<number, number | null>>();+const hours = new Map<string, Map<number, number | null>>();+const cachedOffset = (+ cache: Map<string, Map<number, number | null>>,+ timezone: string,+ timestamp: number,+ size: number+) => {+ let offsets = cache.get(timezone);+ if (!offsets) {+ offsets = new Map();+ cache.set(timezone, offsets);+ }+ const bucket = Math.floor(timestamp / size);+ let offset = offsets.get(bucket);+ if (offset === undefined) {+ const start = exactOffset(timezone, bucket * size);+ offset =+ start === exactOffset(timezone, bucket * size + size - 1000)+ ? start+ : null;+ offsets.set(bucket, offset);+ }+ return offset;+};++const offsetAt = (timezone: string, timestamp: number) => {+ const day = cachedOffset(days, timezone, timestamp, DAY);+ if (day !== null) {+ return day;+ }+ const hour = cachedOffset(hours, timezone, timestamp, HOUR);+ return hour !== null ? hour : exactOffset(timezone, timestamp);+};++// a wall clock (as UTC milliseconds) to an instant, with the rules of+// new Date(y, m, d, ...): a skipped time moves forward, a repeated one takes+// the earlier instant+const wallToInstant = (timezone: string, wall: number) => {+ const before = offsetAt(timezone, wall - DAY);+ const after = offsetAt(timezone, wall + DAY);+ const first = wall - before * MINUTE;+ if (before === after) {+ return first;+ }+ const second = wall - after * MINUTE;+ const firstValid = offsetAt(timezone, first) === before;+ const secondValid = offsetAt(timezone, second) === after;+ if (firstValid && secondValid) {+ return Math.min(first, second);+ }+ return secondValid ? second : first;};-const SetTimezone: FC = () => {- useEffect(() => {- dayjs.utc = (config?: ConfigType, format?: string, strict?: boolean) => {- const result = originalUtc(config, format, strict);+const zoned = (instant: number, timezone: string, locale?: string): Dayjs =>+ dayjs(isNaN(instant) ? NaN : instant + offsetAt(timezone, instant) * MINUTE, {+ locale,+ utc: true,+ x: { $zone: timezone },+ $I: instant,+ } as any);- // Attach `.local()` method to the returned Dayjs object- result.local = function () {- return result.tz(getTimezone());- };+const STEPS: Record<string, number> = {+ minute: MINUTE,+ hour: HOUR,+ second: 1000,+};++// Dates from newDayjs() and fromUtc() carry the user's timezone ($x.$zone).+// They keep its wall clock in dayjs' UTC mode, so startOf, add and set work on+// it without DST, and keep the real instant ($I) for valueOf, utc() and diff.+// Every other dayjs date (plain dayjs(), Mantine) is left as it is.+// dayjs/plugin/timezone isn't used: every .tz() runs toLocaleString (~40µs,+// which made the calendar slow) and keeps a fixed offset that drifts on DST.+// This relies on dayjs internals ($d, $x, parse, init, clone), which is why+// dayjs is pinned to an exact version in package.json.+const zonedPlugin: PluginFunc = (option, dayjsClass) => {+ const proto = dayjsClass.prototype as any;+ const zoneOf = (date: any): string | undefined =>+ date?.$x && date.$offset === undefined ? date.$x.$zone : undefined;++ const oldParse = proto.parse;+ proto.parse = function (this: any, cfg: any) {+ if (cfg.x?.$zone) {+ this.$x = cfg.x;+ cfg.utc = true;+ this.$K = cfg.$I;+ }+ oldParse.call(this, cfg);+ };++ const oldInit = proto.init;+ proto.init = function (this: any) {+ const timezone = zoneOf(this);+ if (timezone && this.$K !== undefined) {+ // built from an instant: keep it, even inside a repeated hour+ this.$I = this.$K;+ this.$K = undefined;+ } else if (timezone && isNaN(this.$d.getTime())) {+ this.$I = NaN;+ } else if (timezone) {+ // built from a wall clock: a skipped time moves forward, like a local date+ const wall = this.$d.getTime();+ this.$I = wallToInstant(timezone, wall);+ const normalized = this.$I + offsetAt(timezone, this.$I) * MINUTE;+ if (normalized !== wall) {+ this.$d = new Date(normalized);+ }+ }+ oldInit.call(this);+ };++ const oldClone = proto.clone;+ proto.clone = function (this: any) {+ return zoneOf(this)+ ? dayjs(this.$d, {+ locale: this.$L,+ utc: true,+ x: this.$x,+ $I: this.$I,+ } as any)+ : oldClone.call(this);+ };++ const oldValueOf = proto.valueOf;+ proto.valueOf = function (this: any) {+ return zoneOf(this) ? this.$I : oldValueOf.call(this);+ };++ const oldToDate = proto.toDate;+ proto.toDate = function (this: any, type?: string) {+ if (zoneOf(this)) {+ return new Date(type === 's' ? this.$d.getTime() : this.$I);+ }+ return oldToDate.call(this, type);+ };++ const oldUtcOffset = proto.utcOffset;+ proto.utcOffset = function (this: any, input?: any, keepLocalTime?: any) {+ if (zoneOf(this)) {+ if (input === undefined) {+ return Math.round((this.$d.getTime() - this.$I) / MINUTE);+ }+ return dayjs(this.$I).utcOffset(input, keepLocalTime);+ }+ return oldUtcOffset.call(this, input, keepLocalTime);+ };- return result;- };- if (localStorage.getItem('timezone')) {- dayjs.tz.setDefault(getTimezone());+ const oldAdd = proto.add;+ proto.add = function (this: any, number: number, units?: any) {+ const timezone = zoneOf(this);+ const unit = timezone && this.$utils().p(units);+ if (!timezone || ['month', 'year', 'day', 'week'].includes(unit)) {+ return oldAdd.call(this, number, units);}- }, []);- return null;+ // hours and below are elapsed time, not the wall clock+ return zoned(+ this.$I + Number(number) * (STEPS[unit] || 1),+ timezone,+ this.$L+ );+ };++ const oldLocal = proto.local;+ proto.local = function (this: any) {+ return zoneOf(this) ? this.clone() : oldLocal.call(this);+ };++ const oldIsUTC = proto.isUTC;+ proto.isUTC = function (this: any) {+ return zoneOf(this) ? false : oldIsUTC.call(this);+ };++ const oldFormat = proto.format;+ proto.format = function (this: any, formatStr?: string) {+ return oldFormat.call(+ this,+ !formatStr && zoneOf(this) ? 'YYYY-MM-DDTHH:mm:ssZ' : formatStr+ );+ };++ // relativeTime compares UTC mode dates with a UTC "now"+ const oldFromNow = proto.fromNow;+ proto.fromNow = function (this: any, withoutSuffix?: boolean) {+ const timezone = zoneOf(this);+ return timezone+ ? this.from(zoned(Date.now(), timezone, this.$L), withoutSuffix)+ : oldFromNow.call(this, withoutSuffix);+ };+ const oldToNow = proto.toNow;+ proto.toNow = function (this: any, withoutSuffix?: boolean) {+ const timezone = zoneOf(this);+ return timezone+ ? this.to(zoned(Date.now(), timezone, this.$L), withoutSuffix)+ : oldToNow.call(this, withoutSuffix);+ };++ // a machine-local date (or another timezone) is compared in this timezone,+ // UTC dates are already offset-compensated by dayjs' own diff+ const oldDiff = proto.diff;+ proto.diff = function (this: any, input: any, units?: any, float?: boolean) {+ const timezone = zoneOf(this);+ const that: any = timezone ? dayjs(input) : undefined;+ if (timezone && (zoneOf(that) ? zoneOf(that) !== timezone : !that.$u)) {+ return oldDiff.call(+ this,+ zoned(that.valueOf(), timezone, this.$L),+ units,+ float+ );+ }+ return oldDiff.call(this, input, units, float);+ };+};+dayjs.extend(zonedPlugin);++export const browserTimezone = () =>+ Intl.DateTimeFormat().resolvedOptions().timeZone;++export const isTimezone = (timezone: string) => {+ try {+ Intl.DateTimeFormat('en-US', { timeZone: timezone });+ return true;+ } catch (err) {+ return false;+ }+};++// null is the browser's timezone, where plain dayjs is already right+let userTimezone: string | null = null;+const applyTimezone = (timezone?: string | null) => {+ userTimezone =+ timezone && timezone !== browserTimezone() && isTimezone(timezone)+ ? timezone+ : null;};-export default SetTimezone;+// the timezone dates are shown in, for Intl formatting outside of dayjs+export const getTimezone = () => userTimezone || browserTimezone();++// pages outside the logged-in layout (connecting a channel, the extension)+// don't load the user, they start from the timezone the app loaded last+if (typeof window !== 'undefined') {+ try {+ applyTimezone(localStorage.getItem(STORAGE_KEY));+ } catch (err) {}+}++export const setUserTimezone = (timezone?: string | null) => {+ applyTimezone(timezone);+ try {+ if (timezone) {+ localStorage.setItem(STORAGE_KEY, timezone);+ } else {+ localStorage.removeItem(STORAGE_KEY);+ }+ } catch (err) {}+};++// dayjs' local string format, anything else (Z, offsets, Dates) is an instant+const LOCAL_STRING =+ /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/;++// "now", a wall clock or an instant, in the user's timezone+export const newDayjs = (config?: ConfigType) => {+ if (!userTimezone) {+ return dayjs(config);+ }+ if (+ typeof config === 'string' &&+ !/Z$/i.test(config) &&+ LOCAL_STRING.test(config)+ ) {+ return dayjs(config, { utc: true, x: { $zone: userTimezone } } as any);+ }+ return zoned(+ config === undefined ? Date.now() : dayjs(config).valueOf(),+ userTimezone+ );+};++// a UTC date (an API string with or without the Z, or a UTC dayjs) in the+// user's timezone+export const fromUtc = (config?: ConfigType) =>+ userTimezone+ ? zoned(dayjs.utc(config).valueOf(), userTimezone)+ : dayjs.utc(config).local();++// Mantine's pickers only take native dates in the machine's timezone, so they+// get the wall clock as one+export const toPickerDate = (date: Dayjs) =>+ new Date(+ date.year(),+ date.month(),+ date.date(),+ date.hour(),+ date.minute(),+ date.second()+ );diff --git a/apps/frontend/src/components/new-launch/add.edit.modal.tsx b/apps/frontend/src/components/new-launch/add.edit.modal.tsxindex aa29e6bbc..e9fecf7e0 100644--- a/apps/frontend/src/components/new-launch/add.edit.modal.tsx+++ b/apps/frontend/src/components/new-launch/add.edit.modal.tsx@@ -8,7 +8,10 @@ import { ManageModal } from '@gitroom/frontend/components/new-launch/manage.modaimport { Integrations } from '@gitroom/frontend/components/launches/calendar.context';import { useShallow } from 'zustand/react/shallow';import { useExistingData } from '@gitroom/frontend/components/launches/helpers/use.existing.data';-import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';+import {+ fromUtc,+ newDayjs,+} from '@gitroom/frontend/components/layout/set.timezone';import { useModals } from '@gitroom/frontend/components/layout/new-modal';import { useToaster } from '@gitroom/react/toaster/toaster';import { useT } from '@gitroom/react/translation/get.transation.service.client';@@ -218,7 +221,7 @@ export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {addInternalValue(0, sibling.integration, postValues(sibling.posts));setChannelDate(sibling.integration,- dayjs.utc(sibling.posts[0].publishDate).local()+ fromUtc(sibling.posts[0].publishDate));}}diff --git a/apps/frontend/src/components/new-layout/layout.component.tsx b/apps/frontend/src/components/new-layout/layout.component.tsxindex 413d0d97a..f33da7b1f 100644--- a/apps/frontend/src/components/new-layout/layout.component.tsx+++ b/apps/frontend/src/components/new-layout/layout.component.tsx@@ -43,6 +43,7 @@ import { AttachToFeedbackIcon } from '@gitroom/frontend/components/new-layout/seimport { FirstBillingComponent } from '@gitroom/frontend/components/billing/first.billing.component';import { TrialTracker } from '@gitroom/frontend/components/layout/gtm.component';import { setSentryUser } from '@gitroom/react/sentry/initialize.sentry.client';+import { setUserTimezone } from '@gitroom/frontend/components/layout/set.timezone';export const LayoutComponent = ({ children }: { children: ReactNode }) => {const fetch = useFetch();@@ -60,6 +61,8 @@ export const LayoutComponent = ({ children }: { children: ReactNode }) => {return await (await fetch(path)).json();}, []);const { data: user, mutate } = useSWR('/user/self', load, {+ // set before anything renders a date in the user's timezone+ onSuccess: (data) => setUserTimezone(data?.timezoneName),revalidateOnFocus: false,revalidateOnReconnect: false,revalidateIfStale: false,diff --git a/apps/frontend/src/components/notifications/notification.component.tsx b/apps/frontend/src/components/notifications/notification.component.tsxindex 95b51b0eb..30936165a 100644--- a/apps/frontend/src/components/notifications/notification.component.tsx+++ b/apps/frontend/src/components/notifications/notification.component.tsx@@ -4,7 +4,7 @@ import { useFetch } from '@gitroom/helpers/utils/custom.fetch';import useSWR from 'swr';import { FC, useCallback, useState } from 'react';import clsx from 'clsx';-import dayjs from 'dayjs';+import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';import { useClickAway } from '@uidotdev/usehooks';import ReactLoading from '@gitroom/frontend/components/layout/loading';import { useT } from '@gitroom/react/translation/get.transation.service.client';@@ -27,8 +27,8 @@ export const ShowNotification: FC<{const [newNotification] = useState(new Date(notification.createdAt) > new Date(props.lastReadNotification));- const createdAt = dayjs(notification.createdAt);- const isWithin24h = dayjs().diff(createdAt, 'hour') < 24;+ const createdAt = newDayjs(notification.createdAt);+ const isWithin24h = newDayjs().diff(createdAt, 'hour') < 24;const fullDate = createdAt.format('MMM D, YYYY h:mm A');return (<divdiff --git a/apps/frontend/src/components/preview/comments.components.tsx b/apps/frontend/src/components/preview/comments.components.tsxindex 630ad20b2..74838d4b1 100644--- a/apps/frontend/src/components/preview/comments.components.tsx+++ b/apps/frontend/src/components/preview/comments.components.tsx@@ -13,6 +13,7 @@ import { useVariables } from '@gitroom/react/helpers/variable.context';import { useToaster } from '@gitroom/react/toaster/toaster';import clsx from 'clsx';import dayjs from 'dayjs';+import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';import {PreviewComment,usePreviewComments,@@ -313,7 +314,7 @@ const CommentBody: FC<{ comment: PreviewComment }> = ({ comment }) => {</div><div className="text-[12px] text-textItemBlur">{comment.name || t('reviewer', 'Reviewer')} ·{' '}- {dayjs(comment.createdAt).format('MMM D, YYYY HH:mm')}+ {newDayjs(comment.createdAt).format('MMM D, YYYY HH:mm')}</div></div>);diff --git a/apps/frontend/src/components/preview/render.preview.date.tsx b/apps/frontend/src/components/preview/render.preview.date.tsxindex 543f06450..83dd33753 100644--- a/apps/frontend/src/components/preview/render.preview.date.tsx+++ b/apps/frontend/src/components/preview/render.preview.date.tsx@@ -1,11 +1,9 @@'use client';import { FC } from 'react';-import dayjs from 'dayjs';-import utc from 'dayjs/plugin/utc';-dayjs.extend(utc);+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';export const RenderPreviewDate: FC<{ date: string }> = ({ date }) => {console.log(date);- return <>{dayjs.utc(date).local().format('MMMM D, YYYY h:mm A')}</>;+ return <>{fromUtc(date).format('MMMM D, YYYY h:mm A')}</>;};diff --git a/apps/frontend/src/components/settings/metric.component.tsx b/apps/frontend/src/components/settings/metric.component.tsxindex 8869c1f6d..d406ef0df 100644--- a/apps/frontend/src/components/settings/metric.component.tsx+++ b/apps/frontend/src/components/settings/metric.component.tsx@@ -1,36 +1,61 @@'use client';import { Select } from '@gitroom/react/form/select';-import React, { useState } from 'react';+import React, { useCallback, useState } from 'react';import { isUSCitizen } from '@gitroom/frontend/components/launches/helpers/isuscitizen.utils';import timezones from 'timezones-list';+import { useFetch } from '@gitroom/helpers/utils/custom.fetch';+import { useToaster } from '@gitroom/react/toaster/toaster';+import { useT } from '@gitroom/react/translation/get.transation.service.client';+import { useUser } from '@gitroom/frontend/components/layout/user.context';+import {+ browserTimezone,+ isTimezone,+} from '@gitroom/frontend/components/layout/set.timezone';const dateMetrics = [{ label: 'AM:PM', value: 'US' },{ label: '24 hours', value: 'GLOBAL' },];-import dayjs from 'dayjs';-import timezone from 'dayjs/plugin/timezone';-dayjs.extend(timezone);+// the list has names that aren't IANA timezones (Europe/Zaporizhzhia)+const timezoneOptions = timezones.filter((zone) => isTimezone(zone.tzCode));const MetricComponent = () => {+ const t = useT();+ const fetch = useFetch();+ const toaster = useToaster();+ const user = useUser();const [currentMetric, setCurrentMetric] = useState(isUSCitizen());- const [timezone, setTimezone] = useState(- localStorage.getItem('timezone') || dayjs.tz.guess()- );+ const [timezone, setTimezone] = useState(user?.timezoneName || '');const changeMetric = (event: React.ChangeEvent<HTMLSelectElement>) => {const value = event.target.value;setCurrentMetric(value === 'US');localStorage.setItem('isUS', value);};- const changeTimezone = (event: React.ChangeEvent<HTMLSelectElement>) => {- const value = event.target.value;- console.log(value);- setTimezone(value);- localStorage.setItem('timezone', value);- dayjs.tz.setDefault(value);- };+ const changeTimezone = useCallback(+ async (event: React.ChangeEvent<HTMLSelectElement>) => {+ const value = event.target.value;+ setTimezone(value);+ const response = await fetch('/user/timezone', {+ method: 'POST',+ body: JSON.stringify({ timezoneName: value || null }),+ });++ if (response.status !== 200 && response.status !== 201) {+ setTimezone(user?.timezoneName || '');+ toaster.show(+ t('could_not_save_timezone', 'Could not save the timezone'),+ 'warning'+ );+ return;+ }++ // everything on screen was rendered in the previous timezone+ window.location.reload();+ },+ []+ );return (<div className="my-[16px] mt-[16px] bg-sixth border-fifth border rounded-[4px] p-[24px] flex flex-col gap-[24px]"><div className="mt-[4px]">Date Metrics</div>@@ -45,23 +70,26 @@ const MetricComponent = () => {))}</Select>- {/*<div className="mt-[4px]">Current Timezone</div>*/}- {/*<Select*/}- {/* name="timezone"*/}- {/* disableForm={true}*/}- {/* label=""*/}- {/* onChange={changeTimezone}*/}- {/*>*/}- {/* {timezones.map((metric) => (*/}- {/* <option*/}- {/* key={metric.name}*/}- {/* value={metric.tzCode}*/}- {/* selected={metric.tzCode === timezone}*/}- {/* >*/}- {/* {metric.label}*/}- {/* </option>*/}- {/* ))}*/}- {/*</Select>*/}+ <div className="mt-[4px]">{t('timezone', 'Timezone')}</div>+ <Select+ name="timezone"+ disableForm={true}+ label=""+ onChange={changeTimezone}+ value={timezone}+ >+ <option value="">+ {t('automatic_timezone', 'Automatic ({{timezone}})', {+ timezone: browserTimezone(),+ interpolation: { escapeValue: false },+ })}+ </option>+ {timezoneOptions.map((zone) => (+ <option key={zone.tzCode} value={zone.tzCode}>+ {zone.label}+ </option>+ ))}+ </Select></div>);};diff --git a/apps/frontend/src/components/standalone-modal/standalone.modal.tsx b/apps/frontend/src/components/standalone-modal/standalone.modal.tsxindex 469ca79c1..b452480ae 100644--- a/apps/frontend/src/components/standalone-modal/standalone.modal.tsx+++ b/apps/frontend/src/components/standalone-modal/standalone.modal.tsx@@ -4,10 +4,12 @@ import 'reflect-metadata';import { FC, useCallback } from 'react';import useSWR from 'swr';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';-import dayjs from 'dayjs';import { useParams } from 'next/navigation';import { AddEditModal } from '@gitroom/frontend/components/new-launch/add.edit.modal';-import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';+import {+ fromUtc,+ newDayjs,+} from '@gitroom/frontend/components/layout/set.timezone';export const StandaloneModal: FC = () => {const fetch = useFetch();const params = useParams<{ platform: string }>();@@ -57,7 +59,7 @@ export const StandaloneModal: FC = () => {integrations={integrations}reopenModal={() => {}}allIntegrations={integrations}- date={dayjs.utc(data).local()}+ date={fromUtc(data)}/>);};diff --git a/i18n.lock b/i18n.lockindex 8b14ef24d..5a567f513 100644--- a/i18n.lock+++ b/i18n.lock@@ -884,3 +884,6 @@ checksums:only_channel: 5687ae99e7f5b168e35532f895efd2e8hubspot_installed: 5937d91a1e1f8093b2bf31c834ebc18dhubspot_installed_description: d0044e3cca1e574871461cab9f8722c0+ timezone: 370780b854bdbef55320f977a4fb9ddb+ automatic_timezone: bb2d180231d5caccb2507ada3bb8329e+ could_not_save_timezone: d0e1af80e2c1de9a40f748fd5198d7a5diff --git a/libraries/nestjs-libraries/src/database/prisma/schema.prisma b/libraries/nestjs-libraries/src/database/prisma/schema.prismaindex f3feb10aa..2fd85ec45 100644--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma@@ -92,6 +92,7 @@ model User {pictureId String?providerId String?timezone Int+ timezoneName String?createdAt DateTime @default(now())updatedAt DateTime @updatedAtlastReadNotifications DateTime @default(now())diff --git a/libraries/nestjs-libraries/src/database/prisma/users/users.repository.ts b/libraries/nestjs-libraries/src/database/prisma/users/users.repository.tsindex da2b18d13..894a798e7 100644--- a/libraries/nestjs-libraries/src/database/prisma/users/users.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/users/users.repository.ts@@ -8,6 +8,7 @@ import { Provider, Role } from '@prisma/client';import { AuthService } from '@gitroom/helpers/auth/auth.service';import { UserDetailDto } from '@gitroom/nestjs-libraries/dtos/users/user.details.dto';import { EmailNotificationsDto } from '@gitroom/nestjs-libraries/dtos/users/email-notifications.dto';+import { TimezoneDto } from '@gitroom/nestjs-libraries/dtos/users/timezone.dto';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';@Injectable()@@ -299,4 +300,18 @@ export class UsersRepository {},});}++ async updateTimezone(userId: string, body: TimezoneDto) {+ await this._user.model.user.update({+ where: {+ id: userId,+ },+ data: {+ timezoneName: body.timezoneName || null,+ },+ select: {+ id: true,+ },+ });+ }}diff --git a/libraries/nestjs-libraries/src/database/prisma/users/users.service.ts b/libraries/nestjs-libraries/src/database/prisma/users/users.service.tsindex b162eeb83..226b55f00 100644--- a/libraries/nestjs-libraries/src/database/prisma/users/users.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/users/users.service.ts@@ -3,6 +3,7 @@ import { UsersRepository } from '@gitroom/nestjs-libraries/database/prisma/usersimport { Provider, Role } from '@prisma/client';import { UserDetailDto } from '@gitroom/nestjs-libraries/dtos/users/user.details.dto';import { EmailNotificationsDto } from '@gitroom/nestjs-libraries/dtos/users/email-notifications.dto';+import { TimezoneDto } from '@gitroom/nestjs-libraries/dtos/users/timezone.dto';import { OrganizationRepository } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.repository';import { IntegrationRepository } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.repository';import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';@@ -174,4 +175,8 @@ export class UsersService {updateEmailNotifications(userId: string, body: EmailNotificationsDto) {return this._usersRepository.updateEmailNotifications(userId, body);}++ updateTimezone(userId: string, body: TimezoneDto) {+ return this._usersRepository.updateTimezone(userId, body);+ }}diff --git a/libraries/nestjs-libraries/src/dtos/users/timezone.dto.ts b/libraries/nestjs-libraries/src/dtos/users/timezone.dto.tsnew file mode 100644index 000000000..6496f5b8c--- /dev/null+++ b/libraries/nestjs-libraries/src/dtos/users/timezone.dto.ts@@ -0,0 +1,8 @@+import { IsOptional, IsTimeZone } from 'class-validator';++export class TimezoneDto {+ // empty means the browser's timezone+ @IsOptional()+ @IsTimeZone()+ timezoneName?: string;+}diff --git a/libraries/nestjs-libraries/src/track/track.cookies.ts b/libraries/nestjs-libraries/src/track/track.cookies.tsnew file mode 100644index 000000000..d18196b71--- /dev/null+++ b/libraries/nestjs-libraries/src/track/track.cookies.ts@@ -0,0 +1,55 @@+import { Request, Response } from 'express';+import { randomInt } from 'crypto';+import { makeId } from '@gitroom/nestjs-libraries/services/make.is';+import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';++const DAY = 1000 * 60 * 60 * 24;++const cookieOptions = (expiresInDays: number, httpOnly: boolean) => ({+ domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),+ ...(!process.env.NOT_SECURED+ ? {+ secure: true,+ httpOnly,+ sameSite: 'none' as const,+ }+ : {}),+ expires: new Date(Date.now() + DAY * expiresInDays),+});++// Sets the visitor cookies on the root domain, so postiz.com and+// platform.postiz.com share them, and returns the ids for the Conversions API.+//+// _fbc / _fbp are written by the server in Meta's own format instead of+// waiting for the pixel: when an adblocker kills the pixel nothing else would+// create them, and the server events would lose the ad click and the browser+// id. They are not httpOnly because the pixel (when it loads) reuses them and+// the billing page reads them for the Stripe metadata.+export const applyTrackCookies = (+ req: Request,+ res: Response,+ fbclid?: string+) => {+ const uniqueId = req?.cookies?.track || makeId(10);+ if (!req?.cookies?.track) {+ res.cookie('track', uniqueId, cookieOptions(365, true));+ }++ // a new ad click replaces the old one, the same click keeps its creation time+ const currentFbc = req?.cookies?._fbc;+ const isNewClick = !!fbclid && !currentFbc?.endsWith(`.${fbclid}`);+ const fbc = isNewClick+ ? `fb.1.${Date.now()}.${fbclid}`+ : // the fbclid cookie was set by older versions of this endpoint+ currentFbc || req?.cookies?.fbclid;+ if (isNewClick) {+ res.cookie('_fbc', fbc, cookieOptions(90, false));+ }++ const fbp = req?.cookies?._fbp || `fb.1.${Date.now()}.${randomInt(2 ** 31)}`;+ if (!req?.cookies?._fbp) {+ res.cookie('_fbp', fbp, cookieOptions(90, false));+ }++ return { uniqueId, fbc, fbp };+};diff --git a/libraries/react-shared-libraries/src/helpers/utc.date.render.tsx b/libraries/react-shared-libraries/src/helpers/utc.date.render.tsxindex 3fa1c8b9c..a7e8ac233 100644--- a/libraries/react-shared-libraries/src/helpers/utc.date.render.tsx+++ b/libraries/react-shared-libraries/src/helpers/utc.date.render.tsx@@ -1,13 +1,11 @@'use client';-import dayjs from 'dayjs';-import utc from 'dayjs/plugin/utc';import { FC } from 'react';-dayjs.extend(utc);+import { fromUtc } from '@gitroom/frontend/components/layout/set.timezone';export const UtcToLocalDateRender: FC<{date: string;format: string;}> = (props) => {const { date, format } = props;- return <>{dayjs.utc(date).local().format(format)}</>;+ return <>{fromUtc(date).format(format)}</>;};diff --git a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json b/libraries/react-shared-libraries/src/translation/locales/ar/translation.jsonindex 388ba1d1b..6db7dcb50 100644--- a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ar/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "جدولة جميع القنوات","only_channel": "فقط","hubspot_installed": "تم تثبيت Postiz في HubSpot",- "hubspot_installed_description": "اربط هنا في Postiz القنوات التي تريد النشر عليها. بعد ذلك، افتح Agent Hub > Agent Builder في HubSpot، وأضف أداة، واختر Postiz MCP ضمن MCP Servers، ثم انقر على Connect and add."+ "hubspot_installed_description": "اربط هنا في Postiz القنوات التي تريد النشر عليها. بعد ذلك، افتح Agent Hub > Agent Builder في HubSpot، وأضف أداة، واختر Postiz MCP ضمن MCP Servers، ثم انقر على Connect and add.",+ "timezone": "المنطقة الزمنية",+ "automatic_timezone": "تلقائي ({{timezone}})",+ "could_not_save_timezone": "تعذر حفظ المنطقة الزمنية"}diff --git a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json b/libraries/react-shared-libraries/src/translation/locales/bn/translation.jsonindex 283a93452..25dacbcd9 100644--- a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/bn/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "সব চ্যানেলের সময়সূচী করুন","only_channel": "শুধুমাত্র চ্যানেল:","hubspot_installed": "Postiz HubSpot-এ ইনস্টল করা হয়েছে",- "hubspot_installed_description": "যেসব চ্যানেলে পোস্ট করতে চান, সেগুলো এখানে Postiz-এ সংযুক্ত করুন। এরপর HubSpot-এ Agent Hub > Agent Builder খুলুন, একটি টুল যোগ করুন, MCP Servers-এর অধীনে Postiz MCP বেছে নিন এবং Connect and add-এ ক্লিক করুন।"+ "hubspot_installed_description": "যেসব চ্যানেলে পোস্ট করতে চান, সেগুলো এখানে Postiz-এ সংযুক্ত করুন। এরপর HubSpot-এ Agent Hub > Agent Builder খুলুন, একটি টুল যোগ করুন, MCP Servers-এর অধীনে Postiz MCP বেছে নিন এবং Connect and add-এ ক্লিক করুন।",+ "timezone": "সময় অঞ্চল",+ "automatic_timezone": "স্বয়ংক্রিয় ({{timezone}})",+ "could_not_save_timezone": "সময় অঞ্চল সংরক্ষণ করা যায়নি"}diff --git a/libraries/react-shared-libraries/src/translation/locales/de/translation.json b/libraries/react-shared-libraries/src/translation/locales/de/translation.jsonindex 6fffccf59..9f68ac70a 100644--- a/libraries/react-shared-libraries/src/translation/locales/de/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/de/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "In allen Kanälen planen","only_channel": "Nur","hubspot_installed": "Postiz ist in HubSpot installiert",- "hubspot_installed_description": "Verbinden Sie hier in Postiz die Kanäle, auf denen Sie posten möchten. Öffnen Sie dann in HubSpot Agent Hub > Agent Builder, fügen Sie ein Tool hinzu, wählen Sie unter MCP Servers Postiz MCP aus und klicken Sie auf Connect and add."+ "hubspot_installed_description": "Verbinden Sie hier in Postiz die Kanäle, auf denen Sie posten möchten. Öffnen Sie dann in HubSpot Agent Hub > Agent Builder, fügen Sie ein Tool hinzu, wählen Sie unter MCP Servers Postiz MCP aus und klicken Sie auf Connect and add.",+ "timezone": "Zeitzone",+ "automatic_timezone": "Automatisch ({{timezone}})",+ "could_not_save_timezone": "Die Zeitzone konnte nicht gespeichert werden"}diff --git a/libraries/react-shared-libraries/src/translation/locales/en/translation.json b/libraries/react-shared-libraries/src/translation/locales/en/translation.jsonindex 7d1c24948..34bac4459 100644--- a/libraries/react-shared-libraries/src/translation/locales/en/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/en/translation.json@@ -881,5 +881,8 @@"schedule_all_channels": "Schedule all channels","only_channel": "Only","hubspot_installed": "Postiz is installed in HubSpot",- "hubspot_installed_description": "Connect the channels you want to post to here in Postiz. Then, in HubSpot, open Agent Hub > Agent Builder, add a tool, pick Postiz MCP under MCP Servers and click Connect and add."+ "hubspot_installed_description": "Connect the channels you want to post to here in Postiz. Then, in HubSpot, open Agent Hub > Agent Builder, add a tool, pick Postiz MCP under MCP Servers and click Connect and add.",+ "timezone": "Timezone",+ "automatic_timezone": "Automatic ({{timezone}})",+ "could_not_save_timezone": "Could not save the timezone"}diff --git a/libraries/react-shared-libraries/src/translation/locales/es/translation.json b/libraries/react-shared-libraries/src/translation/locales/es/translation.jsonindex dfc1b278c..770a87b56 100644--- a/libraries/react-shared-libraries/src/translation/locales/es/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/es/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "Programar todos los canales","only_channel": "Solo","hubspot_installed": "Postiz está instalado en HubSpot",- "hubspot_installed_description": "Conecta aquí, en Postiz, los canales en los que quieres publicar. Luego, en HubSpot, abre Agent Hub > Agent Builder, añade una herramienta, elige Postiz MCP en MCP Servers y haz clic en Connect and add."+ "hubspot_installed_description": "Conecta aquí, en Postiz, los canales en los que quieres publicar. Luego, en HubSpot, abre Agent Hub > Agent Builder, añade una herramienta, elige Postiz MCP en MCP Servers y haz clic en Connect and add.",+ "timezone": "Zona horaria",+ "automatic_timezone": "Automática ({{timezone}})",+ "could_not_save_timezone": "No se pudo guardar la zona horaria"}diff --git a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json b/libraries/react-shared-libraries/src/translation/locales/fr/translation.jsonindex 4707bf5de..95bd9cf17 100644--- a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/fr/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "Planifier tous les canaux","only_channel": "Uniquement","hubspot_installed": "Postiz est installé dans HubSpot",- "hubspot_installed_description": "Connectez ici, dans Postiz, les canaux sur lesquels vous souhaitez publier. Ensuite, dans HubSpot, ouvrez Agent Hub > Agent Builder, ajoutez un outil, choisissez Postiz MCP sous MCP Servers et cliquez sur Connect and add."+ "hubspot_installed_description": "Connectez ici, dans Postiz, les canaux sur lesquels vous souhaitez publier. Ensuite, dans HubSpot, ouvrez Agent Hub > Agent Builder, ajoutez un outil, choisissez Postiz MCP sous MCP Servers et cliquez sur Connect and add.",+ "timezone": "Fuseau horaire",+ "automatic_timezone": "Automatique ({{timezone}})",+ "could_not_save_timezone": "Impossible d'enregistrer le fuseau horaire"}diff --git a/libraries/react-shared-libraries/src/translation/locales/he/translation.json b/libraries/react-shared-libraries/src/translation/locales/he/translation.jsonindex f260bc6c9..0502c88a9 100644--- a/libraries/react-shared-libraries/src/translation/locales/he/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/he/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "תזמן את כל הערוצים","only_channel": "רק","hubspot_installed": "Postiz הותקן ב-HubSpot",- "hubspot_installed_description": "חבר כאן ב-Postiz את הערוצים שאליהם תרצה לפרסם. לאחר מכן, ב-HubSpot, פתח את Agent Hub > Agent Builder, הוסף כלי, בחר את Postiz MCP תחת MCP Servers ולחץ על Connect and add."+ "hubspot_installed_description": "חבר כאן ב-Postiz את הערוצים שאליהם תרצה לפרסם. לאחר מכן, ב-HubSpot, פתח את Agent Hub > Agent Builder, הוסף כלי, בחר את Postiz MCP תחת MCP Servers ולחץ על Connect and add.",+ "timezone": "אזור זמן",+ "automatic_timezone": "אוטומטי ({{timezone}})",+ "could_not_save_timezone": "לא ניתן היה לשמור את אזור הזמן"}diff --git a/libraries/react-shared-libraries/src/translation/locales/it/translation.json b/libraries/react-shared-libraries/src/translation/locales/it/translation.jsonindex 6f158340b..0f2c68072 100644--- a/libraries/react-shared-libraries/src/translation/locales/it/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/it/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "Programma tutti i canali","only_channel": "Solo","hubspot_installed": "Postiz è installato in HubSpot",- "hubspot_installed_description": "Collega qui, in Postiz, i canali su cui vuoi pubblicare. Poi, in HubSpot, apri Agent Hub > Agent Builder, aggiungi uno strumento, scegli Postiz MCP in MCP Servers e fai clic su Connect and add."+ "hubspot_installed_description": "Collega qui, in Postiz, i canali su cui vuoi pubblicare. Poi, in HubSpot, apri Agent Hub > Agent Builder, aggiungi uno strumento, scegli Postiz MCP in MCP Servers e fai clic su Connect and add.",+ "timezone": "Fuso orario",+ "automatic_timezone": "Automatico ({{timezone}})",+ "could_not_save_timezone": "Impossibile salvare il fuso orario"}diff --git a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json b/libraries/react-shared-libraries/src/translation/locales/ja/translation.jsonindex be7eec156..1b930690a 100644--- a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ja/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "すべてのチャンネルでスケジュール","only_channel": "このチャンネルのみ:","hubspot_installed": "Postiz を HubSpot にインストールしました",- "hubspot_installed_description": "投稿したいチャンネルをここ Postiz で接続してください。次に HubSpot で Agent Hub > Agent Builder を開き、ツールを追加して MCP Servers から Postiz MCP を選択し、Connect and add をクリックしてください。"+ "hubspot_installed_description": "投稿したいチャンネルをここ Postiz で接続してください。次に HubSpot で Agent Hub > Agent Builder を開き、ツールを追加して MCP Servers から Postiz MCP を選択し、Connect and add をクリックしてください。",+ "timezone": "タイムゾーン",+ "automatic_timezone": "自動 ({{timezone}})",+ "could_not_save_timezone": "タイムゾーンを保存できませんでした"}diff --git a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json b/libraries/react-shared-libraries/src/translation/locales/ko/translation.jsonindex 7e8c9cd83..509a300ec 100644--- a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ko/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "모든 채널에 예약","only_channel": "다음 채널만:","hubspot_installed": "Postiz가 HubSpot에 설치되었습니다",- "hubspot_installed_description": "게시할 채널을 여기 Postiz에서 연결하세요. 그런 다음 HubSpot에서 Agent Hub > Agent Builder를 열고 도구를 추가한 뒤 MCP Servers에서 Postiz MCP를 선택하고 Connect and add를 클릭하세요."+ "hubspot_installed_description": "게시할 채널을 여기 Postiz에서 연결하세요. 그런 다음 HubSpot에서 Agent Hub > Agent Builder를 열고 도구를 추가한 뒤 MCP Servers에서 Postiz MCP를 선택하고 Connect and add를 클릭하세요.",+ "timezone": "시간대",+ "automatic_timezone": "자동 ({{timezone}})",+ "could_not_save_timezone": "시간대를 저장할 수 없습니다"}diff --git a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json b/libraries/react-shared-libraries/src/translation/locales/pt/translation.jsonindex 00c01ad7c..aa23f98c2 100644--- a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/pt/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "Agendar todos os canais","only_channel": "Apenas","hubspot_installed": "O Postiz está instalado no HubSpot",- "hubspot_installed_description": "Conecte aqui, no Postiz, os canais em que você deseja publicar. Depois, no HubSpot, abra Agent Hub > Agent Builder, adicione uma ferramenta, escolha Postiz MCP em MCP Servers e clique em Connect and add."+ "hubspot_installed_description": "Conecte aqui, no Postiz, os canais em que você deseja publicar. Depois, no HubSpot, abra Agent Hub > Agent Builder, adicione uma ferramenta, escolha Postiz MCP em MCP Servers e clique em Connect and add.",+ "timezone": "Fuso horário",+ "automatic_timezone": "Automático ({{timezone}})",+ "could_not_save_timezone": "Não foi possível salvar o fuso horário"}diff --git a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json b/libraries/react-shared-libraries/src/translation/locales/ru/translation.jsonindex 355c41472..3c2ab9ab4 100644--- a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ru/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "Запланировать во всех каналах","only_channel": "Только","hubspot_installed": "Postiz установлен в HubSpot",- "hubspot_installed_description": "Подключите здесь, в Postiz, каналы, в которых хотите публиковать. Затем в HubSpot откройте Agent Hub > Agent Builder, добавьте инструмент, выберите Postiz MCP в разделе MCP Servers и нажмите Connect and add."+ "hubspot_installed_description": "Подключите здесь, в Postiz, каналы, в которых хотите публиковать. Затем в HubSpot откройте Agent Hub > Agent Builder, добавьте инструмент, выберите Postiz MCP в разделе MCP Servers и нажмите Connect and add.",+ "timezone": "Часовой пояс",+ "automatic_timezone": "Автоматически ({{timezone}})",+ "could_not_save_timezone": "Не удалось сохранить часовой пояс"}diff --git a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json b/libraries/react-shared-libraries/src/translation/locales/tr/translation.jsonindex db335f789..60fdbe976 100644--- a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/tr/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "Tüm kanalları zamanla","only_channel": "Yalnızca şu kanal:","hubspot_installed": "Postiz, HubSpot'a yüklendi",- "hubspot_installed_description": "Paylaşım yapmak istediğiniz kanalları burada, Postiz'de bağlayın. Ardından HubSpot'ta Agent Hub > Agent Builder'ı açın, bir araç ekleyin, MCP Servers altında Postiz MCP'yi seçin ve Connect and add'e tıklayın."+ "hubspot_installed_description": "Paylaşım yapmak istediğiniz kanalları burada, Postiz'de bağlayın. Ardından HubSpot'ta Agent Hub > Agent Builder'ı açın, bir araç ekleyin, MCP Servers altında Postiz MCP'yi seçin ve Connect and add'e tıklayın.",+ "timezone": "Saat dilimi",+ "automatic_timezone": "Otomatik ({{timezone}})",+ "could_not_save_timezone": "Saat dilimi kaydedilemedi"}diff --git a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json b/libraries/react-shared-libraries/src/translation/locales/vi/translation.jsonindex 404932389..718e4463a 100644--- a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/vi/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "Lên lịch cho tất cả các kênh","only_channel": "Chỉ","hubspot_installed": "Postiz đã được cài đặt trong HubSpot",- "hubspot_installed_description": "Hãy kết nối tại đây, trong Postiz, các kênh bạn muốn đăng bài. Sau đó, trong HubSpot, mở Agent Hub > Agent Builder, thêm một công cụ, chọn Postiz MCP trong MCP Servers và nhấp vào Connect and add."+ "hubspot_installed_description": "Hãy kết nối tại đây, trong Postiz, các kênh bạn muốn đăng bài. Sau đó, trong HubSpot, mở Agent Hub > Agent Builder, thêm một công cụ, chọn Postiz MCP trong MCP Servers và nhấp vào Connect and add.",+ "timezone": "Múi giờ",+ "automatic_timezone": "Tự động ({{timezone}})",+ "could_not_save_timezone": "Không thể lưu múi giờ"}diff --git a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json b/libraries/react-shared-libraries/src/translation/locales/zh/translation.jsonindex fe627261c..af0515add 100644--- a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/zh/translation.json@@ -879,5 +879,8 @@"schedule_all_channels": "在所有频道安排发布","only_channel": "仅","hubspot_installed": "Postiz 已安装到 HubSpot",- "hubspot_installed_description": "请先在 Postiz 中连接您要发布内容的渠道。然后在 HubSpot 中打开 Agent Hub > Agent Builder,添加一个工具,在 MCP Servers 下选择 Postiz MCP,然后点击 Connect and add。"+ "hubspot_installed_description": "请先在 Postiz 中连接您要发布内容的渠道。然后在 HubSpot 中打开 Agent Hub > Agent Builder,添加一个工具,在 MCP Servers 下选择 Postiz MCP,然后点击 Connect and add。",+ "timezone": "时区",+ "automatic_timezone": "自动 ({{timezone}})",+ "could_not_save_timezone": "无法保存时区"}diff --git a/package.json b/package.jsonindex c6f2a9c39..db623e853 100644--- a/package.json+++ b/package.json@@ -160,7 +160,7 @@"cookie-parser": "^1.4.7","copy-to-clipboard": "^3.3.3","crypto-hash": "^3.0.0",- "dayjs": "^1.11.10",+ "dayjs": "1.11.19","dotenv": "^16.5.0","dotenv-cli": "^8.0.0","emoji-picker-react": "^4.12.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 64aa6effa..86f6cc519 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -378,7 +378,7 @@ importers:specifier: ^3.0.0version: 3.1.0dayjs:- specifier: ^1.11.10+ specifier: 1.11.19version: 1.11.19dotenv:specifier: ^16.5.0