### Authentication Setup with Better-Auth (TypeScript) Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/CLAUDE.md.md This code illustrates the setup of Better-Auth with a Prisma adapter in TypeScript. It shows how to initialize the authentication library and configure it to use Prisma for session management. ```typescript import { PrismaClient } from "@prisma/client"; import { BetterAuthApi } from "better-auth-fastify"; import { PrismaAdapter } from "better-auth-prisma-adapter"; const prisma = new PrismaClient(); const auth = new BetterAuthApi({ adapter: new PrismaAdapter(prisma), secret: process.env.BETTER_AUTH_SECRET as string, url: process.env.BETTER_AUTH_URL as string, // Other configuration options can go here }); export { auth }; ``` -------------------------------- ### Start Workout Session (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Initiates a new workout session for a specific day. Only the plan owner can start sessions, and the plan must be active. Returns an error if a session already exists for the day. Requires workoutPlanId and workoutDayId. ```bash # Iniciar sessão de treino curl -X POST http://localhost:8081/workout-plans/plan-uuid-123/days/day-uuid-1/sessions \ -b cookies.txt ``` -------------------------------- ### POST /workout-plans/:workoutPlanId/days/:workoutDayId/sessions Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Starts a new training session for a specific workout day. Only the plan owner can start sessions, and the plan must be active. Returns a 409 error if a session for this day already exists. ```APIDOC ## POST /workout-plans/:workoutPlanId/days/:workoutDayId/sessions ### Description Inicia uma nova sessão de treino para um dia específico. Apenas o dono do plano pode iniciar sessões, e o plano deve estar ativo. Retorna erro 409 se já existir uma sessão para este dia. ### Method POST ### Endpoint `/workout-plans/:workoutPlanId/days/:workoutDayId/sessions` ### Parameters #### Path Parameters - **workoutPlanId** (string) - Required - The ID of the workout plan. - **workoutDayId** (string) - Required - The ID of the workout day. ### Request Example ```bash curl -X POST http://localhost:8081/workout-plans/plan-uuid-123/days/day-uuid-1/sessions \ -b cookies.txt ``` ### Response #### Success Response (201 Created) - **userWorkoutSessionId** (string) - The ID of the newly created workout session. #### Response Example ```json { "userWorkoutSessionId": "session-uuid-new" } ``` #### Error Response (409 Conflict) - **error** (string) - Description of the error. - **code** (string) - Error code. #### Error Response Example (409 Conflict) ```json { "error": "A session has already been started for this day", "code": "SESSION_ALREADY_STARTED_ERROR" } ``` #### Error Response (422 Unprocessable Entity) - **error** (string) - Description of the error. - **code** (string) - Error code. #### Error Response Example (422 Unprocessable Entity) ```json { "error": "Workout plan is not active", "code": "WORKOUT_PLAN_NOT_ACTIVE_ERROR" } ``` ``` -------------------------------- ### Fastify Route Handler Example (TypeScript) Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/CLAUDE.md.md An example of a Fastify route handler using TypeScript, demonstrating how to define routes, use Zod schemas for validation, and interact with use cases. It shows session extraction and HTTP status code setting. ```typescript import { FastifyInstance } from "fastify"; import { ZodTypeProvider } from "fastify-type-provider-zod"; import { z } from "zod"; import { NotFoundError } from "@/errors/NotFoundError"; import { auth } from "@/lib/auth"; export async function userRoutes(app: FastifyInstance) { app.withTypeProvider().route({ method: "GET", url: "/api/users/:id", schema: { params: z.object({ id: z.string().uuid(), }), response: { 200: z.object({ id: z.string().uuid(), email: z.string().email(), }), 404: z.object({ message: z.string(), }), }, }, onRequest: [auth.api.getSession], handler: async (request, reply) => { const { id } = request.params; const session = await auth.api.getSession(request, reply); if (!session) { return reply.status(401).send({ message: "Unauthorized" }); } // Example of using a use case and handling custom errors try { const user = await app.container.get("UserService").getUserById(id); if (!user) { throw new NotFoundError(`User with id ${id} not found.`); } return reply.send(user); } catch (error) { if (error instanceof NotFoundError) { return reply.status(404).send({ message: error.message }); } throw error; // Re-throw other errors for global handling } }, }); } ``` -------------------------------- ### Development Server and Database Commands (Bash) Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/CLAUDE.md.md This snippet outlines essential bash commands for running the development server with hot-reloading, starting the PostgreSQL database using Docker Compose, and performing Prisma database migrations and generation. ```bash # Iniciar servidor de desenvolvimento (hot-reload na porta 8081) pnpm dev # Iniciar PostgreSQL docker-compose up -d # Migrations do Prisma pnpm exec prisma migrate dev pnpm exec prisma generate # Lint pnpm exec eslint . # Formatacao pnpm exec prettier --write . ``` -------------------------------- ### Definição de Interface de Requisição para Rota GET /home/{date} Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/tasks/03.md Define as interfaces TypeScript para os parâmetros, corpo e query da requisição da rota GET /home/{date}. A interface `Params` especifica que o parâmetro `date` é uma string. ```typescript interface Body {} ``` ```typescript interface Params { date: string; } ``` ```typescript interface Query {} ``` -------------------------------- ### GET /home/{date} Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/tasks/03.md Retrieves necessary data for the authenticated user to populate the application's home page. Requires a date in YYYY-MM-DD format as a route parameter. ```APIDOC ## GET /home/{date} ### Description Retrieves necessary data for the authenticated user to populate the application's home page. ### Method GET ### Endpoint /home/{date} ### Parameters #### Path Parameters - **date** (string) - Required - The date in YYYY-MM-DD format for which to retrieve home page data. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **activeWorkoutPlanId** (string) - The ID of the user's active workout plan. - **todayWorkoutDay** (object) - Details about the workout day for the specified date. - **workoutPlanId** (string) - The ID of the workout plan. - **id** (string) - The ID of the workout day. - **name** (string) - The name of the workout day. - **isRest** (boolean) - Indicates if this day is a rest day. - **weekDay** (string) - The day of the week. - **estimatedDurationInSeconds** (number) - The estimated duration of the workout in seconds. - **coverImageUrl** (string) - Optional URL for the workout cover image. - **exercisesCount** (number) - The number of exercises for this workout day. - **workoutStreak** (number) - The number of consecutive days the user has completed a workout or rest day. - **consistencyByDay** (object) - An object mapping dates (YYYY-MM-DD) to workout completion status. - **[key: string]** (object) - Represents a specific day. - **workoutDayCompleted** (boolean) - True if the workout day was completed. - **workoutDayStarted** (boolean) - True if the workout day was started. #### Response Example ```json { "activeWorkoutPlanId": "plan-123", "todayWorkoutDay": { "workoutPlanId": "plan-123", "id": "day-001", "name": "Leg Day", "isRest": false, "weekDay": "Monday", "estimatedDurationInSeconds": 3600, "coverImageUrl": "http://example.com/cover.jpg", "exercisesCount": 5 }, "workoutStreak": 7, "consistencyByDay": { "2025-01-01": { "workoutDayCompleted": true, "workoutDayStarted": true }, "2025-01-02": { "workoutDayCompleted": false, "workoutDayStarted": true } } } ``` ``` -------------------------------- ### Definição de Interface de Resposta para Rota GET /home/{date} Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/tasks/03.md Define a interface TypeScript para a resposta bem-sucedida (status code 200) da rota GET /home/{date}. Inclui detalhes sobre o plano de treino ativo, progresso diário e consistência do usuário. ```typescript interface StatusCode200 { activeWorkoutPlanId: string; todayWorkoutDay: { workoutPlanId: string; id: string; name: string; isRest: boolean; weekDay: string; estimatedDurationInSeconds: number; coverImageUrl?: string; exercisesCount: number; }; workoutStreak: number; consistencyByDay: { // key: "2025-01-01" — incluir TODOS os dias, mesmo os que não possuem sessão [key: string]: { workoutDayCompleted: boolean; workoutDayStarted: boolean; }; }; } ``` -------------------------------- ### GET /workout-plans/:workoutPlanId Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves the details of a specific workout plan for the authenticated user, including a summary of all workout days with exercise counts. ```APIDOC ## GET /workout-plans/:workoutPlanId ### Description Obtém os detalhes de um plano de treino específico do usuário autenticado, incluindo resumo de todos os dias de treino com contagem de exercícios. ### Method GET ### Endpoint `/workout-plans/:workoutPlanId` ### Parameters #### Path Parameters - **workoutPlanId** (string) - Required - The ID of the workout plan to retrieve. ### Request Example ```bash curl -X GET http://localhost:8081/workout-plans/plan-uuid-123 \ -b cookies.txt ``` ### Response #### Success Response (200 OK) - **id** (string) - The unique identifier of the workout plan. - **name** (string) - The name of the workout plan. - **workoutDays** (array) - An array of workout day summaries. - **id** (string) - The unique identifier of the workout day. - **weekDay** (string) - The day of the week for this workout. - **name** (string) - The name of the workout day. - **isRest** (boolean) - Indicates if this day is a rest day. - **coverImageUrl** (string) - URL for the cover image of the workout day. - **estimatedDurationInSeconds** (integer) - Estimated duration of the workout in seconds. - **exercisesCount** (integer) - The number of exercises in this workout day. #### Response Example ```json { "id": "plan-uuid-123", "name": "Plano Upper/Lower 4x", "workoutDays": [ { "id": "day-uuid-1", "weekDay": "MONDAY", "name": "Superior A - Peito e Costas", "isRest": false, "coverImageUrl": "https://gw8hy3fdcv.ufs.sh/f/ccoBDpLoAPCO3y8pQ6GBg8iqe9pP2JrHjwd1nfKtVSQskI0v", "estimatedDurationInSeconds": 3600, "exercisesCount": 6 }, { "id": "day-uuid-2", "weekDay": "TUESDAY", "name": "Inferior A - Quadríceps e Posterior", "isRest": false, "coverImageUrl": "https://gw8hy3fdcv.ufs.sh/f/ccoBDpLoAPCOgCHaUgNGronCvXmSzAMs1N3KgLdE5yHT6Ykj", "estimatedDurationInSeconds": 3300, "exercisesCount": 5 } ] } ``` #### Error Response (404 Not Found) - **error** (string) - Description of the error. - **code** (string) - Error code. #### Error Response Example ```json { "error": "Workout plan not found", "code": "NOT_FOUND_ERROR" } ``` ``` -------------------------------- ### GET /home/:date Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves the home screen data for a specific date, including the day's workout, current training streak, and weekly consistency. The date must be in ISO format (YYYY-MM-DD). ```APIDOC ## GET /home/:date ### Description Obtém os dados da tela inicial para uma data específica, incluindo o treino do dia, streak atual de treinos e consistência da semana. A data deve estar no formato ISO (YYYY-MM-DD). ### Method GET ### Endpoint `/home/:date` ### Parameters #### Path Parameters - **date** (string) - Required - The date for which to retrieve home screen data (YYYY-MM-DD format). ### Request Example ```bash # Buscar dados da home para hoje curl -X GET http://localhost:8081/home/2024-01-15 \ -b cookies.txt ``` ### Response #### Success Response (200 OK) (Response structure not provided in the input text, but would typically include workout of the day, streak information, and consistency metrics.) #### Response Example (Example response structure not provided in the input text.) ``` -------------------------------- ### Get Home Screen Data (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves the home screen data for a specific date, including the day's workout, current training streak, and weekly consistency. The date must be in ISO format (YYYY-MM-DD). ```bash # Buscar dados da home para hoje curl -X GET http://localhost:8081/home/2024-01-15 \ -b cookies.txt ``` -------------------------------- ### Get Workout Plan Details (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves the details of a specific workout plan for the authenticated user, including a summary of all workout days and exercise counts. Requires a valid workoutPlanId. ```bash # Buscar plano específico curl -X GET http://localhost:8081/workout-plans/plan-uuid-123 \ -b cookies.txt ``` -------------------------------- ### Start Workout Session Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/doc/API_PROMPT.md Initiates a workout session for a specific day within a workout plan. This action creates a new WorkoutSession record in the database. ```APIDOC ## POST /workout-plans/{id}/days/{id}/sessions ### Description Initiates a workout session for a specific day of a workout plan. This creates a `WorkoutSession` in the database. ### Method POST ### Endpoint `/workout-plans/{id}/days/{id}/sessions` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the workout plan. - **id** (string) - Required - The ID of the workout day. #### Query Parameters None #### Request Body An empty object is expected for the request body. ### Request Example ```json {} ``` ### Response #### Success Response (201) - **userWorkoutSessionId** (string) - The ID of the newly created workout session. #### Response Example ```json { "userWorkoutSessionId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` #### Error Responses - **401 Unauthorized**: If the user is not authenticated. - **403 Forbidden**: If the authenticated user is not the owner of the workout plan. - **409 Conflict**: If a workout session has already been started for the given day (indicated by a present `startedAt` timestamp). ``` -------------------------------- ### GET /workout-plans/:workoutPlanId/days/:workoutDayId Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves the complete details of a specific workout day, including all ordered exercises and history of training sessions performed on this day. ```APIDOC ## GET /workout-plans/:workoutPlanId/days/:workoutDayId ### Description Obtém os detalhes completos de um dia de treino específico, incluindo todos os exercícios ordenados e histórico de sessões de treino realizadas neste dia. ### Method GET ### Endpoint `/workout-plans/:workoutPlanId/days/:workoutDayId` ### Parameters #### Path Parameters - **workoutPlanId** (string) - Required - The ID of the workout plan. - **workoutDayId** (string) - Required - The ID of the workout day. ### Request Example ```bash curl -X GET http://localhost:8081/workout-plans/plan-uuid-123/days/day-uuid-1 \ -b cookies.txt ``` ### Response #### Success Response (200 OK) - **id** (string) - The unique identifier of the workout day. - **name** (string) - The name of the workout day. - **isRest** (boolean) - Indicates if this day is a rest day. - **coverImageUrl** (string) - URL for the cover image of the workout day. - **estimatedDurationInSeconds** (integer) - Estimated duration of the workout in seconds. - **weekDay** (string) - The day of the week for this workout. - **exercises** (array) - An array of exercises for this workout day. - **id** (string) - The unique identifier of the exercise. - **name** (string) - The name of the exercise. - **order** (integer) - The order of the exercise within the workout day. - **workoutDayId** (string) - The ID of the workout day this exercise belongs to. - **sets** (integer) - The number of sets for the exercise. - **reps** (integer) - The number of repetitions for the exercise. - **restTimeInSeconds** (integer) - The rest time in seconds between sets. - **sessions** (array) - An array of training sessions performed on this day. - **id** (string) - The unique identifier of the session. - **workoutDayId** (string) - The ID of the workout day this session belongs to. - **startedAt** (string) - The date and time the session started (ISO 8601 format). - **completedAt** (string) - The date and time the session was completed (ISO 8601 format). #### Response Example ```json { "id": "day-uuid-1", "name": "Superior A - Peito e Costas", "isRest": false, "coverImageUrl": "https://gw8hy3fdcv.ufs.sh/f/ccoBDpLoAPCO3y8pQ6GBg8iqe9pP2JrHjwd1nfKtVSQskI0v", "estimatedDurationInSeconds": 3600, "weekDay": "MONDAY", "exercises": [ { "id": "ex-uuid-1", "name": "Supino Reto com Barra", "order": 1, "workoutDayId": "day-uuid-1", "sets": 4, "reps": 10, "restTimeInSeconds": 90 }, { "id": "ex-uuid-2", "name": "Remada Curvada", "order": 2, "workoutDayId": "day-uuid-1", "sets": 4, "reps": 10, "restTimeInSeconds": 90 } ], "sessions": [ { "id": "session-uuid-1", "workoutDayId": "day-uuid-1", "startedAt": "2024-01-15", "completedAt": "2024-01-15" } ] } ``` ``` -------------------------------- ### Business Logic Use Case Example (TypeScript) Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/CLAUDE.md.md This snippet demonstrates a business logic use case class written in TypeScript. It shows how to inject dependencies (like Prisma client), handle DTOs, and use Prisma transactions for atomic operations. ```typescript import { PrismaClient } from "@prisma/client"; import { injectable, inject } from "inversify"; import { z } from "zod"; // Define DTOs using Zod interfaces const CreateUserDto = z.object({ email: z.string().email(), password: z.string().min(6), }); interface IUserService { createUser(dto: z.infer): Promise; // Replace 'any' with actual return type getUserById(id: string): Promise; // Replace 'any' with actual return type } @injectable() class UserService implements IUserService { constructor(@inject("PrismaClient") private prisma: PrismaClient) {} async createUser(dto: z.infer): Promise { // Example of using Prisma transaction for atomicity return await this.prisma.$transaction(async (tx) => { // Check if email already exists const existingUser = await tx.user.findUnique({ where: { email: dto.email } }); if (existingUser) { throw new Error("Email already in use."); } // Hash password here in a real application const newUser = await tx.user.create({ data: { email: dto.email, password: dto.password, // Hashed password would go here }, }); return newUser; }); } async getUserById(id: string): Promise { return await this.prisma.user.findUnique({ where: { id } }); } } export { UserService, IUserService }; ``` -------------------------------- ### GET /stats Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves detailed user workout statistics for a specified period, including workout streak, completion rate, total completed workouts, and total workout time. ```APIDOC ## GET /stats ### Description Retrieves detailed user workout statistics for a specified period, including workout streak, completion rate, total completed workouts, and total workout time. ### Method GET ### Endpoint `/stats` #### Query Parameters - **from** (string) - Required - The start date for the statistics period (YYYY-MM-DD). - **to** (string) - Required - The end date for the statistics period (YYYY-MM-DD). ### Response #### Success Response (200 OK) - **workoutStreak** (integer) - The current workout streak of the user. - **consistencyByDay** (object) - An object where keys are dates and values indicate workout completion and start status for that day. - **workoutDayCompleted** (boolean) - Indicates if the workout for the day was completed. - **workoutDayStarted** (boolean) - Indicates if the workout for the day was started. - **completedWorkoutsCount** (integer) - The total number of workouts completed. - **conclusionRate** (number) - The rate of workout completion. - **totalTimeInSeconds** (integer) - The total time spent on workouts in seconds. #### Error Response (404 Not Found) - **error** (string) - Description of the error, e.g., "Active workout plan not found". - **code** (string) - Error code, e.g., "NOT_FOUND_ERROR". ### Request Example ```bash curl -X GET "http://localhost:8081/stats?from=2024-01-01&to=2024-01-31" \ -b cookies.txt ``` ### Response Example (200 OK) ```json { "workoutStreak": 15, "consistencyByDay": { "2024-01-02": { "workoutDayCompleted": true, "workoutDayStarted": true }, "2024-01-03": { "workoutDayCompleted": true, "workoutDayStarted": true }, "2024-01-04": { "workoutDayCompleted": false, "workoutDayStarted": true } }, "completedWorkoutsCount": 18, "conclusionRate": 0.9, "totalTimeInSeconds": 64800 } ``` ``` -------------------------------- ### GET /workout-plans/:id/days/:id Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/tasks/05.md Retrieves a specific workout day from a workout plan, including its exercises and their sessions. ```APIDOC ## GET /workout-plans/:id/days/:id ### Description Retrieves a specific workout day from a workout plan, including its exercises and their sessions. ### Method GET ### Endpoint /workout-plans/:id/days/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the workout plan. - **id** (string) - Required - The ID of the workout day. #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **id** (string) - The unique identifier for the workout day. - **name** (string) - The name of the workout day. - **isRest** (boolean) - Indicates if this is a rest day. - **coverImageUrl** (string) - Optional URL for a cover image. - **estimatedDurationInSeconds** (number) - The estimated duration of the workout day in seconds. - **exercises** (Array) - A list of exercises for the workout day. - **weekDay** (string) - The day of the week. - **sessions** (Array) - A list of workout sessions for the day. - **id** (string) - The unique identifier for the session. - **workoutDayId** (string) - The ID of the workout day this session belongs to. - **startedAt** (string) - Optional start date of the session (YYYY-MM-DD). - **completedAt** (string) - Optional completion date of the session (YYYY-MM-DD). #### Response Example ```json { "id": "day123", "name": "Leg Day", "isRest": false, "coverImageUrl": "https://example.com/image.jpg", "estimatedDurationInSeconds": 3600, "exercises": [ { "id": "exer456", "name": "Squats", "sets": 3, "reps": 10, "restTimeInSeconds": 60 } ], "weekDay": "Monday", "sessions": [ { "id": "sess789", "workoutDayId": "day123", "startedAt": "2023-10-27", "completedAt": "2023-10-27" } ] } ``` ``` -------------------------------- ### Get Specific Workout Day Details (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves the complete details of a specific workout day, including all exercises ordered by sequence and historical training sessions for that day. Requires workoutPlanId and workoutDayId. ```bash # Buscar dia de treino específico curl -X GET http://localhost:8081/workout-plans/plan-uuid-123/days/day-uuid-1 \ -b cookies.txt ``` -------------------------------- ### User Data: Get Current User (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves the authenticated user's training data, including weight, height, age, and body fat percentage. Returns null if the user has not yet registered their physical data. Requires authentication via cookies. ```bash # Buscar dados do usuário curl -X GET http://localhost:8081/me \ -b cookies.txt # Resposta esperada (200 OK) - usuário com dados: { "userId": "abc123...", "userName": "João Silva", "weightInGrams": 75000, "heightInCentimeters": 178, "age": 28, "bodyFatPercentage": 18 } # Resposta esperada (200 OK) - usuário sem dados: null # Resposta de erro (401 Unauthorized): { "error": "Unauthorized", "code": "UNAUTHORIZED" } ``` -------------------------------- ### Get User Training Data Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/tasks/07.md Retrieves the training data for a specific user, including their username. If the training data does not exist, it returns null with a 200 status code. ```APIDOC ## GET /users/{userId}/train-data ### Description Retrieves the training data for a specific user, including their username. Returns null with a 200 status code if the training data does not exist. ### Method GET ### Endpoint /users/{userId}/train-data ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **userId** (string) - The unique identifier of the user. - **userName** (string) - The username of the user. - **weightInGrams** (number) - The user's weight in grams. - **heightInCentimeters** (number) - The user's height in centimeters. - **age** (number) - The user's age. - **bodyFatPercentage** (number) - The user's body fat percentage. #### Response Example (Data exists) ```json { "userId": "user123", "userName": "John Doe", "weightInGrams": 75000, "heightInCentimeters": 180, "age": 30, "bodyFatPercentage": 0.15 } ``` #### Response Example (Data does not exist) ```json null ``` ``` -------------------------------- ### Get Current User Training Data Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/tasks/07.md Retrieves the training data for the currently authenticated user. If the training data does not exist, it returns null with a 200 status code. ```APIDOC ## GET /me ### Description Retrieves the training data for the currently authenticated user. Returns null with a 200 status code if the training data does not exist. ### Method GET ### Endpoint /me ### Parameters None ### Response #### Success Response (200) - **userId** (string) - The unique identifier of the user. - **userName** (string) - The username of the user. - **weightInGrams** (number) - The user's weight in grams. - **heightInCentimeters** (number) - The user's height in centimeters. - **age** (number) - The user's age. - **bodyFatPercentage** (number) - The user's body fat percentage. #### Response Example (Data exists) ```json { "userId": "user123", "userName": "John Doe", "weightInGrams": 75000, "heightInCentimeters": 180, "age": 30, "bodyFatPercentage": 0.15 } ``` #### Response Example (Data does not exist) ```json null ``` ``` -------------------------------- ### Get User Workout Statistics (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Retrieves detailed workout statistics for a user over a specified period. This includes workout streak, daily consistency, completed workout count, and total workout time. Requires session cookies for authentication. ```bash # Buscar estatísticas do mês curl -X GET "http://localhost:8081/stats?from=2024-01-01&to=2024-01-31" \ -b cookies.txt ``` -------------------------------- ### User Authentication: Sign Up (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Registers a new user with email and password using Better-Auth. It returns user information and establishes an authenticated session. Requires 'name', 'email', and 'password' in the request body. ```bash # Criar novo usuário curl -X POST http://localhost:8081/api/auth/sign-up \ -H "Content-Type: application/json" \ -d '{ "name": "João Silva", "email": "joao@exemplo.com", "password": "senhaSegura123" }' # Resposta esperada (200 OK): { "user": { "id": "abc123...", "name": "João Silva", "email": "joao@exemplo.com", "emailVerified": false, "createdAt": "2024-01-15T10:30:00.000Z", "updatedAt": "2024-01-15T10:30:00.000Z" }, "session": { "id": "session123...", "token": "eyJ...", "expiresAt": "2024-02-15T10:30:00.000Z" } } ``` -------------------------------- ### AI Chat for Workout Plan Creation (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Initiates a chat with an AI assistant (GPT-4o-mini) to create personalized 7-day workout plans. The assistant collects user data, understands objectives, and generates plans. It can internally call tools like `getUserTrainData`, `updateUserTrainData`, `getWorkoutPlans`, and `createWorkoutPlan`. Responses are streamed as Server-Sent Events (SSE). ```bash # Iniciar conversa com IA curl -X POST http://localhost:8081/ai \ -H "Content-Type: application/json" \ -b cookies.txt \ -d '{ "messages": [ { "role": "user", "content": "Olá! Quero criar um plano de treino para ganhar massa muscular. Posso treinar 4 dias por semana." } ] }' ``` ```bash # Exemplo de mensagens subsequentes: curl -X POST http://localhost:8081/ai \ -H "Content-Type: application/json" \ -b cookies.txt \ -d '{ "messages": [ { "role": "user", "content": "Olá!" }, { "role": "assistant", "content": "Olá! Para criar seu plano personalizado, preciso de algumas informações: nome, peso (kg), altura (cm), idade e percentual de gordura corporal." }, { "role": "user", "content": "Me chamo João, tenho 28 anos, peso 75kg, 178cm de altura e 18% de gordura" } ] }' ``` -------------------------------- ### Workout Plans: List All (Bash) Source: https://context7.com/geilsonssantos/ia-de-treino/llms.txt Lists all workout plans for the authenticated user. Supports filtering by active or inactive plans using the 'active' query parameter. Plans are returned in descending order of creation. Requires authentication via cookies. ```bash # Listar todos os planos curl -X GET http://localhost:8081/workout-plans \ -b cookies.txt # Listar apenas planos ativos curl -X GET "http://localhost:8081/workout-plans?active=true" \ -b cookies.txt ``` -------------------------------- ### GET /stats Source: https://github.com/geilsonssantos/ia-de-treino/blob/master/tasks/06.md Retrieves workout statistics for the authenticated user within a specified date range. Requires authentication. ```APIDOC ## GET /stats ### Description This endpoint returns statistics for the authenticated user regarding completed and initiated workouts within a specified period. ### Method GET ### Endpoint /stats ### Query Parameters - **from** (string) - Required - The start date for the statistics period in YYYY-MM-DD format. - **to** (string) - Required - The end date for the statistics period in YYYY-MM-DD format. ### Request Example ``` GET /stats?from=2023-01-01&to=2023-01-31 ``` ### Response #### Success Response (200) - **workoutStreak** (number) - The number of consecutive days the user completed a workout. - **consistencyByDay** (object) - An object where keys are dates (YYYY-MM-DD) and values indicate workout status for that day. - **workoutDayCompleted** (boolean) - True if a workout was completed on this day. - **workoutDayStarted** (boolean) - True if a workout was started on this day. - **completedWorkoutsCount** (number) - The total number of completed workouts within the period. - **conclusionRate** (number) - The rate of completed workouts (completedWorkoutsCount / total sessions). - **totalTimeInSeconds** (number) - The total time spent in completed workouts, in seconds. #### Response Example ```json { "workoutStreak": 5, "consistencyByDay": { "2023-01-01": { "workoutDayCompleted": true, "workoutDayStarted": true }, "2023-01-02": { "workoutDayCompleted": false, "workoutDayStarted": true } }, "completedWorkoutsCount": 10, "conclusionRate": 0.8, "totalTimeInSeconds": 3600 } ``` ```