recruter/src/sourcing.ts
2026-11-14 21:45:11 +05:00

139 lines
5.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { DatabaseSync } from "node:sqlite";
import type { Resume, SourceAdapter } from "./sources.js";
import { getVacancy } from "./vacancies.js";
export function normalizePhone(p?: string): string | undefined {
if (!p) return undefined;
let d = p.replace(/\D/g, "");
if (d.length === 11 && d.startsWith("8")) d = "7" + d.slice(1);
return d || undefined;
}
const normEmail = (e?: string) => e?.trim().toLowerCase() || undefined;
const normName = (r: Resume) =>
r.fullName && r.city ? `${r.fullName.trim().toLowerCase()}|${r.city.trim().toLowerCase()}` : undefined;
function keysOf(r: Resume): string[] {
const k: string[] = [];
const ph = normalizePhone(r.phone);
if (ph) k.push(`p:${ph}`);
const em = normEmail(r.email);
if (em) k.push(`e:${em}`);
const nm = normName(r);
if (nm) k.push(`n:${nm}`);
return k;
}
interface Group {
resume: Resume;
keys: Set<string>;
sources: Map<string, { source: string; url: string }>;
matched: Set<number>;
}
export interface SearchResult { queries: number; found: number; failedSources: string[]; runId: number }
/** Ежедневный поиск: требование × площадка, дедупликация, скоринг, сохранение. */
export async function runDailySearch(
db: DatabaseSync,
vacancyId: number,
adapters: SourceAdapter[],
): Promise<SearchResult> {
const vacancy = getVacancy(db, vacancyId);
if (!vacancy) throw new Error(`вакансия ${vacancyId} не найдена`);
let queries = 0;
const failed = new Set<string>();
const groups: Group[] = [];
for (const req of vacancy.requirements) {
for (const ad of adapters) {
queries++;
let resumes: Resume[];
try {
resumes = await ad.search(req.text);
} catch {
failed.add(ad.name);
continue;
}
for (const r of resumes) {
const keys = keysOf(r);
let g = groups.find((x) => keys.some((k) => x.keys.has(k)));
if (!g) {
g = { resume: r, keys: new Set(), sources: new Map(), matched: new Set() };
groups.push(g);
}
keys.forEach((k) => g.keys.add(k));
g.resume = { ...r, ...Object.fromEntries(Object.entries(g.resume).filter(([, v]) => v)) } as Resume;
g.sources.set(`${ad.name}|${r.url}`, { source: ad.name, url: r.url });
g.matched.add(req.id);
}
}
}
const total = vacancy.requirements.reduce((s, r) => s + r.weight, 0);
const mandatory = vacancy.requirements.filter((r) => r.mandatory);
let found = 0;
for (const g of groups) {
if (!mandatory.every((m) => g.matched.has(m.id))) continue;
const got = vacancy.requirements.filter((r) => g.matched.has(r.id)).reduce((s, r) => s + r.weight, 0);
const score = total ? Math.round((got / total) * 1000) / 10 : 0;
let candId = findExisting(db, vacancyId, [...g.keys]);
if (candId === undefined) {
const r = g.resume;
const res = db
.prepare(
"INSERT INTO candidates (vacancy_id, full_name, phone, email, city, channel, score) VALUES (?,?,?,?,?,?,?)",
)
.run(vacancyId, r.fullName, normalizePhone(r.phone) ?? null, normEmail(r.email) ?? null, r.city ?? null, r.channel ?? null, score);
candId = Number(res.lastInsertRowid);
found++;
} else {
db.prepare("UPDATE candidates SET score = MAX(score, ?) WHERE id = ?").run(score, candId);
}
const have = new Set(
(db.prepare("SELECT source, url FROM candidate_sources WHERE candidate_id = ?").all(candId) as { source: string; url: string }[]).map(
(s) => `${s.source}|${s.url}`,
),
);
for (const [k, s] of g.sources) {
if (!have.has(k))
db.prepare("INSERT INTO candidate_sources (candidate_id, source, url, requirement_ids) VALUES (?,?,?,?)").run(
candId, s.source, s.url, JSON.stringify([...g.matched]),
);
}
}
const run = db
.prepare("INSERT INTO runs (vacancy_id, queries, found, failed_sources) VALUES (?,?,?,?)")
.run(vacancyId, queries, found, JSON.stringify([...failed]));
return { queries, found, failedSources: [...failed], runId: Number(run.lastInsertRowid) };
}
function findExisting(db: DatabaseSync, vacancyId: number, keys: string[]): number | undefined {
for (const k of keys) {
const [t, v] = [k[0], k.slice(2)];
let row: { id: number } | undefined;
if (t === "p") row = db.prepare("SELECT id FROM candidates WHERE vacancy_id=? AND phone=?").get(vacancyId, v) as typeof row;
else if (t === "e") row = db.prepare("SELECT id FROM candidates WHERE vacancy_id=? AND email=?").get(vacancyId, v) as typeof row;
else {
const [name = "", city = ""] = v.split("|");
row = db
.prepare("SELECT id FROM candidates WHERE vacancy_id=? AND lower(full_name)=? AND lower(city)=?")
.get(vacancyId, name, city) as typeof row;
}
if (row) return row.id;
}
return undefined;
}
export function candidateList(db: DatabaseSync, vacancyId: number) {
return db
.prepare(
"SELECT id, full_name AS fullName, phone, email, city, channel, score, status, ready_for_training AS readyForTraining FROM candidates WHERE vacancy_id = ? ORDER BY score DESC, id",
)
.all(vacancyId);
}