- {/* Header */}
-
+
+
+
Dashboard
+
AI-powered recruitment platform for Nordic agencies
+
- {/* Hero */}
-
-
- Welcome to Your Company
-
-
- This is your company website scaffold built with React, shadcn/ui, and TailwindCSS.
- Start building your product here.
-
-
-
-
-
-
+
+
+
+ Total Candidates
+
+
+ {stats.candidates}
+
+
+
+
+ Active Jobs
+
+
+ {stats.jobs}
+
+
+
+
+ Applications
+
+
+ {stats.applications}
+
+
+
+
+ Scorecards
+
+
+ {stats.scorecards}
+
+
+
-
-
- {/* Features */}
-
- Features
-
-
-
- Feature One
- Description of the first feature.
-
-
-
- Add details about this feature here.
-
-
-
-
-
- Feature Two
- Description of the second feature.
-
-
-
- Add details about this feature here.
-
-
-
-
-
- Feature Three
- Description of the third feature.
-
-
-
- Add details about this feature here.
-
-
-
-
-
-
- {/* Footer */}
-
+
+
+
+ AI CV Parsing
+
+
+
+ Upload CVs and automatically extract candidate information — skills, experience, education — using AI parsing.
+
+ Go to Candidates →
+
+
+
+
+ Multi-Channel Job Posting
+
+
+
+ Post jobs to LinkedIn, Indeed, Arbetsförmedlingen, and your company career page with a single click.
+
+ Go to Jobs →
+
+
+
+
+ Collaborative Scorecards
+
+
+
+ Multiple interviewers score candidates using standardized criteria for consistent, unbiased evaluations.
+
+ Go to Scorecards →
+
+
+
)
}
diff --git a/client/src/pages/Jobs.tsx b/client/src/pages/Jobs.tsx
new file mode 100644
index 0000000..70c4d29
--- /dev/null
+++ b/client/src/pages/Jobs.tsx
@@ -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
([])
+ 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(null)
+ const [postChannels, setPostChannels] = useState([])
+ const [postingTo, setPostingTo] = useState(null)
+ const [postResult, setPostResult] = useState | 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 (
+
+
+
+
Jobs
+
Create and post jobs to multiple platforms
+
+
+
+
+ {message && (
+
+ {message}
+
+ )}
+
+ {showForm && (
+
+ Create New Job
+
+ setForm(f => ({ ...f, title: e.target.value }))} />
+
+
+ )}
+
+ {selected && (
+
+
+
+ Post "{selected.title}" to Channels
+
+
+
+
+
+ {CHANNELS.map(ch => (
+
+ ))}
+
+
+ {postResult && (
+
+
Posted successfully to:
+ {Object.entries(postResult).map(([ch, result]: [string, any]) => (
+
+ ✓ {result.platform} — {new Date(result.postedAt).toLocaleString()}
+
+ ))}
+
+ )}
+
+
+ )}
+
+
+
All Jobs ({jobs.length})
+ {loading ? (
+
Loading...
+ ) : jobs.length === 0 ? (
+
+
💼
+
No jobs yet. Create your first job posting.
+
+ ) : (
+
+ {jobs.map(j => (
+
+
+
+
+
{j.title}
+ {j.location &&
{j.location}
}
+ {(j.salary_min || j.salary_max) && (
+
+ {j.salary_min && j.salary_max ? `${j.salary_min.toLocaleString()} – ${j.salary_max.toLocaleString()} SEK` : `From ${(j.salary_min || j.salary_max)?.toLocaleString()} SEK`}
+
+ )}
+ {j.channels?.length > 0 && (
+
+ {j.channels.map(ch => (
+ {ch}
+ ))}
+
+ )}
+
+
+
+ {j.status}
+
+
+
+
+
+
+ ))}
+
+ )}
+
+
+ )
+}
diff --git a/client/src/pages/Scorecards.tsx b/client/src/pages/Scorecards.tsx
new file mode 100644
index 0000000..0f34d29
--- /dev/null
+++ b/client/src/pages/Scorecards.tsx
@@ -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
+ 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([])
+ const [jobs, setJobs] = useState([])
+ const [scorecards, setScorecards] = useState([])
+ 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>(
+ 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 (
+
+
+
+
Scorecards
+
Collaborative candidate evaluations
+
+
+
+
+ {message && (
+
+ {message}
+
+ )}
+
+ {showForm && (
+
+ New Scorecard
+
+
+
+
+
+
+
+
+
+
+
+
+ setForm(f => ({ ...f, interviewer: e.target.value }))}
+ />
+
+
+
+
+
Scoring (1–5)
+
+ {CRITERIA.map(c => (
+
+
{c.label}
+
+ {[1, 2, 3, 4, 5].map(n => (
+
+ ))}
+
+
setCriteria(prev => ({ ...prev, [c.key]: { ...prev[c.key], notes: e.target.value } }))}
+ />
+
+ ))}
+
+
+
+
+
+
+
+
+
+
+ setForm(f => ({ ...f, comments: e.target.value }))}
+ />
+
+
+
+
+
+
+ )}
+
+
+
All Scorecards ({scorecards.length})
+ {loading ? (
+
Loading...
+ ) : scorecards.length === 0 ? (
+
+
📋
+
No scorecards yet. Evaluate your first candidate.
+
+ ) : (
+
+ {scorecards.map(sc => {
+ const candidate = getCandidate(sc.candidate_id)
+ const job = getJob(sc.job_id)
+ const recColors: Record
= {
+ 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 (
+
+
+
+
+
{candidate?.name || `Candidate #${sc.candidate_id}`}
+
{job?.title || `Job #${sc.job_id}`} • Interviewer: {sc.interviewer}
+ {sc.comments &&
{sc.comments}
}
+
+
+ {sc.total_score}/5
+ {sc.recommendation && (
+
+ {sc.recommendation.replace('_', ' ')}
+
+ )}
+
+
+
+
+ )
+ })}
+
+ )}
+
+
+ )
+}
diff --git a/package.json b/package.json
index a83c5dc..ec43a05 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,8 @@
"express": "^4.18.2",
"pg": "^8.11.3",
"redis": "^4.6.12",
- "cors": "^2.8.5"
+ "cors": "^2.8.5",
+ "multer": "^1.4.5-lts.1"
},
"devDependencies": {
"nodemon": "^3.0.2",
diff --git a/server.js b/server.js
index 7837a0e..3942361 100644
--- a/server.js
+++ b/server.js
@@ -2,11 +2,12 @@ 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 app = express();
const PORT = process.env.PORT || 3000;
-// Middleware
app.use(express.json());
// PostgreSQL connection
@@ -27,61 +28,396 @@ const redisClient = redis.createClient({
});
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)
+ );
+ `);
+ console.log('Database schema initialized');
+ } catch (err) {
+ console.error('DB init error:', err.message);
+ }
+}
pool.query('SELECT NOW()', (err, res) => {
if (err) {
console.error('PostgreSQL connection error:', err);
} else {
console.log('PostgreSQL connected at:', res.rows[0].now);
+ initDb();
}
});
-redisClient.on('connect', () => console.log('Redis connected'));
-redisClient.on('error', (err) => console.error('Redis error:', err));
+// Simple CV parser using regex patterns
+function parseCV(text) {
+ const emailMatch = text.match(/[\w.-]+@[\w.-]+\.\w+/);
+ const phoneMatch = text.match(/(\+?[\d\s()-]{7,})/);
-// --- API Routes ---
+ // 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
+ };
+}
// 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,
- 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 });
}
});
-// Example API endpoint — replace with your own
-app.get('/api/status', async (req, res) => {
+// --- Candidates API ---
+
+// Get all candidates
+app.get('/api/candidates', async (req, res) => {
try {
- const pgResult = await pool.query('SELECT NOW()');
- res.json({ ok: true, time: pgResult.rows[0].now });
- } catch (error) {
- res.status(500).json({ ok: false, error: error.message });
+ 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 });
}
});
-// --- Serve React Frontend ---
-// In production, serve the built React app from client/dist
+// 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));
-
-// SPA fallback — all non-API routes serve index.html so React Router works
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}`);
});
-// Export for testing
module.exports = { app, pool, redisClient };