RCT-1: каркас, SQLite-миграции, API вакансий
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9250f18a72
commit
ea187f822d
4
.gitignore
vendored
4
.gitignore
vendored
@ -2,3 +2,7 @@ node_modules/
|
||||
.env
|
||||
.env.local
|
||||
.DS_Store
|
||||
dist/
|
||||
*.db
|
||||
*.db-*
|
||||
data/
|
||||
|
||||
@ -1 +1,3 @@
|
||||
{"slug":"recruter","key":"RCT","name":"Виртуальны рекрутер","peppaUrl":"https://peppa.telecom.quest"}
|
||||
{"slug":"recruter","key":"RCT","name":"Виртуальны рекрутер","peppaUrl":"https://peppa.telecom.quest",
|
||||
"checks":{"install":"pnpm install --frozen-lockfile","lint":"pnpm lint","typecheck":"pnpm typecheck","test":"pnpm test","build":"pnpm build"},
|
||||
"deploy":{"compose":"deploy/compose.yml","service":"web","port":3000,"health":"/healthz"}}
|
||||
|
||||
16
Dockerfile
Normal file
16
Dockerfile
Normal file
@ -0,0 +1,16 @@
|
||||
FROM node:24-bookworm-slim AS build
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY package.json pnpm-lock.yaml* ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY . .
|
||||
RUN pnpm build && pnpm prune --prod
|
||||
|
||||
FROM node:24-bookworm-slim
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production PORT=3000
|
||||
COPY --from=build /app/package.json ./
|
||||
COPY --from=build /app/node_modules ./node_modules
|
||||
COPY --from=build /app/dist ./dist
|
||||
EXPOSE 3000
|
||||
CMD ["node", "dist/index.js"]
|
||||
6
eslint.config.js
Normal file
6
eslint.config.js
Normal file
@ -0,0 +1,6 @@
|
||||
import tseslint from "typescript-eslint";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist/**", "node_modules/**"] },
|
||||
...tseslint.configs.recommended,
|
||||
);
|
||||
@ -9,7 +9,7 @@
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **Стек: TypeScript (Node 22), Fastify, SQLite через better-sqlite3 (миграции SQL), vitest, eslint.** Один процесс: API + планировщик (cron-подобный тикер). Просто деплоится по шаблону Пеппы (`/healthz`, `$PORT`). Альтернатива Postgres отложена до реальной нагрузки.
|
||||
1. **Стек: TypeScript (Node 22), Fastify, SQLite через встроенный `node:sqlite` (Node 24, без нативной сборки; миграции SQL), vitest, eslint.** Один процесс: API + планировщик (cron-подобный тикер). Просто деплоится по шаблону Пеппы (`/healthz`, `$PORT`). Альтернатива Postgres отложена до реальной нагрузки.
|
||||
2. **Адаптеры за интерфейсами:** `SourceAdapter` (поиск резюме), `ChannelAdapter` (WhatsApp/Telegram), `Screener` (ведение диалога, LLM). Реализации `mockSourceAdapter`, `mockChannelAdapter`, `mockScreener` повторяют контракт реальных; реальные подключаются конфигом.
|
||||
3. **Поиск по каждому требованию отдельно:** запрос на площадку строится на каждое требование; кандидат получает совпадения по каждому, итоговый скор — взвешенная сумма; обязательные («must») требования отсекают.
|
||||
4. **Дедупликация** по нормализованному телефону, затем по e-mail, затем по (ФИО + город + источник-ссылка).
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
## 1. Основа проекта
|
||||
- [ ] 1.1 Каркас TS/Fastify, `/healthz`, `$PORT`, eslint, vitest, Dockerfile, `checks` в `.peppa/project.json`
|
||||
- [ ] 1.2 SQLite + миграции: вакансии, требования, кандидаты, контакты, встречи, прогоны
|
||||
- [x] 1.1 Каркас TS/Fastify, `/healthz`, `$PORT`, eslint, vitest, Dockerfile, `checks` в `.peppa/project.json`
|
||||
- [x] 1.2 SQLite + миграции: вакансии, требования, кандидаты, контакты, встречи, прогоны
|
||||
|
||||
## 2. Вакансии
|
||||
- [ ] 2.1 API вакансий с отдельным полем `description`, требованиями, валидацией, токен-аутентификация
|
||||
- [ ] 2.2 Тесты по сценариям vacancy-profiles
|
||||
- [x] 2.1 API вакансий с отдельным полем `description`, требованиями, валидацией, токен-аутентификация
|
||||
- [x] 2.2 Тесты по сценариям vacancy-profiles
|
||||
|
||||
## 3. Поиск
|
||||
- [ ] 3.1 Интерфейс `SourceAdapter`, `mockSourceAdapter`
|
||||
|
||||
24
openspec/changes/rct-1-recruiting-agent/tasks.md-E
Normal file
24
openspec/changes/rct-1-recruiting-agent/tasks.md-E
Normal file
@ -0,0 +1,24 @@
|
||||
## 1. Основа проекта
|
||||
- [ ] 1.1 Каркас TS/Fastify, `/healthz`, `$PORT`, eslint, vitest, Dockerfile, `checks` в `.peppa/project.json`
|
||||
- [ ] 1.2 SQLite + миграции: вакансии, требования, кандидаты, контакты, встречи, прогоны
|
||||
|
||||
## 2. Вакансии
|
||||
- [ ] 2.1 API вакансий с отдельным полем `description`, требованиями, валидацией, токен-аутентификация
|
||||
- [ ] 2.2 Тесты по сценариям vacancy-profiles
|
||||
|
||||
## 3. Поиск
|
||||
- [ ] 3.1 Интерфейс `SourceAdapter`, `mockSourceAdapter`
|
||||
- [ ] 3.2 Ежедневный планировщик: запрос на требование × площадку, обработка сбоев
|
||||
- [ ] 3.3 Дедупликация и скоринг, сводный список; тесты
|
||||
|
||||
## 4. Общение
|
||||
- [ ] 4.1 Интерфейсы `ChannelAdapter`, `Screener`, моки `mockChannelAdapter`, `mockScreener`
|
||||
- [ ] 4.2 Первичный контакт, стоп-слово, лимит сообщений
|
||||
- [ ] 4.3 Скрининг и назначение встречи; тесты
|
||||
|
||||
## 5. Воронка и отчёт
|
||||
- [ ] 5.1 Расчёт объёма поиска, дневной нормы
|
||||
- [ ] 5.2 Ежедневный отчёт руководителю (API)
|
||||
|
||||
## 6. Завершение
|
||||
- [ ] 6.1 Тесты, линтеры, `openspec validate rct-1-recruiting-agent`
|
||||
26
package.json
Normal file
26
package.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "recruter",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"start": "node dist/index.js",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^5.12.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^26.6.6",
|
||||
"eslint": "^10.14.0",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.72.2",
|
||||
"vitest": "^5.1.0"
|
||||
}
|
||||
}
|
||||
1850
pnpm-lock.yaml
generated
Normal file
1850
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
44
src/app.ts
Normal file
44
src/app.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import Fastify from "fastify";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { createVacancy, getVacancy, listVacancies, validateVacancy, ValidationError } from "./vacancies.js";
|
||||
|
||||
export interface AppOptions { db: DatabaseSync; apiToken: string }
|
||||
|
||||
function tokenOk(header: string | undefined, expected: string): boolean {
|
||||
if (!header?.startsWith("Bearer ")) return false;
|
||||
const a = Buffer.from(header.slice(7));
|
||||
const b = Buffer.from(expected);
|
||||
return a.length === b.length && timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
export function buildApp({ db, apiToken }: AppOptions) {
|
||||
if (!apiToken) throw new Error("API_TOKEN не задан");
|
||||
const app = Fastify();
|
||||
|
||||
app.get("/healthz", async () => ({ ok: true }));
|
||||
|
||||
app.register(async (api) => {
|
||||
api.addHook("onRequest", async (req, reply) => {
|
||||
if (!tokenOk(req.headers.authorization, apiToken)) {
|
||||
return reply.code(401).send({ error: "unauthorized" });
|
||||
}
|
||||
});
|
||||
api.setErrorHandler((err, _req, reply) => {
|
||||
if (err instanceof ValidationError) return reply.code(400).send({ error: err.message });
|
||||
reply.send(err);
|
||||
});
|
||||
|
||||
api.post("/vacancies", async (req, reply) => {
|
||||
const v = createVacancy(db, validateVacancy(req.body));
|
||||
return reply.code(201).send(v);
|
||||
});
|
||||
api.get("/vacancies", async () => listVacancies(db));
|
||||
api.get<{ Params: { id: string } }>("/vacancies/:id", async (req, reply) => {
|
||||
const v = getVacancy(db, Number(req.params.id));
|
||||
return v ?? reply.code(404).send({ error: "not found" });
|
||||
});
|
||||
}, { prefix: "/api" });
|
||||
|
||||
return app;
|
||||
}
|
||||
84
src/db.ts
Normal file
84
src/db.ts
Normal file
@ -0,0 +1,84 @@
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
|
||||
const MIGRATIONS: string[] = [
|
||||
`
|
||||
CREATE TABLE vacancies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
target_count INTEGER NOT NULL,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE requirements (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
vacancy_id INTEGER NOT NULL REFERENCES vacancies(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL,
|
||||
weight INTEGER NOT NULL,
|
||||
mandatory INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE candidates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
vacancy_id INTEGER NOT NULL REFERENCES vacancies(id) ON DELETE CASCADE,
|
||||
full_name TEXT NOT NULL,
|
||||
phone TEXT,
|
||||
email TEXT,
|
||||
city TEXT,
|
||||
channel TEXT,
|
||||
score REAL NOT NULL DEFAULT 0,
|
||||
status TEXT NOT NULL DEFAULT 'found',
|
||||
ready_for_training INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE candidate_sources (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
candidate_id INTEGER NOT NULL REFERENCES candidates(id) ON DELETE CASCADE,
|
||||
source TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
requirement_ids TEXT NOT NULL DEFAULT '[]'
|
||||
);
|
||||
CREATE TABLE messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
candidate_id INTEGER NOT NULL REFERENCES candidates(id) ON DELETE CASCADE,
|
||||
direction TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE meetings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
candidate_id INTEGER NOT NULL REFERENCES candidates(id) ON DELETE CASCADE,
|
||||
starts_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
vacancy_id INTEGER NOT NULL REFERENCES vacancies(id) ON DELETE CASCADE,
|
||||
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
queries INTEGER NOT NULL DEFAULT 0,
|
||||
found INTEGER NOT NULL DEFAULT 0,
|
||||
failed_sources TEXT NOT NULL DEFAULT '[]'
|
||||
);
|
||||
`,
|
||||
];
|
||||
|
||||
export function openDb(path = ":memory:"): DatabaseSync {
|
||||
const db = new DatabaseSync(path);
|
||||
db.exec("PRAGMA foreign_keys = ON");
|
||||
migrate(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
export function migrate(db: DatabaseSync): void {
|
||||
db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY)");
|
||||
const row = db.prepare("SELECT COALESCE(MAX(version), 0) AS v FROM schema_migrations").get() as { v: number };
|
||||
for (let i = row.v; i < MIGRATIONS.length; i++) {
|
||||
db.exec("BEGIN");
|
||||
try {
|
||||
db.exec(MIGRATIONS[i] as string);
|
||||
db.prepare("INSERT INTO schema_migrations (version) VALUES (?)").run(i + 1);
|
||||
db.exec("COMMIT");
|
||||
} catch (e) {
|
||||
db.exec("ROLLBACK");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
5
src/index.ts
Normal file
5
src/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { buildApp } from "./app.js";
|
||||
import { openDb } from "./db.js";
|
||||
|
||||
const app = buildApp({ db: openDb(process.env.DB_PATH ?? "data.db"), apiToken: process.env.API_TOKEN ?? "" });
|
||||
await app.listen({ port: Number(process.env.PORT ?? 3000), host: "0.0.0.0" });
|
||||
61
src/vacancies.ts
Normal file
61
src/vacancies.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
|
||||
export interface RequirementInput { text: string; weight: number; mandatory?: boolean }
|
||||
export interface VacancyInput {
|
||||
title: string;
|
||||
description?: string;
|
||||
targetCount: number;
|
||||
requirements?: RequirementInput[];
|
||||
}
|
||||
|
||||
export class ValidationError extends Error {}
|
||||
|
||||
export function validateVacancy(input: unknown): VacancyInput {
|
||||
const v = input as Partial<VacancyInput> | null;
|
||||
if (!v || typeof v !== "object") throw new ValidationError("тело запроса должно быть объектом");
|
||||
if (typeof v.title !== "string" || v.title.trim() === "") throw new ValidationError("название вакансии обязательно");
|
||||
if (v.description !== undefined && typeof v.description !== "string") throw new ValidationError("description должно быть строкой");
|
||||
if (!Number.isInteger(v.targetCount) || (v.targetCount as number) < 1) throw new ValidationError("targetCount должно быть целым числом от 1");
|
||||
const reqs = v.requirements ?? [];
|
||||
if (!Array.isArray(reqs)) throw new ValidationError("requirements должно быть массивом");
|
||||
for (const r of reqs) {
|
||||
if (!r || typeof r.text !== "string" || r.text.trim() === "") throw new ValidationError("текст требования обязателен");
|
||||
if (!Number.isInteger(r.weight) || r.weight < 1 || r.weight > 10) throw new ValidationError("вес должен быть от 1 до 10");
|
||||
}
|
||||
return { title: v.title.trim(), description: v.description ?? "", targetCount: v.targetCount as number, requirements: reqs };
|
||||
}
|
||||
|
||||
export function createVacancy(db: DatabaseSync, input: VacancyInput) {
|
||||
db.exec("BEGIN");
|
||||
try {
|
||||
const res = db
|
||||
.prepare("INSERT INTO vacancies (title, description, target_count) VALUES (?, ?, ?)")
|
||||
.run(input.title, input.description ?? "", input.targetCount);
|
||||
const id = Number(res.lastInsertRowid);
|
||||
const ins = db.prepare("INSERT INTO requirements (vacancy_id, text, weight, mandatory) VALUES (?, ?, ?, ?)");
|
||||
for (const r of input.requirements ?? []) ins.run(id, r.text.trim(), r.weight, r.mandatory ? 1 : 0);
|
||||
db.exec("COMMIT");
|
||||
return getVacancy(db, id)!;
|
||||
} catch (e) {
|
||||
db.exec("ROLLBACK");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export function getVacancy(db: DatabaseSync, id: number) {
|
||||
const v = db.prepare("SELECT id, title, description, target_count AS targetCount, active FROM vacancies WHERE id = ?").get(id) as
|
||||
| { id: number; title: string; description: string; targetCount: number; active: number }
|
||||
| undefined;
|
||||
if (!v) return undefined;
|
||||
const requirements = (
|
||||
db.prepare("SELECT id, text, weight, mandatory FROM requirements WHERE vacancy_id = ? ORDER BY id").all(id) as {
|
||||
id: number; text: string; weight: number; mandatory: number;
|
||||
}[]
|
||||
).map((r) => ({ ...r, mandatory: r.mandatory === 1 }));
|
||||
return { ...v, active: v.active === 1, requirements };
|
||||
}
|
||||
|
||||
export function listVacancies(db: DatabaseSync) {
|
||||
const ids = db.prepare("SELECT id FROM vacancies ORDER BY id").all() as { id: number }[];
|
||||
return ids.map((r) => getVacancy(db, r.id)!);
|
||||
}
|
||||
39
test/vacancies.test.ts
Normal file
39
test/vacancies.test.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { openDb } from "../src/db.js";
|
||||
|
||||
const auth = { authorization: "Bearer t0ken" };
|
||||
const app = () => buildApp({ db: openDb(), apiToken: "t0ken" });
|
||||
|
||||
describe("vacancy-profiles", () => {
|
||||
it("Scenario: Создание вакансии — описание отдельным полем", async () => {
|
||||
const a = app();
|
||||
const res = await a.inject({ method: "POST", url: "/api/vacancies", headers: auth, payload: {
|
||||
title: "Оператор call-центра", description: "Работа в смену…", targetCount: 10,
|
||||
requirements: [{ text: "продажи", weight: 8, mandatory: true }] } });
|
||||
expect(res.statusCode).toBe(201);
|
||||
const v = res.json();
|
||||
expect(v.description).toBe("Работа в смену…");
|
||||
expect(v.requirements[0]).toMatchObject({ text: "продажи", weight: 8, mandatory: true });
|
||||
});
|
||||
|
||||
it("Scenario: Вакансия без названия", async () => {
|
||||
const a = app();
|
||||
const res = await a.inject({ method: "POST", url: "/api/vacancies", headers: auth, payload: { title: " ", targetCount: 1 } });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect((await a.inject({ method: "GET", url: "/api/vacancies", headers: auth })).json()).toEqual([]);
|
||||
});
|
||||
|
||||
it("Scenario: Обязательное требование — вес вне диапазона", async () => {
|
||||
const res = await app().inject({ method: "POST", url: "/api/vacancies", headers: auth, payload: {
|
||||
title: "X", targetCount: 1, requirements: [{ text: "Опыт продаж", weight: 15, mandatory: true }] } });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain("от 1 до 10");
|
||||
});
|
||||
|
||||
it("без токена — 401, /healthz открыт", async () => {
|
||||
const a = app();
|
||||
expect((await a.inject({ method: "GET", url: "/api/vacancies" })).statusCode).toBe(401);
|
||||
expect((await a.inject({ method: "GET", url: "/healthz" })).statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
3
tsconfig.build.json
Normal file
3
tsconfig.build.json
Normal file
@ -0,0 +1,3 @@
|
||||
{ "extends": "./tsconfig.json",
|
||||
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
|
||||
"include": ["src"] }
|
||||
8
tsconfig.json
Normal file
8
tsconfig.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023", "module": "NodeNext", "moduleResolution": "NodeNext",
|
||||
"strict": true, "noUncheckedIndexedAccess": true, "esModuleInterop": true,
|
||||
"skipLibCheck": true, "outDir": "dist", "rootDir": ".", "types": ["node"]
|
||||
},
|
||||
"include": ["src", "test", "vitest.config.ts", "eslint.config.js"]
|
||||
}
|
||||
3
vitest.config.ts
Normal file
3
vitest.config.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({ test: { include: ["test/**/*.test.ts"] } });
|
||||
Loading…
Reference in New Issue
Block a user