Initial project setup for PhaseFlow
Set up Next.js 16 project with TypeScript for a training decision app that integrates menstrual cycle phases with Garmin biometrics for Hashimoto's thyroiditis management. Stack: Next.js 16, React 19, Tailwind/shadcn, PocketBase, Drizzle, Zod, Resend, Vitest, Biome, Lefthook, Nix dev environment. Includes: - 7 page routes (dashboard, login, settings, calendar, history, plan) - 12 API endpoints (garmin, user, cycle, calendar, overrides, cron) - Core lib utilities (decision engine, cycle phases, nutrition, ICS) - Type definitions and component scaffolding - Python script for Garmin token bootstrapping - Initial unit tests for cycle utilities 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
23
src/app/api/calendar/[userId]/[token].ics/route.ts
Normal file
23
src/app/api/calendar/[userId]/[token].ics/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
// ABOUTME: API route for ICS calendar feed generation.
|
||||
// ABOUTME: Returns subscribable iCal feed with cycle phases and warnings.
|
||||
import { type NextRequest, NextResponse } from "next/server";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{
|
||||
userId: string;
|
||||
token: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export async function GET(_request: NextRequest, { params }: RouteParams) {
|
||||
const { userId, token } = await params;
|
||||
void token; // Token will be used for validation
|
||||
// TODO: Implement ICS feed generation
|
||||
// Validate token, generate ICS content, return with correct headers
|
||||
return new NextResponse(`ICS feed for user ${userId} not implemented`, {
|
||||
status: 501,
|
||||
headers: {
|
||||
"Content-Type": "text/calendar; charset=utf-8",
|
||||
},
|
||||
});
|
||||
}
|
||||
8
src/app/api/calendar/regenerate-token/route.ts
Normal file
8
src/app/api/calendar/regenerate-token/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// ABOUTME: API route for regenerating calendar subscription token.
|
||||
// ABOUTME: Creates new random token, invalidating old calendar URLs.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST() {
|
||||
// TODO: Implement token regeneration
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
16
src/app/api/cron/garmin-sync/route.ts
Normal file
16
src/app/api/cron/garmin-sync/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
// ABOUTME: Cron endpoint for syncing Garmin data.
|
||||
// ABOUTME: Fetches body battery, HRV, and intensity minutes for all users.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Verify cron secret
|
||||
const authHeader = request.headers.get("authorization");
|
||||
const expectedSecret = process.env.CRON_SECRET;
|
||||
|
||||
if (!expectedSecret || authHeader !== `Bearer ${expectedSecret}`) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// TODO: Implement Garmin data sync
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
16
src/app/api/cron/notifications/route.ts
Normal file
16
src/app/api/cron/notifications/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
// ABOUTME: Cron endpoint for sending daily email notifications.
|
||||
// ABOUTME: Sends morning training decision emails to all users.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Verify cron secret
|
||||
const authHeader = request.headers.get("authorization");
|
||||
const expectedSecret = process.env.CRON_SECRET;
|
||||
|
||||
if (!expectedSecret || authHeader !== `Bearer ${expectedSecret}`) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// TODO: Implement notification sending
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
8
src/app/api/cycle/current/route.ts
Normal file
8
src/app/api/cycle/current/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// ABOUTME: API route for current cycle phase information.
|
||||
// ABOUTME: Returns current cycle day, phase, and phase limits.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
// TODO: Implement current cycle info
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
8
src/app/api/cycle/period/route.ts
Normal file
8
src/app/api/cycle/period/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// ABOUTME: API route for logging period start dates.
|
||||
// ABOUTME: Recalculates all phase dates when period is logged.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST() {
|
||||
// TODO: Implement period logging
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
8
src/app/api/garmin/status/route.ts
Normal file
8
src/app/api/garmin/status/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// ABOUTME: API route for checking Garmin connection status.
|
||||
// ABOUTME: Returns connection state and token expiry information.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
// TODO: Implement status check
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
13
src/app/api/garmin/tokens/route.ts
Normal file
13
src/app/api/garmin/tokens/route.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
// ABOUTME: API route for storing Garmin OAuth tokens.
|
||||
// ABOUTME: Accepts tokens from the bootstrap script and encrypts them for storage.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST() {
|
||||
// TODO: Implement token storage
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
|
||||
export async function DELETE() {
|
||||
// TODO: Implement token deletion
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
8
src/app/api/history/route.ts
Normal file
8
src/app/api/history/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// ABOUTME: API route for historical daily logs.
|
||||
// ABOUTME: Returns paginated list of past training decisions and data.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
// TODO: Implement history retrieval
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
13
src/app/api/overrides/route.ts
Normal file
13
src/app/api/overrides/route.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
// ABOUTME: API route for managing training overrides.
|
||||
// ABOUTME: Handles flare, stress, sleep, and PMS override toggles.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST() {
|
||||
// TODO: Implement override setting
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
|
||||
export async function DELETE() {
|
||||
// TODO: Implement override removal
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
8
src/app/api/today/route.ts
Normal file
8
src/app/api/today/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// ABOUTME: API route for today's training decision and data.
|
||||
// ABOUTME: Returns complete daily snapshot with decision, biometrics, and nutrition.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
// TODO: Implement today's data retrieval
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
13
src/app/api/user/route.ts
Normal file
13
src/app/api/user/route.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
// ABOUTME: API route for user profile management.
|
||||
// ABOUTME: Handles GET for profile retrieval and PATCH for updates.
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
// TODO: Implement user profile retrieval
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
|
||||
export async function PATCH() {
|
||||
// TODO: Implement user profile update
|
||||
return NextResponse.json({ message: "Not implemented" }, { status: 501 });
|
||||
}
|
||||
11
src/app/calendar/page.tsx
Normal file
11
src/app/calendar/page.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
// ABOUTME: In-app calendar view showing cycle phases.
|
||||
// ABOUTME: Displays monthly calendar with color-coded phases and ICS subscription info.
|
||||
export default function CalendarPage() {
|
||||
return (
|
||||
<div className="container mx-auto p-8">
|
||||
<h1 className="text-2xl font-bold mb-8">Calendar</h1>
|
||||
{/* Calendar view will be implemented here */}
|
||||
<p className="text-gray-500">Calendar view placeholder</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
BIN
src/app/favicon.ico
Normal file
BIN
src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
125
src/app/globals.css
Normal file
125
src/app/globals.css
Normal file
@@ -0,0 +1,125 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
11
src/app/history/page.tsx
Normal file
11
src/app/history/page.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
// ABOUTME: Historical data view for past training decisions.
|
||||
// ABOUTME: Shows table of daily logs with biometrics and decisions.
|
||||
export default function HistoryPage() {
|
||||
return (
|
||||
<div className="container mx-auto p-8">
|
||||
<h1 className="text-2xl font-bold mb-8">History</h1>
|
||||
{/* History table will be implemented here */}
|
||||
<p className="text-gray-500">History table placeholder</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
src/app/layout.tsx
Normal file
37
src/app/layout.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
// ABOUTME: Root layout for PhaseFlow application.
|
||||
// ABOUTME: Configures fonts, metadata, and global styles.
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "PhaseFlow",
|
||||
description:
|
||||
"Automated training decisions for Hashimoto's thyroiditis based on menstrual cycle phases and Garmin biometrics",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
13
src/app/login/page.tsx
Normal file
13
src/app/login/page.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
// ABOUTME: Login page for user authentication.
|
||||
// ABOUTME: Provides email/password login form using PocketBase auth.
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="w-full max-w-md space-y-8 p-8">
|
||||
<h1 className="text-2xl font-bold text-center">PhaseFlow Login</h1>
|
||||
{/* Login form will be implemented here */}
|
||||
<p className="text-center text-gray-500">Login form placeholder</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
28
src/app/page.tsx
Normal file
28
src/app/page.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
// ABOUTME: Main dashboard page for PhaseFlow.
|
||||
// ABOUTME: Displays today's training decision, biometrics, and quick actions.
|
||||
export default function Dashboard() {
|
||||
return (
|
||||
<div className="min-h-screen bg-zinc-50 dark:bg-black">
|
||||
<header className="border-b bg-white dark:bg-zinc-900 px-6 py-4">
|
||||
<div className="container mx-auto flex justify-between items-center">
|
||||
<h1 className="text-xl font-bold">PhaseFlow</h1>
|
||||
<a
|
||||
href="/settings"
|
||||
className="text-sm text-zinc-600 hover:text-zinc-900"
|
||||
>
|
||||
Settings
|
||||
</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="container mx-auto p-6">
|
||||
<div className="text-center py-12">
|
||||
<p className="text-zinc-500">Dashboard placeholder</p>
|
||||
<p className="text-sm text-zinc-400 mt-2">
|
||||
Connect your Garmin and set your period date to get started.
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
src/app/plan/page.tsx
Normal file
11
src/app/plan/page.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
// ABOUTME: Exercise plan reference page.
|
||||
// ABOUTME: Displays the full monthly exercise plan by phase.
|
||||
export default function PlanPage() {
|
||||
return (
|
||||
<div className="container mx-auto p-8">
|
||||
<h1 className="text-2xl font-bold mb-8">Exercise Plan</h1>
|
||||
{/* Exercise plan content will be implemented here */}
|
||||
<p className="text-gray-500">Exercise plan placeholder</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
13
src/app/settings/garmin/page.tsx
Normal file
13
src/app/settings/garmin/page.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
// ABOUTME: Garmin connection settings page.
|
||||
// ABOUTME: Allows users to paste OAuth tokens from the bootstrap script.
|
||||
export default function GarminSettingsPage() {
|
||||
return (
|
||||
<div className="container mx-auto p-8">
|
||||
<h1 className="text-2xl font-bold mb-8">
|
||||
Settings > Garmin Connection
|
||||
</h1>
|
||||
{/* Garmin token input will be implemented here */}
|
||||
<p className="text-gray-500">Garmin settings placeholder</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
src/app/settings/page.tsx
Normal file
11
src/app/settings/page.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
// ABOUTME: User settings page for profile and preferences.
|
||||
// ABOUTME: Allows configuration of notification time, timezone, and cycle length.
|
||||
export default function SettingsPage() {
|
||||
return (
|
||||
<div className="container mx-auto p-8">
|
||||
<h1 className="text-2xl font-bold mb-8">Settings</h1>
|
||||
{/* Settings form will be implemented here */}
|
||||
<p className="text-gray-500">Settings form placeholder</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
38
src/components/calendar/day-cell.tsx
Normal file
38
src/components/calendar/day-cell.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
// ABOUTME: Individual day cell for calendar views.
|
||||
// ABOUTME: Shows day number with phase-appropriate background color.
|
||||
import type { CyclePhase } from "@/types";
|
||||
|
||||
interface DayCellProps {
|
||||
date: Date;
|
||||
cycleDay: number;
|
||||
phase: CyclePhase;
|
||||
isToday: boolean;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
const PHASE_COLORS: Record<CyclePhase, string> = {
|
||||
MENSTRUAL: "bg-blue-100",
|
||||
FOLLICULAR: "bg-green-100",
|
||||
OVULATION: "bg-purple-100",
|
||||
EARLY_LUTEAL: "bg-yellow-100",
|
||||
LATE_LUTEAL: "bg-red-100",
|
||||
};
|
||||
|
||||
export function DayCell({
|
||||
date,
|
||||
cycleDay,
|
||||
phase,
|
||||
isToday,
|
||||
onClick,
|
||||
}: DayCellProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`p-2 rounded ${PHASE_COLORS[phase]} ${isToday ? "ring-2 ring-black" : ""}`}
|
||||
>
|
||||
<span className="text-sm font-medium">{date.getDate()}</span>
|
||||
<span className="text-xs text-gray-500 block">Day {cycleDay}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
32
src/components/calendar/month-view.tsx
Normal file
32
src/components/calendar/month-view.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
// ABOUTME: Full month calendar view component.
|
||||
// ABOUTME: Displays calendar grid with phase colors and day details.
|
||||
interface MonthViewProps {
|
||||
year: number;
|
||||
month: number;
|
||||
lastPeriodDate: Date;
|
||||
cycleLength: number;
|
||||
}
|
||||
|
||||
export function MonthView({
|
||||
year,
|
||||
month,
|
||||
lastPeriodDate,
|
||||
cycleLength,
|
||||
}: MonthViewProps) {
|
||||
return (
|
||||
<div className="rounded-lg border p-4">
|
||||
<h2 className="text-xl font-bold mb-4">
|
||||
{new Date(year, month).toLocaleDateString("en-US", {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
})}
|
||||
</h2>
|
||||
{/* Calendar grid will be implemented here */}
|
||||
<p className="text-gray-500">Month view placeholder</p>
|
||||
<p className="text-xs text-gray-400">
|
||||
Cycle length: {cycleLength} days, Last period:{" "}
|
||||
{lastPeriodDate.toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
34
src/components/dashboard/data-panel.tsx
Normal file
34
src/components/dashboard/data-panel.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
// ABOUTME: Dashboard panel showing biometric data.
|
||||
// ABOUTME: Displays body battery, HRV, and intensity minutes.
|
||||
interface DataPanelProps {
|
||||
bodyBatteryCurrent: number | null;
|
||||
bodyBatteryYesterdayLow: number | null;
|
||||
hrvStatus: string;
|
||||
weekIntensity: number;
|
||||
phaseLimit: number;
|
||||
remainingMinutes: number;
|
||||
}
|
||||
|
||||
export function DataPanel({
|
||||
bodyBatteryCurrent,
|
||||
bodyBatteryYesterdayLow,
|
||||
hrvStatus,
|
||||
weekIntensity,
|
||||
phaseLimit,
|
||||
remainingMinutes,
|
||||
}: DataPanelProps) {
|
||||
return (
|
||||
<div className="rounded-lg border p-4">
|
||||
<h3 className="font-semibold mb-4">YOUR DATA</h3>
|
||||
<ul className="space-y-2 text-sm">
|
||||
<li>Body Battery: {bodyBatteryCurrent ?? "N/A"}</li>
|
||||
<li>Yesterday Low: {bodyBatteryYesterdayLow ?? "N/A"}</li>
|
||||
<li>HRV: {hrvStatus}</li>
|
||||
<li>
|
||||
Week: {weekIntensity}/{phaseLimit} min
|
||||
</li>
|
||||
<li>Remaining: {remainingMinutes} min</li>
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
17
src/components/dashboard/decision-card.tsx
Normal file
17
src/components/dashboard/decision-card.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
// ABOUTME: Dashboard card displaying today's training decision.
|
||||
// ABOUTME: Shows decision status, icon, and reason prominently.
|
||||
import type { Decision } from "@/types";
|
||||
|
||||
interface DecisionCardProps {
|
||||
decision: Decision;
|
||||
}
|
||||
|
||||
export function DecisionCard({ decision }: DecisionCardProps) {
|
||||
return (
|
||||
<div className="rounded-lg border p-6">
|
||||
<div className="text-4xl mb-2">{decision.icon}</div>
|
||||
<h2 className="text-2xl font-bold">{decision.status}</h2>
|
||||
<p className="text-gray-600">{decision.reason}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
29
src/components/dashboard/mini-calendar.tsx
Normal file
29
src/components/dashboard/mini-calendar.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
// ABOUTME: Compact calendar widget for the dashboard.
|
||||
// ABOUTME: Shows current month with color-coded cycle phases.
|
||||
interface MiniCalendarProps {
|
||||
currentDate: Date;
|
||||
cycleDay: number;
|
||||
phase: string;
|
||||
}
|
||||
|
||||
export function MiniCalendar({
|
||||
currentDate,
|
||||
cycleDay,
|
||||
phase,
|
||||
}: MiniCalendarProps) {
|
||||
return (
|
||||
<div className="rounded-lg border p-4">
|
||||
<h3 className="font-semibold mb-4">
|
||||
Day {cycleDay} • {phase}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{currentDate.toLocaleDateString("en-US", {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
})}
|
||||
</p>
|
||||
{/* Full calendar grid will be implemented here */}
|
||||
<p className="text-gray-400 text-xs mt-4">Calendar grid placeholder</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
20
src/components/dashboard/nutrition-panel.tsx
Normal file
20
src/components/dashboard/nutrition-panel.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
// ABOUTME: Dashboard panel showing nutrition guidance.
|
||||
// ABOUTME: Displays seed cycling and macro recommendations.
|
||||
import type { NutritionGuidance } from "@/types";
|
||||
|
||||
interface NutritionPanelProps {
|
||||
nutrition: NutritionGuidance;
|
||||
}
|
||||
|
||||
export function NutritionPanel({ nutrition }: NutritionPanelProps) {
|
||||
return (
|
||||
<div className="rounded-lg border p-4">
|
||||
<h3 className="font-semibold mb-4">NUTRITION TODAY</h3>
|
||||
<ul className="space-y-2 text-sm">
|
||||
<li>🌱 {nutrition.seeds}</li>
|
||||
<li>🍽️ Carbs: {nutrition.carbRange}</li>
|
||||
<li>🥑 Keto: {nutrition.ketoGuidance}</li>
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
41
src/components/dashboard/override-toggles.tsx
Normal file
41
src/components/dashboard/override-toggles.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
// ABOUTME: Dashboard component for emergency training overrides.
|
||||
// ABOUTME: Provides toggles for flare, stress, sleep, and PMS modes.
|
||||
import type { OverrideType } from "@/types";
|
||||
|
||||
interface OverrideTogglesProps {
|
||||
activeOverrides: OverrideType[];
|
||||
onToggle: (override: OverrideType) => void;
|
||||
}
|
||||
|
||||
const OVERRIDE_OPTIONS: { type: OverrideType; label: string }[] = [
|
||||
{ type: "flare", label: "Flare Mode" },
|
||||
{ type: "stress", label: "High Stress" },
|
||||
{ type: "sleep", label: "Poor Sleep" },
|
||||
{ type: "pms", label: "PMS Symptoms" },
|
||||
];
|
||||
|
||||
export function OverrideToggles({
|
||||
activeOverrides,
|
||||
onToggle,
|
||||
}: OverrideTogglesProps) {
|
||||
return (
|
||||
<div className="rounded-lg border p-4">
|
||||
<h3 className="font-semibold mb-4">OVERRIDES</h3>
|
||||
<ul className="space-y-2">
|
||||
{OVERRIDE_OPTIONS.map(({ type, label }) => (
|
||||
<li key={type}>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={activeOverrides.includes(type)}
|
||||
onChange={() => onToggle(type)}
|
||||
className="rounded"
|
||||
/>
|
||||
{label}
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
62
src/lib/cycle.test.ts
Normal file
62
src/lib/cycle.test.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
// ABOUTME: Unit tests for cycle phase calculation utilities.
|
||||
// ABOUTME: Tests getCycleDay, getPhase, and phase limit functions.
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getCycleDay, getPhase, getPhaseLimit } from "./cycle";
|
||||
|
||||
describe("getCycleDay", () => {
|
||||
it("returns 1 on the first day of the cycle", () => {
|
||||
const lastPeriod = new Date("2025-01-01");
|
||||
const currentDate = new Date("2025-01-01");
|
||||
expect(getCycleDay(lastPeriod, 31, currentDate)).toBe(1);
|
||||
});
|
||||
|
||||
it("returns correct day within cycle", () => {
|
||||
const lastPeriod = new Date("2025-01-01");
|
||||
const currentDate = new Date("2025-01-15");
|
||||
expect(getCycleDay(lastPeriod, 31, currentDate)).toBe(15);
|
||||
});
|
||||
|
||||
it("wraps around after cycle length", () => {
|
||||
const lastPeriod = new Date("2025-01-01");
|
||||
const currentDate = new Date("2025-02-01"); // 31 days later
|
||||
expect(getCycleDay(lastPeriod, 31, currentDate)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getPhase", () => {
|
||||
it("returns MENSTRUAL for days 1-3", () => {
|
||||
expect(getPhase(1)).toBe("MENSTRUAL");
|
||||
expect(getPhase(3)).toBe("MENSTRUAL");
|
||||
});
|
||||
|
||||
it("returns FOLLICULAR for days 4-14", () => {
|
||||
expect(getPhase(4)).toBe("FOLLICULAR");
|
||||
expect(getPhase(14)).toBe("FOLLICULAR");
|
||||
});
|
||||
|
||||
it("returns OVULATION for days 15-16", () => {
|
||||
expect(getPhase(15)).toBe("OVULATION");
|
||||
expect(getPhase(16)).toBe("OVULATION");
|
||||
});
|
||||
|
||||
it("returns EARLY_LUTEAL for days 17-24", () => {
|
||||
expect(getPhase(17)).toBe("EARLY_LUTEAL");
|
||||
expect(getPhase(24)).toBe("EARLY_LUTEAL");
|
||||
});
|
||||
|
||||
it("returns LATE_LUTEAL for days 25-31", () => {
|
||||
expect(getPhase(25)).toBe("LATE_LUTEAL");
|
||||
expect(getPhase(31)).toBe("LATE_LUTEAL");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getPhaseLimit", () => {
|
||||
it("returns correct weekly limits for each phase", () => {
|
||||
expect(getPhaseLimit("MENSTRUAL")).toBe(30);
|
||||
expect(getPhaseLimit("FOLLICULAR")).toBe(120);
|
||||
expect(getPhaseLimit("OVULATION")).toBe(80);
|
||||
expect(getPhaseLimit("EARLY_LUTEAL")).toBe(100);
|
||||
expect(getPhaseLimit("LATE_LUTEAL")).toBe(50);
|
||||
});
|
||||
});
|
||||
73
src/lib/cycle.ts
Normal file
73
src/lib/cycle.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
// ABOUTME: Cycle phase calculation utilities.
|
||||
// ABOUTME: Determines current cycle day and phase from last period date.
|
||||
import type { CyclePhase, PhaseConfig } from "@/types";
|
||||
|
||||
export const PHASE_CONFIGS: PhaseConfig[] = [
|
||||
{
|
||||
name: "MENSTRUAL",
|
||||
days: [1, 3],
|
||||
weeklyLimit: 30,
|
||||
dailyAvg: 10,
|
||||
trainingType: "Gentle rebounding only",
|
||||
},
|
||||
{
|
||||
name: "FOLLICULAR",
|
||||
days: [4, 14],
|
||||
weeklyLimit: 120,
|
||||
dailyAvg: 17,
|
||||
trainingType: "Strength + rebounding",
|
||||
},
|
||||
{
|
||||
name: "OVULATION",
|
||||
days: [15, 16],
|
||||
weeklyLimit: 80,
|
||||
dailyAvg: 40,
|
||||
trainingType: "Peak performance",
|
||||
},
|
||||
{
|
||||
name: "EARLY_LUTEAL",
|
||||
days: [17, 24],
|
||||
weeklyLimit: 100,
|
||||
dailyAvg: 14,
|
||||
trainingType: "Moderate training",
|
||||
},
|
||||
{
|
||||
name: "LATE_LUTEAL",
|
||||
days: [25, 31],
|
||||
weeklyLimit: 50,
|
||||
dailyAvg: 8,
|
||||
trainingType: "Gentle rebounding ONLY",
|
||||
},
|
||||
];
|
||||
|
||||
export function getCycleDay(
|
||||
lastPeriodDate: Date,
|
||||
cycleLength: number,
|
||||
currentDate: Date = new Date(),
|
||||
): number {
|
||||
const diffMs = currentDate.getTime() - lastPeriodDate.getTime();
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
return (diffDays % cycleLength) + 1;
|
||||
}
|
||||
|
||||
export function getPhase(cycleDay: number): CyclePhase {
|
||||
for (const config of PHASE_CONFIGS) {
|
||||
if (cycleDay >= config.days[0] && cycleDay <= config.days[1]) {
|
||||
return config.name;
|
||||
}
|
||||
}
|
||||
// Default to late luteal for any days beyond 31
|
||||
return "LATE_LUTEAL";
|
||||
}
|
||||
|
||||
export function getPhaseConfig(phase: CyclePhase): PhaseConfig {
|
||||
const config = PHASE_CONFIGS.find((c) => c.name === phase);
|
||||
if (!config) {
|
||||
throw new Error(`Unknown phase: ${phase}`);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
export function getPhaseLimit(phase: CyclePhase): number {
|
||||
return getPhaseConfig(phase).weeklyLimit;
|
||||
}
|
||||
64
src/lib/decision-engine.ts
Normal file
64
src/lib/decision-engine.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
// ABOUTME: Training decision engine based on biometric and cycle data.
|
||||
// ABOUTME: Implements priority-based rules for daily training recommendations.
|
||||
import type { DailyData, Decision } from "@/types";
|
||||
|
||||
export function getTrainingDecision(data: DailyData): Decision {
|
||||
const {
|
||||
hrvStatus,
|
||||
bbYesterdayLow,
|
||||
phase,
|
||||
weekIntensity,
|
||||
phaseLimit,
|
||||
bbCurrent,
|
||||
} = data;
|
||||
|
||||
if (hrvStatus === "Unbalanced") {
|
||||
return { status: "REST", reason: "HRV Unbalanced", icon: "🛑" };
|
||||
}
|
||||
|
||||
if (bbYesterdayLow < 30) {
|
||||
return { status: "REST", reason: "BB too depleted", icon: "🛑" };
|
||||
}
|
||||
|
||||
if (phase === "LATE_LUTEAL") {
|
||||
return {
|
||||
status: "GENTLE",
|
||||
reason: "Gentle rebounding only (10-15min)",
|
||||
icon: "🟡",
|
||||
};
|
||||
}
|
||||
|
||||
if (phase === "MENSTRUAL") {
|
||||
return {
|
||||
status: "GENTLE",
|
||||
reason: "Gentle rebounding only (10min)",
|
||||
icon: "🟡",
|
||||
};
|
||||
}
|
||||
|
||||
if (weekIntensity >= phaseLimit) {
|
||||
return {
|
||||
status: "REST",
|
||||
reason: "WEEKLY LIMIT REACHED - Rest",
|
||||
icon: "🛑",
|
||||
};
|
||||
}
|
||||
|
||||
if (bbCurrent < 75) {
|
||||
return {
|
||||
status: "LIGHT",
|
||||
reason: "Light activity only - BB not recovered",
|
||||
icon: "🟡",
|
||||
};
|
||||
}
|
||||
|
||||
if (bbCurrent < 85) {
|
||||
return { status: "REDUCED", reason: "Reduce intensity 25%", icon: "🟡" };
|
||||
}
|
||||
|
||||
return {
|
||||
status: "TRAIN",
|
||||
reason: "OK to train - follow phase plan",
|
||||
icon: "✅",
|
||||
};
|
||||
}
|
||||
83
src/lib/email.ts
Normal file
83
src/lib/email.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
// ABOUTME: Email sending utilities using Resend.
|
||||
// ABOUTME: Sends daily training notifications and period confirmation emails.
|
||||
import { Resend } from "resend";
|
||||
|
||||
const resend = new Resend(process.env.RESEND_API_KEY);
|
||||
|
||||
const EMAIL_FROM = process.env.EMAIL_FROM || "phaseflow@example.com";
|
||||
|
||||
export interface DailyEmailData {
|
||||
to: string;
|
||||
cycleDay: number;
|
||||
phase: string;
|
||||
decision: {
|
||||
status: string;
|
||||
reason: string;
|
||||
icon: string;
|
||||
};
|
||||
bodyBatteryCurrent: number | null;
|
||||
bodyBatteryYesterdayLow: number | null;
|
||||
hrvStatus: string;
|
||||
weekIntensity: number;
|
||||
phaseLimit: number;
|
||||
remainingMinutes: number;
|
||||
seeds: string;
|
||||
carbRange: string;
|
||||
ketoGuidance: string;
|
||||
}
|
||||
|
||||
export async function sendDailyEmail(data: DailyEmailData): Promise<void> {
|
||||
const subject = `Today's Training: ${data.decision.icon} ${data.decision.status}`;
|
||||
|
||||
const body = `Good morning!
|
||||
|
||||
📅 CYCLE DAY: ${data.cycleDay} (${data.phase})
|
||||
|
||||
💪 TODAY'S PLAN:
|
||||
${data.decision.icon} ${data.decision.reason}
|
||||
|
||||
📊 YOUR DATA:
|
||||
• Body Battery Now: ${data.bodyBatteryCurrent ?? "N/A"}
|
||||
• Yesterday's Low: ${data.bodyBatteryYesterdayLow ?? "N/A"}
|
||||
• HRV Status: ${data.hrvStatus}
|
||||
• Week Intensity: ${data.weekIntensity} / ${data.phaseLimit} minutes
|
||||
• Remaining: ${data.remainingMinutes} minutes
|
||||
|
||||
🌱 SEEDS: ${data.seeds}
|
||||
|
||||
🍽️ MACROS: ${data.carbRange}
|
||||
🥑 KETO: ${data.ketoGuidance}
|
||||
|
||||
---
|
||||
Auto-generated by PhaseFlow`;
|
||||
|
||||
await resend.emails.send({
|
||||
from: EMAIL_FROM,
|
||||
to: data.to,
|
||||
subject,
|
||||
text: body,
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendPeriodConfirmationEmail(
|
||||
to: string,
|
||||
lastPeriodDate: Date,
|
||||
cycleLength: number,
|
||||
): Promise<void> {
|
||||
const subject = "🔵 Period Tracking Updated";
|
||||
|
||||
const body = `Your cycle has been reset. Last period: ${lastPeriodDate.toLocaleDateString()}
|
||||
Phase calendar updated for next ${cycleLength} days.
|
||||
|
||||
Your calendar will update automatically within 24 hours.
|
||||
|
||||
---
|
||||
Auto-generated by PhaseFlow`;
|
||||
|
||||
await resend.emails.send({
|
||||
from: EMAIL_FROM,
|
||||
to,
|
||||
subject,
|
||||
text: body,
|
||||
});
|
||||
}
|
||||
49
src/lib/encryption.ts
Normal file
49
src/lib/encryption.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
// ABOUTME: AES-256 encryption utilities for sensitive data like Garmin tokens.
|
||||
// ABOUTME: Provides encrypt/decrypt functions using environment-based keys.
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
||||
|
||||
const ALGORITHM = "aes-256-gcm";
|
||||
const IV_LENGTH = 16;
|
||||
|
||||
function getEncryptionKey(): Buffer {
|
||||
const key = process.env.ENCRYPTION_KEY;
|
||||
if (!key) {
|
||||
throw new Error("ENCRYPTION_KEY environment variable is required");
|
||||
}
|
||||
// Ensure key is exactly 32 bytes for AES-256
|
||||
return Buffer.from(key.padEnd(32, "0").slice(0, 32));
|
||||
}
|
||||
|
||||
export function encrypt(plaintext: string): string {
|
||||
const key = getEncryptionKey();
|
||||
const iv = randomBytes(IV_LENGTH);
|
||||
const cipher = createCipheriv(ALGORITHM, key, iv);
|
||||
|
||||
let encrypted = cipher.update(plaintext, "utf8", "hex");
|
||||
encrypted += cipher.final("hex");
|
||||
|
||||
const authTag = cipher.getAuthTag();
|
||||
|
||||
// Format: iv:authTag:encrypted
|
||||
return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
|
||||
}
|
||||
|
||||
export function decrypt(ciphertext: string): string {
|
||||
const key = getEncryptionKey();
|
||||
const [ivHex, authTagHex, encrypted] = ciphertext.split(":");
|
||||
|
||||
if (!ivHex || !authTagHex || !encrypted) {
|
||||
throw new Error("Invalid ciphertext format");
|
||||
}
|
||||
|
||||
const iv = Buffer.from(ivHex, "hex");
|
||||
const authTag = Buffer.from(authTagHex, "hex");
|
||||
|
||||
const decipher = createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
|
||||
let decrypted = decipher.update(encrypted, "hex", "utf8");
|
||||
decrypted += decipher.final("utf8");
|
||||
|
||||
return decrypted;
|
||||
}
|
||||
39
src/lib/garmin.ts
Normal file
39
src/lib/garmin.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
// ABOUTME: Garmin Connect API client using stored OAuth tokens.
|
||||
// ABOUTME: Fetches body battery, HRV, and intensity minutes from Garmin.
|
||||
import type { GarminTokens } from "@/types";
|
||||
|
||||
const GARMIN_BASE_URL = "https://connect.garmin.com/modern/proxy";
|
||||
|
||||
interface GarminApiOptions {
|
||||
oauth2Token: string;
|
||||
}
|
||||
|
||||
export async function fetchGarminData(
|
||||
endpoint: string,
|
||||
options: GarminApiOptions,
|
||||
): Promise<unknown> {
|
||||
const response = await fetch(`${GARMIN_BASE_URL}${endpoint}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${options.oauth2Token}`,
|
||||
NK: "NT",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Garmin API error: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function isTokenExpired(tokens: GarminTokens): boolean {
|
||||
const expiresAt = new Date(tokens.expires_at);
|
||||
return expiresAt <= new Date();
|
||||
}
|
||||
|
||||
export function daysUntilExpiry(tokens: GarminTokens): number {
|
||||
const expiresAt = new Date(tokens.expires_at);
|
||||
const now = new Date();
|
||||
const diffMs = expiresAt.getTime() - now.getTime();
|
||||
return Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
}
|
||||
97
src/lib/ics.ts
Normal file
97
src/lib/ics.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
// ABOUTME: ICS calendar feed generation for cycle phase events.
|
||||
// ABOUTME: Creates subscribable calendar with phase blocks and warnings.
|
||||
import { createEvents, type EventAttributes } from "ics";
|
||||
|
||||
import { getCycleDay, getPhase, PHASE_CONFIGS } from "./cycle";
|
||||
|
||||
const PHASE_EMOJIS: Record<string, string> = {
|
||||
MENSTRUAL: "🔵",
|
||||
FOLLICULAR: "🟢",
|
||||
OVULATION: "🟣",
|
||||
EARLY_LUTEAL: "🟡",
|
||||
LATE_LUTEAL: "🔴",
|
||||
};
|
||||
|
||||
interface IcsGeneratorOptions {
|
||||
lastPeriodDate: Date;
|
||||
cycleLength: number;
|
||||
monthsAhead?: number;
|
||||
}
|
||||
|
||||
export function generateIcsFeed(options: IcsGeneratorOptions): string {
|
||||
const { lastPeriodDate, cycleLength, monthsAhead = 3 } = options;
|
||||
const events: EventAttributes[] = [];
|
||||
|
||||
const endDate = new Date();
|
||||
endDate.setMonth(endDate.getMonth() + monthsAhead);
|
||||
|
||||
const currentDate = new Date(lastPeriodDate);
|
||||
let currentPhase = getPhase(
|
||||
getCycleDay(lastPeriodDate, cycleLength, currentDate),
|
||||
);
|
||||
let phaseStartDate = new Date(currentDate);
|
||||
|
||||
while (currentDate <= endDate) {
|
||||
const cycleDay = getCycleDay(lastPeriodDate, cycleLength, currentDate);
|
||||
const phase = getPhase(cycleDay);
|
||||
|
||||
// Add warning events
|
||||
if (cycleDay === 22) {
|
||||
events.push({
|
||||
start: dateToArray(currentDate),
|
||||
end: dateToArray(currentDate),
|
||||
title: "⚠️ Late Luteal Phase Starts in 3 Days",
|
||||
description: "Begin reducing training intensity",
|
||||
});
|
||||
}
|
||||
|
||||
if (cycleDay === 25) {
|
||||
events.push({
|
||||
start: dateToArray(currentDate),
|
||||
end: dateToArray(currentDate),
|
||||
title: "🔴 CRITICAL PHASE - Gentle Rebounding Only!",
|
||||
description: "Late luteal phase - protect your cycle",
|
||||
});
|
||||
}
|
||||
|
||||
// Track phase changes
|
||||
if (phase !== currentPhase) {
|
||||
// Close previous phase event
|
||||
events.push(createPhaseEvent(currentPhase, phaseStartDate, currentDate));
|
||||
currentPhase = phase;
|
||||
phaseStartDate = new Date(currentDate);
|
||||
}
|
||||
|
||||
currentDate.setDate(currentDate.getDate() + 1);
|
||||
}
|
||||
|
||||
// Close final phase
|
||||
events.push(createPhaseEvent(currentPhase, phaseStartDate, currentDate));
|
||||
|
||||
const { value, error } = createEvents(events);
|
||||
if (error) {
|
||||
throw new Error(`ICS generation error: ${error}`);
|
||||
}
|
||||
|
||||
return value || "";
|
||||
}
|
||||
|
||||
function createPhaseEvent(
|
||||
phase: string,
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
): EventAttributes {
|
||||
const config = PHASE_CONFIGS.find((c) => c.name === phase);
|
||||
const emoji = PHASE_EMOJIS[phase] || "📅";
|
||||
|
||||
return {
|
||||
start: dateToArray(startDate),
|
||||
end: dateToArray(endDate),
|
||||
title: `${emoji} ${phase.replace("_", " ")}`,
|
||||
description: config?.trainingType || "",
|
||||
};
|
||||
}
|
||||
|
||||
function dateToArray(date: Date): [number, number, number, number, number] {
|
||||
return [date.getFullYear(), date.getMonth() + 1, date.getDate(), 0, 0];
|
||||
}
|
||||
44
src/lib/nutrition.ts
Normal file
44
src/lib/nutrition.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// ABOUTME: Nutrition guidance based on cycle day.
|
||||
// ABOUTME: Provides seed cycling and macro recommendations by phase.
|
||||
import type { NutritionGuidance } from "@/types";
|
||||
|
||||
export function getNutritionGuidance(cycleDay: number): NutritionGuidance {
|
||||
// Seed cycling
|
||||
const seeds =
|
||||
cycleDay <= 14
|
||||
? "Flax (1-2 tbsp) + Pumpkin (1-2 tbsp)"
|
||||
: "Sesame (1-2 tbsp) + Sunflower (1-2 tbsp)";
|
||||
|
||||
// Macro guidance by day range
|
||||
let carbRange: string;
|
||||
let ketoGuidance: string;
|
||||
|
||||
if (cycleDay >= 1 && cycleDay <= 3) {
|
||||
carbRange = "100-150g";
|
||||
ketoGuidance = "No - body needs carbs during menstruation";
|
||||
} else if (cycleDay >= 4 && cycleDay <= 6) {
|
||||
carbRange = "75-100g";
|
||||
ketoGuidance = "No - transition phase";
|
||||
} else if (cycleDay >= 7 && cycleDay <= 14) {
|
||||
carbRange = "20-100g";
|
||||
ketoGuidance = "OPTIONAL - optimal keto window";
|
||||
} else if (cycleDay >= 15 && cycleDay <= 16) {
|
||||
carbRange = "100-150g";
|
||||
ketoGuidance = "No - exit keto, need carbs for ovulation";
|
||||
} else if (cycleDay >= 17 && cycleDay <= 24) {
|
||||
carbRange = "75-125g";
|
||||
ketoGuidance = "No - progesterone needs carbs";
|
||||
} else {
|
||||
carbRange = "100-150g+";
|
||||
ketoGuidance = "NEVER - mood/hormones need carbs for PMS";
|
||||
}
|
||||
|
||||
return { seeds, carbRange, ketoGuidance };
|
||||
}
|
||||
|
||||
export function getSeedSwitchAlert(cycleDay: number): string | null {
|
||||
if (cycleDay === 15) {
|
||||
return "🌱 SWITCH TODAY! Start Sesame + Sunflower";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
10
src/lib/pocketbase.ts
Normal file
10
src/lib/pocketbase.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
// ABOUTME: PocketBase client initialization and utilities.
|
||||
// ABOUTME: Provides typed access to the PocketBase backend for auth and data.
|
||||
import PocketBase from "pocketbase";
|
||||
|
||||
const POCKETBASE_URL = process.env.POCKETBASE_URL || "http://localhost:8090";
|
||||
|
||||
export const pb = new PocketBase(POCKETBASE_URL);
|
||||
|
||||
// Disable auto-cancellation for server-side usage
|
||||
pb.autoCancellation(false);
|
||||
8
src/lib/utils.ts
Normal file
8
src/lib/utils.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// ABOUTME: Utility functions for className merging with Tailwind CSS.
|
||||
// ABOUTME: Provides cn() helper for combining conditional class names.
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
103
src/types/index.ts
Normal file
103
src/types/index.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
// ABOUTME: Central type definitions for the PhaseFlow application.
|
||||
// ABOUTME: Contains interfaces for users, daily logs, decisions, and cycle data.
|
||||
|
||||
export type CyclePhase =
|
||||
| "MENSTRUAL"
|
||||
| "FOLLICULAR"
|
||||
| "OVULATION"
|
||||
| "EARLY_LUTEAL"
|
||||
| "LATE_LUTEAL";
|
||||
|
||||
export type HrvStatus = "Balanced" | "Unbalanced" | "Unknown";
|
||||
|
||||
export type DecisionStatus = "REST" | "GENTLE" | "LIGHT" | "REDUCED" | "TRAIN";
|
||||
|
||||
export type OverrideType = "flare" | "stress" | "sleep" | "pms";
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
|
||||
// Garmin
|
||||
garminConnected: boolean;
|
||||
garminOauth1Token: string; // encrypted JSON
|
||||
garminOauth2Token: string; // encrypted JSON
|
||||
garminTokenExpiresAt: Date;
|
||||
|
||||
// Calendar
|
||||
calendarToken: string; // random secret for ICS URL
|
||||
|
||||
// Cycle
|
||||
lastPeriodDate: Date;
|
||||
cycleLength: number; // default: 31
|
||||
|
||||
// Preferences
|
||||
notificationTime: string; // "07:00"
|
||||
timezone: string;
|
||||
|
||||
// Overrides
|
||||
activeOverrides: OverrideType[];
|
||||
|
||||
created: Date;
|
||||
updated: Date;
|
||||
}
|
||||
|
||||
export interface DailyLog {
|
||||
id: string;
|
||||
user: string; // relation
|
||||
date: Date;
|
||||
cycleDay: number;
|
||||
phase: CyclePhase;
|
||||
bodyBatteryCurrent: number | null;
|
||||
bodyBatteryYesterdayLow: number | null;
|
||||
hrvStatus: HrvStatus;
|
||||
weekIntensityMinutes: number;
|
||||
phaseLimit: number;
|
||||
remainingMinutes: number;
|
||||
trainingDecision: string;
|
||||
decisionReason: string;
|
||||
notificationSentAt: Date | null;
|
||||
created: Date;
|
||||
}
|
||||
|
||||
export interface PeriodLog {
|
||||
id: string;
|
||||
user: string; // relation
|
||||
startDate: Date;
|
||||
created: Date;
|
||||
}
|
||||
|
||||
export interface Decision {
|
||||
status: DecisionStatus;
|
||||
reason: string;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
export interface DailyData {
|
||||
hrvStatus: HrvStatus;
|
||||
bbYesterdayLow: number;
|
||||
phase: CyclePhase;
|
||||
weekIntensity: number;
|
||||
phaseLimit: number;
|
||||
bbCurrent: number;
|
||||
}
|
||||
|
||||
export interface GarminTokens {
|
||||
oauth1: string;
|
||||
oauth2: string;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
export interface PhaseConfig {
|
||||
name: CyclePhase;
|
||||
days: [number, number]; // start and end day
|
||||
weeklyLimit: number;
|
||||
dailyAvg: number;
|
||||
trainingType: string;
|
||||
}
|
||||
|
||||
export interface NutritionGuidance {
|
||||
seeds: string;
|
||||
carbRange: string;
|
||||
ketoGuidance: string;
|
||||
}
|
||||
Reference in New Issue
Block a user