Skip to content

Commit

Permalink
fix week count calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
jameszhang-a committed Feb 27, 2024
1 parent ab4a90e commit 388014d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
16 changes: 15 additions & 1 deletion src/server/api/routers/habit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,21 @@ export async function getUserTimezoneOffsetFromHid(
return getTimezoneOffset(timezone);
}

export async function getUserTime(hid: string) {
const ctx = createInnerTRPCContext({ session: null });

const res = await ctx.prisma.habit.findFirst({
where: { id: hid },
select: { user: true },
});

const timezone = !res ? "America/New_York" : res.user.timezone;

return (date: Date) => {
return utcToZonedTime(date, timezone);
};
}

type LoggedOnDateInput = {
hid: string;
date?: Date;
Expand Down Expand Up @@ -53,7 +68,6 @@ async function loggedOnDate({
const ctx = createInnerTRPCContext({ session: null });

if (startTime && endTime) {
console.log("checking start and time: ", { startTime, endTime });
const log = await ctx.prisma.habitLog.findFirst({
where: {
habitId: hid,
Expand Down
4 changes: 3 additions & 1 deletion src/server/api/routers/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { createTRPCRouter, publicProcedure } from "../trpc";
import { addMilliseconds, subDays, subMilliseconds } from "date-fns";
import { getTimezoneOffset, utcToZonedTime, zonedTimeToUtc } from "date-fns-tz";
import { getUserTime } from "./habit";

export const statsRouter = createTRPCRouter({
/**
Expand Down Expand Up @@ -134,6 +135,7 @@ export const statsRouter = createTRPCRouter({
.input(z.object({ hid: z.string().array() }))
.query(async ({ ctx, input }) => {
const { hid } = input;
const getLocalTime = await getUserTime(hid[0] ?? "");

const res: { [key: string]: number[] } = {};

Expand All @@ -150,7 +152,7 @@ export const statsRouter = createTRPCRouter({

for (const log of logs) {
// Get the day of the week (0-6) where 0 is monday and 6 is sunday.
const day = (log.date.getDay() + 6) % 7;
const day = (getLocalTime(log.date).getDay() + 6) % 7;

data[day]++;
}
Expand Down

0 comments on commit 388014d

Please sign in to comment.