# Marketplace

A full-stack online marketplace and rental platform where users can buy, sell, and rent items ranging from electronics and furniture to apartments, cars, and bicycles. The platform includes real-time chat, an offer/negotiation system, Stripe-powered payments, and a multi-role admin panel with content moderation.

## Tech Stack

| Layer          | Technology                                           |
|----------------|------------------------------------------------------|
| **Client**     | React 19, TypeScript, Tailwind CSS 4, Vite 6         |
| **Routing**    | React Router 7                                       |
| **Server**     | Express 4, TypeScript, tsx (dev runner)               |
| **Database**   | PostgreSQL 17 (Docker), Prisma ORM 6                 |
| **Auth**       | JWT (access + refresh tokens), bcryptjs               |
| **Payments**   | Stripe (PaymentIntents, Connect, Webhooks)            |
| **Real-time**  | Socket.io 4 (notifications, chat)                    |
| **File Upload**| Multer (local storage)                               |
| **Validation** | Zod                                                  |
| **Charts**     | Recharts 3 (admin dashboard)                         |
| **Icons**      | Lucide React                                         |

## Features

- **Listings** -- Create, browse, search, and filter buy/sell listings across categories (Electronics, Furniture, Clothing, Vehicles, etc.)
- **Offers & Negotiation** -- Make offers, counter, accept, or decline with real-time notifications
- **Rentals** -- Full rental system for apartments, houses, cars, motorcycles, bicycles, and e-bikes with daily/monthly pricing, booking management, deposits, and cancellation policies
- **Chat** -- Real-time messaging between buyers/sellers and tenants/landlords via Socket.io
- **Payments** -- Stripe integration for listing fees, commissions, rental bookings, deposits, and landlord payouts via Stripe Connect
- **Subscriptions & Promotions** -- Tiered seller subscriptions (Basic, Pro, Business) and listing promotion/boosting
- **Notifications** -- Real-time in-app notifications for offers, messages, bookings, payouts, and moderation actions
- **Moderation** -- Content reporting, review queue, user banning, and moderation logs
- **Admin Panel** -- Dashboard with analytics, user management, listing management, and moderation tools
- **Auth & Roles** -- JWT authentication with four roles: `USER`, `MODERATOR`, `ADMIN`, `SUPER_ADMIN`
- **Location** -- Google Maps autocomplete for listing and rental locations

## Prerequisites

- **Node.js** >= 18
- **npm** >= 9 (uses npm workspaces)
- **Docker** (for PostgreSQL)

## Getting Started

### 1. Start the Database

If the Docker container already exists:

```bash
docker start marketplace-postgres
```

If you need to create it from scratch:

```bash
docker run -d \
  --name marketplace-postgres \
  -e POSTGRES_USER=marketplace \
  -e POSTGRES_PASSWORD=marketplace_dev \
  -e POSTGRES_DB=marketplace \
  -p 5432:5432 \
  -v marketplace-pgdata:/var/lib/postgresql/data \
  --restart unless-stopped \
  postgres:17-alpine
```

Verify it is running:

```bash
docker ps -f name=marketplace-postgres
```

### 2. Install Dependencies

From the project root:

```bash
npm install
```

This installs dependencies for both the `client` and `server` workspaces.

### 3. Configure Environment Variables

Create `server/.env`:

```env
DATABASE_URL=postgresql://marketplace:marketplace_dev@localhost:5432/marketplace
JWT_SECRET=your-secret-key
JWT_REFRESH_SECRET=your-refresh-secret-key
STRIPE_SECRET_KEY=sk_test_...
STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
GOOGLE_MAPS_API_KEY=your-google-maps-key
CLIENT_URL=http://localhost:5173
UPLOAD_DIR=./uploads
PORT=3000
```

For local development, only `DATABASE_URL` is strictly required. Stripe keys are optional (payment features will be disabled). The server provides sensible defaults for all other values.

### 4. Set Up the Database Schema

```bash
cd server
npx prisma db push
```

Or use migrations:

```bash
cd server
npx prisma migrate dev
```

### 5. Seed the Database (Optional)

```bash
cd server
npx tsx prisma/seed.ts
```

### 6. Run the Application

Start both client and server simultaneously:

```bash
npm run dev
```

Or run them separately:

```bash
npm run dev:server   # Express API on http://localhost:3000
npm run dev:client   # React app on http://localhost:5173
```

## Seed Data

After seeding, the following test users are available (all use password `password123`):

| Email                      | Name           |
|----------------------------|----------------|
| alice.chen@example.com     | Alice Chen     |
| bob.smith@example.com      | Bob Smith      |
| carol.jones@example.com   | Carol Jones    |
| david.wilson@example.com  | David Wilson   |
| eva.martinez@example.com  | Eva Martinez   |

## Project Structure

```
marketplace/
├── package.json              # Root workspace config
├── CLAUDE.md                 # Dev notes (DB setup, commands)
├── docs/                     # Documentation
│   ├── README.md             # This file
│   └── architecture.md       # Architecture overview
├── client/                   # React frontend
│   ├── package.json
│   └── src/
│       ├── api/              # API client functions
│       ├── components/       # Reusable UI components
│       ├── context/          # React context providers
│       ├── pages/            # Route page components
│       ├── router.tsx        # Route definitions
│       ├── types/            # TypeScript type definitions
│       ├── utils/            # Utility functions
│       ├── App.tsx           # App root component
│       └── main.tsx          # Entry point
└── server/                   # Express backend
    ├── package.json
    ├── prisma/
    │   ├── schema.prisma     # Database schema
    │   └── seed.ts           # Seed script
    └── src/
        ├── config/           # Environment config
        ├── middleware/        # Auth, upload, validation, error handling
        ├── routes/           # API route handlers
        │   └── admin/        # Admin-specific routes
        ├── socket/           # Socket.io setup and handlers
        ├── utils/            # Shared utilities
        ├── validators/       # Zod validation schemas
        └── index.ts          # Server entry point
```

## Environment Variables Reference

| Variable                  | Required | Default                          | Description                        |
|---------------------------|----------|----------------------------------|------------------------------------|
| `DATABASE_URL`            | Yes      | localhost connection string      | PostgreSQL connection URL          |
| `PORT`                    | No       | `3000`                           | Server port                        |
| `JWT_SECRET`              | No*      | Dev fallback                     | Access token signing secret        |
| `JWT_REFRESH_SECRET`      | No*      | Dev fallback                     | Refresh token signing secret       |
| `CLIENT_URL`              | No       | `http://localhost:5173`          | CORS allowed origin                |
| `UPLOAD_DIR`              | No       | `./uploads`                      | File upload directory              |
| `STRIPE_SECRET_KEY`       | No       | Empty (payments disabled)        | Stripe secret key                  |
| `STRIPE_PUBLISHABLE_KEY`  | No       | Empty (payments disabled)        | Stripe publishable key             |
| `STRIPE_WEBHOOK_SECRET`   | No       | Empty                            | Stripe webhook signing secret      |
| `GOOGLE_MAPS_API_KEY`     | No       | Dev key                          | Google Maps API key                |

*Must be set to secure values in production.

## Useful Commands

| Command                   | Description                              |
|---------------------------|------------------------------------------|
| `npm run dev`             | Start client + server concurrently       |
| `npm run dev:client`      | Start React dev server (port 5173)       |
| `npm run dev:server`      | Start Express dev server (port 3000)     |
| `npm run build`           | Build client and server for production   |
| `npm run lint`            | Lint client code                         |
| `npx prisma studio`      | Open Prisma Studio (DB browser)          |
| `npx prisma db push`     | Push schema changes to database          |
| `npx prisma migrate dev` | Create and apply a migration             |
| `npx tsx prisma/seed.ts` | Seed the database                        |
