> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sagozen.digital/llms.txt
> Use this file to discover all available pages before exploring further.

# Installation Guide

> Complete guide to setting up the Pet Service Management System locally

# Installation Guide

This guide walks you through setting up the Pet Service Management System on your local development environment.

<Note>
  **Prerequisites:** Node.js 18+, PostgreSQL 12+, Git
</Note>

## Quick Start

### 1. Clone the Repository

```bash theme={null}
git clone <repository-url>
cd pet-service
```

### 2. Install Dependencies

<Tabs>
  <Tab title="Backend">
    ```bash theme={null}
    cd backend
    npm install
    ```
  </Tab>

  <Tab title="Frontend">
    ```bash theme={null}
    cd frontend
    npm install
    ```
  </Tab>
</Tabs>

***

## Backend Setup

### Step 1: Environment Configuration

Create a `.env` file in the `backend/` directory:

```bash .env theme={null}
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/petservice

# Application
NODE_ENV=development
PORT=3001

# Better Auth Configuration
BETTER_AUTH_URL=http://localhost:3001/api/auth
BETTER_AUTH_SECRET=your-better-auth-secret-here-min-32-chars
SESSION_SECRET=your-session-secret-here-min-32-chars
JWT_SECRET=your-jwt-secret-here-min-32-chars

# CORS
FRONTEND_URL=http://localhost:3000

# Email (Optional for development)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=noreply@example.com
SMTP_PASS=your-email-password
```

<Warning>
  **Security:** Use strong, unique secrets for production. Generate with:

  ```bash theme={null}
  openssl rand -base64 32
  ```
</Warning>

### Step 2: Database Setup

<Steps>
  <Step title="Create PostgreSQL Database">
    ```bash theme={null}
    # Using psql
    psql -U postgres
    CREATE DATABASE petservice;
    \q
    ```
  </Step>

  <Step title="Generate Prisma Client">
    ```bash theme={null}
    cd backend
    npm run prisma:generate
    ```
  </Step>

  <Step title="Apply Database Schema">
    ```bash theme={null}
    npm run prisma:db:push
    ```

    This creates all tables, indexes, and constraints defined in `prisma/schema.prisma`.
  </Step>

  <Step title="Verify Database">
    ```bash theme={null}
    npm run prisma:studio
    ```

    Opens Prisma Studio at `http://localhost:5555` to inspect your database.
  </Step>
</Steps>

### Step 3: Seed Database (Optional)

<Info>
  Seeding creates sample data for development and testing.
</Info>

```bash theme={null}
cd backend
npm run prisma:db:seed
```

**Seed Data Includes:**

* Admin user (email: `admin@example.com`, password: `admin123`)
* Manager user (email: `manager@example.com`, password: `manager123`)
* Staff user (email: `staff@example.com`, password: `staff123`)
* Customer users
* 6 service categories (Boarding, Grooming, Veterinary, Training, Daycare, Transport)
* Sample pets
* Sample bookings

### Step 4: Start Backend Server

```bash theme={null}
cd backend
npm run start:dev
```

<Check>
  Backend running at `http://localhost:3001`
</Check>

**Verify Backend:**

```bash theme={null}
curl http://localhost:3001/health
# Expected: {"status":"ok","timestamp":"..."}
```

***

## Frontend Setup

### Step 1: Environment Configuration

Create a `.env.local` file in the `frontend/` directory:

```bash .env.local theme={null}
# API Configuration
NEXT_PUBLIC_API_URL=http://localhost:3001

# Application URL
NEXT_PUBLIC_APP_URL=http://localhost:3000

# Better Auth (if using OAuth)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
```

### Step 2: Start Frontend Server

```bash theme={null}
cd frontend
npm run dev
```

<Check>
  Frontend running at `http://localhost:3000`
</Check>

**Test the Application:**

1. Open `http://localhost:3000` in your browser
2. Navigate to `/en` or `/vi` for localized content
3. Try logging in with seeded credentials

***

## Database Management

### Common Commands

<CodeGroup>
  ```bash Generate Prisma Client theme={null}
  cd backend
  npm run prisma:generate
  ```

  ```bash Apply Schema Changes theme={null}
  npm run prisma:db:push
  ```

  ```bash Create Migration theme={null}
  npm run prisma:migrate dev --name migration_name
  ```

  ```bash Reset Database theme={null}
  npm run prisma:migrate reset
  # ⚠️ Warning: This deletes all data
  ```

  ```bash Open Prisma Studio theme={null}
  npm run prisma:studio
  # Opens at http://localhost:5555
  ```

  ```bash Seed Database theme={null}
  npm run prisma:db:seed
  ```
</CodeGroup>

### Database Schema

The database includes the following main entities:

<AccordionGroup>
  <Accordion title="User & Authentication">
    * **User**: Core user accounts with roles (ADMIN, MANAGER, STAFF, CUSTOMER)
    * **Session**: Active user sessions
    * **Account**: OAuth provider accounts
    * **Verification**: Email verification tokens
  </Accordion>

  <Accordion title="Booking System">
    * **Booking**: Main booking records with status tracking
    * **BookingPet**: Junction table linking bookings to pets
    * **BookingService**: Junction table linking bookings to services with pricing
  </Accordion>

  <Accordion title="Pet Management">
    * **Pet**: Pet profiles with medical history, vaccinations, allergies
    * Supports multiple images
    * JSON-based vaccination records
  </Accordion>

  <Accordion title="Service & Staff">
    * **Service**: Service catalog with JSONB multi-language fields
    * **Staff**: Employee profiles with working hours and specializations
    * **StaffService**: Junction table with proficiency levels
  </Accordion>

  <Accordion title="System">
    * **Setting**: Key-value configuration store with JSONB values
    * **AuditLog**: Complete audit trail of user actions
  </Accordion>
</AccordionGroup>

***

## Environment Variables Reference

### Backend Environment Variables

| Variable             | Required | Description                    | Example                                    |
| -------------------- | -------- | ------------------------------ | ------------------------------------------ |
| `DATABASE_URL`       | ✅        | PostgreSQL connection string   | `postgresql://user:pass@localhost:5432/db` |
| `NODE_ENV`           | ✅        | Environment mode               | `development`, `production`                |
| `PORT`               | ✅        | Backend server port            | `3001`                                     |
| `BETTER_AUTH_URL`    | ✅        | Better Auth endpoint           | `http://localhost:3001/api/auth`           |
| `BETTER_AUTH_SECRET` | ✅        | Better Auth secret (32+ chars) | Generated string                           |
| `SESSION_SECRET`     | ✅        | Session encryption secret      | Generated string                           |
| `JWT_SECRET`         | ✅        | JWT signing secret             | Generated string                           |
| `FRONTEND_URL`       | ✅        | Frontend URL for CORS          | `http://localhost:3000`                    |
| `SMTP_HOST`          | ❌        | Email server host              | `smtp.gmail.com`                           |
| `SMTP_PORT`          | ❌        | Email server port              | `587`                                      |
| `SMTP_USER`          | ❌        | Email username                 | `noreply@example.com`                      |
| `SMTP_PASS`          | ❌        | Email password                 | Your password                              |

### Frontend Environment Variables

| Variable               | Required | Description            | Example                 |
| ---------------------- | -------- | ---------------------- | ----------------------- |
| `NEXT_PUBLIC_API_URL`  | ✅        | Backend API URL        | `http://localhost:3001` |
| `NEXT_PUBLIC_APP_URL`  | ✅        | Frontend app URL       | `http://localhost:3000` |
| `GOOGLE_CLIENT_ID`     | ❌        | Google OAuth client ID | From Google Console     |
| `GOOGLE_CLIENT_SECRET` | ❌        | Google OAuth secret    | From Google Console     |
| `GITHUB_CLIENT_ID`     | ❌        | GitHub OAuth client ID | From GitHub Settings    |
| `GITHUB_CLIENT_SECRET` | ❌        | GitHub OAuth secret    | From GitHub Settings    |

***

## Code Quality & Testing

### Linting & Formatting

<CodeGroup>
  ```bash Backend theme={null}
  cd backend
  npm run lint          # ESLint check
  npm run format        # Prettier format
  ```

  ```bash Frontend theme={null}
  cd frontend
  npm run lint          # ESLint check
  ```
</CodeGroup>

### Type Checking

```bash theme={null}
# Backend
cd backend
tsc --noEmit

# Frontend
cd frontend
tsc --noEmit
```

### Running Tests

<Tabs>
  <Tab title="Backend">
    ```bash theme={null}
    cd backend

    # Unit tests
    npm run test

    # Watch mode
    npm run test:watch

    # Coverage report
    npm run test:cov

    # E2E tests
    npm run test:e2e
    ```
  </Tab>

  <Tab title="Frontend">
    ```bash theme={null}
    cd frontend

    # Lint check
    npm run lint
    ```
  </Tab>
</Tabs>

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Database Connection Error">
    **Problem:** `connect ECONNREFUSED 127.0.0.1:5432`

    **Solution:**

    1. Ensure PostgreSQL is running: `brew services start postgresql` (macOS)
    2. Check `DATABASE_URL` in `.env`
    3. Verify credentials: `psql -U postgres`
    4. Check PostgreSQL logs: `tail -f /usr/local/var/log/postgres.log`
  </Accordion>

  <Accordion title="Port Already in Use">
    **Problem:** `Error: listen EADDRINUSE: address already in use :::3000`

    **Solution:**

    ```bash theme={null}
    # Kill process on port (macOS/Linux)
    lsof -ti:3000 | xargs kill -9

    # Or use different port
    PORT=3002 npm run dev
    ```
  </Accordion>

  <Accordion title="Missing Environment Variables">
    **Problem:** Application crashes with undefined env variables

    **Solution:**

    1. Copy example env files to `.env` / `.env.local`
    2. Ensure all required variables are set
    3. Restart development server
  </Accordion>

  <Accordion title="Prisma Client Not Generated">
    **Problem:** `PrismaClient not found`

    **Solution:**

    ```bash theme={null}
    cd backend
    npm run prisma:generate
    ```
  </Accordion>

  <Accordion title="Module Not Found">
    **Problem:** `Cannot find module 'xxx'`

    **Solution:**

    ```bash theme={null}
    # Delete node_modules and reinstall
    rm -rf node_modules package-lock.json
    npm install
    ```
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Architecture Overview" icon="diagram-project" href="/architecture">
    Understand system design and data flow
  </Card>

  <Card title="Deployment Guide" icon="rocket" href="/deployment">
    Deploy to production with Docker or Railway
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore REST API endpoints
  </Card>

  <Card title="Back to Home" icon="home" href="/">
    Return to homepage
  </Card>
</CardGroup>

***

<Note>
  **Need Help?** Check [Troubleshooting](#troubleshooting) or reach out to [support@petservice.example.com](mailto:support@petservice.example.com)
</Note>
