Compare commits
13 Commits
6f53061edc
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| c4940e9691 | |||
| ede906ed3a | |||
| 6db9eadb6f | |||
|
|
3d33977471 | ||
|
|
e349453fbb | ||
|
|
bb1a05af07 | ||
|
|
5b37f88477 | ||
| 0e21d26c05 | |||
| 3eeda1f347 | |||
| ee7a9e0308 | |||
| 926f941ae3 | |||
| 2010a8d4ec | |||
| e699340831 |
@@ -1,6 +1,17 @@
|
||||
# Dependencies — installed inside the container via npm install
|
||||
node_modules
|
||||
client/node_modules
|
||||
|
||||
# Built React output — the Dockerfile builds this fresh inside the container
|
||||
# using a multi-stage build (COPY --from=builder). Excluding it here prevents
|
||||
# stale local builds from leaking into the Docker build context.
|
||||
client/dist
|
||||
|
||||
# Files not needed in the Docker image
|
||||
npm-debug.log
|
||||
.git
|
||||
.gitignore
|
||||
README.md
|
||||
SAAC_DEPLOYMENT.md
|
||||
.env
|
||||
.saac
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -4,3 +4,6 @@ npm-debug.log
|
||||
.DS_Store
|
||||
*.log
|
||||
.saac/
|
||||
client/dist/
|
||||
client/node_modules/
|
||||
*.tsbuildinfo
|
||||
|
||||
52
Dockerfile
52
Dockerfile
@@ -1,28 +1,60 @@
|
||||
FROM node:18-alpine
|
||||
# Multi-stage Dockerfile for React + Express application (PRODUCTION container)
|
||||
# See SAAC_DEPLOYMENT.md for deployment rules and common mistakes.
|
||||
#
|
||||
# This Dockerfile is ONLY used by the production container (yourapp.<server>.domain.com).
|
||||
# The hot-reload container (yourapp-hot.<server>.domain.com) does NOT use this file —
|
||||
# it mounts your source code directly and uses nodemon.json to watch for changes.
|
||||
#
|
||||
# Stage 1 (builder): Installs client deps and builds the React app with Vite.
|
||||
# Stage 2 (production): Installs server deps only, copies built React output.
|
||||
#
|
||||
# The .dockerignore excludes client/dist from the build context — this is
|
||||
# intentional. The builder stage creates a fresh dist/ inside the container,
|
||||
# and COPY --from=builder copies it between stages (bypasses .dockerignore).
|
||||
|
||||
# --- Stage 1: Build React frontend ---
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app/client
|
||||
|
||||
# Install client dependencies first (layer caching — only re-runs if package*.json change)
|
||||
COPY client/package*.json ./
|
||||
RUN npm install
|
||||
|
||||
# Copy client source and build
|
||||
COPY client/ ./
|
||||
RUN npm run build
|
||||
|
||||
# --- Stage 2: Production server ---
|
||||
FROM node:20-alpine
|
||||
|
||||
# Build arguments - Coolify provides SOURCE_COMMIT automatically
|
||||
ARG SOURCE_COMMIT=unknown
|
||||
ARG APP_VERSION=1.0.0
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install curl for healthcheck and git for version control operations
|
||||
RUN apk add --no-cache curl git
|
||||
# curl is required for the Docker healthcheck below
|
||||
RUN apk add --no-cache curl
|
||||
|
||||
# Copy package files first for layer caching
|
||||
# Install server dependencies only (not devDependencies — they're not needed in production).
|
||||
# If your app needs devDependencies for a build step (e.g. TypeScript), install ALL deps
|
||||
# first, run the build, then prune: RUN npm install && npm run build && npm prune --production
|
||||
COPY package*.json ./
|
||||
RUN npm install --production
|
||||
|
||||
# Copy app code (changes more often — below the cached layer)
|
||||
COPY . .
|
||||
# Copy server code
|
||||
COPY server.js ./
|
||||
|
||||
# Set environment variables for runtime
|
||||
# Extract first 7 characters of SOURCE_COMMIT for short hash
|
||||
ENV GIT_COMMIT=${SOURCE_COMMIT:0:7} \
|
||||
# Copy built React app from the builder stage (not from host — .dockerignore doesn't apply)
|
||||
COPY --from=builder /app/client/dist ./client/dist
|
||||
|
||||
ENV GIT_COMMIT=${SOURCE_COMMIT} \
|
||||
APP_VERSION=${APP_VERSION}
|
||||
|
||||
# Use "expose" in docker-compose.yml, not "ports". This EXPOSE is just documentation.
|
||||
EXPOSE 3000
|
||||
|
||||
# Healthcheck — must match the healthcheck in docker-compose.yml
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=2 \
|
||||
CMD curl -f http://localhost:3000/health || exit 1
|
||||
|
||||
|
||||
611
README.md
611
README.md
@@ -1,580 +1,73 @@
|
||||
# Template 001 - Start an AI Company Deployment Template
|
||||
# Company Website Template
|
||||
|
||||
This is a template site demonstrating how to deploy applications on Start an AI Company servers using Docker Compose and Traefik.
|
||||
React + shadcn/ui + Express + PostgreSQL + Redis scaffold for SAAC deployment.
|
||||
|
||||
---
|
||||
## Stack
|
||||
|
||||
## Hi AI Developer Agent!
|
||||
- **Frontend**: React 19 + Vite + TypeScript + TailwindCSS v4 + shadcn/ui
|
||||
- **Backend**: Express.js (Node 20)
|
||||
- **Database**: PostgreSQL 16
|
||||
- **Cache**: Redis 7
|
||||
- **Deploy**: Docker Compose via `saac deploy`
|
||||
|
||||
In order to work with Start an AI Company repositories and deploy applications, you need to follow these steps:
|
||||
## Structure
|
||||
|
||||
### 1. Check Environment Variables
|
||||
```
|
||||
├── server.js # Express backend (API + serves React build)
|
||||
├── client/ # React frontend (Vite + shadcn/ui)
|
||||
│ ├── src/
|
||||
│ │ ├── components/ui/ # shadcn/ui components (Button, Card, Input, etc.)
|
||||
│ │ ├── lib/utils.ts # cn() utility for Tailwind class merging
|
||||
│ │ ├── pages/ # Page components
|
||||
│ │ ├── App.tsx # Router
|
||||
│ │ └── main.tsx # Entry point
|
||||
│ ├── components.json # shadcn/ui config
|
||||
│ ├── vite.config.ts # Vite config with path aliases
|
||||
│ └── package.json # Client dependencies
|
||||
├── docker-compose.yml # PostgreSQL + Redis + App (see comments inside)
|
||||
├── Dockerfile # Multi-stage: build React → serve with Express
|
||||
├── SAAC_DEPLOYMENT.md # Deployment rules — READ THIS FIRST
|
||||
└── package.json # Server dependencies
|
||||
```
|
||||
|
||||
First, verify you have the required authentication credentials:
|
||||
## Development
|
||||
|
||||
```bash
|
||||
echo $SAAC_USER_API_KEY
|
||||
echo $SAAC_USER_EMAIL
|
||||
```
|
||||
|
||||
If you are running in a Start an AI Company container, these should already be set. If they're not set, you'll need to obtain them from your account administrator.
|
||||
|
||||
### 2. Validate SAAC CLI Tools
|
||||
|
||||
Check if you have the `saac` CLI tool installed and if you're already logged in:
|
||||
|
||||
```bash
|
||||
saac status
|
||||
```
|
||||
|
||||
If the command is not found, install it:
|
||||
|
||||
```bash
|
||||
npm install -g @startanaicompany/cli
|
||||
```
|
||||
|
||||
### 3. Login to SAAC
|
||||
|
||||
Use your credentials to login:
|
||||
|
||||
```bash
|
||||
saac login -e $SAAC_USER_EMAIL -k $SAAC_USER_API_KEY
|
||||
```
|
||||
|
||||
You should see a success message confirming your session has been created.
|
||||
|
||||
**Note:** SAAC AI agents already have their Git account connected by default, so you don't need to run `saac git connect`.
|
||||
|
||||
### 4. Publishing This Repository
|
||||
|
||||
To deploy this template application:
|
||||
|
||||
```bash
|
||||
# Navigate to your project directory
|
||||
cd /path/to/your/project
|
||||
|
||||
# Create and deploy the application
|
||||
saac create application \
|
||||
-s your-subdomain \
|
||||
-r git@git.startanaicompany.com:username/your-repo.git \
|
||||
--build-pack dockercompose
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
saac create application \
|
||||
-s template-001 \
|
||||
-r git@git.startanaicompany.com:StartAnAiCompanyTemplates/template_001.git \
|
||||
--build-pack dockercompose
|
||||
```
|
||||
|
||||
Replace `username` with your actual Git username and `your-repo` with your repository name.
|
||||
|
||||
The application will be available at: `https://your-subdomain.startanaicompany.com`
|
||||
|
||||
### 5. **CRITICAL: Port Configuration**
|
||||
|
||||
**DO NOT** use host port mappings like `3000:3000` in your `docker-compose.yml` file!
|
||||
|
||||
**Why?** If you map ports like `3000:3000`, Docker Compose will try to bind to the HOST's port 3000, which is blocked by default for security reasons. Your application will fail to start.
|
||||
|
||||
**Correct Configuration:**
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
expose:
|
||||
- "3000" # ✅ Only expose internally
|
||||
# DO NOT USE:
|
||||
# ports:
|
||||
# - "3000:3000" # ❌ This will fail!
|
||||
```
|
||||
|
||||
We use **Traefik** for automatic routing and SSL. Traefik will:
|
||||
- Automatically discover your container
|
||||
- Route traffic from your subdomain to your container
|
||||
- Handle SSL certificates via Let's Encrypt
|
||||
- Manage external port assignments
|
||||
|
||||
**Traefik Configuration:**
|
||||
|
||||
Your service must include these labels in `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.your-app.rule=Host(`your-subdomain.startanaicompany.com`)"
|
||||
- "traefik.http.routers.your-app.entrypoints=websecure"
|
||||
- "traefik.http.routers.your-app.tls=true"
|
||||
- "traefik.http.routers.your-app.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.your-app.loadbalancer.server.port=3000"
|
||||
```
|
||||
|
||||
### 6. Database Access Limitations
|
||||
|
||||
**Important:** There is currently **no direct database access** for security reasons.
|
||||
|
||||
To manage your database, you should:
|
||||
- Expose a password-protected CRUD API
|
||||
- Create an admin user interface with authentication
|
||||
- Use database migration scripts during deployment
|
||||
- Implement seed data scripts if needed
|
||||
|
||||
**Example: Adding Database Migrations**
|
||||
|
||||
```bash
|
||||
saac create application \
|
||||
-s myapp \
|
||||
-r git@git.startanaicompany.com:user/repo.git \
|
||||
--build-pack dockercompose \
|
||||
--pre-deploy-cmd "npm run db:migrate"
|
||||
```
|
||||
|
||||
### 7. Deployment Time Expectations
|
||||
|
||||
**Be patient!** Deployments can take time:
|
||||
- Simple applications: 2-5 minutes
|
||||
- Large applications: 5-10 minutes
|
||||
- Applications with complex builds: Up to 10+ minutes
|
||||
|
||||
**Best Practices:**
|
||||
- Always run `npm run build` or equivalent build commands locally first to catch errors (if possible)
|
||||
- Review your docker-compose.yml for correct port configuration (use `expose`, not `ports`)
|
||||
- Deploy to Start an AI Company servers and check build logs: `saac logs --follow`
|
||||
- For AI agents without local build tools: Deploy directly and monitor logs for errors
|
||||
|
||||
### 8. Other Available Templates
|
||||
|
||||
**Coming Soon:**
|
||||
- Template 002: Full-stack application with authentication
|
||||
- Template 003: Microservices architecture
|
||||
- Template 004: Static site deployment
|
||||
- Template 005: Python/Django application
|
||||
- Template 006: Python/FastAPI application
|
||||
- Template 007: Ruby on Rails application
|
||||
- Template 008: PHP/Laravel application
|
||||
- Template 009: Go application
|
||||
- Template 010: Rust application
|
||||
|
||||
Check back for updates or contribute your own templates!
|
||||
|
||||
---
|
||||
|
||||
## Step-by-Step Deployment Guide
|
||||
|
||||
This section documents the exact commands used to create and deploy this template application.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. SSH key configured for git.startanaicompany.com
|
||||
2. SAAC CLI tools installed
|
||||
3. Logged into SAAC
|
||||
4. Git account connected via OAuth
|
||||
|
||||
### Step 1: Initialize Git Repository
|
||||
|
||||
```bash
|
||||
# Initialize git repository
|
||||
git init
|
||||
|
||||
# Add remote repository
|
||||
git remote add origin git@git.startanaicompany.com:StartAnAiCompanyTemplates/template_001.git
|
||||
```
|
||||
|
||||
### Step 2: Create Application Files
|
||||
|
||||
The following files were created:
|
||||
|
||||
**package.json** - Node.js dependencies
|
||||
```bash
|
||||
# Created with Express, PostgreSQL, and Redis dependencies
|
||||
```
|
||||
|
||||
**server.js** - Main application server
|
||||
```bash
|
||||
# Node.js Express server with PostgreSQL and Redis connections
|
||||
# Health check endpoint at /health
|
||||
```
|
||||
|
||||
**public/index.html** - Frontend website
|
||||
```bash
|
||||
# Modern white design with template information
|
||||
```
|
||||
|
||||
**Dockerfile** - Container configuration
|
||||
```bash
|
||||
# Node.js 18 Alpine image
|
||||
# Production dependencies only
|
||||
```
|
||||
|
||||
**docker-compose.yml** - Multi-container orchestration
|
||||
```bash
|
||||
# Three services: app, postgres, redis
|
||||
# Traefik labels for routing
|
||||
# No host port mappings (only expose)
|
||||
```
|
||||
|
||||
**.dockerignore** - Files to exclude from Docker build
|
||||
**.gitignore** - Files to exclude from Git
|
||||
|
||||
### Step 3: Configure Git User
|
||||
|
||||
```bash
|
||||
# Set git user configuration
|
||||
git config --global user.name "ryan.gogo"
|
||||
git config --global user.email "git@startanaicompany.com"
|
||||
```
|
||||
|
||||
### Step 4: Commit and Push
|
||||
|
||||
```bash
|
||||
# Stage all files
|
||||
git add .
|
||||
|
||||
# Create initial commit
|
||||
git commit -m "Initial commit: Template site for Start an AI Company deployment
|
||||
|
||||
- Node.js Express application with modern white UI
|
||||
- PostgreSQL and Redis integration
|
||||
- Docker Compose configuration without host port mappings
|
||||
- Traefik-ready with proper labels
|
||||
- Health check endpoint"
|
||||
|
||||
# Push to remote repository
|
||||
git push -u origin master
|
||||
```
|
||||
|
||||
### Step 5: Deploy with SAAC
|
||||
|
||||
```bash
|
||||
# Create and deploy application
|
||||
saac create application \
|
||||
-s template-001 \
|
||||
-r git@git.startanaicompany.com:StartAnAiCompanyTemplates/template_001.git \
|
||||
--build-pack dockercompose
|
||||
```
|
||||
|
||||
**Note:** The first deployment may fail if the deployment key is not approved. To fix:
|
||||
1. Go to: `https://git.startanaicompany.com/YOUR-USERNAME/YOUR-REPO/settings/keys`
|
||||
2. Approve any deployment keys that appear
|
||||
3. Redeploy with: `saac deploy`
|
||||
|
||||
### Step 6: Monitor Deployment
|
||||
|
||||
```bash
|
||||
# View live deployment logs
|
||||
saac logs --follow
|
||||
|
||||
# Check application status
|
||||
saac status
|
||||
|
||||
# View deployment history
|
||||
saac deployments
|
||||
```
|
||||
|
||||
### Step 7: Verify Deployment
|
||||
|
||||
```bash
|
||||
# Check health endpoint (includes git commit ID)
|
||||
curl https://template-001.startanaicompany.com/health
|
||||
|
||||
# You should see a response like:
|
||||
# {
|
||||
# "status": "healthy",
|
||||
# "postgres": "connected",
|
||||
# "redis": "connected",
|
||||
# "timestamp": "2026-02-14T10:30:00.000Z",
|
||||
# "git_commit": "0e993d9",
|
||||
# "version": "1.0.0"
|
||||
# }
|
||||
|
||||
# View the website
|
||||
curl https://template-001.startanaicompany.com
|
||||
```
|
||||
|
||||
**Note:** The `git_commit` field in the health endpoint shows which version is deployed, making it easy for AI agents to track deployments.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Application Stack
|
||||
|
||||
- **Frontend**: Static HTML/CSS served by Express
|
||||
- **Backend**: Node.js Express server (port 3000)
|
||||
- **Database**: PostgreSQL 15 (Alpine)
|
||||
- **Cache**: Redis 7 (Alpine)
|
||||
- **Reverse Proxy**: Traefik (managed by infrastructure)
|
||||
|
||||
### Network Architecture
|
||||
|
||||
```
|
||||
Internet
|
||||
↓
|
||||
Traefik (Reverse Proxy)
|
||||
↓
|
||||
Docker Network (app-network)
|
||||
├── app:3000 (Node.js)
|
||||
├── postgres:5432
|
||||
└── redis:6379
|
||||
```
|
||||
|
||||
### Data Persistence
|
||||
|
||||
- PostgreSQL data: `postgres-data` volume
|
||||
- Redis data: `redis-data` volume
|
||||
|
||||
Both volumes are persistent and survive container restarts.
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **Modern UI**: Clean white design (no purple!)
|
||||
- **Health Checks**: `/health` endpoint for monitoring
|
||||
- **Database Integration**: PostgreSQL for relational data
|
||||
- **Caching**: Redis for high-performance caching
|
||||
- **Docker Ready**: Full containerization with Docker Compose
|
||||
- **Production Ready**: Optimized for production deployment
|
||||
- **SSL/TLS**: Automatic HTTPS via Traefik and Let's Encrypt
|
||||
- **Zero Downtime**: Rolling deployments supported
|
||||
|
||||
---
|
||||
|
||||
## Local Development
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18 or higher
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
# Install all dependencies (postinstall auto-installs client deps)
|
||||
npm install
|
||||
|
||||
# Run development server (without Docker)
|
||||
# Run in dev mode (watches server.js + client/src, auto-rebuilds on changes)
|
||||
npm run dev
|
||||
|
||||
# Or for local development with Vite HMR (browser hot-reload):
|
||||
npm run dev:local # Express :3000 + Vite :5173 concurrently
|
||||
|
||||
# Or run separately:
|
||||
npm run dev:server # Express on :3000 (with nodemon auto-restart)
|
||||
npm run dev:client # Vite on :5173 (proxies /api to :3000)
|
||||
```
|
||||
|
||||
The application will be available at http://localhost:3000
|
||||
|
||||
**Note for AI Agents:** SAAC AI agents do not have Docker available. Testing should be done by deploying directly to Start an AI Company servers using `saac deploy`.
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
The application uses the following environment variables:
|
||||
|
||||
### Application Configuration
|
||||
|
||||
- `NODE_ENV`: Environment (default: `production`)
|
||||
- `PORT`: Application port (default: `3000`)
|
||||
|
||||
### PostgreSQL Configuration
|
||||
|
||||
- `POSTGRES_HOST`: PostgreSQL host (default: `postgres`)
|
||||
- `POSTGRES_PORT`: PostgreSQL port (default: `5432`)
|
||||
- `POSTGRES_USER`: PostgreSQL username (default: `postgres`)
|
||||
- `POSTGRES_PASSWORD`: PostgreSQL password (default: `postgres`)
|
||||
- `POSTGRES_DB`: PostgreSQL database name (default: `template_db`)
|
||||
|
||||
### Redis Configuration
|
||||
|
||||
- `REDIS_HOST`: Redis host (default: `redis`)
|
||||
- `REDIS_PORT`: Redis port (default: `6379`)
|
||||
|
||||
### Setting Environment Variables
|
||||
## Adding shadcn/ui Components
|
||||
|
||||
```bash
|
||||
# Set environment variables for your deployment
|
||||
saac env set NODE_ENV=production \
|
||||
POSTGRES_PASSWORD=secure_password_here \
|
||||
CUSTOM_VAR=value
|
||||
cd client
|
||||
npx shadcn@latest add dialog # Add Dialog component
|
||||
npx shadcn@latest add table # Add Table component
|
||||
npx shadcn@latest add select # Add Select component
|
||||
```
|
||||
|
||||
# Redeploy to apply changes
|
||||
Import: `import { Button } from "@/components/ui/button"`
|
||||
|
||||
## Deploy
|
||||
|
||||
```bash
|
||||
saac deploy
|
||||
```
|
||||
|
||||
---
|
||||
See `SAAC_DEPLOYMENT.md` for deployment rules, common mistakes, and debugging commands.
|
||||
|
||||
## API Endpoints
|
||||
## API Routes
|
||||
|
||||
### GET /
|
||||
|
||||
Returns the main template website with information about the deployment.
|
||||
|
||||
### GET /health
|
||||
|
||||
Health check endpoint that verifies connections to PostgreSQL and Redis, and returns deployment version information.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "healthy",
|
||||
"postgres": "connected",
|
||||
"redis": "connected",
|
||||
"timestamp": "2026-02-14T10:30:00.000Z",
|
||||
"git_commit": "0e993d9",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Error Response:**
|
||||
```json
|
||||
{
|
||||
"status": "unhealthy",
|
||||
"error": "Connection error message",
|
||||
"git_commit": "0e993d9",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Version Tracking:**
|
||||
- `git_commit`: Short Git commit SHA (7 characters) of the deployed code, automatically provided by Start an AI Company deployment infrastructure
|
||||
- `version`: Application version (defaults to 1.0.0, can be set via APP_VERSION env var)
|
||||
|
||||
This allows AI agents and monitoring tools to verify which version is currently running. The short commit ID is industry standard for deployment tracking, providing a balance between uniqueness and readability.
|
||||
|
||||
**Note:** Git commit tracking works automatically - no additional configuration needed.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Deployment Fails
|
||||
|
||||
**Check logs:**
|
||||
```bash
|
||||
saac logs --follow
|
||||
```
|
||||
|
||||
**Common issues:**
|
||||
1. Deploy key not approved in repository settings
|
||||
2. Build errors (review application code)
|
||||
3. Port configuration errors (don't use host port mappings)
|
||||
4. Invalid Traefik labels
|
||||
|
||||
### Application Not Accessible
|
||||
|
||||
**Check status:**
|
||||
```bash
|
||||
saac status
|
||||
```
|
||||
|
||||
**Verify Traefik configuration:**
|
||||
- Ensure labels are correct in `docker-compose.yml`
|
||||
- Subdomain must match the rule in Traefik labels
|
||||
- Wait 1-2 minutes for DNS and SSL propagation
|
||||
|
||||
### Database Connection Errors
|
||||
|
||||
**Check environment variables:**
|
||||
```bash
|
||||
saac env list
|
||||
```
|
||||
|
||||
**Verify service names:**
|
||||
- PostgreSQL host should be `postgres` (service name in docker-compose.yml)
|
||||
- Redis host should be `redis` (service name in docker-compose.yml)
|
||||
|
||||
### Container Keeps Restarting
|
||||
|
||||
**View container logs:**
|
||||
```bash
|
||||
saac logs --follow
|
||||
```
|
||||
|
||||
**Common causes:**
|
||||
- Missing environment variables
|
||||
- Database connection failures
|
||||
- Port conflicts (check you're not using host port mappings)
|
||||
- Application crashes on startup
|
||||
|
||||
### How to Debug
|
||||
|
||||
**Check deployment logs:**
|
||||
```bash
|
||||
saac logs --follow
|
||||
```
|
||||
|
||||
**View environment variables:**
|
||||
```bash
|
||||
saac env list
|
||||
```
|
||||
|
||||
**Check application status:**
|
||||
```bash
|
||||
saac status
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Pre-deployment Scripts
|
||||
|
||||
Run database migrations before deployment:
|
||||
|
||||
```bash
|
||||
saac update --pre-deploy-cmd "npm run db:migrate"
|
||||
saac deploy
|
||||
```
|
||||
|
||||
### Health Check Configuration
|
||||
|
||||
Enable health checks:
|
||||
|
||||
```bash
|
||||
saac update \
|
||||
--health-check \
|
||||
--health-path /health \
|
||||
--health-interval 30 \
|
||||
--health-timeout 10 \
|
||||
--health-retries 3
|
||||
|
||||
saac deploy
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
To contribute to this template:
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch
|
||||
3. Make your changes
|
||||
4. Test by deploying with `saac deploy` to verify functionality
|
||||
5. Submit a pull request
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT License - Feel free to use this template for your own projects.
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
For issues or questions:
|
||||
- Check the troubleshooting section above
|
||||
- Review SAAC CLI documentation: `saac manual`
|
||||
- Contact support at support@startanaicompany.com
|
||||
|
||||
---
|
||||
|
||||
## Changelog
|
||||
|
||||
### Version 1.0.0 (2026-02-14)
|
||||
|
||||
- Initial release
|
||||
- Node.js Express application
|
||||
- PostgreSQL and Redis integration
|
||||
- Docker Compose configuration
|
||||
- Traefik-ready setup
|
||||
- Modern white UI
|
||||
- Health check endpoint
|
||||
- Comprehensive documentation
|
||||
- `GET /health` — Health check (PostgreSQL + Redis)
|
||||
- `GET /api/status` — Example API endpoint
|
||||
- `GET /*` — React SPA (served from client/dist)
|
||||
|
||||
@@ -3,6 +3,82 @@
|
||||
> **READ THIS FIRST.** This file explains exactly how SAAC deploys your app.
|
||||
> Understanding this will save you hours of debugging.
|
||||
|
||||
## Your Two Domains
|
||||
|
||||
Every app gets **two live URLs** on the server. Both are created automatically when you deploy:
|
||||
|
||||
```
|
||||
yourapp.<server>.startanaicompany.com ← PRODUCTION (customers see this)
|
||||
yourapp-hot.<server>.startanaicompany.com ← HOT-RELOAD (you develop with this)
|
||||
```
|
||||
|
||||
For example, if your app domain is `my-saas.adam.startanaicompany.com`:
|
||||
- Production: `https://my-saas.adam.startanaicompany.com`
|
||||
- Hot-reload: `https://my-saas-hot.adam.startanaicompany.com`
|
||||
|
||||
### How to Use Them
|
||||
|
||||
**Hot-reload (`-hot` domain)** — Use this while developing. Every `git push` automatically:
|
||||
1. Pulls your latest code
|
||||
2. Rebuilds the React frontend (`npm run build`)
|
||||
3. Restarts the Express server
|
||||
4. Your changes are live in ~10-20 seconds
|
||||
|
||||
**Recommended development workflow:**
|
||||
```bash
|
||||
# 1. Make your code changes
|
||||
# 2. Push to git
|
||||
git add . && git commit -m "Add login page" && git push
|
||||
|
||||
# 3. Wait ~15 seconds, then check the hot domain
|
||||
curl https://yourapp-hot.adam.startanaicompany.com/health
|
||||
|
||||
# 4. Once it works on hot, deploy to production
|
||||
saac deploy
|
||||
|
||||
# 5. Verify production
|
||||
curl https://yourapp.adam.startanaicompany.com/health
|
||||
```
|
||||
|
||||
**Production domain** — Only updates when you run `saac deploy`. This rebuilds the Docker image from your Dockerfile and restarts everything. Use this for the final, tested version.
|
||||
|
||||
### Why Two Containers?
|
||||
|
||||
| Container | Domain | How it runs your code | When it updates |
|
||||
|-----------|--------|----------------------|-----------------|
|
||||
| **Production** | `yourapp.example.com` | Built from your `Dockerfile` (immutable Docker image) | Only on `saac deploy` |
|
||||
| **Hot-reload** | `yourapp-hot.example.com` | Volume-mounts your git repo, runs `npm run dev` via nodemon | Automatically on every `git push` |
|
||||
|
||||
**Key differences:**
|
||||
- **Production** uses your Dockerfile. The Docker image is built once and runs until next deploy.
|
||||
- **Hot-reload** does NOT use your Dockerfile. It mounts your source code directly, installs dependencies, builds the React client, and runs Express with nodemon.
|
||||
- **Hot-reload auto-rebuilds everything** — `nodemon.json` watches both `server.js` and `client/src/`. When files change (after `git push`), it runs `npm run build` (React) and restarts `node server.js`.
|
||||
|
||||
### How nodemon.json Works
|
||||
|
||||
The `nodemon.json` file in your repo tells the hot-reload container what to watch:
|
||||
|
||||
```json
|
||||
{
|
||||
"watch": ["server.js", "client/src"],
|
||||
"ext": "js,ts,tsx,jsx,css,json",
|
||||
"exec": "npm run build && node server.js"
|
||||
}
|
||||
```
|
||||
|
||||
- **watch**: Directories/files to monitor for changes
|
||||
- **ext**: File extensions that trigger a rebuild
|
||||
- **exec**: What to run when changes are detected — rebuilds React, restarts Express
|
||||
|
||||
**You can customize this.** For example, if you add a `lib/` directory with shared code:
|
||||
```json
|
||||
{
|
||||
"watch": ["server.js", "client/src", "lib"],
|
||||
"ext": "js,ts,tsx,jsx,css,json",
|
||||
"exec": "npm run build && node server.js"
|
||||
}
|
||||
```
|
||||
|
||||
## The Build Process
|
||||
|
||||
When you run `saac deploy`, the daemon executes these exact commands in your repo:
|
||||
@@ -46,12 +122,41 @@ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/mydb
|
||||
|
||||
# CORRECT — "postgres" is the service name in docker-compose.yml
|
||||
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/mydb
|
||||
|
||||
# ALSO CORRECT — if using shared org database
|
||||
DATABASE_URL: postgresql://postgres:postgres@postgres.internal:5432/mydb
|
||||
```
|
||||
|
||||
### Rule 3: Dockerfile must produce a running container
|
||||
### Rule 3: Database name must match between app and postgres service
|
||||
|
||||
The `POSTGRES_DB` in your postgres service creates the database. Your app must connect to the SAME name.
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
environment:
|
||||
# Must match POSTGRES_DB below!
|
||||
- DATABASE_URL=postgresql://postgres:postgres@postgres:5432/postgres
|
||||
postgres:
|
||||
environment:
|
||||
- POSTGRES_DB=postgres # This creates the database
|
||||
```
|
||||
|
||||
**WARNING:** If you change `POSTGRES_DB` after first deploy, the old name persists in the Docker volume. The new name won't exist. Either keep the original name or destroy and recreate the postgres volume.
|
||||
|
||||
### Rule 4: Keep it simple — iterate incrementally
|
||||
|
||||
**Start with the working template, then add features one at a time.**
|
||||
|
||||
DO NOT:
|
||||
- Replace Express with TypeScript + Prisma + monorepo in one commit
|
||||
- Create complex multi-stage Dockerfiles before the basic app works
|
||||
- Have multiple agents push changes simultaneously (causes deploy loops)
|
||||
|
||||
DO:
|
||||
- Get the template deploying first (`saac deploy`, verify with `saac logs`)
|
||||
- Add one feature, push, check the hot domain
|
||||
- When it works, add the next feature
|
||||
- **Coordinate deploys** — only ONE agent should push/deploy at a time
|
||||
|
||||
### Rule 5: Dockerfile must produce a running container
|
||||
|
||||
```dockerfile
|
||||
FROM node:20-alpine
|
||||
@@ -63,64 +168,46 @@ COPY . .
|
||||
CMD ["node", "server.js"]
|
||||
```
|
||||
|
||||
Key points:
|
||||
- `npm install` happens INSIDE the container (not on host)
|
||||
- `COPY . .` copies your source into the container
|
||||
- `CMD` must start your app
|
||||
- For TypeScript: add `RUN npm run build` before CMD, use `CMD ["node", "dist/server.js"]`
|
||||
|
||||
### Rule 4: Keep it simple — iterate incrementally
|
||||
|
||||
**Start with the working template, then add features one at a time.**
|
||||
|
||||
DO NOT:
|
||||
- Replace Express with a full TypeScript/Prisma/monorepo stack in one commit
|
||||
- Create complex multi-stage Dockerfiles before the basic app works
|
||||
- Add workspace configurations before single-service works
|
||||
- Change the directory structure before deploying successfully once
|
||||
|
||||
DO:
|
||||
- Get the template deploying first (`saac deploy`, verify with `saac logs`)
|
||||
- Add one feature, deploy, verify
|
||||
- Add the next feature, deploy, verify
|
||||
|
||||
### Rule 5: .dockerignore should NOT exclude build outputs
|
||||
|
||||
For TypeScript projects:
|
||||
```dockerfile
|
||||
FROM node:20-alpine
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install # Install ALL deps (including devDependencies for tsc)
|
||||
COPY . .
|
||||
RUN npm run build # Compile TypeScript
|
||||
RUN npm prune --production # Remove devDeps from final image
|
||||
CMD ["node", "dist/server.js"]
|
||||
```
|
||||
# Good .dockerignore
|
||||
node_modules
|
||||
.git
|
||||
.env
|
||||
```
|
||||
|
||||
Do NOT add `dist/` or `build/` — those are generated INSIDE the container by `RUN npm run build`. The .dockerignore only affects what gets COPIED into the build context.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Env vars set via `saac env set KEY=VALUE` are written to `.env` in your repo directory before build. Reference them in docker-compose.yml:
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
- DATABASE_URL=${DATABASE_URL}
|
||||
```
|
||||
|
||||
Or use `env_file: .env` on your service.
|
||||
|
||||
## Two Containers Per App
|
||||
|
||||
Every app gets:
|
||||
- **Production** (`yourapp.startanaicompany.com`) — immutable image, rebuilt on `saac deploy`
|
||||
- **Hot-reload** (`yourapp-hot.startanaicompany.com`) — volume-mounted source, auto-updates on `git push`
|
||||
Env vars set via `saac env set KEY=VALUE` are written to `.env` in your repo directory before build.
|
||||
|
||||
## Debugging Commands
|
||||
|
||||
```bash
|
||||
saac logs # Runtime logs
|
||||
saac logs # Runtime logs (production container)
|
||||
saac logs --type build # Build/deploy logs
|
||||
saac exec "ls -la" # Run command in container
|
||||
saac exec "cat package.json" # Check what's actually in the container
|
||||
saac exec "ls -la" # Run command in production container
|
||||
saac exec "cat package.json" # Check what's in the container
|
||||
saac db sql "SELECT * FROM users LIMIT 5" # Query database
|
||||
saac db containers # List database containers
|
||||
```
|
||||
|
||||
## Quick Reference: Development Cycle
|
||||
|
||||
```
|
||||
git push ──→ hot-reload updates (~15s) ──→ check yourapp-hot domain
|
||||
│ │
|
||||
│ ┌─────── works? ──┘
|
||||
│ │
|
||||
│ YES ────┤──── NO
|
||||
│ │ │ │
|
||||
│ saac deploy │ fix code, git push again
|
||||
│ │ │
|
||||
│ production │
|
||||
│ updated │
|
||||
└────────────────────────────┘
|
||||
```
|
||||
|
||||
## Common Mistakes and Fixes
|
||||
@@ -129,12 +216,13 @@ saac db containers # List database containers
|
||||
|---------|-----|
|
||||
| `ports: "3000:3000"` | Change to `expose: ["3000"]` |
|
||||
| `DB_HOST=localhost` | Change to `DB_HOST=postgres` (service name) |
|
||||
| No Dockerfile | Create one (see Rule 3) |
|
||||
| TypeScript not compiling | Add `RUN npm run build` in Dockerfile |
|
||||
| Changed `POSTGRES_DB` name after first deploy | Keep original name or delete postgres volume |
|
||||
| `tsc: not found` in Dockerfile | Install ALL deps first: `RUN npm install` (not `--production`) |
|
||||
| `.dockerignore` has `dist/` | Remove it — dist is built inside container |
|
||||
| `npm start` undefined | Add `"start": "node server.js"` to package.json scripts |
|
||||
| Container exits immediately | Check `saac logs` — usually a missing env var or import error |
|
||||
| "ECONNREFUSED 127.0.0.1" | You're using localhost — change to the Docker service name |
|
||||
| Multiple agents deploying simultaneously | Coordinate — one agent deploys at a time |
|
||||
| "App serves old code" on production | Run `saac deploy` to rebuild the Docker image |
|
||||
| "App serves old code" on hot domain | Wait ~15s after push. Check `saac logs` for rebuild errors |
|
||||
| Hot-reload container crashes | Check `saac logs` — usually a missing dependency or build error |
|
||||
|
||||
## Do NOT Add Traefik Labels
|
||||
|
||||
|
||||
21
client/components.json
Normal file
21
client/components.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
13
client/index.html
Normal file
13
client/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Company Name</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
4411
client/package-lock.json
generated
Normal file
4411
client/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
37
client/package.json
Normal file
37
client/package.json
Normal file
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "client",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-dialog": "^1.1.4",
|
||||
"@radix-ui/react-label": "^2.1.1",
|
||||
"@radix-ui/react-select": "^2.1.4",
|
||||
"@radix-ui/react-separator": "^1.1.1",
|
||||
"@radix-ui/react-slot": "^1.1.1",
|
||||
"@radix-ui/react-tabs": "^1.1.2",
|
||||
"@radix-ui/react-toast": "^1.2.4",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.469.0",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-router-dom": "^7.1.0",
|
||||
"tailwind-merge": "^2.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "~5.7.0",
|
||||
"vite": "^6.0.0"
|
||||
}
|
||||
}
|
||||
79
client/src/App.tsx
Normal file
79
client/src/App.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import { BrowserRouter, Routes, Route, NavLink, Navigate } from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from '@/lib/auth'
|
||||
import HomePage from '@/pages/Home'
|
||||
import CandidatesPage from '@/pages/Candidates'
|
||||
import JobsPage from '@/pages/Jobs'
|
||||
import ScorecardsPage from '@/pages/Scorecards'
|
||||
import LoginPage from '@/pages/Login'
|
||||
import RegisterPage from '@/pages/Register'
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, loading } = useAuth()
|
||||
if (loading) return <div className="min-h-screen flex items-center justify-center text-muted-foreground">Loading...</div>
|
||||
if (!user) return <Navigate to="/login" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
function Layout() {
|
||||
const { user, logout } = useAuth()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#F9FAFB]">
|
||||
<header className="border-b sticky top-0 bg-white z-10 shadow-sm">
|
||||
<div className="container mx-auto flex h-16 items-center justify-between px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl font-bold text-[#3B82F6]">HireFlow</span>
|
||||
<span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full hidden sm:block">AI Recruitment</span>
|
||||
</div>
|
||||
<nav className="flex items-center gap-1">
|
||||
<NavLink to="/" end className={({ isActive }) =>
|
||||
`px-3 py-2 rounded-md text-sm font-medium transition-colors ${isActive ? 'bg-[#3B82F6] text-white' : 'hover:bg-muted'}`
|
||||
}>Dashboard</NavLink>
|
||||
<NavLink to="/candidates" className={({ isActive }) =>
|
||||
`px-3 py-2 rounded-md text-sm font-medium transition-colors ${isActive ? 'bg-[#3B82F6] text-white' : 'hover:bg-muted'}`
|
||||
}>Candidates</NavLink>
|
||||
<NavLink to="/jobs" className={({ isActive }) =>
|
||||
`px-3 py-2 rounded-md text-sm font-medium transition-colors ${isActive ? 'bg-[#3B82F6] text-white' : 'hover:bg-muted'}`
|
||||
}>Jobs</NavLink>
|
||||
<NavLink to="/scorecards" className={({ isActive }) =>
|
||||
`px-3 py-2 rounded-md text-sm font-medium transition-colors ${isActive ? 'bg-[#3B82F6] text-white' : 'hover:bg-muted'}`
|
||||
}>Scorecards</NavLink>
|
||||
</nav>
|
||||
{user && (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="hidden sm:block text-right">
|
||||
<p className="text-xs font-medium">{user.email}</p>
|
||||
<p className="text-xs text-muted-foreground capitalize">{user.role.replace('_', ' ')}</p>
|
||||
</div>
|
||||
<button onClick={logout} className="text-xs text-muted-foreground hover:text-foreground px-2 py-1 rounded hover:bg-muted transition-colors">
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
<Routes>
|
||||
<Route path="/" element={<ProtectedRoute><HomePage /></ProtectedRoute>} />
|
||||
<Route path="/candidates" element={<ProtectedRoute><CandidatesPage /></ProtectedRoute>} />
|
||||
<Route path="/jobs" element={<ProtectedRoute><JobsPage /></ProtectedRoute>} />
|
||||
<Route path="/scorecards" element={<ProtectedRoute><ScorecardsPage /></ProtectedRoute>} />
|
||||
</Routes>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/register" element={<RegisterPage />} />
|
||||
<Route path="/*" element={<Layout />} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
52
client/src/components/ui/button.tsx
Normal file
52
client/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive cursor-pointer",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40",
|
||||
outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground",
|
||||
secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
64
client/src/components/ui/card.tsx
Normal file
64
client/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn("flex flex-col gap-1.5 px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
||||
20
client/src/components/ui/input.tsx
Normal file
20
client/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
22
client/src/components/ui/label.tsx
Normal file
22
client/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
import { Label as LabelPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
25
client/src/components/ui/separator.tsx
Normal file
25
client/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
107
client/src/index.css
Normal file
107
client/src/index.css
Normal file
@@ -0,0 +1,107 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-sidebar-background: var(--sidebar-background);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--sidebar-background: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.145 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.145 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.985 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.269 0 0);
|
||||
--input: oklch(0.269 0 0);
|
||||
--ring: oklch(0.439 0 0);
|
||||
--sidebar-background: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(0.269 0 0);
|
||||
--sidebar-ring: oklch(0.439 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
127
client/src/lib/auth.tsx
Normal file
127
client/src/lib/auth.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
email: string
|
||||
role: 'admin' | 'recruiter' | 'hiring_manager'
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null
|
||||
accessToken: string | null
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => Promise<void>
|
||||
register: (email: string, password: string, role?: string) => Promise<void>
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [accessToken, setAccessToken] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
const refreshToken = localStorage.getItem('refreshToken')
|
||||
if (token && refreshToken) {
|
||||
// Verify token by fetching /auth/me
|
||||
fetch('/auth/me', { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.id) {
|
||||
setUser(data)
|
||||
setAccessToken(token)
|
||||
} else {
|
||||
// Try refresh
|
||||
return refreshAccessToken(refreshToken)
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false))
|
||||
} else {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function refreshAccessToken(refreshToken: string) {
|
||||
const res = await fetch('/auth/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refreshToken })
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setAccessToken(data.accessToken)
|
||||
setUser(data.user)
|
||||
localStorage.setItem('accessToken', data.accessToken)
|
||||
} else {
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('refreshToken')
|
||||
}
|
||||
}
|
||||
|
||||
async function login(email: string, password: string) {
|
||||
const res = await fetch('/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password })
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.error || 'Login failed')
|
||||
setUser(data.user)
|
||||
setAccessToken(data.accessToken)
|
||||
localStorage.setItem('accessToken', data.accessToken)
|
||||
localStorage.setItem('refreshToken', data.refreshToken)
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
const token = accessToken || localStorage.getItem('accessToken')
|
||||
if (token) {
|
||||
await fetch('/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
}).catch(() => {})
|
||||
}
|
||||
setUser(null)
|
||||
setAccessToken(null)
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('refreshToken')
|
||||
}
|
||||
|
||||
async function register(email: string, password: string, role = 'recruiter') {
|
||||
const res = await fetch('/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password, role })
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.error || 'Registration failed')
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, accessToken, login, logout, register, loading }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Helper to make authenticated API calls
|
||||
export async function authFetch(url: string, options: RequestInit = {}) {
|
||||
const token = localStorage.getItem('accessToken')
|
||||
return fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...options.headers
|
||||
}
|
||||
})
|
||||
}
|
||||
6
client/src/lib/utils.ts
Normal file
6
client/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
10
client/src/main.tsx
Normal file
10
client/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
171
client/src/pages/Candidates.tsx
Normal file
171
client/src/pages/Candidates.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
interface Candidate {
|
||||
id: number
|
||||
name: string
|
||||
email: string | null
|
||||
phone: string | null
|
||||
skills: string[]
|
||||
experience_years: number | null
|
||||
education: string | null
|
||||
summary: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export default function CandidatesPage() {
|
||||
const [candidates, setCandidates] = useState<Candidate[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [cvText, setCvText] = useState('')
|
||||
const [parsing, setParsing] = useState(false)
|
||||
const [message, setMessage] = useState('')
|
||||
const [selected, setSelected] = useState<Candidate | null>(null)
|
||||
|
||||
const loadCandidates = () => {
|
||||
setLoading(true)
|
||||
fetch('/api/candidates')
|
||||
.then(r => r.json())
|
||||
.then(d => setCandidates(d.candidates || []))
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
|
||||
useEffect(() => { loadCandidates() }, [])
|
||||
|
||||
const parseCV = async () => {
|
||||
if (!cvText.trim()) return
|
||||
setParsing(true)
|
||||
setMessage('')
|
||||
try {
|
||||
const res = await fetch('/api/candidates/parse-cv', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: cvText })
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.success) {
|
||||
setMessage(`✓ CV parsed: ${data.candidate.name} added`)
|
||||
setCvText('')
|
||||
loadCandidates()
|
||||
} else {
|
||||
setMessage(`Error: ${data.error}`)
|
||||
}
|
||||
} catch (e) {
|
||||
setMessage('Failed to parse CV')
|
||||
} finally {
|
||||
setParsing(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
const text = await file.text()
|
||||
setCvText(text)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Candidates</h1>
|
||||
<p className="text-muted-foreground text-sm">AI-powered CV parsing and candidate profiles</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2 mb-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Parse CV</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Upload CV file</label>
|
||||
<Input type="file" accept=".txt,.md,.rtf" onChange={handleFileUpload} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Or paste CV text</label>
|
||||
<textarea
|
||||
className="w-full min-h-[120px] rounded-md border border-input bg-background px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
placeholder="Paste CV text here..."
|
||||
value={cvText}
|
||||
onChange={e => setCvText(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{message && (
|
||||
<div className={`text-sm p-2 rounded ${message.startsWith('✓') ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
<Button onClick={parseCV} disabled={parsing || !cvText.trim()} className="w-full">
|
||||
{parsing ? 'Parsing...' : 'Parse CV with AI'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selected && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex justify-between items-center">
|
||||
{selected.name}
|
||||
<button onClick={() => setSelected(null)} className="text-muted-foreground text-sm">✕</button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
{selected.email && <div><span className="font-medium">Email:</span> {selected.email}</div>}
|
||||
{selected.phone && <div><span className="font-medium">Phone:</span> {selected.phone}</div>}
|
||||
{selected.experience_years && <div><span className="font-medium">Experience:</span> {selected.experience_years} years</div>}
|
||||
{selected.education && <div><span className="font-medium">Education:</span> {selected.education}</div>}
|
||||
{selected.summary && <div><span className="font-medium">Summary:</span> {selected.summary}</div>}
|
||||
{selected.skills?.length > 0 && (
|
||||
<div>
|
||||
<span className="font-medium">Skills:</span>
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
{selected.skills.map(s => (
|
||||
<span key={s} className="bg-primary/10 text-primary text-xs px-2 py-0.5 rounded-full">{s}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-4">All Candidates ({candidates.length})</h2>
|
||||
{loading ? (
|
||||
<div className="text-muted-foreground text-sm">Loading...</div>
|
||||
) : candidates.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<div className="text-4xl mb-2">👤</div>
|
||||
<div>No candidates yet. Parse a CV to add the first one.</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{candidates.map(c => (
|
||||
<Card key={c.id} className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setSelected(c)}>
|
||||
<CardContent className="pt-4">
|
||||
<div className="font-medium">{c.name}</div>
|
||||
<div className="text-sm text-muted-foreground">{c.email || 'No email'}</div>
|
||||
{c.experience_years && (
|
||||
<div className="text-xs text-muted-foreground mt-1">{c.experience_years}y experience</div>
|
||||
)}
|
||||
{c.skills?.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-2">
|
||||
{c.skills.slice(0, 4).map(s => (
|
||||
<span key={s} className="bg-muted text-xs px-1.5 py-0.5 rounded">{s}</span>
|
||||
))}
|
||||
{c.skills.length > 4 && <span className="text-xs text-muted-foreground">+{c.skills.length - 4}</span>}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
208
client/src/pages/Home.tsx
Normal file
208
client/src/pages/Home.tsx
Normal file
@@ -0,0 +1,208 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { authFetch } from '@/lib/auth'
|
||||
|
||||
interface Metrics {
|
||||
totalCandidates: number
|
||||
activeJobs: number
|
||||
totalApplications: number
|
||||
interviewsThisWeek: number
|
||||
}
|
||||
|
||||
interface PipelineSummary {
|
||||
applied: number
|
||||
screening: number
|
||||
interview: number
|
||||
offer: number
|
||||
hired: number
|
||||
}
|
||||
|
||||
interface Activity {
|
||||
type: string
|
||||
title: string
|
||||
subtitle: string | null
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const [metrics, setMetrics] = useState<Metrics>({ totalCandidates: 0, activeJobs: 0, totalApplications: 0, interviewsThisWeek: 0 })
|
||||
const [pipeline, setPipeline] = useState<PipelineSummary>({ applied: 0, screening: 0, interview: 0, offer: 0, hired: 0 })
|
||||
const [activities, setActivities] = useState<Activity[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const load = () => {
|
||||
authFetch('/api/dashboard/metrics').then(r => r.json()).then(setMetrics).catch(() => {})
|
||||
authFetch('/api/dashboard/pipeline-summary').then(r => r.json()).then(setPipeline).catch(() => {})
|
||||
authFetch('/api/dashboard/recent-activity').then(r => r.json()).then(d => setActivities(d.activities || [])).catch(() => {})
|
||||
}
|
||||
load()
|
||||
const interval = setInterval(load, 30000)
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
const pipelineStages = [
|
||||
{ key: 'applied', label: 'Applied', color: 'bg-gray-100 text-gray-700' },
|
||||
{ key: 'screening', label: 'Screening', color: 'bg-blue-100 text-blue-700' },
|
||||
{ key: 'interview', label: 'Interview', color: 'bg-yellow-100 text-yellow-700' },
|
||||
{ key: 'offer', label: 'Offer', color: 'bg-purple-100 text-purple-700' },
|
||||
{ key: 'hired', label: 'Hired', color: 'bg-green-100 text-green-700' },
|
||||
]
|
||||
|
||||
const activityTypeLabel: Record<string, string> = {
|
||||
candidate_added: 'New Candidate',
|
||||
job_posted: 'Job Posted',
|
||||
application: 'Application'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-8 gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Dashboard</h1>
|
||||
<p className="text-muted-foreground mt-1">Your recruitment activity at a glance</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Link to="/jobs">
|
||||
<Button className="bg-[#3B82F6] hover:bg-blue-600 text-white">Post a Job</Button>
|
||||
</Link>
|
||||
<Link to="/candidates">
|
||||
<Button variant="outline">Add Candidate</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Metrics */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4 mb-8">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Total Candidates</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-[#3B82F6]">{metrics.totalCandidates}</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">In your database</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Active Jobs</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-[#3B82F6]">{metrics.activeJobs}</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">Currently posted</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Applications</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-[#3B82F6]">{metrics.totalApplications}</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">Total received</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Interviews This Week</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-[#3B82F6]">{metrics.interviewsThisWeek}</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">Scorecards submitted</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2 mb-6">
|
||||
{/* Pipeline Overview */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Pipeline Overview</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{pipeline.applied + pipeline.screening + pipeline.interview + pipeline.offer + pipeline.hired === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<p className="text-sm">No candidates in pipeline yet.</p>
|
||||
<Link to="/candidates" className="text-[#3B82F6] text-sm hover:underline mt-2 inline-block">Add your first candidate →</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{pipelineStages.map(stage => (
|
||||
<div key={stage.key} className="flex items-center gap-3">
|
||||
<span className={`text-xs font-medium px-2 py-1 rounded-full w-24 text-center ${stage.color}`}>{stage.label}</span>
|
||||
<div className="flex-1 bg-gray-100 rounded-full h-2">
|
||||
<div
|
||||
className="bg-[#3B82F6] h-2 rounded-full transition-all"
|
||||
style={{ width: `${Math.min(100, (pipeline[stage.key as keyof PipelineSummary] / Math.max(1, metrics.totalApplications)) * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-sm font-medium w-8 text-right">{pipeline[stage.key as keyof PipelineSummary]}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Activity */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recent Activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{activities.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<p className="text-sm">No activity yet. Start by posting a job or adding a candidate.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{activities.map((activity, i) => (
|
||||
<div key={i} className="flex items-start gap-3 py-2 border-b last:border-0">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{activity.title}</p>
|
||||
<p className="text-xs text-muted-foreground">{activityTypeLabel[activity.type] || activity.type}{activity.subtitle ? ` — ${activity.subtitle}` : ''}</p>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{new Date(activity.timestamp).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Card className="hover:shadow-md transition-shadow cursor-pointer">
|
||||
<CardContent className="pt-6">
|
||||
<Link to="/jobs" className="block">
|
||||
<div className="text-2xl mb-2">💼</div>
|
||||
<h3 className="font-semibold">Post a Job</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">Publish to LinkedIn, Indeed, and more</p>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="hover:shadow-md transition-shadow cursor-pointer">
|
||||
<CardContent className="pt-6">
|
||||
<Link to="/candidates" className="block">
|
||||
<div className="text-2xl mb-2">👤</div>
|
||||
<h3 className="font-semibold">Add Candidate</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">Upload CV or enter details manually</p>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="hover:shadow-md transition-shadow cursor-pointer">
|
||||
<CardContent className="pt-6">
|
||||
<Link to="/scorecards" className="block">
|
||||
<div className="text-2xl mb-2">📋</div>
|
||||
<h3 className="font-semibold">Create Scorecard</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">Evaluate and compare candidates</p>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
236
client/src/pages/Jobs.tsx
Normal file
236
client/src/pages/Jobs.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
interface Job {
|
||||
id: number
|
||||
title: string
|
||||
description: string | null
|
||||
requirements: string | null
|
||||
location: string | null
|
||||
salary_min: number | null
|
||||
salary_max: number | null
|
||||
channels: string[]
|
||||
status: string
|
||||
posted_at: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
const CHANNELS = [
|
||||
{ id: 'linkedin', label: 'LinkedIn Jobs' },
|
||||
{ id: 'indeed', label: 'Indeed' },
|
||||
{ id: 'arbetsformedlingen', label: 'Arbetsförmedlingen' },
|
||||
{ id: 'company_site', label: 'Company Career Page' },
|
||||
{ id: 'glassdoor', label: 'Glassdoor' },
|
||||
]
|
||||
|
||||
export default function JobsPage() {
|
||||
const [jobs, setJobs] = useState<Job[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({ title: '', description: '', requirements: '', location: '', salary_min: '', salary_max: '' })
|
||||
const [posting, setPosting] = useState(false)
|
||||
const [message, setMessage] = useState('')
|
||||
const [selected, setSelected] = useState<Job | null>(null)
|
||||
const [postChannels, setPostChannels] = useState<string[]>([])
|
||||
const [postingTo, setPostingTo] = useState<number | null>(null)
|
||||
const [postResult, setPostResult] = useState<Record<string, any> | null>(null)
|
||||
|
||||
const loadJobs = () => {
|
||||
setLoading(true)
|
||||
fetch('/api/jobs')
|
||||
.then(r => r.json())
|
||||
.then(d => setJobs(d.jobs || []))
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
|
||||
useEffect(() => { loadJobs() }, [])
|
||||
|
||||
const createJob = async () => {
|
||||
if (!form.title.trim()) return
|
||||
setPosting(true)
|
||||
setMessage('')
|
||||
try {
|
||||
const res = await fetch('/api/jobs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...form,
|
||||
salary_min: form.salary_min ? parseInt(form.salary_min) : null,
|
||||
salary_max: form.salary_max ? parseInt(form.salary_max) : null,
|
||||
})
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.success) {
|
||||
setMessage(`✓ Job "${data.job.title}" created`)
|
||||
setForm({ title: '', description: '', requirements: '', location: '', salary_min: '', salary_max: '' })
|
||||
setShowForm(false)
|
||||
loadJobs()
|
||||
} else {
|
||||
setMessage(`Error: ${data.error}`)
|
||||
}
|
||||
} catch (e) {
|
||||
setMessage('Failed to create job')
|
||||
} finally {
|
||||
setPosting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const postToChannels = async (jobId: number) => {
|
||||
if (!postChannels.length) return
|
||||
setPostingTo(jobId)
|
||||
setPostResult(null)
|
||||
try {
|
||||
const res = await fetch(`/api/jobs/${jobId}/post`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ channels: postChannels })
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.success) {
|
||||
setPostResult(data.postingResults)
|
||||
loadJobs()
|
||||
}
|
||||
} finally {
|
||||
setPostingTo(null)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleChannel = (ch: string) => {
|
||||
setPostChannels(prev => prev.includes(ch) ? prev.filter(c => c !== ch) : [...prev, ch])
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Jobs</h1>
|
||||
<p className="text-muted-foreground text-sm">Create and post jobs to multiple platforms</p>
|
||||
</div>
|
||||
<Button onClick={() => setShowForm(!showForm)}>
|
||||
{showForm ? 'Cancel' : '+ New Job'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`mb-4 text-sm p-2 rounded ${message.startsWith('✓') ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showForm && (
|
||||
<Card className="mb-6">
|
||||
<CardHeader><CardTitle className="text-base">Create New Job</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<Input placeholder="Job title *" value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} />
|
||||
<textarea
|
||||
className="w-full min-h-[80px] rounded-md border border-input bg-background px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
placeholder="Job description"
|
||||
value={form.description}
|
||||
onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
|
||||
/>
|
||||
<textarea
|
||||
className="w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
placeholder="Requirements"
|
||||
value={form.requirements}
|
||||
onChange={e => setForm(f => ({ ...f, requirements: e.target.value }))}
|
||||
/>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<Input placeholder="Location" value={form.location} onChange={e => setForm(f => ({ ...f, location: e.target.value }))} />
|
||||
<Input placeholder="Min salary" type="number" value={form.salary_min} onChange={e => setForm(f => ({ ...f, salary_min: e.target.value }))} />
|
||||
<Input placeholder="Max salary" type="number" value={form.salary_max} onChange={e => setForm(f => ({ ...f, salary_max: e.target.value }))} />
|
||||
</div>
|
||||
<Button onClick={createJob} disabled={posting || !form.title.trim()}>
|
||||
{posting ? 'Creating...' : 'Create Job'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{selected && (
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex justify-between items-center">
|
||||
Post "{selected.title}" to Channels
|
||||
<button onClick={() => { setSelected(null); setPostResult(null); setPostChannels([]) }} className="text-muted-foreground text-sm">✕</button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2 mb-4">
|
||||
{CHANNELS.map(ch => (
|
||||
<label key={ch.id} className={`flex items-center gap-2 p-2 rounded border cursor-pointer text-sm ${postChannels.includes(ch.id) ? 'border-primary bg-primary/5' : 'border-input'}`}>
|
||||
<input type="checkbox" checked={postChannels.includes(ch.id)} onChange={() => toggleChannel(ch.id)} className="accent-primary" />
|
||||
{ch.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => postToChannels(selected.id)}
|
||||
disabled={!postChannels.length || postingTo === selected.id}
|
||||
>
|
||||
{postingTo === selected.id ? 'Posting...' : `Post to ${postChannels.length} channel${postChannels.length !== 1 ? 's' : ''}`}
|
||||
</Button>
|
||||
{postResult && (
|
||||
<div className="mt-4 space-y-2">
|
||||
<div className="font-medium text-sm">Posted successfully to:</div>
|
||||
{Object.entries(postResult).map(([ch, result]: [string, any]) => (
|
||||
<div key={ch} className="text-sm text-green-700 bg-green-50 p-2 rounded">
|
||||
✓ {result.platform} — {new Date(result.postedAt).toLocaleString()}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-4">All Jobs ({jobs.length})</h2>
|
||||
{loading ? (
|
||||
<div className="text-muted-foreground text-sm">Loading...</div>
|
||||
) : jobs.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<div className="text-4xl mb-2">💼</div>
|
||||
<div>No jobs yet. Create your first job posting.</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{jobs.map(j => (
|
||||
<Card key={j.id}>
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1">
|
||||
<div className="font-medium">{j.title}</div>
|
||||
{j.location && <div className="text-sm text-muted-foreground">{j.location}</div>}
|
||||
{(j.salary_min || j.salary_max) && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{j.salary_min && j.salary_max ? `${j.salary_min.toLocaleString()} – ${j.salary_max.toLocaleString()} SEK` : `From ${(j.salary_min || j.salary_max)?.toLocaleString()} SEK`}
|
||||
</div>
|
||||
)}
|
||||
{j.channels?.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-2">
|
||||
{j.channels.map(ch => (
|
||||
<span key={ch} className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">{ch}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-2">
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full ${j.status === 'posted' ? 'bg-green-100 text-green-700' : 'bg-muted text-muted-foreground'}`}>
|
||||
{j.status}
|
||||
</span>
|
||||
<Button variant="outline" size="sm" onClick={() => { setSelected(j); setPostChannels(j.channels || []); setPostResult(null) }}>
|
||||
Post to Channels
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
86
client/src/pages/Login.tsx
Normal file
86
client/src/pages/Login.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
export default function LoginPage() {
|
||||
const { login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await login(email, password)
|
||||
navigate('/')
|
||||
} catch (err: any) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#F9FAFB] flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-md">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-bold text-[#3B82F6]">HireFlow</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">AI Recruitment Platform</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl">Sign in to your account</CardTitle>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="you@company.com"
|
||||
value={email}
|
||||
onChange={e => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col gap-3">
|
||||
<Button type="submit" className="w-full bg-[#3B82F6] hover:bg-blue-600" disabled={loading}>
|
||||
{loading ? 'Signing in...' : 'Sign In'}
|
||||
</Button>
|
||||
<p className="text-sm text-center text-gray-500">
|
||||
No account yet?{' '}
|
||||
<Link to="/register" className="text-[#3B82F6] hover:underline font-medium">Register</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
89
client/src/pages/Register.tsx
Normal file
89
client/src/pages/Register.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
export default function RegisterPage() {
|
||||
const { register } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
const [role, setRole] = useState('recruiter')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
if (password !== confirmPassword) { setError('Passwords do not match'); return }
|
||||
if (password.length < 8) { setError('Password must be at least 8 characters'); return }
|
||||
setLoading(true)
|
||||
try {
|
||||
await register(email, password, role)
|
||||
navigate('/login?registered=1')
|
||||
} catch (err: any) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#F9FAFB] flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-md">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-bold text-[#3B82F6]">HireFlow</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">AI Recruitment Platform</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl">Create your account</CardTitle>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Work Email</Label>
|
||||
<Input id="email" type="email" placeholder="you@company.com" value={email} onChange={e => setEmail(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="role">Role</Label>
|
||||
<select id="role" value={role} onChange={e => setRole(e.target.value)}
|
||||
className="w-full border border-input rounded-md px-3 py-2 text-sm bg-background">
|
||||
<option value="recruiter">Recruiter</option>
|
||||
<option value="hiring_manager">Hiring Manager</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input id="password" type="password" placeholder="Min. 8 characters" value={password} onChange={e => setPassword(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">Confirm Password</Label>
|
||||
<Input id="confirmPassword" type="password" placeholder="Repeat password" value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)} required />
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col gap-3">
|
||||
<Button type="submit" className="w-full bg-[#3B82F6] hover:bg-blue-600" disabled={loading}>
|
||||
{loading ? 'Creating account...' : 'Create Account'}
|
||||
</Button>
|
||||
<p className="text-sm text-center text-gray-500">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="text-[#3B82F6] hover:underline font-medium">Sign in</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
266
client/src/pages/Scorecards.tsx
Normal file
266
client/src/pages/Scorecards.tsx
Normal file
@@ -0,0 +1,266 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
interface Candidate { id: number; name: string; email: string | null }
|
||||
interface Job { id: number; title: string }
|
||||
interface Scorecard {
|
||||
id: number
|
||||
job_id: number
|
||||
candidate_id: number
|
||||
interviewer: string
|
||||
criteria: Record<string, { score: number; notes: string }>
|
||||
total_score: number
|
||||
comments: string | null
|
||||
recommendation: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
const CRITERIA = [
|
||||
{ key: 'technical', label: 'Technical Skills' },
|
||||
{ key: 'communication', label: 'Communication' },
|
||||
{ key: 'culture_fit', label: 'Culture Fit' },
|
||||
{ key: 'problem_solving', label: 'Problem Solving' },
|
||||
{ key: 'experience', label: 'Relevant Experience' },
|
||||
]
|
||||
|
||||
export default function ScorecardsPage() {
|
||||
const [candidates, setCandidates] = useState<Candidate[]>([])
|
||||
const [jobs, setJobs] = useState<Job[]>([])
|
||||
const [scorecards, setScorecards] = useState<Scorecard[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({
|
||||
job_id: '',
|
||||
candidate_id: '',
|
||||
interviewer: '',
|
||||
comments: '',
|
||||
recommendation: 'maybe',
|
||||
})
|
||||
const [criteria, setCriteria] = useState<Record<string, { score: number; notes: string }>>(
|
||||
Object.fromEntries(CRITERIA.map(c => [c.key, { score: 3, notes: '' }]))
|
||||
)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
fetch('/api/candidates').then(r => r.json()),
|
||||
fetch('/api/jobs').then(r => r.json()),
|
||||
fetch('/api/scorecards').then(r => r.json()),
|
||||
]).then(([c, j, s]) => {
|
||||
setCandidates(c.candidates || [])
|
||||
setJobs(j.jobs || [])
|
||||
setScorecards(s.scorecards || [])
|
||||
}).finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
const loadScorecards = () => {
|
||||
fetch('/api/scorecards').then(r => r.json()).then(d => setScorecards(d.scorecards || []))
|
||||
}
|
||||
|
||||
const submitScorecard = async () => {
|
||||
if (!form.job_id || !form.candidate_id || !form.interviewer) return
|
||||
setSubmitting(true)
|
||||
setMessage('')
|
||||
try {
|
||||
const res = await fetch('/api/scorecards', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
job_id: parseInt(form.job_id),
|
||||
candidate_id: parseInt(form.candidate_id),
|
||||
interviewer: form.interviewer,
|
||||
criteria,
|
||||
comments: form.comments,
|
||||
recommendation: form.recommendation,
|
||||
})
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.success) {
|
||||
setMessage(`✓ Scorecard submitted by ${form.interviewer}`)
|
||||
setShowForm(false)
|
||||
loadScorecards()
|
||||
} else {
|
||||
setMessage(`Error: ${data.error}`)
|
||||
}
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const getCandidate = (id: number) => candidates.find(c => c.id === id)
|
||||
const getJob = (id: number) => jobs.find(j => j.id === id)
|
||||
|
||||
const scoreColor = (score: number) => {
|
||||
if (score >= 4) return 'text-green-600'
|
||||
if (score >= 3) return 'text-yellow-600'
|
||||
return 'text-red-600'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Scorecards</h1>
|
||||
<p className="text-muted-foreground text-sm">Collaborative candidate evaluations</p>
|
||||
</div>
|
||||
<Button onClick={() => setShowForm(!showForm)}>
|
||||
{showForm ? 'Cancel' : '+ New Scorecard'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`mb-4 text-sm p-2 rounded ${message.startsWith('✓') ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showForm && (
|
||||
<Card className="mb-6">
|
||||
<CardHeader><CardTitle className="text-base">New Scorecard</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Job *</label>
|
||||
<select
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
value={form.job_id}
|
||||
onChange={e => setForm(f => ({ ...f, job_id: e.target.value }))}
|
||||
>
|
||||
<option value="">Select job...</option>
|
||||
{jobs.map(j => <option key={j.id} value={j.id}>{j.title}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Candidate *</label>
|
||||
<select
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
value={form.candidate_id}
|
||||
onChange={e => setForm(f => ({ ...f, candidate_id: e.target.value }))}
|
||||
>
|
||||
<option value="">Select candidate...</option>
|
||||
{candidates.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Interviewer *</label>
|
||||
<Input
|
||||
placeholder="Your name"
|
||||
value={form.interviewer}
|
||||
onChange={e => setForm(f => ({ ...f, interviewer: e.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm font-medium mb-2">Scoring (1–5)</div>
|
||||
<div className="space-y-2">
|
||||
{CRITERIA.map(c => (
|
||||
<div key={c.key} className="flex items-center gap-3">
|
||||
<span className="text-sm w-36 flex-shrink-0">{c.label}</span>
|
||||
<div className="flex gap-1">
|
||||
{[1, 2, 3, 4, 5].map(n => (
|
||||
<button
|
||||
key={n}
|
||||
onClick={() => setCriteria(prev => ({ ...prev, [c.key]: { ...prev[c.key], score: n } }))}
|
||||
className={`w-8 h-8 rounded text-sm font-medium border transition-colors ${criteria[c.key].score === n ? 'bg-primary text-primary-foreground border-primary' : 'border-input hover:bg-muted'}`}
|
||||
>{n}</button>
|
||||
))}
|
||||
</div>
|
||||
<Input
|
||||
className="flex-1 h-8 text-xs"
|
||||
placeholder="Notes..."
|
||||
value={criteria[c.key].notes}
|
||||
onChange={e => setCriteria(prev => ({ ...prev, [c.key]: { ...prev[c.key], notes: e.target.value } }))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Recommendation</label>
|
||||
<select
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
value={form.recommendation}
|
||||
onChange={e => setForm(f => ({ ...f, recommendation: e.target.value }))}
|
||||
>
|
||||
<option value="strong_yes">Strong Yes</option>
|
||||
<option value="yes">Yes</option>
|
||||
<option value="maybe">Maybe</option>
|
||||
<option value="no">No</option>
|
||||
<option value="strong_no">Strong No</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Comments</label>
|
||||
<Input
|
||||
placeholder="Overall comments..."
|
||||
value={form.comments}
|
||||
onChange={e => setForm(f => ({ ...f, comments: e.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={submitScorecard}
|
||||
disabled={submitting || !form.job_id || !form.candidate_id || !form.interviewer}
|
||||
>
|
||||
{submitting ? 'Submitting...' : 'Submit Scorecard'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-4">All Scorecards ({scorecards.length})</h2>
|
||||
{loading ? (
|
||||
<div className="text-muted-foreground text-sm">Loading...</div>
|
||||
) : scorecards.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<div className="text-4xl mb-2">📋</div>
|
||||
<div>No scorecards yet. Evaluate your first candidate.</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{scorecards.map(sc => {
|
||||
const candidate = getCandidate(sc.candidate_id)
|
||||
const job = getJob(sc.job_id)
|
||||
const recColors: Record<string, string> = {
|
||||
strong_yes: 'bg-green-100 text-green-800',
|
||||
yes: 'bg-green-50 text-green-700',
|
||||
maybe: 'bg-yellow-50 text-yellow-700',
|
||||
no: 'bg-red-50 text-red-700',
|
||||
strong_no: 'bg-red-100 text-red-800',
|
||||
}
|
||||
return (
|
||||
<Card key={sc.id}>
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1">
|
||||
<div className="font-medium">{candidate?.name || `Candidate #${sc.candidate_id}`}</div>
|
||||
<div className="text-sm text-muted-foreground">{job?.title || `Job #${sc.job_id}`} • Interviewer: {sc.interviewer}</div>
|
||||
{sc.comments && <div className="text-sm mt-1 text-muted-foreground">{sc.comments}</div>}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<span className={`text-2xl font-bold ${scoreColor(sc.total_score)}`}>{sc.total_score}/5</span>
|
||||
{sc.recommendation && (
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full capitalize ${recColors[sc.recommendation] || 'bg-muted'}`}>
|
||||
{sc.recommendation.replace('_', ' ')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
1
client/src/vite-env.d.ts
vendored
Normal file
1
client/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
3
client/tsconfig.app.json
Normal file
3
client/tsconfig.app.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./tsconfig.json"
|
||||
}
|
||||
25
client/tsconfig.json
Normal file
25
client/tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
22
client/vite.config.ts
Normal file
22
client/vite.config.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': 'http://localhost:3000',
|
||||
'/health': 'http://localhost:3000',
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
},
|
||||
})
|
||||
@@ -1,3 +1,17 @@
|
||||
# SAAC Application Stack — PRODUCTION container
|
||||
# See SAAC_DEPLOYMENT.md for full deployment rules and common mistakes.
|
||||
#
|
||||
# This file is used by "saac deploy" to build the production Docker image.
|
||||
# Your app also gets a HOT-RELOAD container (yourapp-hot.<server>.domain.com)
|
||||
# that auto-rebuilds on every git push — see nodemon.json for its config.
|
||||
#
|
||||
# Key rules:
|
||||
# 1. Use "expose", NEVER "ports" — Traefik handles routing
|
||||
# 2. Database host = service name ("postgres"), NEVER "localhost"
|
||||
# 3. Do NOT change POSTGRES_DB after first deploy — Docker volume keeps the old name
|
||||
# 4. Do NOT add Traefik labels — SAAC uses file provider, labels are ignored
|
||||
# 5. Keep it simple — get this working first, then iterate
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
@@ -9,11 +23,17 @@ services:
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- PORT=3000
|
||||
# Database host MUST be the service name ("postgres"), not "localhost".
|
||||
# In Docker, localhost = inside this container. "postgres" resolves to
|
||||
# the postgres service below via Docker DNS.
|
||||
- POSTGRES_HOST=postgres
|
||||
- POSTGRES_PORT=5432
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=postgres
|
||||
- POSTGRES_DB=template_db
|
||||
# WARNING: Do NOT change POSTGRES_DB after first deploy!
|
||||
# The Docker volume persists the original database name.
|
||||
# If you change this, the new database won't exist and your app will crash.
|
||||
- POSTGRES_DB=postgres
|
||||
- REDIS_HOST=redis
|
||||
- REDIS_PORT=6379
|
||||
- APP_VERSION=${APP_VERSION:-1.0.0}
|
||||
@@ -22,6 +42,9 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
# Use "expose" to make the port available to Traefik on the Docker network.
|
||||
# NEVER use "ports" (e.g. "3000:3000") — it binds to the host and conflicts
|
||||
# with other apps. Traefik handles all external routing automatically.
|
||||
expose:
|
||||
- "3000"
|
||||
healthcheck:
|
||||
@@ -37,7 +60,8 @@ services:
|
||||
environment:
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=postgres
|
||||
- POSTGRES_DB=template_db
|
||||
# This creates the database on first start. Must match POSTGRES_DB above.
|
||||
- POSTGRES_DB=postgres
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
expose:
|
||||
|
||||
5
nodemon.json
Normal file
5
nodemon.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"watch": ["server.js", "client/src"],
|
||||
"ext": "js,ts,tsx,jsx,css,json",
|
||||
"exec": "npm run build && node server.js"
|
||||
}
|
||||
2077
package-lock.json
generated
Normal file
2077
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
14
package.json
14
package.json
@@ -1,18 +1,28 @@
|
||||
{
|
||||
"name": "template-001",
|
||||
"version": "1.0.0",
|
||||
"description": "Template site for Start an AI Company deployment",
|
||||
"description": "SAAC company website template — React + shadcn/ui + Express + PostgreSQL",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "nodemon server.js"
|
||||
"dev": "nodemon",
|
||||
"build": "cd client && npm run build",
|
||||
"postinstall": "[ -d client ] && cd client && npm install || true",
|
||||
"dev:local": "concurrently \"nodemon server.js\" \"cd client && npm run dev\"",
|
||||
"dev:server": "nodemon server.js",
|
||||
"dev:client": "cd client && npm run dev"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.18.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"pg": "^8.11.3",
|
||||
"redis": "^4.6.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^8.2.2",
|
||||
"nodemon": "^3.0.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Template Site - Start an AI Company</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.08);
|
||||
padding: 60px 40px;
|
||||
max-width: 800px;
|
||||
text-align: center;
|
||||
border: 1px solid rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
border-radius: 16px;
|
||||
margin: 0 auto 30px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 40px;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 2.5rem;
|
||||
color: #1a202c;
|
||||
margin-bottom: 20px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1.2rem;
|
||||
color: #4a5568;
|
||||
line-height: 1.8;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.features {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.feature {
|
||||
background: #f7fafc;
|
||||
padding: 25px 20px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid #e2e8f0;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.feature:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.feature-icon {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.feature-title {
|
||||
font-weight: 600;
|
||||
color: #2d3748;
|
||||
margin-bottom: 8px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.feature-desc {
|
||||
font-size: 0.875rem;
|
||||
color: #718096;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.footer {
|
||||
margin-top: 50px;
|
||||
padding-top: 30px;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
color: #718096;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.status-indicator {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
background: #48bb78;
|
||||
border-radius: 50%;
|
||||
margin-right: 8px;
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="logo">T</div>
|
||||
<h1>This site is a template site on how to deploy on Start an AI Company servers</h1>
|
||||
<p>A modern, scalable deployment template featuring Docker Compose, PostgreSQL, Redis, and Traefik integration.</p>
|
||||
|
||||
<div class="features">
|
||||
<div class="feature">
|
||||
<div class="feature-icon">🐳</div>
|
||||
<div class="feature-title">Docker Ready</div>
|
||||
<p class="feature-desc">Containerized with Docker Compose</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="feature-icon">🗄️</div>
|
||||
<div class="feature-title">PostgreSQL</div>
|
||||
<p class="feature-desc">Robust database solution</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="feature-icon">⚡</div>
|
||||
<div class="feature-title">Redis Cache</div>
|
||||
<p class="feature-desc">High-performance caching</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="feature-icon">🚀</div>
|
||||
<div class="feature-title">Traefik Ready</div>
|
||||
<p class="feature-desc">Automatic routing & SSL</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>
|
||||
<span class="status-indicator"></span>
|
||||
Status: Running on Start an AI Company infrastructure
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
609
server.js
609
server.js
@@ -2,9 +2,18 @@ const express = require('express');
|
||||
const { Pool } = require('pg');
|
||||
const redis = require('redis');
|
||||
const path = require('path');
|
||||
const multer = require('multer');
|
||||
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } });
|
||||
const jwt = require('jsonwebtoken');
|
||||
const bcryptjs = require('bcryptjs');
|
||||
const bcrypt = bcryptjs;
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'hireflow-secret-key-change-in-production';
|
||||
const JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET || 'hireflow-refresh-secret-change-in-production';
|
||||
|
||||
app.use(express.json());
|
||||
|
||||
// PostgreSQL connection
|
||||
const pool = new Pool({
|
||||
@@ -12,7 +21,7 @@ const pool = new Pool({
|
||||
port: process.env.POSTGRES_PORT || 5432,
|
||||
user: process.env.POSTGRES_USER || 'postgres',
|
||||
password: process.env.POSTGRES_PASSWORD || 'postgres',
|
||||
database: process.env.POSTGRES_DB || 'template_db'
|
||||
database: process.env.POSTGRES_DB || 'postgres'
|
||||
});
|
||||
|
||||
// Redis connection
|
||||
@@ -23,57 +32,599 @@ const redisClient = redis.createClient({
|
||||
}
|
||||
});
|
||||
|
||||
// Connect to Redis
|
||||
redisClient.connect().catch(console.error);
|
||||
redisClient.on('connect', () => console.log('Redis connected'));
|
||||
redisClient.on('error', (err) => console.error('Redis error:', err));
|
||||
|
||||
// Initialize database schema
|
||||
async function initDb() {
|
||||
try {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS candidates (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255),
|
||||
phone VARCHAR(100),
|
||||
skills TEXT[],
|
||||
experience_years INTEGER,
|
||||
education TEXT,
|
||||
summary TEXT,
|
||||
raw_cv TEXT,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS jobs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
requirements TEXT,
|
||||
location VARCHAR(255),
|
||||
salary_min INTEGER,
|
||||
salary_max INTEGER,
|
||||
channels TEXT[],
|
||||
status VARCHAR(50) DEFAULT 'draft',
|
||||
posted_at TIMESTAMP,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scorecards (
|
||||
id SERIAL PRIMARY KEY,
|
||||
job_id INTEGER REFERENCES jobs(id),
|
||||
candidate_id INTEGER REFERENCES candidates(id),
|
||||
interviewer VARCHAR(255) NOT NULL,
|
||||
criteria JSONB,
|
||||
total_score INTEGER,
|
||||
comments TEXT,
|
||||
recommendation VARCHAR(50),
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS job_applications (
|
||||
id SERIAL PRIMARY KEY,
|
||||
job_id INTEGER REFERENCES jobs(id),
|
||||
candidate_id INTEGER REFERENCES candidates(id),
|
||||
status VARCHAR(50) DEFAULT 'applied',
|
||||
stage VARCHAR(50) DEFAULT 'screening',
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
UNIQUE(job_id, candidate_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
email VARCHAR(255) UNIQUE NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
role VARCHAR(50) NOT NULL DEFAULT 'recruiter',
|
||||
agency_id INTEGER,
|
||||
is_active BOOLEAN DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
deleted_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER REFERENCES users(id),
|
||||
token_hash VARCHAR(255) NOT NULL,
|
||||
expires_at TIMESTAMP NOT NULL,
|
||||
revoked_at TIMESTAMP,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
`);
|
||||
console.log('Database schema initialized');
|
||||
} catch (err) {
|
||||
console.error('DB init error:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Test database connections
|
||||
pool.query('SELECT NOW()', (err, res) => {
|
||||
if (err) {
|
||||
console.error('PostgreSQL connection error:', err);
|
||||
} else {
|
||||
console.log('PostgreSQL connected successfully at:', res.rows[0].now);
|
||||
console.log('PostgreSQL connected at:', res.rows[0].now);
|
||||
initDb();
|
||||
}
|
||||
});
|
||||
|
||||
redisClient.on('connect', () => {
|
||||
console.log('Redis connected successfully');
|
||||
// Simple CV parser using regex patterns
|
||||
function parseCV(text) {
|
||||
const emailMatch = text.match(/[\w.-]+@[\w.-]+\.\w+/);
|
||||
const phoneMatch = text.match(/(\+?[\d\s()-]{7,})/);
|
||||
|
||||
// Extract name (first line or after common headers)
|
||||
const lines = text.split('\n').filter(l => l.trim());
|
||||
const name = lines[0]?.trim() || 'Unknown';
|
||||
|
||||
// Extract skills
|
||||
const skillKeywords = ['JavaScript', 'TypeScript', 'React', 'Node.js', 'Python', 'Java', 'SQL',
|
||||
'PostgreSQL', 'MongoDB', 'Redis', 'Docker', 'AWS', 'Git', 'HTML', 'CSS', 'REST', 'GraphQL',
|
||||
'Vue', 'Angular', 'PHP', 'Ruby', 'Go', 'Rust', 'Swift', 'Kotlin', 'C++', 'C#', 'Agile', 'Scrum'];
|
||||
const skills = skillKeywords.filter(skill =>
|
||||
text.toLowerCase().includes(skill.toLowerCase())
|
||||
);
|
||||
|
||||
// Extract experience years
|
||||
const expMatch = text.match(/(\d+)\s*(?:\+\s*)?years?\s*(?:of\s*)?(?:experience|exp)/i);
|
||||
const experienceYears = expMatch ? parseInt(expMatch[1]) : null;
|
||||
|
||||
// Extract education
|
||||
const eduKeywords = ['Bachelor', 'Master', 'PhD', 'BSc', 'MSc', 'MBA', 'University', 'College'];
|
||||
const eduLines = lines.filter(l => eduKeywords.some(k => l.includes(k)));
|
||||
const education = eduLines.slice(0, 2).join('; ') || null;
|
||||
|
||||
return {
|
||||
name,
|
||||
email: emailMatch ? emailMatch[0] : null,
|
||||
phone: phoneMatch ? phoneMatch[0].trim() : null,
|
||||
skills: skills.length > 0 ? skills : ['General'],
|
||||
experience_years: experienceYears,
|
||||
education,
|
||||
summary: lines.slice(1, 4).join(' ').substring(0, 500) || null
|
||||
};
|
||||
}
|
||||
|
||||
// Auth middleware
|
||||
function authenticateToken(req, res, next) {
|
||||
const authHeader = req.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
if (!token) return res.status(401).json({ error: 'Access token required' });
|
||||
try {
|
||||
const user = jwt.verify(token, JWT_SECRET);
|
||||
req.user = user;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: 'Invalid or expired token' });
|
||||
}
|
||||
}
|
||||
|
||||
function requireRole(...roles) {
|
||||
return (req, res, next) => {
|
||||
if (!req.user || !roles.includes(req.user.role)) {
|
||||
return res.status(403).json({ error: 'Insufficient permissions' });
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
// POST /auth/register
|
||||
app.post('/auth/register', async (req, res) => {
|
||||
try {
|
||||
const { email, password, role } = req.body;
|
||||
if (!email || !password) return res.status(400).json({ error: 'Email and password required' });
|
||||
const allowedRoles = ['admin', 'recruiter', 'hiring_manager'];
|
||||
const userRole = allowedRoles.includes(role) ? role : 'recruiter';
|
||||
const passwordHash = await bcrypt.hash(password, 12);
|
||||
const result = await pool.query(
|
||||
'INSERT INTO users (email, password_hash, role) VALUES ($1, $2, $3) RETURNING id, email, role, created_at',
|
||||
[email.toLowerCase(), passwordHash, userRole]
|
||||
);
|
||||
res.status(201).json({ success: true, user: result.rows[0] });
|
||||
} catch (err) {
|
||||
if (err.code === '23505') return res.status(409).json({ error: 'Email already registered' });
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
redisClient.on('error', (err) => {
|
||||
console.error('Redis connection error:', err);
|
||||
// POST /auth/login
|
||||
app.post('/auth/login', async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
if (!email || !password) return res.status(400).json({ error: 'Email and password required' });
|
||||
const result = await pool.query('SELECT * FROM users WHERE email = $1 AND deleted_at IS NULL', [email.toLowerCase()]);
|
||||
if (!result.rows.length) return res.status(401).json({ error: 'Invalid credentials' });
|
||||
const user = result.rows[0];
|
||||
if (!user.is_active) return res.status(401).json({ error: 'Account is disabled' });
|
||||
const valid = await bcrypt.compare(password, user.password_hash);
|
||||
if (!valid) return res.status(401).json({ error: 'Invalid credentials' });
|
||||
const accessToken = jwt.sign({ id: user.id, email: user.email, role: user.role }, JWT_SECRET, { expiresIn: '15m' });
|
||||
const refreshToken = jwt.sign({ id: user.id }, JWT_REFRESH_SECRET, { expiresIn: '7d' });
|
||||
const refreshHash = await bcrypt.hash(refreshToken, 10);
|
||||
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
||||
await pool.query('INSERT INTO refresh_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)', [user.id, refreshHash, expiresAt]);
|
||||
res.json({ success: true, accessToken, refreshToken, user: { id: user.id, email: user.email, role: user.role } });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Serve static files
|
||||
app.use(express.static('public'));
|
||||
// POST /auth/refresh
|
||||
app.post('/auth/refresh', async (req, res) => {
|
||||
try {
|
||||
const { refreshToken } = req.body;
|
||||
if (!refreshToken) return res.status(401).json({ error: 'Refresh token required' });
|
||||
let payload;
|
||||
try { payload = jwt.verify(refreshToken, JWT_REFRESH_SECRET); } catch { return res.status(401).json({ error: 'Invalid refresh token' }); }
|
||||
const tokens = await pool.query('SELECT * FROM refresh_tokens WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > NOW()', [payload.id]);
|
||||
let validToken = null;
|
||||
for (const t of tokens.rows) {
|
||||
if (await bcrypt.compare(refreshToken, t.token_hash)) { validToken = t; break; }
|
||||
}
|
||||
if (!validToken) return res.status(401).json({ error: 'Invalid or expired refresh token' });
|
||||
const user = await pool.query('SELECT id, email, role FROM users WHERE id = $1 AND is_active = true AND deleted_at IS NULL', [payload.id]);
|
||||
if (!user.rows.length) return res.status(401).json({ error: 'User not found' });
|
||||
const accessToken = jwt.sign({ id: user.rows[0].id, email: user.rows[0].email, role: user.rows[0].role }, JWT_SECRET, { expiresIn: '15m' });
|
||||
res.json({ success: true, accessToken, user: user.rows[0] });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Health check endpoint
|
||||
// POST /auth/logout
|
||||
app.post('/auth/logout', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
await pool.query('UPDATE refresh_tokens SET revoked_at = NOW() WHERE user_id = $1 AND revoked_at IS NULL', [req.user.id]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /auth/me
|
||||
app.get('/auth/me', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT id, email, role, agency_id, is_active, created_at FROM users WHERE id = $1 AND deleted_at IS NULL', [req.user.id]);
|
||||
if (!result.rows.length) return res.status(404).json({ error: 'User not found' });
|
||||
res.json(result.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/users (admin only)
|
||||
app.get('/api/users', authenticateToken, requireRole('admin'), async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT id, email, role, agency_id, is_active, created_at FROM users WHERE deleted_at IS NULL ORDER BY created_at DESC');
|
||||
res.json({ users: result.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// PATCH /api/users/:id/role (admin only)
|
||||
app.patch('/api/users/:id/role', authenticateToken, requireRole('admin'), async (req, res) => {
|
||||
try {
|
||||
const { role } = req.body;
|
||||
const allowedRoles = ['admin', 'recruiter', 'hiring_manager'];
|
||||
if (!allowedRoles.includes(role)) return res.status(400).json({ error: 'Invalid role' });
|
||||
const result = await pool.query('UPDATE users SET role = $1, updated_at = NOW() WHERE id = $2 AND deleted_at IS NULL RETURNING id, email, role', [role, req.params.id]);
|
||||
if (!result.rows.length) return res.status(404).json({ error: 'User not found' });
|
||||
res.json({ success: true, user: result.rows[0] });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Add dashboard endpoints
|
||||
app.get('/api/dashboard/metrics', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const [candidates, jobs, applications, interviews] = await Promise.all([
|
||||
pool.query('SELECT COUNT(*) FROM candidates'),
|
||||
pool.query("SELECT COUNT(*) FROM jobs WHERE status = 'posted'"),
|
||||
pool.query('SELECT COUNT(*) FROM job_applications'),
|
||||
pool.query("SELECT COUNT(*) FROM scorecards WHERE created_at >= NOW() - INTERVAL '7 days'"),
|
||||
]);
|
||||
res.json({
|
||||
totalCandidates: parseInt(candidates.rows[0].count),
|
||||
activeJobs: parseInt(jobs.rows[0].count),
|
||||
totalApplications: parseInt(applications.rows[0].count),
|
||||
interviewsThisWeek: parseInt(interviews.rows[0].count),
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/dashboard/pipeline-summary', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT stage, COUNT(*) as count FROM job_applications GROUP BY stage');
|
||||
const stages = { applied: 0, screening: 0, interview: 0, offer: 0, hired: 0 };
|
||||
result.rows.forEach(r => { if (stages.hasOwnProperty(r.stage)) stages[r.stage] = parseInt(r.count); });
|
||||
res.json(stages);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/dashboard/recent-activity', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query(`
|
||||
SELECT 'candidate_added' as type, c.name as title, c.email as subtitle, c.created_at as timestamp
|
||||
FROM candidates c
|
||||
UNION ALL
|
||||
SELECT 'job_posted' as type, j.title, j.location as subtitle, j.created_at as timestamp
|
||||
FROM jobs j
|
||||
UNION ALL
|
||||
SELECT 'application' as type, c.name as title, jo.title as subtitle, ja.created_at as timestamp
|
||||
FROM job_applications ja JOIN candidates c ON ja.candidate_id = c.id JOIN jobs jo ON ja.job_id = jo.id
|
||||
ORDER BY timestamp DESC LIMIT 10
|
||||
`);
|
||||
res.json({ activities: result.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Health check
|
||||
app.get('/health', async (req, res) => {
|
||||
try {
|
||||
const pgResult = await pool.query('SELECT NOW()');
|
||||
await redisClient.ping();
|
||||
res.json({
|
||||
status: 'healthy',
|
||||
postgres: 'connected',
|
||||
redis: 'connected',
|
||||
timestamp: pgResult.rows[0].now,
|
||||
git_commit: process.env.GIT_COMMIT || 'unknown',
|
||||
version: process.env.APP_VERSION || '1.0.0'
|
||||
});
|
||||
res.json({ status: 'healthy', postgres: 'connected', redis: 'connected', timestamp: pgResult.rows[0].now });
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
status: 'unhealthy',
|
||||
error: error.message,
|
||||
git_commit: process.env.GIT_COMMIT || 'unknown',
|
||||
version: process.env.APP_VERSION || '1.0.0'
|
||||
});
|
||||
res.status(500).json({ status: 'unhealthy', error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Main route
|
||||
app.get('/', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'public', 'index.html'));
|
||||
// --- Candidates API ---
|
||||
|
||||
// Get all candidates
|
||||
app.get('/api/candidates', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM candidates ORDER BY created_at DESC');
|
||||
res.json({ candidates: result.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get single candidate
|
||||
app.get('/api/candidates/:id', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM candidates WHERE id = $1', [req.params.id]);
|
||||
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
|
||||
res.json(result.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Upload and parse CV
|
||||
app.post('/api/candidates/parse-cv', upload.single('cv'), async (req, res) => {
|
||||
try {
|
||||
if (!req.file && !req.body.text) {
|
||||
return res.status(400).json({ error: 'No CV file or text provided' });
|
||||
}
|
||||
|
||||
const cvText = req.file ? req.file.buffer.toString('utf-8') : req.body.text;
|
||||
const parsed = parseCV(cvText);
|
||||
|
||||
// Save to database
|
||||
const result = await pool.query(
|
||||
`INSERT INTO candidates (name, email, phone, skills, experience_years, education, summary, raw_cv)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *`,
|
||||
[parsed.name, parsed.email, parsed.phone, parsed.skills, parsed.experience_years,
|
||||
parsed.education, parsed.summary, cvText.substring(0, 5000)]
|
||||
);
|
||||
|
||||
res.json({ success: true, candidate: result.rows[0], parsed });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Create candidate manually
|
||||
app.post('/api/candidates', async (req, res) => {
|
||||
try {
|
||||
const { name, email, phone, skills, experience_years, education, summary } = req.body;
|
||||
const result = await pool.query(
|
||||
`INSERT INTO candidates (name, email, phone, skills, experience_years, education, summary)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *`,
|
||||
[name, email, phone, skills || [], experience_years, education, summary]
|
||||
);
|
||||
res.json({ success: true, candidate: result.rows[0] });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Jobs API ---
|
||||
|
||||
// Get all jobs
|
||||
app.get('/api/jobs', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM jobs ORDER BY created_at DESC');
|
||||
res.json({ jobs: result.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get single job
|
||||
app.get('/api/jobs/:id', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM jobs WHERE id = $1', [req.params.id]);
|
||||
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
|
||||
res.json(result.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Create job
|
||||
app.post('/api/jobs', async (req, res) => {
|
||||
try {
|
||||
const { title, description, requirements, location, salary_min, salary_max, channels } = req.body;
|
||||
if (!title) return res.status(400).json({ error: 'Title required' });
|
||||
|
||||
const result = await pool.query(
|
||||
`INSERT INTO jobs (title, description, requirements, location, salary_min, salary_max, channels)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *`,
|
||||
[title, description, requirements, location, salary_min, salary_max, channels || []]
|
||||
);
|
||||
res.json({ success: true, job: result.rows[0] });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Post job to channels (multi-channel posting simulation)
|
||||
app.post('/api/jobs/:id/post', async (req, res) => {
|
||||
try {
|
||||
const { channels } = req.body;
|
||||
if (!channels || !channels.length) {
|
||||
return res.status(400).json({ error: 'At least one channel required' });
|
||||
}
|
||||
|
||||
// Simulate posting to each channel
|
||||
const postingResults = {};
|
||||
const availableChannels = {
|
||||
'linkedin': 'LinkedIn Jobs',
|
||||
'indeed': 'Indeed',
|
||||
'arbetsformedlingen': 'Arbetsförmedlingen',
|
||||
'company_site': 'Company Career Page',
|
||||
'glassdoor': 'Glassdoor'
|
||||
};
|
||||
|
||||
for (const channel of channels) {
|
||||
// Simulate API call to each platform
|
||||
postingResults[channel] = {
|
||||
status: 'posted',
|
||||
platform: availableChannels[channel] || channel,
|
||||
url: `https://${channel}.example.com/jobs/${req.params.id}`,
|
||||
postedAt: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`UPDATE jobs SET channels = $1, status = 'posted', posted_at = NOW() WHERE id = $2`,
|
||||
[channels, req.params.id]
|
||||
);
|
||||
|
||||
const job = await pool.query('SELECT * FROM jobs WHERE id = $1', [req.params.id]);
|
||||
res.json({ success: true, postingResults, job: job.rows[0] });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Applications API ---
|
||||
|
||||
// Get applications for a job
|
||||
app.get('/api/jobs/:id/applications', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT ja.*, c.name, c.email, c.skills, c.experience_years
|
||||
FROM job_applications ja JOIN candidates c ON ja.candidate_id = c.id
|
||||
WHERE ja.job_id = $1 ORDER BY ja.created_at DESC`,
|
||||
[req.params.id]
|
||||
);
|
||||
res.json({ applications: result.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Apply candidate to job
|
||||
app.post('/api/jobs/:jobId/apply/:candidateId', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO job_applications (job_id, candidate_id) VALUES ($1, $2)
|
||||
ON CONFLICT (job_id, candidate_id) DO NOTHING RETURNING *`,
|
||||
[req.params.jobId, req.params.candidateId]
|
||||
);
|
||||
res.json({ success: true, application: result.rows[0] });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Scorecards API ---
|
||||
|
||||
// Get scorecards for a candidate
|
||||
app.get('/api/scorecards', async (req, res) => {
|
||||
try {
|
||||
const { job_id, candidate_id } = req.query;
|
||||
let query = 'SELECT * FROM scorecards WHERE 1=1';
|
||||
const params = [];
|
||||
if (job_id) { params.push(job_id); query += ` AND job_id = $${params.length}`; }
|
||||
if (candidate_id) { params.push(candidate_id); query += ` AND candidate_id = $${params.length}`; }
|
||||
query += ' ORDER BY created_at DESC';
|
||||
|
||||
const result = await pool.query(query, params);
|
||||
res.json({ scorecards: result.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Create scorecard
|
||||
app.post('/api/scorecards', async (req, res) => {
|
||||
try {
|
||||
const { job_id, candidate_id, interviewer, criteria, comments, recommendation } = req.body;
|
||||
if (!job_id || !candidate_id || !interviewer) {
|
||||
return res.status(400).json({ error: 'job_id, candidate_id, and interviewer are required' });
|
||||
}
|
||||
|
||||
// Calculate total score from criteria
|
||||
let total_score = 0;
|
||||
if (criteria && typeof criteria === 'object') {
|
||||
const scores = Object.values(criteria).map(c => c.score || 0);
|
||||
total_score = scores.length > 0 ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length) : 0;
|
||||
}
|
||||
|
||||
const result = await pool.query(
|
||||
`INSERT INTO scorecards (job_id, candidate_id, interviewer, criteria, total_score, comments, recommendation)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *`,
|
||||
[job_id, candidate_id, interviewer, JSON.stringify(criteria || {}), total_score, comments, recommendation]
|
||||
);
|
||||
res.json({ success: true, scorecard: result.rows[0] });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get aggregate scorecard for a candidate on a job
|
||||
app.get('/api/scorecards/summary/:jobId/:candidateId', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT
|
||||
COUNT(*) as total_interviewers,
|
||||
AVG(total_score) as avg_score,
|
||||
json_agg(json_build_object(
|
||||
'interviewer', interviewer,
|
||||
'score', total_score,
|
||||
'recommendation', recommendation,
|
||||
'comments', comments
|
||||
)) as interviews
|
||||
FROM scorecards
|
||||
WHERE job_id = $1 AND candidate_id = $2`,
|
||||
[req.params.jobId, req.params.candidateId]
|
||||
);
|
||||
res.json(result.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Stats API ---
|
||||
app.get('/api/stats', async (req, res) => {
|
||||
try {
|
||||
const [candidates, jobs, scorecards, applications] = await Promise.all([
|
||||
pool.query('SELECT COUNT(*) FROM candidates'),
|
||||
pool.query('SELECT COUNT(*) FROM jobs'),
|
||||
pool.query('SELECT COUNT(*) FROM scorecards'),
|
||||
pool.query('SELECT COUNT(*) FROM job_applications'),
|
||||
]);
|
||||
res.json({
|
||||
candidates: parseInt(candidates.rows[0].count),
|
||||
jobs: parseInt(jobs.rows[0].count),
|
||||
scorecards: parseInt(scorecards.rows[0].count),
|
||||
applications: parseInt(applications.rows[0].count),
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Serve React frontend
|
||||
const clientDist = path.join(__dirname, 'client', 'dist');
|
||||
app.use(express.static(clientDist));
|
||||
app.get('*', (req, res, next) => {
|
||||
if (req.path.startsWith('/api/') || req.path === '/health') return next();
|
||||
res.sendFile(path.join(clientDist, 'index.html'));
|
||||
});
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`Server running on port ${PORT}`);
|
||||
console.log(`HireFlow server running on port ${PORT}`);
|
||||
});
|
||||
|
||||
module.exports = { app, pool, redisClient };
|
||||
|
||||
Reference in New Issue
Block a user