Skip to content

Commit

Permalink
Merge pull request #8 from AloyBranCheung/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
AloyBranCheung authored Nov 27, 2023
2 parents 9972772 + ab810ee commit cba3cd2
Show file tree
Hide file tree
Showing 34 changed files with 1,033 additions and 64 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"react-dom": "18.2.0",
"react-hook-form": "^7.44.1",
"react-toastify": "^9.1.3",
"recharts": "^2.10.1",
"swiper": "^11.0.4",
"tailwind-merge": "^1.13.2",
"tailwindcss": "3.3.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Warnings:
- A unique constraint covering the columns `[activityId]` on the table `Session` will be added. If there are existing duplicate values, this will fail.
*/
-- DropForeignKey
ALTER TABLE "Set" DROP CONSTRAINT "Set_sessionId_fkey";

-- AlterTable
ALTER TABLE "Session" ADD COLUMN "activityId" UUID;

-- CreateIndex
CREATE UNIQUE INDEX "Session_activityId_key" ON "Session"("activityId");

-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_activityId_fkey" FOREIGN KEY ("activityId") REFERENCES "Activity"("activityId") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Set" ADD CONSTRAINT "Set_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "Session"("sessionId") ON DELETE CASCADE ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
Warnings:
- Made the column `userId` on table `Session` required. This step will fail if there are existing NULL values in that column.
- Made the column `activityId` on table `Session` required. This step will fail if there are existing NULL values in that column.
*/
-- DropForeignKey
ALTER TABLE "Session" DROP CONSTRAINT "Session_activityId_fkey";

-- DropForeignKey
ALTER TABLE "Session" DROP CONSTRAINT "Session_userId_fkey";

-- AlterTable
ALTER TABLE "Session" ALTER COLUMN "userId" SET NOT NULL,
ALTER COLUMN "activityId" SET NOT NULL;

-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_activityId_fkey" FOREIGN KEY ("activityId") REFERENCES "Activity"("activityId") ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- DropForeignKey
ALTER TABLE "Session" DROP CONSTRAINT "Session_userId_fkey";

-- AlterTable
ALTER TABLE "Session" ALTER COLUMN "userId" SET DATA TYPE TEXT;

-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("userId") ON DELETE CASCADE ON UPDATE CASCADE;
25 changes: 25 additions & 0 deletions prisma/migrations/20231126140814_change_relation/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Warnings:
- You are about to drop the column `activityId` on the `Session` table. All the data in the column will be lost.
- A unique constraint covering the columns `[sessionId]` on the table `Activity` will be added. If there are existing duplicate values, this will fail.
- Added the required column `sessionId` to the `Activity` table without a default value. This is not possible if the table is not empty.
*/
-- DropForeignKey
ALTER TABLE "Session" DROP CONSTRAINT "Session_activityId_fkey";

-- DropIndex
DROP INDEX "Session_activityId_key";

-- AlterTable
ALTER TABLE "Activity" ADD COLUMN "sessionId" UUID NOT NULL;

-- AlterTable
ALTER TABLE "Session" DROP COLUMN "activityId";

-- CreateIndex
CREATE UNIQUE INDEX "Activity_sessionId_key" ON "Activity"("sessionId");

-- AddForeignKey
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "Session"("sessionId") ON DELETE CASCADE ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
Warnings:
- A unique constraint covering the columns `[runId]` on the table `Activity` will be added. If there are existing duplicate values, this will fail.
*/
-- AlterTable
ALTER TABLE "Activity" ADD COLUMN "runId" UUID,
ALTER COLUMN "sessionId" DROP NOT NULL;

-- CreateIndex
CREATE UNIQUE INDEX "Activity_runId_key" ON "Activity"("runId");

-- AddForeignKey
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_runId_fkey" FOREIGN KEY ("runId") REFERENCES "Run"("runId") ON DELETE CASCADE ON UPDATE CASCADE;
26 changes: 17 additions & 9 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,19 @@ model Profile {

// Activity Table
model Activity {
activityId String @id @unique @default(uuid()) @db.Uuid
updatedAt DateTime @default(now()) @updatedAt
createdAt DateTime @default(now())
activityId String @id @unique @default(uuid()) @db.Uuid
updatedAt DateTime @default(now()) @updatedAt
createdAt DateTime @default(now())
// relations
runExercise RunExercise?
run Run? @relation(fields: [runId], references: [runId], onDelete: Cascade)
runId String? @unique @db.Uuid
user User @relation(fields: [userId], references: [userId], onDelete: Cascade)
userId String
session Session? @relation(fields: [sessionId], references: [sessionId], onDelete: Cascade)
sessionId String? @unique @db.Uuid
user User @relation(fields: [userId], references: [userId], onDelete: Cascade)
userId String
RunExercise RunExercise?
}

// Exercises Table
Expand Down Expand Up @@ -95,8 +100,10 @@ model Session {
planId String? @db.Uuid
currActiveSesh CurrActiveSesh?
User User? @relation(fields: [userId], references: [id])
userId Int?
user User @relation(fields: [userId], references: [userId], onDelete: Cascade)
userId String
activity Activity?
}

// Exercise History Table
Expand All @@ -110,7 +117,7 @@ model Set {
note String?
// relations
session Session @relation(fields: [sessionId], references: [sessionId])
session Session @relation(fields: [sessionId], references: [sessionId], onDelete: Cascade)
sessionId String @db.Uuid
exercise Exercise @relation(fields: [exerciseId], references: [exerciseId])
Expand Down Expand Up @@ -180,6 +187,7 @@ model Run {
// relation
runExercise RunExercise @relation(fields: [exerciseId], references: [exerciseId])
exerciseId String @db.Uuid
Activity Activity?
}

model GymLocation {
Expand Down
3 changes: 3 additions & 0 deletions src/components/CurrActiveSesh/Set.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ interface SetProps {
sessionId: string
unit: string
isDone?: boolean
exerciseName: string | undefined
}

export default function Set({
Expand All @@ -30,6 +31,7 @@ export default function Set({
sessionId,
unit,
isDone,
exerciseName,
}: SetProps) {
const { addToDb } = useCurrActiveSeshIndexDb()

Expand All @@ -42,6 +44,7 @@ export default function Set({
sessionId,
exerciseId,
setNumber,
exerciseName: exerciseName ?? "",
})

return (
Expand Down
1 change: 1 addition & 0 deletions src/components/CurrActiveSesh/SetGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export default function SetGrid({ sets, currActiveExercise }: SetGridProps) {
unit={unit}
frontendSetId={frontendSetId}
isDone={isDone}
exerciseName={currActiveExercise?.name}
/>
)
)
Expand Down
45 changes: 28 additions & 17 deletions src/components/CurrActiveSesh/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React, { useState, useMemo } from "react"
import { useRouter } from "next/router"
import Pino from "pino"
import { z } from "zod"
// types
import { ISet } from "src/types/curr-active-sesh"
// utils
import { trpc } from "src/utils/trpc"
// validators
Expand All @@ -14,6 +16,7 @@ import useCurrActiveSeshIndexDb, {
IndexedDBStore,
} from "src/hooks/useCurrActiveSeshIndexDb"
import useToastMessage, { ToastMessage } from "src/hooks/useToastMessage"
import useGetSetsByExerciseId from "src/hooks/useGetSetsByExerciseId"
// lodash
import { capitalize } from "lodash"
// components
Expand Down Expand Up @@ -43,17 +46,6 @@ export interface Exercise {
targetSets: number | null
}

export interface ISet {
name: Exercise["name"]
weight: Exercise["unit"]
reps: Exercise["targetReps"]
setNumber: number
exerciseId: Exercise["exerciseId"]
sessionId: string
unit: Exercise["unit"]
isDone: boolean
}

export default function CurrActiveSeshContainer() {
const utils = trpc.useContext()
const { getAllFromDb, clearDb } = useCurrActiveSeshIndexDb()
Expand All @@ -75,6 +67,9 @@ export default function CurrActiveSeshContainer() {
const [isCompleteWorkout, setIsCompleteWorkout] = useState(false)
const [isCompleteIncompleteWorkout, setIsCompleteIncompleteWorkout] =
useState(false)
const { data: exerciseSetList } = useGetSetsByExerciseId(
currActiveExercise?.exerciseId ?? ""
)

const exerciseHashmap = useMemo(() => {
const exercisesArr = sessionRes?.workoutPlan?.exercises
Expand Down Expand Up @@ -116,14 +111,16 @@ export default function CurrActiveSeshContainer() {
return list
}, [exerciseHashmap, exercisesList])

const mostRecentWeight = exerciseSetList?.[0]?.weight?.toString() ?? "0"

const sets = useMemo(() => {
if (!currActiveExercise?.targetSets) return []
const sets: ISet[] = []
for (let i = 0; i < currActiveExercise.targetSets; i++) {
sets.push({
setNumber: i + 1,
name: currActiveExercise.name,
weight: "0", // TODO: add last weight exercise was completed in
exerciseName: currActiveExercise.name,
weight: mostRecentWeight ?? "0",
reps: currActiveExercise.targetReps,
unit: currActiveExercise.unit,
exerciseId: currActiveExercise.exerciseId,
Expand All @@ -132,13 +129,20 @@ export default function CurrActiveSeshContainer() {
})
}
return sets
}, [currActiveExercise, currActiveSeshId])
}, [currActiveExercise, currActiveSeshId, mostRecentWeight])

const handleCompleteWorkout = async () => {
// get saved things from db
const completedSets = (await getAllFromDb(
IndexedDBStore.CurrActiveSesh
)) as ISet[]
const exerciseOrderArr = sessionRes?.workoutPlan?.exerciseOrder
if (!exerciseOrderArr) return
const sortedCompletedSets = completedSets.sort(
(a, b) =>
exerciseOrderArr.indexOf(a.exerciseId) -
exerciseOrderArr.indexOf(b.exerciseId)
)

// calculate total sets to be completed
let targetTotalSets = 0
Expand All @@ -150,7 +154,7 @@ export default function CurrActiveSeshContainer() {
}

// if not all set fields are touched
if (completedSets.length !== targetTotalSets) {
if (sortedCompletedSets.length !== targetTotalSets) {
setIsCompleteIncompleteWorkout(true)
}
// modal for complete workout
Expand All @@ -164,10 +168,17 @@ export default function CurrActiveSeshContainer() {
const completedSets = (await getAllFromDb(
IndexedDBStore.CurrActiveSesh
)) as ISet[]
const exerciseOrderArr = sessionRes?.workoutPlan?.exerciseOrder
if (!exerciseOrderArr) return
const sortedCompletedSets = completedSets.sort(
(a, b) =>
exerciseOrderArr.indexOf(a.exerciseId) -
exerciseOrderArr.indexOf(b.exerciseId)
)

// validate
try {
const validated = CompletedSetsSchema.parse(completedSets)
const validated = CompletedSetsSchema.parse(sortedCompletedSets)
// mutate
mutate(validated, {
onSuccess: () => {
Expand Down Expand Up @@ -200,7 +211,7 @@ export default function CurrActiveSeshContainer() {
router.push({
pathname: "/workouts/curr-active-workout/summary",
query: {
data: JSON.stringify(completedSets),
data: JSON.stringify(sortedCompletedSets),
},
})
}
Expand Down
6 changes: 5 additions & 1 deletion src/components/HomePage/RecentActivity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ export default function RecentActivity({

return (
<ParentCard cardTitle="Recent Activity">
<div className="flex flex-col gap-7">{recentActivitiesCards}</div>
<div className="flex flex-col gap-7">
{recentActivitiesCards.length > 0
? recentActivitiesCards
: "Start a workout to get started :)"}
</div>
</ParentCard>
)
}
44 changes: 43 additions & 1 deletion src/components/HomePage/TopStats.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import React from "react"
// recharts
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Label,
} from "recharts"
// components
import ParentCard from "../UI/ParentCard"
import { ITopStats } from "src/types/home-page"
import SecondaryCard from "../UI/SecondaryCard"
import Text from "../UI/typography/Text"

interface TopStatsProps {
topStats: ITopStats
Expand Down Expand Up @@ -39,7 +51,37 @@ export default function TopStats({ topStats }: TopStatsProps) {
</p>
</div>
</SecondaryCard>
<SecondaryCard>Recharts Graph Here for Random Lift</SecondaryCard>
<SecondaryCard className="w-full h-[60vh]">
<Text
text={topStats.randomGraph.exerciseName}
className="text-center w-full"
bold
/>
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={topStats.randomGraph.data}
margin={{ bottom: 70, left: 10, top: 15, right: 15 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" angle={-45} textAnchor="end" />
<YAxis width={50}>
<Label
value={`Weight (${topStats.randomGraph.unit})`}
position="insideLeft"
angle={-90}
style={{ textAnchor: "middle" }}
/>
</YAxis>
<Tooltip />
<Line
type="monotone"
dataKey="weight"
stroke="#2f08a6"
activeDot={{ r: 8 }}
/>
</LineChart>
</ResponsiveContainer>
</SecondaryCard>
</div>
</ParentCard>
)
Expand Down
Loading

0 comments on commit cba3cd2

Please sign in to comment.