Feature/multiple schedules post turbo (#2150)

* Concluded merge

* Applied stash to newly merged

* Always disconnect + remove redundant success message

* Added named dialog to replace new=1

* Merged with main p2

* Set eventTypeId to @unique

* WIP

* Undo vscode changes

* Availability dropdown works

* Remove console.log + set schedule to null as it is unneeded

* Added schedule to availability endpoint

* Reduce one refresh; hotfix state inconsistency with forced refresh for now

* Add missing translations

* Fixed some type errors I missed

* Ditch outdated remnant from before packages/prisma

* Remove Availability section for teams

* Bringing back the Availability section temporarily to teams to allow configuration

* Migrated getting-started to new availability system + updated translations + updated seed

* Fixed type error coming from main

* Titlecase 'default' by providing translation

* Fixed broken 'radio' buttons.

* schedule deleted translation added

* Added empty state for when no schedules are configured

* Added correct created message + hotfix reload hard on delete to refresh state

* Removed index renames

* Type fixes

* Update NewScheduleButton.tsx

Co-authored-by: zomars <[email protected]>
Co-authored-by: Bailey Pumfleet <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2022-03-17 09:48:23 -07:00
1 parent bcbf8390e0
commit 6a211dd5b3
28 files changed
+1073 -1207

No files matched your search

+42 -1
View File
@@ -3,6 +3,7 @@ import customParseFormat from "dayjs/plugin/customParseFormat";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import { nameOfDay } from "@calcom/lib/weekday";
import type { Availability } from "@calcom/prisma/client";
import type { Schedule, TimeRange, WorkingHours } from "@calcom/types/schedule";
@@ -38,7 +39,9 @@ export function getAvailabilityFromSchedule(schedule: Schedule): Availability[]
let idx;
if (
(idx = availability.findIndex(
(schedule) => schedule.startTime === time.start && schedule.endTime === time.end
(schedule) =>
schedule.startTime.toString() === time.start.toString() &&
schedule.endTime.toString() === time.end.toString()
)) !== -1
) {
availability[idx].days.push(day);
@@ -124,3 +127,41 @@ export function getWorkingHours(
return workingHours;
}
export function availabilityAsString(availability: Availability, locale: string) {
const weekSpan = (availability: Availability) => {
const days = availability.days.slice(1).reduce(
(days, day) => {
if (days[days.length - 1].length === 1 && days[days.length - 1][0] === day - 1) {
// append if the range is not complete (but the next day needs adding)
days[days.length - 1].push(day);
} else if (days[days.length - 1][days[days.length - 1].length - 1] === day - 1) {
// range complete, overwrite if the last day directly preceeds the current day
days[days.length - 1] = [days[days.length - 1][0], day];
} else {
// new range
days.push([day]);
}
return days;
},
[[availability.days[0]]] as number[][]
);
return days
.map((dayRange) => dayRange.map((day) => nameOfDay(locale, day, "short")).join(" - "))
.join(", ");
};
const timeSpan = (availability: Availability) => {
return (
new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "numeric" }).format(
new Date(availability.startTime.toISOString().slice(0, -1))
) +
" - " +
new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "numeric" }).format(
new Date(availability.endTime.toISOString().slice(0, -1))
)
);
};
return weekSpan(availability) + ", " + timeSpan(availability);
}
+8
View File
@@ -0,0 +1,8 @@
// By default starts on Sunday (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
export function weekdayNames(locale: string | string[], weekStart = 0, type: "short" | "long" = "long") {
return Array.from(Array(7).keys()).map((d) => nameOfDay(locale, d + weekStart, type));
}
export function nameOfDay(locale: string | string[], day: number, type: "short" | "long" = "long") {
return new Intl.DateTimeFormat(locale, { weekday: type }).format(new Date(1970, 0, day + 4));
}
@@ -0,0 +1,30 @@
/*
Warnings:
- You are about to drop the column `label` on the `Availability` table. All the data in the column will be lost.
- You are about to drop the column `freeBusyTimes` on the `Schedule` table. All the data in the column will be lost.
- You are about to drop the column `title` on the `Schedule` table. All the data in the column will be lost.
- A unique constraint covering the columns `[eventTypeId]` on the table `Schedule` will be added. If there are existing duplicate values, this will fail.
- Added the required column `name` to the `Schedule` table without a default value. This is not possible if the table is not empty.
- Made the column `userId` on table `Schedule` required. This step will fail if there are existing NULL values in that column.
*/
-- AlterTable
ALTER TABLE "Availability" DROP COLUMN "label",
ADD COLUMN "scheduleId" INTEGER;
-- AlterTable
ALTER TABLE "Schedule" DROP COLUMN "freeBusyTimes",
DROP COLUMN "title",
ADD COLUMN "name" TEXT NOT NULL,
ADD COLUMN "timeZone" TEXT,
ALTER COLUMN "userId" SET NOT NULL;
-- AlterTable
ALTER TABLE "users" ADD COLUMN "defaultScheduleId" INTEGER;
-- CreateIndex
CREATE UNIQUE INDEX "Schedule_eventTypeId_key" ON "Schedule"("eventTypeId");
-- AddForeignKey
ALTER TABLE "Availability" ADD CONSTRAINT "Availability_scheduleId_fkey" FOREIGN KEY ("scheduleId") REFERENCES "Schedule"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+14 -11
View File
@@ -62,7 +62,7 @@ model EventType {
beforeEventBuffer Int @default(0)
afterEventBuffer Int @default(0)
schedulingType SchedulingType?
Schedule Schedule[]
schedule Schedule?
price Int @default(0)
currency String @default("usd")
slotInterval Int?
@@ -128,7 +128,8 @@ model User {
credentials Credential[]
teams Membership[]
bookings Booking[]
availability Availability[]
schedules Schedule[]
defaultScheduleId Int?
selectedCalendars SelectedCalendar[]
completedOnboarding Boolean @default(false)
locale String?
@@ -137,9 +138,9 @@ model User {
twoFactorEnabled Boolean @default(false)
identityProvider IdentityProvider @default(CAL)
identityProviderId String?
availability Availability[]
invitedTo Int?
plan UserPlan @default(TRIAL)
Schedule Schedule[]
webhooks Webhook[]
brandColor String @default("#292929")
darkBrandColor String @default("#fafafa")
@@ -255,18 +256,18 @@ model Booking {
}
model Schedule {
id Int @id @default(autoincrement())
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int?
eventType EventType? @relation(fields: [eventTypeId], references: [id])
eventTypeId Int?
title String?
freeBusyTimes Json?
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
eventType EventType? @relation(fields: [eventTypeId], references: [id])
eventTypeId Int? @unique
name String
timeZone String?
availability Availability[]
}
model Availability {
id Int @id @default(autoincrement())
label String?
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int?
eventType EventType? @relation(fields: [eventTypeId], references: [id])
@@ -275,6 +276,8 @@ model Availability {
startTime DateTime @db.Time
endTime DateTime @db.Time
date DateTime? @db.Date
Schedule Schedule? @relation(fields: [scheduleId], references: [id])
scheduleId Int?
}
model SelectedCalendar {
+12 -5
View File
@@ -29,11 +29,18 @@ async function createUserAndEventType(opts: {
emailVerified: new Date(),
completedOnboarding: opts.user.completedOnboarding ?? true,
locale: "en",
availability: {
createMany: {
data: getAvailabilityFromSchedule(DEFAULT_SCHEDULE),
},
},
schedules: opts.user.completedOnboarding
? {
create: {
name: "Working Hours",
availability: {
createMany: {
data: getAvailabilityFromSchedule(DEFAULT_SCHEDULE),
},
},
},
}
: undefined,
};
const user = await prisma.user.upsert({
where: { email: opts.user.email },
+7 -3
View File
@@ -1,4 +1,4 @@
import { CheckCircleIcon, InformationCircleIcon, XCircleIcon } from "@heroicons/react/solid";
import { CheckCircleIcon, ExclamationIcon, InformationCircleIcon, XCircleIcon } from "@heroicons/react/solid";
import classNames from "classnames";
import { ReactNode } from "react";
@@ -7,7 +7,7 @@ export interface AlertProps {
message?: ReactNode;
actions?: ReactNode;
className?: string;
severity: "success" | "warning" | "error";
severity: "success" | "warning" | "error" | "info";
}
export function Alert(props: AlertProps) {
const { severity } = props;
@@ -19,6 +19,7 @@ export function Alert(props: AlertProps) {
props.className,
severity === "error" && "border-red-900 bg-red-50 text-red-800",
severity === "warning" && "border-yellow-700 bg-yellow-50 text-yellow-700",
severity === "info" && "border-sky-700 bg-sky-50 text-sky-700",
severity === "success" && "bg-gray-900 text-white"
)}>
<div className="flex">
@@ -27,7 +28,10 @@ export function Alert(props: AlertProps) {
<XCircleIcon className={classNames("h-5 w-5 text-red-400")} aria-hidden="true" />
)}
{severity === "warning" && (
<InformationCircleIcon className={classNames("h-5 w-5 text-yellow-400")} aria-hidden="true" />
<ExclamationIcon className={classNames("h-5 w-5 text-yellow-400")} aria-hidden="true" />
)}
{severity === "info" && (
<InformationCircleIcon className={classNames("h-5 w-5 text-sky-400")} aria-hidden="true" />
)}
{severity === "success" && (
<CheckCircleIcon className={classNames("h-5 w-5 text-gray-400")} aria-hidden="true" />
+13 -26
View File
@@ -1,37 +1,22 @@
import { useId } from "@radix-ui/react-id";
import * as Label from "@radix-ui/react-label";
import * as PrimitiveSwitch from "@radix-ui/react-switch";
import React, { useState } from "react";
import React from "react";
import classNames from "@calcom/lib/classNames";
type SwitchProps = React.ComponentProps<typeof PrimitiveSwitch.Root> & {
label: string;
};
export default function Switch(props: SwitchProps) {
const { label, onCheckedChange, ...primitiveProps } = props;
const [checked, setChecked] = useState(props.defaultChecked || false);
const onPrimitiveCheckedChange = (change: boolean) => {
if (onCheckedChange) {
onCheckedChange(change);
}
setChecked(change);
};
const Switch = (
props: React.ComponentProps<typeof PrimitiveSwitch.Root> & {
label: string;
}
) => {
const { label, ...primitiveProps } = props;
const id = useId();
return (
<div className="flex h-[20px] items-center">
<PrimitiveSwitch.Root
className={classNames(checked ? "bg-gray-900" : "bg-gray-400", "h-[20px] w-[36px] rounded-sm p-0.5")}
checked={checked}
onCheckedChange={onPrimitiveCheckedChange}
{...primitiveProps}>
<PrimitiveSwitch.Root className="h-[20px] w-[36px] rounded-sm bg-gray-400 p-0.5" {...primitiveProps}>
<PrimitiveSwitch.Thumb
id={id}
className={classNames(
"block h-[16px] w-[16px] bg-white transition-transform",
checked ? "translate-x-[16px]" : "translate-x-0"
)}
className={"block h-[16px] w-[16px] translate-x-0 bg-white transition-transform"}
/>
</PrimitiveSwitch.Root>
{label && (
@@ -43,4 +28,6 @@ export default function Switch(props: SwitchProps) {
)}
</div>
);
}
};
export default Switch;