feature(dashboard,api): add timezone support

* feat(dashboard): add support for today, yesterday etc (timezones)

* fix(db): escape js dates

* fix(dashboard): ensure we support default timezone

* final fixes

* remove complete series and add sql with fill instead
This commit is contained in:
Carl-Gerhard Lindesvärd
2025-05-23 11:26:44 +02:00
committed by GitHub
parent 46bfeee131
commit 680727355b
48 changed files with 1817 additions and 758 deletions

View File

@@ -1,5 +1,5 @@
import Chat from '@/components/chat/chat';
import { db, getOrganizationBySlug } from '@openpanel/db';
import { db, getOrganizationById } from '@openpanel/db';
import type { UIMessage } from 'ai';
export default async function ChatPage({
@@ -9,7 +9,7 @@ export default async function ChatPage({
}) {
const { projectId } = await params;
const [organization, chat] = await Promise.all([
getOrganizationBySlug(params.organizationSlug),
getOrganizationById(params.organizationSlug),
db.chat.findFirst({
where: {
projectId,

View File

@@ -24,7 +24,6 @@ import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { useAppParams } from '@/hooks/useAppParams';
import { useDispatch, useSelector } from '@/redux';
import { bind } from 'bind-event-listener';
import { endOfDay, startOfDay } from 'date-fns';
import { GanttChartSquareIcon } from 'lucide-react';
import { useEffect } from 'react';
@@ -89,12 +88,8 @@ export default function ReportEditor({
dispatch(changeDateRanges(value));
}}
value={report.range}
onStartDateChange={(date) =>
dispatch(changeStartDate(startOfDay(date).toISOString()))
}
onEndDateChange={(date) =>
dispatch(changeEndDate(endOfDay(date).toISOString()))
}
onStartDateChange={(date) => dispatch(changeStartDate(date))}
onEndDateChange={(date) => dispatch(changeEndDate(date))}
endDate={report.endDate}
startDate={report.startDate}
/>

View File

@@ -1,20 +1,19 @@
'use client';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
import { api, handleError } from '@/trpc/client';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import type { z } from 'zod';
import { Combobox } from '@/components/ui/combobox';
import type { IServiceOrganization } from '@openpanel/db';
import { zEditOrganization } from '@openpanel/validation';
const validator = z.object({
id: z.string().min(2),
name: z.string().min(2),
});
const validator = zEditOrganization;
type IForm = z.infer<typeof validator>;
interface EditOrganizationProps {
@@ -25,8 +24,12 @@ export default function EditOrganization({
}: EditOrganizationProps) {
const router = useRouter();
const { register, handleSubmit, formState, reset } = useForm<IForm>({
defaultValues: organization ?? undefined,
const { register, handleSubmit, formState, reset, control } = useForm<IForm>({
defaultValues: {
id: organization.id,
name: organization.name,
timezone: organization.timezone ?? undefined,
},
});
const mutation = api.organization.update.useMutation({
@@ -34,7 +37,10 @@ export default function EditOrganization({
toast('Organization updated', {
description: 'Your organization has been updated.',
});
reset(res);
reset({
...res,
timezone: res.timezone!,
});
router.refresh();
},
onError: handleError,
@@ -50,14 +56,37 @@ export default function EditOrganization({
<WidgetHead className="flex items-center justify-between">
<span className="title">Details</span>
</WidgetHead>
<WidgetBody className="flex items-end gap-2">
<WidgetBody className="gap-4 col">
<InputWithLabel
className="flex-1"
label="Name"
{...register('name')}
defaultValue={organization?.name}
/>
<Button size="sm" type="submit" disabled={!formState.isDirty}>
<Controller
name="timezone"
control={control}
render={({ field }) => (
<WithLabel label="Timezone">
<Combobox
placeholder="Select timezone"
items={Intl.supportedValuesOf('timeZone').map((item) => ({
value: item,
label: item,
}))}
value={field.value}
onChange={field.onChange}
className="w-full"
/>
</WithLabel>
)}
/>
<Button
size="sm"
type="submit"
disabled={!formState.isDirty}
className="self-end"
>
Save
</Button>
</WidgetBody>

View File

@@ -6,7 +6,7 @@ import { notFound } from 'next/navigation';
import { parseAsStringEnum } from 'nuqs/server';
import { auth } from '@openpanel/auth/nextjs';
import { db, transformOrganization } from '@openpanel/db';
import { db } from '@openpanel/db';
import InvitesServer from './invites';
import MembersServer from './members';

View File

@@ -83,12 +83,7 @@ export default function EditProjectDetails({ project }: Props) {
<span className="title">Details</span>
</WidgetHead>
<WidgetBody>
<form
onSubmit={form.handleSubmit(onSubmit, (errors) => {
console.log(errors);
})}
className="col gap-4"
>
<form onSubmit={form.handleSubmit(onSubmit)} className="col gap-4">
<InputWithLabel
label="Name"
{...form.register('name')}

View File

@@ -0,0 +1,61 @@
'use client';
import { differenceInHours } from 'date-fns';
import { useEffect, useState } from 'react';
import { ProjectLink } from '@/components/links';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import type { IServiceOrganization } from '@openpanel/db';
import { useOpenPanel } from '@openpanel/nextjs';
import { FREE_PRODUCT_IDS } from '@openpanel/payments';
import Billing from './settings/organization/organization/billing';
interface SideEffectsProps {
organization: IServiceOrganization;
}
export default function SideEffectsFreePlan({
organization,
}: SideEffectsProps) {
const op = useOpenPanel();
const willEndInHours = organization.subscriptionEndsAt
? differenceInHours(organization.subscriptionEndsAt, new Date())
: null;
const [isFreePlan, setIsFreePlan] = useState<boolean>(
!!organization.subscriptionProductId &&
FREE_PRODUCT_IDS.includes(organization.subscriptionProductId),
);
useEffect(() => {
if (isFreePlan) {
op.track('free_plan_removed');
}
}, []);
return (
<Dialog open={isFreePlan} onOpenChange={setIsFreePlan}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsFreePlan(false)}
title={'Free plan has been removed'}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,91 @@
'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { Dialog, DialogContent, DialogFooter } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import { api, handleError } from '@/trpc/client';
import { TIMEZONES } from '@openpanel/common';
import type { IServiceOrganization } from '@openpanel/db';
import { toast } from 'sonner';
interface SideEffectsProps {
organization: IServiceOrganization;
}
export default function SideEffectsTimezone({
organization,
}: SideEffectsProps) {
const [isMissingTimezone, setIsMissingTimezone] = useState<boolean>(
!organization.timezone,
);
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const [timezone, setTimezone] = useState<string>(
TIMEZONES.includes(defaultTimezone) ? defaultTimezone : '',
);
const mutation = api.organization.update.useMutation({
onSuccess(res) {
toast('Timezone updated', {
description: 'Your timezone has been updated.',
});
window.location.reload();
},
onError: handleError,
});
return (
<Dialog open={isMissingTimezone} onOpenChange={setIsMissingTimezone}>
<DialogContent
className="max-w-xl"
onEscapeKeyDown={(e) => {
e.preventDefault();
}}
onInteractOutside={(e) => {
e.preventDefault();
}}
>
<ModalHeader
onClose={false}
title="Select your timezone"
text={
<>
We have introduced new features that requires your timezone.
Please select the timezone you want to use for your organization.
</>
}
/>
<Combobox
items={TIMEZONES.map((item) => ({
value: item,
label: item,
}))}
value={timezone}
onChange={setTimezone}
placeholder="Select a timezone"
searchable
size="lg"
className="w-full px-4"
/>
<DialogFooter className="mt-4">
<Button
size="lg"
disabled={!TIMEZONES.includes(timezone)}
loading={mutation.isLoading}
onClick={() =>
mutation.mutate({
id: organization.id,
name: organization.name,
timezone: timezone ?? '',
})
}
>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,67 @@
'use client';
import { differenceInHours } from 'date-fns';
import { useEffect, useState } from 'react';
import { ProjectLink } from '@/components/links';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import type { IServiceOrganization } from '@openpanel/db';
import { useOpenPanel } from '@openpanel/nextjs';
import Billing from './settings/organization/organization/billing';
interface SideEffectsProps {
organization: IServiceOrganization;
}
export default function SideEffectsTrial({ organization }: SideEffectsProps) {
const op = useOpenPanel();
const willEndInHours = organization.subscriptionEndsAt
? differenceInHours(organization.subscriptionEndsAt, new Date())
: null;
const [isTrialDialogOpen, setIsTrialDialogOpen] = useState<boolean>(
willEndInHours !== null &&
organization.subscriptionStatus === 'trialing' &&
organization.subscriptionEndsAt !== null &&
willEndInHours <= 48,
);
useEffect(() => {
if (isTrialDialogOpen) {
op.track('trial_expires_soon');
}
}, [isTrialDialogOpen]);
return (
<>
<Dialog open={isTrialDialogOpen} onOpenChange={setIsTrialDialogOpen}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsTrialDialogOpen(false)}
title={
willEndInHours !== null && willEndInHours > 0
? `Your trial is ending in ${willEndInHours} hours`
: 'Your trial has ended'
}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -4,12 +4,16 @@ import { differenceInHours } from 'date-fns';
import { useEffect, useState } from 'react';
import { ProjectLink } from '@/components/links';
import { Combobox } from '@/components/ui/combobox';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ModalHeader } from '@/modals/Modal/Container';
import type { IServiceOrganization } from '@openpanel/db';
import { useOpenPanel } from '@openpanel/nextjs';
import { FREE_PRODUCT_IDS } from '@openpanel/payments';
import Billing from './settings/organization/organization/billing';
import SideEffectsFreePlan from './side-effects-free-plan';
import SideEffectsTimezone from './side-effects-timezone';
import SideEffectsTrial from './side-effects-trial';
interface SideEffectsProps {
organization: IServiceOrganization;
@@ -17,41 +21,11 @@ interface SideEffectsProps {
export default function SideEffects({ organization }: SideEffectsProps) {
const [mounted, setMounted] = useState(false);
const op = useOpenPanel();
const willEndInHours = organization.subscriptionEndsAt
? differenceInHours(organization.subscriptionEndsAt, new Date())
: null;
const [isTrialDialogOpen, setIsTrialDialogOpen] = useState<boolean>(false);
const [isFreePlan, setIsFreePlan] = useState<boolean>(false);
useEffect(() => {
if (!mounted) {
setMounted(true);
}
setMounted(true);
}, []);
useEffect(() => {
if (
willEndInHours !== null &&
organization.subscriptionStatus === 'trialing' &&
organization.subscriptionEndsAt !== null &&
willEndInHours <= 48
) {
setIsTrialDialogOpen(true);
op.track('trial_expires_soon');
}
}, [mounted, organization]);
useEffect(() => {
if (
organization.subscriptionProductId &&
FREE_PRODUCT_IDS.includes(organization.subscriptionProductId)
) {
setIsFreePlan(true);
op.track('free_plan_removed');
}
}, [mounted, organization]);
// Avoids hydration errors
if (!mounted) {
return null;
@@ -59,56 +33,9 @@ export default function SideEffects({ organization }: SideEffectsProps) {
return (
<>
<Dialog open={isTrialDialogOpen} onOpenChange={setIsTrialDialogOpen}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsTrialDialogOpen(false)}
title={
willEndInHours !== null && willEndInHours > 0
? `Your trial is ending in ${willEndInHours} hours`
: 'Your trial has ended'
}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
<Dialog open={isFreePlan} onOpenChange={setIsFreePlan}>
<DialogContent className="max-w-xl">
<ModalHeader
onClose={() => setIsFreePlan(false)}
title={'Free plan has been removed'}
text={
<>
Please upgrade your plan to continue using OpenPanel. Select a
tier which is appropriate for your needs or{' '}
<ProjectLink
href="/settings/organization?tab=billing"
className="underline text-foreground"
>
manage billing
</ProjectLink>
</>
}
/>
<div className="-mx-4 mt-4">
<Billing organization={organization} />
</div>
</DialogContent>
</Dialog>
<SideEffectsTimezone organization={organization} />
<SideEffectsTrial organization={organization} />
<SideEffectsFreePlan organization={organization} />
</>
);
}