- AI-powered CV parsing (regex extraction of skills, experience, education) - Multi-channel job posting (LinkedIn, Indeed, Arbetsförmedlingen, Glassdoor, company site) - Collaborative hiring scorecards with 5-criteria scoring system - Dashboard with live stats (candidates, jobs, applications, scorecards) - PostgreSQL schema for candidates, jobs, applications, scorecards - REST API for all CRUD operations - React UI with shadcn/ui components throughout Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
424 lines
14 KiB
JavaScript
424 lines
14 KiB
JavaScript
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;
|
|
|
|
app.use(express.json());
|
|
|
|
// PostgreSQL connection
|
|
const pool = new Pool({
|
|
host: process.env.POSTGRES_HOST || 'postgres',
|
|
port: process.env.POSTGRES_PORT || 5432,
|
|
user: process.env.POSTGRES_USER || 'postgres',
|
|
password: process.env.POSTGRES_PASSWORD || 'postgres',
|
|
database: process.env.POSTGRES_DB || 'postgres'
|
|
});
|
|
|
|
// Redis connection
|
|
const redisClient = redis.createClient({
|
|
socket: {
|
|
host: process.env.REDIS_HOST || 'redis',
|
|
port: process.env.REDIS_PORT || 6379
|
|
}
|
|
});
|
|
|
|
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();
|
|
}
|
|
});
|
|
|
|
// 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
|
|
};
|
|
}
|
|
|
|
// 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 });
|
|
} catch (error) {
|
|
res.status(500).json({ status: 'unhealthy', error: error.message });
|
|
}
|
|
});
|
|
|
|
// --- 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(`HireFlow server running on port ${PORT}`);
|
|
});
|
|
|
|
module.exports = { app, pool, redisClient };
|