# ISPM ERP - Backend Setup

## Prerequisites

- Node.js 18+ installed
- npm or yarn

## Quick Start

### Option 1: Run the setup script
```bash
# From the project root
setup-backend.bat
```

### Option 2: Manual setup
```bash
# 1. Install backend dependencies
cd server
npm install

# 2. Generate Prisma client
npx prisma generate

# 3. Run database migration
npx prisma migrate dev --name init

# 4. Seed the database
npx ts-node prisma/seed.ts

# 5. Start the backend
npm run dev
```

### Start the frontend (separate terminal)
```bash
# From project root
npm run dev
```

## Access

- **Frontend**: http://localhost:5173
- **Backend API**: http://localhost:3001

## Demo Accounts

| Role | Email | Password |
|------|-------|----------|
| Admin | admin@ispm.ma | admin123 |
| Directeur | directeur@ispm.ma | dir123 |

## API Endpoints

### Auth
- `POST /api/auth/login` - Login
- `POST /api/auth/register` - Register (admin only)
- `GET /api/auth/me` - Current user

### Dashboard
- `GET /api/dashboard/kpis` - KPI data
- `GET /api/dashboard/revenue-chart` - Monthly revenue
- `GET /api/dashboard/program-ranking` - Top programs

### Filieres
- `GET /api/filieres` - List all
- `POST /api/filieres` - Create (admin)
- `PUT /api/filieres/:id` - Update (admin)
- `DELETE /api/filieres/:id` - Delete (admin)

### Etudiants
- `GET /api/etudiants` - List with filters & pagination
- `GET /api/etudiants/:id` - Student detail
- `POST /api/etudiants` - Create (admin)
- `PUT /api/etudiants/:id` - Update (admin)
- `DELETE /api/etudiants/:id` - Delete (admin)

### Paiements
- `GET /api/paiements` - List payments
- `POST /api/paiements` - Record payment
- `GET /api/paiements/echeancier/:etudiantId` - Payment schedule

### Rapports (add ?format=pdf or ?format=excel)
- `GET /api/rapports/inscriptions`
- `GET /api/rapports/financier-mensuel`
- `GET /api/rapports/financier-annuel`
- `GET /api/rapports/impayes`
- `GET /api/rapports/ca-par-filiere`
- `GET /api/rapports/recouvrement`

### Documents
- `POST /api/documents/upload` - Upload file
- `GET /api/documents/:id/download` - Download file

### Annees Scolaires
- `GET /api/annees-scolaires` - List
- `POST /api/annees-scolaires` - Create (admin)
- `PUT /api/annees-scolaires/:id/activate` - Activate (admin)

## Architecture

```
server/
├── prisma/
│   ├── schema.prisma    # Database schema
│   └── seed.ts          # Sample data
├── src/
│   ├── index.ts         # Express server entry
│   ├── routes/          # API route definitions
│   ├── controllers/     # Request handlers
│   ├── middleware/      # Auth, role-check, validation
│   ├── services/        # Business logic
│   └── utils/           # PDF & Excel generators
├── uploads/             # Student documents
├── package.json
└── tsconfig.json
```
