RCT-1: общение с кандидатами, скрининг, встречи (моки каналов)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
37872a78d0
commit
6c377bd4ba
@ -12,9 +12,9 @@
|
||||
- [x] 3.3 Дедупликация и скоринг, сводный список; тесты
|
||||
|
||||
## 4. Общение
|
||||
- [ ] 4.1 Интерфейсы `ChannelAdapter`, `Screener`, моки `mockChannelAdapter`, `mockScreener`
|
||||
- [ ] 4.2 Первичный контакт, стоп-слово, лимит сообщений
|
||||
- [ ] 4.3 Скрининг и назначение встречи; тесты
|
||||
- [x] 4.1 Интерфейсы `ChannelAdapter`, `Screener`, моки `mockChannelAdapter`, `mockScreener`
|
||||
- [x] 4.2 Первичный контакт, стоп-слово, лимит сообщений
|
||||
- [x] 4.3 Скрининг и назначение встречи; тесты
|
||||
|
||||
## 5. Воронка и отчёт
|
||||
- [ ] 5.1 Расчёт объёма поиска, дневной нормы
|
||||
|
||||
37
src/channels.ts
Normal file
37
src/channels.ts
Normal file
@ -0,0 +1,37 @@
|
||||
export interface Contact { phone: string; channel: "whatsapp" | "telegram" }
|
||||
|
||||
/** Контракт канала связи (WhatsApp/Telegram). */
|
||||
export interface ChannelAdapter {
|
||||
send(to: Contact, text: string): Promise<void>;
|
||||
}
|
||||
|
||||
export interface ScreenState {
|
||||
vacancyTitle: string;
|
||||
answers: string[];
|
||||
}
|
||||
export type ScreenStep =
|
||||
| { kind: "ask"; question: string }
|
||||
| { kind: "done"; suitable: boolean; readyForTraining: boolean };
|
||||
|
||||
/** Контракт ведущего скрининг (реальная реализация — LLM). */
|
||||
export interface Screener {
|
||||
next(state: ScreenState): Promise<ScreenStep>;
|
||||
}
|
||||
|
||||
export class MockChannelAdapter implements ChannelAdapter {
|
||||
readonly sent: { to: Contact; text: string }[] = [];
|
||||
async send(to: Contact, text: string): Promise<void> {
|
||||
this.sent.push({ to, text });
|
||||
}
|
||||
}
|
||||
|
||||
/** Мок скрининга: два фиксированных вопроса; годен и готов, если на оба ответ начинается с «да». */
|
||||
export class MockScreener implements Screener {
|
||||
static readonly questions = ["Вам подходит работа в смену? (да/нет)", "Готовы выйти на обучение? (да/нет)"];
|
||||
async next(state: ScreenState): Promise<ScreenStep> {
|
||||
const q = MockScreener.questions[state.answers.length];
|
||||
if (q) return { kind: "ask", question: q };
|
||||
const yes = (s?: string) => /^\s*да/i.test(s ?? "");
|
||||
return { kind: "done", suitable: yes(state.answers[0]), readyForTraining: yes(state.answers[0]) && yes(state.answers[1]) };
|
||||
}
|
||||
}
|
||||
123
src/outreach.ts
Normal file
123
src/outreach.ts
Normal file
@ -0,0 +1,123 @@
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { ChannelAdapter, Contact, Screener } from "./channels.js";
|
||||
|
||||
export const DAILY_LIMIT = 3;
|
||||
const STOP = /^\s*(стоп|stop|отказ|не пишите)\s*[.!]*\s*$/i;
|
||||
|
||||
interface Cand {
|
||||
id: number; vacancy_id: number; phone: string | null; channel: string | null; status: string;
|
||||
}
|
||||
|
||||
export type SendResult = "sent" | "deferred";
|
||||
|
||||
export class Outreach {
|
||||
constructor(
|
||||
private db: DatabaseSync,
|
||||
private channel: ChannelAdapter,
|
||||
private screener: Screener,
|
||||
private slots: string[],
|
||||
) {}
|
||||
|
||||
private cand(id: number): Cand {
|
||||
const c = this.db.prepare("SELECT id, vacancy_id, phone, channel, status FROM candidates WHERE id=?").get(id) as Cand | undefined;
|
||||
if (!c) throw new Error(`кандидат ${id} не найден`);
|
||||
return c;
|
||||
}
|
||||
|
||||
private contact(c: Cand): Contact {
|
||||
if (!c.phone || (c.channel !== "whatsapp" && c.channel !== "telegram")) throw new Error("у кандидата нет номера или канала связи");
|
||||
return { phone: c.phone, channel: c.channel };
|
||||
}
|
||||
|
||||
private blocked(c: Cand) {
|
||||
return ["declined", "rejected", "meeting_set"].includes(c.status);
|
||||
}
|
||||
|
||||
/** Не более DAILY_LIMIT исходящих за сутки без ответа кандидата. */
|
||||
private async send(c: Cand, text: string): Promise<SendResult> {
|
||||
const { n } = this.db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) AS n FROM messages WHERE candidate_id=? AND direction='out'
|
||||
AND created_at >= datetime('now','-1 day')
|
||||
AND id > COALESCE((SELECT MAX(id) FROM messages WHERE candidate_id=? AND direction='in'), 0)`,
|
||||
)
|
||||
.get(c.id, c.id) as { n: number };
|
||||
if (n >= DAILY_LIMIT) return "deferred";
|
||||
await this.channel.send(this.contact(c), text);
|
||||
this.db.prepare("INSERT INTO messages (candidate_id, direction, body) VALUES (?, 'out', ?)").run(c.id, text);
|
||||
return "sent";
|
||||
}
|
||||
|
||||
private setStatus(id: number, status: string) {
|
||||
this.db.prepare("UPDATE candidates SET status=? WHERE id=?").run(status, id);
|
||||
}
|
||||
|
||||
async startContact(candidateId: number): Promise<SendResult> {
|
||||
const c = this.cand(candidateId);
|
||||
if (c.status !== "found") throw new Error(`контакт уже начат или закрыт (статус ${c.status})`);
|
||||
const v = this.db.prepare("SELECT title FROM vacancies WHERE id=?").get(c.vacancy_id) as { title: string };
|
||||
const text =
|
||||
`Здравствуйте! Я автоматический ассистент рекрутера. Вижу ваше резюме и хочу предложить вакансию «${v.title}». ` +
|
||||
`Можно задать пару вопросов? Если не интересно — напишите «стоп», и я больше не побеспокою.`;
|
||||
const r = await this.send(c, text);
|
||||
if (r === "sent") this.setStatus(c.id, "contacted");
|
||||
return r;
|
||||
}
|
||||
|
||||
async handleReply(candidateId: number, body: string): Promise<void> {
|
||||
const c = this.cand(candidateId);
|
||||
if (this.blocked(c)) return;
|
||||
this.db.prepare("INSERT INTO messages (candidate_id, direction, body) VALUES (?, 'in', ?)").run(c.id, body);
|
||||
if (STOP.test(body)) return this.setStatus(c.id, "declined");
|
||||
|
||||
if (c.status === "qualified" || c.status === "awaiting_slot") return this.handleSlot(c, body);
|
||||
|
||||
this.setStatus(c.id, "screening");
|
||||
const v = this.db.prepare("SELECT title FROM vacancies WHERE id=?").get(c.vacancy_id) as { title: string };
|
||||
// ответы на скрининг: входящие после первого сообщения-согласия (первый ответ — реакция на приветствие)
|
||||
const answers = (
|
||||
this.db.prepare("SELECT body FROM messages WHERE candidate_id=? AND direction='in' ORDER BY id").all(c.id) as { body: string }[]
|
||||
).map((m) => m.body).slice(1);
|
||||
const step = await this.screener.next({ vacancyTitle: v.title, answers });
|
||||
if (step.kind === "ask") {
|
||||
await this.send(c, step.question);
|
||||
return;
|
||||
}
|
||||
if (!step.suitable) {
|
||||
this.setStatus(c.id, "rejected");
|
||||
await this.send(c, "Спасибо за ответы! К сожалению, сейчас вакансия вам не подходит.");
|
||||
return;
|
||||
}
|
||||
this.db.prepare("UPDATE candidates SET ready_for_training=? WHERE id=?").run(step.readyForTraining ? 1 : 0, c.id);
|
||||
if (!step.readyForTraining) {
|
||||
this.setStatus(c.id, "rejected");
|
||||
await this.send(c, "Спасибо! Вернёмся к вам, когда будет набор без обучения.");
|
||||
return;
|
||||
}
|
||||
await this.offerSlots(c);
|
||||
}
|
||||
|
||||
private freeSlots(): string[] {
|
||||
const taken = new Set((this.db.prepare("SELECT starts_at FROM meetings").all() as { starts_at: string }[]).map((m) => m.starts_at));
|
||||
return this.slots.filter((s) => !taken.has(s));
|
||||
}
|
||||
|
||||
private async offerSlots(c: Cand) {
|
||||
const free = this.freeSlots();
|
||||
if (free.length === 0) {
|
||||
this.setStatus(c.id, "awaiting_slot");
|
||||
await this.send(c, "Вы нам подходите! Свободного времени для встречи пока нет — мы напишем, как только появится.");
|
||||
return;
|
||||
}
|
||||
this.setStatus(c.id, "qualified");
|
||||
await this.send(c, `Вы нам подходите! Выберите время встречи, ответив точной датой: ${free.join("; ")}`);
|
||||
}
|
||||
|
||||
private async handleSlot(c: Cand, body: string) {
|
||||
const chosen = this.freeSlots().find((s) => body.includes(s));
|
||||
if (!chosen) return this.offerSlots(c);
|
||||
this.db.prepare("INSERT INTO meetings (candidate_id, starts_at) VALUES (?, ?)").run(c.id, chosen);
|
||||
this.setStatus(c.id, "meeting_set");
|
||||
await this.send(c, `Договорились, встреча ${chosen}. До встречи!`);
|
||||
}
|
||||
}
|
||||
81
test/outreach.test.ts
Normal file
81
test/outreach.test.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MockChannelAdapter, MockScreener } from "../src/channels.js";
|
||||
import { openDb } from "../src/db.js";
|
||||
import { Outreach } from "../src/outreach.js";
|
||||
import { createVacancy } from "../src/vacancies.js";
|
||||
|
||||
function setup(slots = ["2027-01-15 11:00"]) {
|
||||
const db = openDb();
|
||||
const v = createVacancy(db, { title: "Оператор", targetCount: 3 });
|
||||
const id = Number(
|
||||
db.prepare("INSERT INTO candidates (vacancy_id, full_name, phone, channel) VALUES (?, 'Анна', '79001112233', 'telegram')").run(v.id).lastInsertRowid,
|
||||
);
|
||||
const ch = new MockChannelAdapter();
|
||||
return { db, id, ch, o: new Outreach(db, ch, new MockScreener(), slots) };
|
||||
}
|
||||
const status = (db: ReturnType<typeof openDb>, id: number) =>
|
||||
(db.prepare("SELECT status FROM candidates WHERE id=?").get(id) as { status: string }).status;
|
||||
|
||||
describe("candidate-outreach", () => {
|
||||
it("Scenario: Первое сообщение — вакансия, ассистент, способ отказа", async () => {
|
||||
const { o, ch, id } = setup();
|
||||
await o.startContact(id);
|
||||
const t = ch.sent[0]!.text;
|
||||
expect(ch.sent[0]!.to.channel).toBe("telegram");
|
||||
expect(t).toContain("«Оператор»");
|
||||
expect(t).toContain("автоматический ассистент");
|
||||
expect(t).toContain("«стоп»");
|
||||
});
|
||||
|
||||
it("Scenario: Отказ кандидата — «стоп» прекращает контакт", async () => {
|
||||
const { o, ch, id, db } = setup();
|
||||
await o.startContact(id);
|
||||
await o.handleReply(id, "Стоп");
|
||||
expect(status(db, id)).toBe("declined");
|
||||
const n = ch.sent.length;
|
||||
await o.handleReply(id, "ещё вопрос");
|
||||
expect(ch.sent.length).toBe(n);
|
||||
});
|
||||
|
||||
it("Scenario: Кандидат выбирает слот — полный путь до встречи", async () => {
|
||||
const { o, ch, id, db } = setup();
|
||||
await o.startContact(id);
|
||||
await o.handleReply(id, "Здравствуйте, интересно"); // → вопрос 1
|
||||
await o.handleReply(id, "да"); // → вопрос 2
|
||||
await o.handleReply(id, "да, готов"); // → слоты
|
||||
expect(status(db, id)).toBe("qualified");
|
||||
expect(ch.sent.at(-1)!.text).toContain("2027-01-15 11:00");
|
||||
await o.handleReply(id, "Выбираю 2027-01-15 11:00");
|
||||
expect(status(db, id)).toBe("meeting_set");
|
||||
expect(db.prepare("SELECT starts_at FROM meetings WHERE candidate_id=?").get(id)).toEqual({ starts_at: "2027-01-15 11:00" });
|
||||
});
|
||||
|
||||
it("Scenario: Нет свободных слотов — ожидает слот", async () => {
|
||||
const { o, id, db } = setup([]);
|
||||
await o.startContact(id);
|
||||
for (const a of ["ок", "да", "да"]) await o.handleReply(id, a);
|
||||
expect(status(db, id)).toBe("awaiting_slot");
|
||||
});
|
||||
|
||||
it("не готов к обучению — отказ, ready_for_training=0", async () => {
|
||||
const { o, id, db } = setup();
|
||||
await o.startContact(id);
|
||||
for (const a of ["ок", "да", "нет"]) await o.handleReply(id, a);
|
||||
expect(status(db, id)).toBe("rejected");
|
||||
});
|
||||
|
||||
it("Scenario: Превышение лимита — 4-е сообщение откладывается", async () => {
|
||||
const { o, ch, id, db } = setup();
|
||||
db.prepare("UPDATE candidates SET status='contacted' WHERE id=?").run(id);
|
||||
for (let i = 0; i < 3; i++) db.prepare("INSERT INTO messages (candidate_id, direction, body) VALUES (?, 'out', 'x')").run(id);
|
||||
db.prepare("UPDATE candidates SET status='found' WHERE id=?").run(id);
|
||||
expect(await o.startContact(id)).toBe("deferred");
|
||||
expect(ch.sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("нет канала связи — ошибка", async () => {
|
||||
const { o, id, db } = setup();
|
||||
db.prepare("UPDATE candidates SET channel=NULL WHERE id=?").run(id);
|
||||
await expect(o.startContact(id)).rejects.toThrow("нет номера");
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user