import { experimental_trpcMiddleware, TRPCError } from "@trpc/server"; import { and, desc, eq, inArray, notExists } from "drizzle-orm"; import { z } from "zod"; import { db, SqliteError } from "@lifetracker/db"; import { categories, days, hours, users } from "@lifetracker/db/schema"; import { zDaySchema, ZDay } from "@lifetracker/shared/types/days"; import type { Context } from "../index"; import { authedProcedure, router } from "../index"; import { dateFromInput, hoursListInUTC } from "@lifetracker/shared/utils/days"; import { closestIndexTo, format } from "date-fns"; import { TZDate } from "@date-fns/tz"; import { hoursAppRouter, hourColors, hourJoinsQuery } from "./hours"; import spacetime from "spacetime"; import { getHourFromTime, getTimeFromHour } from "@lifetracker/shared/utils/hours"; async function createDay(date: string, ctx: Context) { return await ctx.db.transaction(async (trx) => { try { // Create the Day object const dayRes = await trx .insert(days) .values({ userId: ctx.user!.id, date: date, }) .returning({ id: days.id, date: days.date, mood: days.mood, comment: days.comment, }); return dayRes; } catch (e) { if (e instanceof SqliteError) { if (e.code == "SQLITE_CONSTRAINT_UNIQUE") { throw new TRPCError({ code: "BAD_REQUEST", message: "This day already exists", }); } } throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Something went wrong", }); } }); } async function createHour(day: ZDay, time: number, ctx: Context,) { const newHour = (await ctx.db.insert(hours).values({ dayId: day.id, time: time, userId: ctx.user!.id, }).returning()); return newHour[0]; } async function getTimezone(ctx: Context) { const dbTimezone = await ctx.db.select({ timezone: users.timezone }).from(users).where(eq(users.id, ctx.user!.id)); return dbTimezone[0].timezone as string; } async function getDay(input: { dateQuery: string }, ctx: Context, date: string) { const dayRes = await ctx.db.select({ id: days.id, date: days.date, mood: days.mood, comment: days.comment, }) .from(days) .where(eq(days.date, date)); const day = dayRes.length == 0 ? (await createDay(date, ctx))[0] : (dayRes[0]); const dayHours = await Promise.all( Array.from({ length: 24 }).map(async function (_, i) { const existing = await ctx.db.select({ dayId: hours.dayId, time: hours.time, userId: hours.userId, date: days.date }).from(hours) .leftJoin(days, eq(days.id, hours.dayId)) // Ensure days table is joined first .where(and( eq(hours.userId, ctx.user!.id), eq(hours.dayId, day.id), eq(hours.time, i) )) return existing.length == 0 ? createHour(day, i, ctx) : existing[0]; })); return { hours: dayHours, ...day } } export const daysAppRouter = router({ get: authedProcedure .input(z.object({ dateQuery: z.string(), timezone: z.string().optional(), })) .output(zDaySchema) .query(async ({ input, ctx }) => { // Get a Day // Use timezone and date string to get the local date const timezone = input.timezone ?? await getTimezone(ctx); const date = dateFromInput({ dateQuery: input.dateQuery, timezone: timezone }); // Get the list of UTC hours corresponding to this day const utcHours = hoursListInUTC({ timezone, ...input }); // console.log(`utcHours:\n,${utcHours.map(({ date, time }) => `${date} ${time}\n`)}`); // Flatten the 24 hours to the 2 unique days const uniqueDays = [...new Set(utcHours.map(({ date: date, time: _time }) => date))]; // ...and get their IDs const uniqueDayIds = await Promise.all(uniqueDays.map(async function (date) { const dayObj = await getDay(input, ctx, date); return { id: dayObj.id, date: dayObj.date } })); // Finally, use the two unique day IDs and the 24 hours to get the actual Hour objects for each day const dayHours = await Promise.all(utcHours.map(async function (map: { date: string, time: number }, i) { const dayId = uniqueDayIds.find((dayIds: { id: string, date: string }) => map.date == dayIds.date)!.id; return hourJoinsQuery(ctx, dayId, map.time); })); return { ...await getDay(input, ctx, date), hours: dayHours.flat(), }; }), update: authedProcedure .input( z.object({ mood: z.string().optional().or(z.number()), comment: z.string().optional(), dateQuery: z.string(), timezone: z.string().optional(), }), ) .mutation(async ({ input, ctx }) => { const { dateQuery, timezone, ...updatedProps } = input; // Convert mood to number, if it exists if (updatedProps.mood) { updatedProps.mood = parseInt(updatedProps.mood); } const res = await ctx.db .update(days) .set(updatedProps) .where(eq(days.date, dateFromInput({ dateQuery: dateQuery, timezone: timezone ?? ctx.user.timezone }) )).returning(); return res[0]; }), });