### Install Dependencies for Testing Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/ci-cd-setup.md Run this command to install necessary dependencies before testing reporting scripts locally. ```bash # Install dependencies npm install ``` -------------------------------- ### Manage PWA Installation Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/PWA.md Provides methods to check if the PWA can be installed, prompt the user for installation, and listen for changes in installation availability. Requires the `pwaInstallManager` service. ```typescript import { pwaInstallManager } from "@/services/pwa"; // Check if app can be installed const canInstall = pwaInstallManager.canInstall(); // Prompt user to install const success = await pwaInstallManager.promptInstall(); // Listen for install availability const unsubscribe = pwaInstallManager.onInstallAvailable((canInstall) => { console.log("Install available:", canInstall); }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/BACKGROUND_SYNC_TESTING_README.md Run this command to install project dependencies when encountering 'Cannot find module' errors. ```bash npm install ``` -------------------------------- ### Start Development Server Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/getting-started.md Use this command to start the development server for active development. It enables hot-reloading and other development-specific features. ```bash npm run dev ``` ```bash npm run dev:nightly ``` ```bash npm run dev:prod ``` -------------------------------- ### Create Demo Hook Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/demo/README.md Provides an example of how to create a demo hook. It demonstrates simulating real hook behavior with mock data scenarios. ```ts import { useState } from "react"; // Assuming DemoScenario and getMockData are defined elsewhere // type DemoScenario = "scenario1" | "scenario2"; // const getMockData = (scenario: DemoScenario) => { /* ... */ }; export const useMyFeatureDemo = (scenario: DemoScenario) => { const [data, setData] = useState(getMockData(scenario)); return { data, actions: { simulate: () => { /* mock action */ }, }, }; }; ``` -------------------------------- ### Service Layer: Starting a Session Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/architecture/overview.md Example of a service layer method responsible for starting a new session. It includes business logic, local storage updates, and synchronization with a remote API. ```typescript // Service Layer Example export class SessionService { static async startSession(userId: string): Promise { const session = { id: generateId(), userId, startTime: new Date(), status: 'active', // ... business logic here }; // Save to local storage first (optimistic) await DexieStorage.sessions.add(session); // Sync to Firebase await FirebaseAPI.sessions.create(session); return session; } } ``` -------------------------------- ### PWA Install Manager Service Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/PWA_IMPLEMENTATION_SUMMARY.md Manages the PWA installation lifecycle, including detecting installation availability and triggering the install prompt. Subscribe to install events for UI feedback. ```typescript // Features: // `canInstall()`: Check if app can be installed // `promptInstall()`: Show install prompt to user // `onInstallAvailable()`: Subscribe to install availability changes // `onAppInstalled()`: Subscribe to installation events ``` -------------------------------- ### Create Demo Component Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/demo/README.md Illustrates the basic structure for creating a demo component. It shows how to import and use mock data from demo hooks. ```tsx import React from "react"; import { useMyFeatureDemo } from "../hooks/useMyFeatureDemo"; export const MyFeatureDemo: React.FC = () => { const { mockData, actions } = useMyFeatureDemo(); return
{/* Demo UI */}
; }; ``` -------------------------------- ### Notification Metadata Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/services/notifications/README.md This example shows the structure of metadata included with all notifications, useful for navigation, context, and logging. ```typescript { taskId: 'task-123', type: 'task_assigned', link: '/tasks/task-123', // ... additional metadata } ``` -------------------------------- ### Service: SessionService.startSession Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/architecture/directory-structure.md Handles the business logic for starting a session, involving both local storage and remote API calls. ```javascript export class SessionService { static async startSession(data) { await DexieStorage.sessions.add(data); return await FirebaseAPI.sessions.create(data); } } ``` -------------------------------- ### Point Calculation Examples Source: https://github.com/thef4tdaddy/chastityos/blob/main/IMPLEMENTATION_SUMMARY.md Demonstrates point calculations based on task priority, bonuses for evidence, and early completion. ```plaintext 1. Medium priority, no bonuses: 10 points 2. High priority + evidence: 25 points 3. Critical + evidence + early: 40 points ``` -------------------------------- ### Run Unit Tests for GoalTrackerService Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/goal-tracking-implementation.md Execute the unit tests specifically for the GoalTrackerService. Ensure you have the project dependencies installed. ```bash npm run test:unit -- src/services/__tests__/GoalTrackerService.test.ts ``` -------------------------------- ### Optimize Queries with Indexing Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/security/firebase-rules.md Use efficient queries with proper indexing to retrieve data quickly. This example demonstrates a query for recent sessions, leveraging a composite index on userId and startTime. ```javascript // Use efficient queries with proper indexing function getRecentSessions(userId) { // This query uses composite index: userId + startTime (desc) return query(/databases/$(database)/documents/users/$(userId)/sessions) .where('userId', '==', userId) .orderBy('startTime', 'desc') .limit(10); } ``` -------------------------------- ### Implementing Push Notifications Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/services/notifications/README.md This example demonstrates how to integrate push notifications within existing notification methods. It requires uncommenting and implementing `sendPushNotification` and integrating with a push service like FCM. ```typescript // In each notification method, add: await this.sendPushNotification({ userId: params.userId, title: "Task Assigned", body: "You have a new task...", data: { taskId: params.taskId }, }); ``` -------------------------------- ### Good vs. Bad UI Component Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/architecture/directory-structure.md Illustrates the correct placement of UI rendering and event handling in the components layer, contrasting it with business logic that should reside elsewhere. ```javascript // ✅ GOOD: Pure UI component function SessionTracker({ session, onStart, onPause }) { return (
); } // ❌ BAD: Business logic in component function SessionTracker() { const startSession = async () => { const data = { /* session data */ }; await firebase.firestore().collection("sessions").add(data); // NO! }; } ``` -------------------------------- ### startSession Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/api/services/session-service.md Starts a new chastity session with optimistic updates. It creates an immediate optimistic session, syncs to Firebase in the background, and handles conflicts. ```APIDOC ## startSession(data: StartSessionData): Promise ### Description Starts a new chastity session with optimistic updates. It creates an immediate optimistic session, syncs to Firebase in the background, and handles conflicts. ### Method N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **userId** (string) - Required - The user's Firebase UID - **goalDuration** (number) - Optional - The goal duration in milliseconds - **keyholderRequired** (boolean) - Optional - Whether a keyholder is required - **notes** (string) - Optional - Additional notes for the session ### Request Example ```typescript const session = await SessionService.startSession({ userId: "user123", goalDuration: 24 * 60 * 60 * 1000, // 24 hours keyholderRequired: true, notes: "Starting new challenge", }); ``` ### Response #### Success Response - **session** (ChastitySession) - The created session #### Response Example ```json { "id": "optimistic_session_id", "userId": "user123", "startTime": "2024-01-01T10:00:00Z", "endTime": null, "status": "active", "goalDuration": 86400000, "keyholderRequired": true, "notes": "Starting new challenge" } ``` ``` -------------------------------- ### JSDoc for startSession Method Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/contributing/guidelines.md Documents the startSession method, detailing its purpose, parameters, return value, potential errors, and includes an example of its usage. This is intended for API documentation. ```typescript /** * Starts a new chastity session with optimistic updates * * @param data - Session configuration data * @returns Promise that resolves to the created session * @throws SessionServiceError when validation fails or user has active session * * @example * ```typescript * const session = await SessionService.startSession({ * userId: 'user123', * goalDuration: 24 * 60 * 60 * 1000 // 24 hours * }); * ``` */ async startSession(data: StartSessionData): Promise { // Implementation... } ``` -------------------------------- ### Import React Query DevTools Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/KEYHOLDER_PERFORMANCE_OPTIMIZATIONS.md Import React Query DevTools to monitor cache effectiveness. Ensure React Query is installed and configured in your project. ```typescript import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; ``` -------------------------------- ### UI-Only Component Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/contributing/guidelines.md Demonstrates a correct UI-only component that uses custom hooks for data fetching and mutations. Business logic should be handled outside of components. ```typescript // ✅ CORRECT: UI-only component function SessionTracker() { const { data: session, isLoading } = useCurrentSession(); const { mutate: startSession } = useStartSessionMutation(); if (isLoading) return ; return (
); } ``` ```typescript // ❌ INCORRECT: Business logic in component function SessionTracker() { const [session, setSession] = useState(null); const startSession = async () => { // This belongs in a service! const sessionData = { /* ... */ }; await firebase.firestore().collection('sessions').add(sessionData); setSession(sessionData); }; return ; } ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/contributing/guidelines.md Follow the Conventional Commits specification for formatting commit messages. Use appropriate types like 'feat', 'fix', 'docs', etc. ```bash # Format: type(scope): description git commit -m "feat(sessions): add pause cooldown functionality" git commit -m "fix(auth): resolve Firebase connection timeout" git commit -m "docs(api): update SessionService documentation" git commit -m "refactor(storage): optimize Dexie query performance" git commit -m "test(hooks): add unit tests for useCurrentSession" ``` -------------------------------- ### Handle Database Session Start Errors Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/services/database/README.md Use a try-catch block to handle potential errors during session startup. Detailed error logging is automatically managed by the service. ```typescript try { await sessionDBService.startSession(userId); } catch (error) { // Detailed error logging is handled automatically console.error("Failed to start session:", error); } ``` -------------------------------- ### Initialize Keyholder System Branch Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/COMPLETE_PR_MERGE_STRATEGY.md Sets up the main integration branch for the keyholder system and outlines the initial merge order for core components. ```bash git checkout -b feature/keyholder-system-complete # Merge order: 1. PR #132 - Firebase schema as foundation 2. PR #136 - Security features integration 3. PR #143 - Dexie and React layer # Result: Working keyholder system with advanced features ``` -------------------------------- ### Add Resource Hints in HTML Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/PHASE4_IMPLEMENTATION_GUIDE.md Include resource hints like `` and `` in your `index.html` to optimize the loading of external resources. These hints help the browser establish early connections to critical origins. ```html ``` -------------------------------- ### Notify Session Started Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/services/notifications/README.md Notifies the keyholder of a session start. Requires session, user, and keyholder IDs, and the submissive's name. ```typescript await NotificationService.notifySessionStarted({ sessionId: 'session-123', userId: 'user-123', keyholderUserId: 'keyholder-456', submissiveName: 'Pet', }); ``` -------------------------------- ### Build and Analyze Bundle Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/BUNDLE_OPTIMIZATION.md Use these commands to build your project with statistics enabled, check the resulting bundle sizes, and open an interactive bundle composition report. ```bash # Build with stats npm run build ``` ```bash # Check bundle sizes ls -lh dist/assets/ ``` ```bash # Analyze bundle composition open dist/bundle-report.html ``` -------------------------------- ### Basic Dual-Account System - Week 1-2 Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/SIMPLIFIED_KEYHOLDER_STRATEGY.md This outlines the foundational steps for a basic dual-account system, focusing on account linking and initial functionality. ```typescript // Simple account linking 1. Submissive generates link code 2. Keyholder uses code to establish relationship 3. Keyholder gets read-only dashboard 4. Basic task assignment functionality ``` -------------------------------- ### Playwright E2E Test Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/testing.md Example of an end-to-end test using Playwright. It navigates to a page, waits for network activity, and asserts the visibility of an element after a user action. ```typescript import { test, expect } from "@playwright/test"; test("user can complete a workflow", async ({ page }) => { await page.goto("/"); await page.waitForLoadState("networkidle"); // Test user workflow await page.click('[data-testid="start-button"]'); await expect(page.locator(".success-message")).toBeVisible(); }); ``` -------------------------------- ### React Component Test Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/testing.md Example of a component test using @testing-library/react and Vitest. It demonstrates rendering a component and verifying user interactions like button clicks. ```typescript import { render, screen, fireEvent } from '@testing-library/react'; import { ExampleComponent } from '../ExampleComponent'; describe('ExampleComponent', () => { it('should handle user interactions', () => { const mockClick = vi.fn(); render(); fireEvent.click(screen.getByRole('button')); expect(mockClick).toHaveBeenCalled(); }); }); ``` -------------------------------- ### Run All Tests and CI Pipeline with npm Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/testing.md Execute the complete test suite or the CI pipeline using predefined npm scripts. ```bash # Run complete test suite npm run test:all ``` ```bash # Run CI pipeline npm run ci ``` -------------------------------- ### Build Verification Command Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/BUNDLE_OPTIMIZATION.md Run this command to build the project and verify that bundle splitting and size targets are met. ```bash npm run build ``` -------------------------------- ### Vitest Unit Test Example Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/testing.md Example of a unit test using Vitest. It includes importing testing utilities and defining test cases with assertions for a formatting function. ```typescript import { describe, it, expect } from "vitest"; import { formatElapsedTime } from "../utils/formatting/time"; describe("formatElapsedTime", () => { it("should format seconds correctly", () => { expect(formatElapsedTime(30)).toBe("30s"); expect(formatElapsedTime(90)).toBe("01m 30s"); }); it("should handle edge cases", () => { expect(formatElapsedTime(0)).toBe("0s"); expect(formatElapsedTime(-10)).toBe("0s"); }); }); ``` -------------------------------- ### Build Project Artifacts Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/getting-started.md Commands to build the project for different environments. Use these to generate deployable artifacts. ```bash npm run build ``` ```bash npm run build:nightly ``` ```bash npm run build:production ``` -------------------------------- ### Service Layer: Starting a Session Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/architecture/directory-structure.md Demonstrates a typical service layer function that handles data validation, local storage operations, and Firebase synchronization for starting a new session. ```typescript // ✅ GOOD: Service layer export class SessionService { static async startSession(data: StartSessionData): Promise { // 1. Validate data this.validateSessionData(data); // 2. Save to local storage (optimistic) const localSession = await DexieStorage.sessions.add(data); // 3. Sync to Firebase const firebaseSession = await FirebaseAPI.sessions.create(data); return firebaseSession; } } ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/thef4tdaddy/chastityos/blob/main/VERSIONING.md Examples of conventional commit messages used for automating changelogs and versioning. 'feat:' typically triggers a minor version bump, 'fix:' a patch bump, and 'chore:'/'docs:'/'style:' usually do not. ```git feat: add keyholder rewards page fix: correct session timer rounding chore: update eslint config ``` -------------------------------- ### Run Build Command Source: https://github.com/thef4tdaddy/chastityos/blob/main/TRACKER_ACCESSIBILITY_IMPLEMENTATION.md Executes the build process for the project. This command is used to compile and bundle the application for deployment. ```bash npm run build ✓ built in 21.37s ``` -------------------------------- ### Require Centralized Error Logging Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/tools/eslint-rules.md This rule mandates that all errors be logged using a centralized logger utility instead of direct console methods. The 'Bad' example uses `console.log` within a catch block, while the 'Good' example utilizes a `logger.error` function. ```javascript // ❌ Bad - Direct console.log catch (error) { console.log('Error:', error); // Should use logger } // ✅ Good - Using logger utility catch (error) { logger.error('Failed to start session', error); } ``` -------------------------------- ### Preview Production Build Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/getting-started.md This command allows you to preview the production build locally before deploying it. It helps in verifying the final output. ```bash npm run preview ``` -------------------------------- ### Require Service Layer for Firebase Calls Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/tools/eslint-rules.md This rule ensures all Firebase interactions are abstracted through a service layer for consistency. The 'Bad' example shows a direct Firebase call in a useEffect hook, while the 'Good' example uses a custom hook that abstracts the Firebase call. ```javascript // ❌ Bad - Direct Firebase call useEffect(() => { firebase.firestore().collection("sessions").get().then(setData); }, []); // ✅ Good - Using service layer const { data } = useSessionsQuery(); ``` -------------------------------- ### Build Project Versions Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/getting-started.md Build the nightly and production versions of the project. Use `npm run health-check` to verify the application's health after building. ```bash # Build nightly version npm run build:nightly # Build production version npm run build:production # Run health check npm run health-check ``` -------------------------------- ### Avoid Business Logic in Components Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/tools/eslint-rules.md This rule enforces that components should only handle UI and delegate business logic to a service layer. The 'Bad' example shows logic directly within a component, while the 'Good' example demonstrates using a custom hook or service for the logic. ```javascript // ❌ Bad - Business logic in component function SessionTracker() { const [session, setSession] = useState(null); const startSession = async () => { // Business logic should not be here const sessionData = { id: generateId(), startTime: new Date(), userId: getCurrentUser().id, }; await firebase.firestore().collection("sessions").add(sessionData); setSession(sessionData); }; return ; } // ✅ Good - Using service layer function SessionTracker() { const { mutate: startSession } = useStartSessionMutation(); return ; } ``` -------------------------------- ### Serve Local Build with HTTPS Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/DEPLOYMENT_FCM_CHECKLIST.md Use this command to serve your local build with HTTPS for testing push notification functionality. Ensure you have the necessary SSL certificate files. ```bash npx serve dist -s --ssl-cert localhost.pem --ssl-key localhost-key.pem ``` -------------------------------- ### NotificationService.notifySessionStarted Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/services/notifications/README.md Notifies the keyholder of a session start. Includes session and user details. ```APIDOC ## NotificationService.notifySessionStarted ### Description Notifies keyholder of session start/pause/resume. ### Method Not explicitly defined, but implies an SDK call. ### Endpoint Not applicable (SDK method). ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body None. ### Parameters - **sessionId** (string) - Required - The ID of the session. - **userId** (string) - Required - The ID of the user. - **keyholderUserId** (string) - Required - The ID of the keyholder. - **submissiveName** (string) - Required - The name of the submissive. ``` -------------------------------- ### Component: Session Tracker Button Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/architecture/directory-structure.md A React component that initiates a session start mutation when a button is clicked. ```javascript function SessionTracker() { const { mutate: startSession } = useStartSessionMutation(); return ; } ``` -------------------------------- ### Run Tests Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/development/getting-started.md Commands for executing the test suite. Includes options for watch mode, coverage reports, and the full test suite. ```bash npm run test ``` ```bash npm run test:watch ``` ```bash npm run test:coverage ``` ```bash npm run test:full ``` -------------------------------- ### Common Performance Feedback Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/contributing/guidelines.md An example of performance-related feedback during code review, recommending the use of `useCallback` to optimize re-renders. ```markdown # Performance feedback "Consider using useCallback here to prevent unnecessary re-renders." ``` -------------------------------- ### Migrate Authentication & Settings: Current State Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/features/feature-migration-strategy.md Demonstrates the current approach to authentication and settings management using separate hooks. ```javascript // Current: useAuth.js and useSettings.js const { user, signIn, signOut } = useAuth(); const { settings, updateSettings } = useSettings(); ``` -------------------------------- ### Get Session Trends Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/api/services/session-service.md Fetches session trend data, suitable for charting. Granularity can be 'daily', 'weekly', or 'monthly'. ```typescript const trends = await SessionService.getSessionTrends("user123", "daily"); ``` -------------------------------- ### Setup Hover Prefetching for Navigation Links Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/PHASE4_IMPLEMENTATION_GUIDE.md Enable prefetching of linked resources when a user hovers over a navigation link. This involves using `useRef` and `useEffect` to attach the `prefetchService.setupHoverPrefetch` listener to the anchor element. ```typescript import { prefetchService } from '@/services/performance'; import { useRef, useEffect } from 'react'; function NavigationLink({ to, children }) { const linkRef = useRef(null); useEffect(() => { if (linkRef.current) { prefetchService.setupHoverPrefetch(linkRef.current, to); } }, [to]); return ( {children} ); } ``` -------------------------------- ### Get Current Performance Metrics Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/utils/performance/README.md Retrieve the current performance metrics asynchronously. This can be used to access collected data at any point. ```typescript import { getCurrentMetrics } from './utils/performance/webVitals'; const metrics = await getCurrentMetrics(); console.log('Current metrics:', metrics); // Output: { ttfb: 120, fcp: 850, domContentLoaded: 100, ... } ``` -------------------------------- ### Common Architectural Feedback Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/contributing/guidelines.md Provides an example of architectural feedback during code review, suggesting the separation of business logic from UI components. ```markdown # Architectural feedback "This business logic should be moved to a service. Components should only handle UI." ``` -------------------------------- ### Example Git Merge and Conflict Resolution Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/COMPLETE_PR_MERGE_STRATEGY.md Demonstrates the basic Git commands for merging a branch and resolving conflicts. Use 'git status' to identify conflicted files and manually resolve them before committing. ```bash git merge origin/pr-branch-name # If conflicts: git status # See conflicted files # Manually resolve, preferring best-of-breed features git add resolved-files git commit -m "Merge PR #XXX: description + resolution notes" ``` -------------------------------- ### Configure Playwright Timeout Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/BACKGROUND_SYNC_TESTING_README.md Increase the E2E test timeout in playwright.config.ts to prevent timeouts. This example sets the timeout to 2 minutes. ```typescript timeout: 120 * 1000 # 2 minutes ``` -------------------------------- ### Run Store Tests Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/stores/README.md Execute unit tests for all stores using npm. ```bash npm test -- stores ``` -------------------------------- ### useStartSessionMutation Hook Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/api/services/session-service.md A custom hook that provides a mutation function to start a new session, including optimistic updates and error handling. ```APIDOC ## useStartSessionMutation() ### Description Provides a mutation hook to initiate a new session. It includes optimistic UI updates and handles success and error scenarios for a seamless user experience. ### Usage ```typescript import { useStartSessionMutation } from './sessionService'; function StartSessionButton() { const { mutate: startSession, isLoading } = useStartSessionMutation(); const handleStartSession = () => { startSession({ userId: 'user123', deviceType: 'mobile' }); }; return ( ); } ``` ### Mutation Function (`mutationFn`) Calls `SessionService.startSession`. ### Callbacks - **onMutate**: Handles optimistic updates before the mutation is sent. - **onSuccess**: Updates the cache with the actual data upon successful mutation. - **onError**: Rolls back optimistic updates if the mutation fails. ``` -------------------------------- ### Get Personal Goal Progress Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/goal-tracking-implementation.md Retrieve the progress of a personal goal using the user ID. Calculates and logs the completion percentage. ```typescript import { usePersonalGoalQuery } from '@/hooks/api/usePersonalGoalQueries'; const { data: goal } = usePersonalGoalQuery(userId); if (goal) { const progress = (goal.currentValue / goal.targetValue) * 100; console.log(`Goal is ${progress.toFixed(1)}% complete`); } ``` -------------------------------- ### Integrate Service Layers for Keyholder System Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/COMPLETE_PR_MERGE_STRATEGY.md Lists the service layers to be integrated for the keyholder system, aiming for a unified API and offline capabilities. ```bash # Integrate service layers - KeyholderSystemService (unified) - AccountLinkingService (from #136) - RelationshipService (from #132) - OfflineSyncService (from #143) ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/TESTING_SUMMARY.md Execute all defined unit tests for the project. ```bash npm run test:unit ``` -------------------------------- ### Common Style Feedback Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/contributing/guidelines.md An example of style feedback during code review, promoting the use of a consistent error handling pattern with a logger utility. ```markdown # Style feedback "Let's use the consistent error handling pattern with our logger utility." ``` -------------------------------- ### Run Tests Source: https://github.com/thef4tdaddy/chastityos/blob/main/IMPLEMENTATION_SUMMARY.md Execute the test suite for the project. This command verifies the functionality and stability of the codebase. ```bash npm test ✓ 9 tests passing ✓ 0 tests failing ``` -------------------------------- ### Initialize Web Vitals Tracking Source: https://github.com/thef4tdaddy/chastityos/blob/main/src/utils/performance/README.md Call this function when the application loads to start tracking Core Web Vitals. It is automatically initialized in `src/main.tsx`. ```typescript import { initWebVitals } from './utils/performance/webVitals'; // Initialize when app loads initWebVitals(); ``` -------------------------------- ### Unit Test for SessionService Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/contributing/guidelines.md Tests the SessionService for starting a session with valid data and handling invalid data scenarios. Requires the SessionService to be imported. ```typescript describe("SessionService", () => { it("should start session with valid data", async () => { const mockData = { userId: "test-user" }; const result = await SessionService.startSession(mockData); expect(result.status).toBe("active"); expect(result.userId).toBe("test-user"); }); it("should throw error for invalid data", async () => { const invalidData = { userId: "" }; await expect(SessionService.startSession(invalidData)).rejects.toThrow( "Invalid user ID", ); }); }); ``` -------------------------------- ### Run Unit Tests Source: https://github.com/thef4tdaddy/chastityos/blob/main/docs/PERIODIC_BACKGROUND_SYNC.md Executes unit tests for the periodic sync service. Ensure you are in the project root directory. ```bash npm run test:unit -- src/services/sync/__tests__/PeriodicSyncService.test.ts ```