FRTVL-44: поиск, отбор, каталог и уведомления по программам обучения в СНГ
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5d4665fbdf
commit
a53b5fb7b2
219
src/domain/training.ts
Normal file
219
src/domain/training.ts
Normal file
@ -0,0 +1,219 @@
|
||||
import { isExampleSource, isExpired, normalizeUrl, type RunReport } from "./internship.js";
|
||||
|
||||
/** Формат проведения. Полностью онлайн программы не подходят. */
|
||||
export type TrainingFormat = "in_person" | "hybrid" | "online";
|
||||
|
||||
/** Кто платит за участие: free — бесплатно, host_paid — оплачивает принимающая сторона. */
|
||||
export type ParticipantCost = "free" | "host_paid" | "paid" | "unknown";
|
||||
|
||||
/** Что оплачивает организатор. */
|
||||
export interface TrainingCoverage {
|
||||
tuition: boolean;
|
||||
travel: boolean;
|
||||
accommodation: boolean;
|
||||
meals: boolean;
|
||||
}
|
||||
|
||||
/** Программа обучения в том виде, в каком её вернул провайдер (ещё не отобрана). */
|
||||
export interface RawTraining {
|
||||
title: string;
|
||||
organization: string;
|
||||
/** Страна по-русски. */
|
||||
country: string;
|
||||
city: string | null;
|
||||
/** YYYY-MM-DD. */
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
deadline: string | null;
|
||||
format: TrainingFormat;
|
||||
participantCost: ParticipantCost;
|
||||
/** Условия оплаты прямо написаны на странице организатора. */
|
||||
paymentConfirmed: boolean;
|
||||
coverage: TrainingCoverage;
|
||||
/** Условия оплаты словами, по-русски. */
|
||||
paymentDetails: string;
|
||||
/** Как подать заявку, по-русски. */
|
||||
applyMethod: string;
|
||||
customerService: boolean;
|
||||
sourceUrl: string | null;
|
||||
rationale: string;
|
||||
}
|
||||
|
||||
/** Карточка каталога программ. */
|
||||
export interface Training extends Omit<RawTraining, "sourceUrl"> {
|
||||
id: string;
|
||||
sourceUrl: string;
|
||||
firstSeenAt: string;
|
||||
checkedAt: string;
|
||||
addedInRun: string;
|
||||
/** Когда о программе сообщили в Телеграм; null — ещё нет. */
|
||||
notifiedAt: string | null;
|
||||
}
|
||||
|
||||
export interface TrainingCatalog {
|
||||
trainings: Training[];
|
||||
lastRun: RunReport | null;
|
||||
lastSuccessfulRunId: string | null;
|
||||
}
|
||||
|
||||
export const emptyTrainingCatalog = (): TrainingCatalog => ({ trainings: [], lastRun: null, lastSuccessfulRunId: null });
|
||||
|
||||
/** Страны поиска (СНГ) и их варианты написания. */
|
||||
const CIS_COUNTRIES: Record<string, readonly string[]> = {
|
||||
Россия: ["россия", "российская федерация", "рф"],
|
||||
Беларусь: ["беларусь", "белоруссия", "республика беларусь"],
|
||||
Казахстан: ["казахстан", "республика казахстан"],
|
||||
Кыргызстан: ["кыргызстан", "киргизия", "кыргызская республика"],
|
||||
Узбекистан: ["узбекистан", "республика узбекистан"],
|
||||
Таджикистан: ["таджикистан", "республика таджикистан"],
|
||||
Армения: ["армения", "республика армения"],
|
||||
Азербайджан: ["азербайджан", "азербайджанская республика"],
|
||||
};
|
||||
|
||||
export const TRAINING_COUNTRIES = Object.keys(CIS_COUNTRIES);
|
||||
|
||||
/** Каноническое название страны из списка СНГ или null. */
|
||||
export function cisCountry(name: string): string | null {
|
||||
const key = name.trim().toLowerCase().replace(/ё/g, "е");
|
||||
for (const [canonical, aliases] of Object.entries(CIS_COUNTRIES)) if (aliases.includes(key)) return canonical;
|
||||
return null;
|
||||
}
|
||||
|
||||
const FORMATS: readonly TrainingFormat[] = ["in_person", "hybrid", "online"];
|
||||
const COSTS: readonly ParticipantCost[] = ["free", "host_paid", "paid", "unknown"];
|
||||
|
||||
const optStr = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
|
||||
const isoDate = (v: unknown): string | null => optStr(v)?.match(/^\d{4}-\d{2}-\d{2}/)?.[0] ?? null;
|
||||
|
||||
/** Приводит недоверенный объект к RawTraining; null — не хватает обязательных полей. */
|
||||
export function parseRawTraining(value: unknown): RawTraining | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
const title = optStr(v.title);
|
||||
const organization = optStr(v.organization);
|
||||
const country = optStr(v.country);
|
||||
if (!title || !organization || !country) return null;
|
||||
if (!FORMATS.includes(v.format as TrainingFormat)) return null;
|
||||
const c = (typeof v.coverage === "object" && v.coverage !== null ? v.coverage : {}) as Record<string, unknown>;
|
||||
return {
|
||||
title,
|
||||
organization,
|
||||
country: cisCountry(country) ?? country,
|
||||
city: optStr(v.city),
|
||||
startDate: isoDate(v.startDate),
|
||||
endDate: isoDate(v.endDate),
|
||||
deadline: isoDate(v.deadline),
|
||||
format: v.format as TrainingFormat,
|
||||
participantCost: COSTS.includes(v.participantCost as ParticipantCost) ? (v.participantCost as ParticipantCost) : "unknown",
|
||||
paymentConfirmed: v.paymentConfirmed === true,
|
||||
coverage: {
|
||||
tuition: c.tuition === true,
|
||||
travel: c.travel === true,
|
||||
accommodation: c.accommodation === true,
|
||||
meals: c.meals === true,
|
||||
},
|
||||
paymentDetails: optStr(v.paymentDetails) ?? "",
|
||||
applyMethod: optStr(v.applyMethod) ?? "",
|
||||
customerService: v.customerService === true,
|
||||
sourceUrl: optStr(v.sourceUrl),
|
||||
rationale: optStr(v.rationale) ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/** Дата через n месяцев (YYYY-MM-DD). */
|
||||
export function addMonths(today: string, months: number): string {
|
||||
const date = new Date(`${today}T00:00:00Z`);
|
||||
date.setUTCMonth(date.getUTCMonth() + months);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** Горизонт поиска и «ближайшие» программы, в месяцах. */
|
||||
export const HORIZON_MONTHS = 6;
|
||||
export const SOON_MONTHS = 3;
|
||||
|
||||
/** Критерии отбора из спеки training-search; today — YYYY-MM-DD. */
|
||||
export function isEligibleTraining(item: RawTraining, today: string): boolean {
|
||||
return (
|
||||
normalizeUrl(item.sourceUrl) !== null &&
|
||||
cisCountry(item.country) !== null &&
|
||||
item.format !== "online" &&
|
||||
(item.participantCost === "free" || item.participantCost === "host_paid") &&
|
||||
item.paymentConfirmed &&
|
||||
item.customerService &&
|
||||
item.startDate !== null &&
|
||||
item.startDate <= addMonths(today, HORIZON_MONTHS) &&
|
||||
!isExpired(item.endDate ?? item.startDate, today) &&
|
||||
!isExpired(item.deadline, today)
|
||||
);
|
||||
}
|
||||
|
||||
export interface TrainingMergeResult {
|
||||
catalog: TrainingCatalog;
|
||||
found: number;
|
||||
added: number;
|
||||
rejected: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Отбирает подходящие программы и вливает их в каталог. Известные (по ссылке) обновляют данные,
|
||||
* но сохраняют дату появления и отметку об уведомлении. withoutExamples — убрать примеры (настоящий поиск).
|
||||
*/
|
||||
export function mergeTrainings(
|
||||
catalog: TrainingCatalog,
|
||||
candidates: readonly unknown[],
|
||||
runId: string,
|
||||
now: string,
|
||||
withoutExamples = false,
|
||||
): TrainingMergeResult {
|
||||
const today = now.slice(0, 10);
|
||||
const kept = withoutExamples ? catalog.trainings.filter((item) => !isExampleSource(item.sourceUrl)) : catalog.trainings;
|
||||
const byId = new Map(kept.map((item) => [item.id, item]));
|
||||
const seen = new Set<string>();
|
||||
let found = 0;
|
||||
let added = 0;
|
||||
let rejected = 0;
|
||||
for (const candidate of candidates) {
|
||||
const raw = parseRawTraining(candidate);
|
||||
const id = raw ? normalizeUrl(raw.sourceUrl) : null;
|
||||
if (!raw || !id || !isEligibleTraining(raw, today)) {
|
||||
rejected++;
|
||||
continue;
|
||||
}
|
||||
if (seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
found++;
|
||||
const existing = byId.get(id);
|
||||
if (!existing) added++;
|
||||
byId.set(id, {
|
||||
...raw,
|
||||
id,
|
||||
sourceUrl: raw.sourceUrl as string,
|
||||
firstSeenAt: existing?.firstSeenAt ?? now,
|
||||
checkedAt: now,
|
||||
addedInRun: existing?.addedInRun ?? runId,
|
||||
notifiedAt: existing?.notifiedAt ?? null,
|
||||
});
|
||||
}
|
||||
return { catalog: { ...catalog, trainings: [...byId.values()] }, found, added, rejected };
|
||||
}
|
||||
|
||||
export type TrainingView = Training & { isNew: boolean; soon: boolean };
|
||||
|
||||
/** Программы для показа: прошедшие скрыты; по дедлайну (неизвестный — в конце), затем по дате начала. */
|
||||
export function sortTrainings(catalog: TrainingCatalog, today: string): TrainingView[] {
|
||||
const soonLimit = addMonths(today, SOON_MONTHS);
|
||||
const key = (value: string | null) => value ?? "9999-99-99";
|
||||
return catalog.trainings
|
||||
.filter((item) => !isExpired(item.endDate ?? item.startDate, today))
|
||||
.map((item) => ({
|
||||
...item,
|
||||
isNew: item.addedInRun === catalog.lastSuccessfulRunId,
|
||||
soon: item.startDate !== null && item.startDate <= soonLimit,
|
||||
}))
|
||||
.sort((a, b) => key(a.deadline).localeCompare(key(b.deadline)) || key(a.startDate).localeCompare(key(b.startDate)));
|
||||
}
|
||||
|
||||
/** Программы, о которых ещё не сообщали и подача на которые не закрыта. */
|
||||
export function unnotifiedTrainings(catalog: TrainingCatalog, today: string): Training[] {
|
||||
return catalog.trainings.filter((item) => item.notifiedAt === null && !isExpired(item.deadline, today));
|
||||
}
|
||||
22
src/index.ts
22
src/index.ts
@ -9,7 +9,11 @@ import { mockSearchProvider } from "./search/mockSearchProvider.js";
|
||||
import type { SearchProvider } from "./search/provider.js";
|
||||
import { SearchService } from "./search/searchService.js";
|
||||
import { buildServer } from "./server.js";
|
||||
import { JsonCatalogStore } from "./store/catalogStore.js";
|
||||
import { emptyTrainingCatalog } from "./domain/training.js";
|
||||
import { mockTrainingProvider } from "./search/mockTrainingProvider.js";
|
||||
import { trainingSearchConfig } from "./search/trainingSearchConfig.js";
|
||||
import { JsonCatalogStore, JsonFileStore } from "./store/catalogStore.js";
|
||||
import { TrainingSearch } from "./training/trainingSearch.js";
|
||||
|
||||
const useMock = process.env.MOCK_SEARCH === "1" || !process.env.ANTHROPIC_API_KEY;
|
||||
const provider: SearchProvider = useMock ? mockSearchProvider({ delayMs: 1500 }) : new ClaudeSearchProvider();
|
||||
@ -27,9 +31,22 @@ if (process.env.TELEGRAM_BOT_TOKEN) {
|
||||
}
|
||||
if (telegramProblem === "no_token") console.warn("Telegram: нет TELEGRAM_BOT_TOKEN в окружении — бот работает как пример");
|
||||
if (telegramProblem === "bad_token") console.error("Telegram: Телеграм не принял TELEGRAM_BOT_TOKEN (getMe)");
|
||||
const settings = new JsonSettingsStore(process.env.DATA_DIR ?? "./data");
|
||||
const trainingStore = new JsonFileStore(process.env.DATA_DIR ?? "./data", "trainings.json", emptyTrainingCatalog);
|
||||
const trainingProvider: SearchProvider = useMock
|
||||
? mockTrainingProvider({ delayMs: 1500 })
|
||||
: new ClaudeSearchProvider(undefined, trainingSearchConfig);
|
||||
const trainings = new TrainingSearch({
|
||||
store: trainingStore,
|
||||
provider: trainingProvider,
|
||||
settings,
|
||||
telegram,
|
||||
onError: (error) => Sentry.captureException(error),
|
||||
});
|
||||
const notifier = new Notifier({
|
||||
settings: new JsonSettingsStore(process.env.DATA_DIR ?? "./data"),
|
||||
settings,
|
||||
catalog: store,
|
||||
trainings,
|
||||
search,
|
||||
telegram,
|
||||
telegramProblem,
|
||||
@ -41,6 +58,7 @@ const app = await buildServer({
|
||||
store,
|
||||
search,
|
||||
notifier,
|
||||
trainings: { search: trainings, store: trainingStore, providerName: trainingProvider.name },
|
||||
auth: new OwnerAuth(process.env.OWNER_PASSWORD || undefined),
|
||||
secureCookies: Boolean(process.env.PEPPA_HOST),
|
||||
providerName: provider.name,
|
||||
|
||||
@ -2,6 +2,7 @@ import { randomBytes } from "node:crypto";
|
||||
import { type RunReport, unseenActive } from "../domain/internship.js";
|
||||
import { SearchAlreadyRunningError, type SearchService } from "../search/searchService.js";
|
||||
import type { CatalogStore } from "../store/catalogStore.js";
|
||||
import type { TrainingSearch } from "../training/trainingSearch.js";
|
||||
import { formatMessages } from "./message.js";
|
||||
import { type NotificationSettings, type ScheduledRunResult, type SettingsStore } from "./settingsStore.js";
|
||||
import type { TelegramClient } from "./telegram.js";
|
||||
@ -30,6 +31,8 @@ export interface NotifierOptions {
|
||||
catalog: CatalogStore;
|
||||
search: SearchService;
|
||||
telegram: TelegramClient;
|
||||
/** Поиск программ обучения: ежедневный поиск запускает и его (FRTVL-44). */
|
||||
trainings?: TrainingSearch;
|
||||
/** Причина, по которой бот не работает (для экрана). */
|
||||
telegramProblem?: TelegramProblem;
|
||||
now?: () => Date;
|
||||
@ -220,9 +223,21 @@ export class Notifier {
|
||||
lastRun: { at: this.now().toISOString(), status: "error", sent: 0, error: message },
|
||||
});
|
||||
});
|
||||
await this.runTrainings();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ежедневный поиск программ обучения; уведомления отправляет сам поиск. Сбой не мешает стажировкам. */
|
||||
private async runTrainings(): Promise<void> {
|
||||
const { trainings } = this.options;
|
||||
if (!trainings) return;
|
||||
try {
|
||||
await trainings.start();
|
||||
} catch (error) {
|
||||
if (!(error instanceof SearchAlreadyRunningError)) this.options.onError?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
private async notify(report: RunReport): Promise<void> {
|
||||
const { settings, catalog: catalogStore, telegram } = this.options;
|
||||
const at = this.now().toISOString();
|
||||
|
||||
@ -104,7 +104,34 @@ export interface MessagesStreamer {
|
||||
stream(params: BetaMessageStreamParams): { finalMessage(): Promise<BetaMessage> };
|
||||
}
|
||||
|
||||
export function buildRequest(messages: BetaMessageParam[]): BetaMessageStreamParams {
|
||||
/** Что и как ищет провайдер: промпт, инструмент передачи результата и его схема. */
|
||||
export interface ClaudeSearchConfig {
|
||||
system: string;
|
||||
/** Первое сообщение; today — YYYY-MM-DD. */
|
||||
userPrompt(today: string): string;
|
||||
/** Напоминание вызвать инструмент, если модель закончила без него. */
|
||||
reminder: string;
|
||||
toolName: string;
|
||||
toolDescription: string;
|
||||
schema: object;
|
||||
/** Поле входа инструмента со списком результатов. */
|
||||
resultKey: string;
|
||||
}
|
||||
|
||||
export const internshipSearchConfig: ClaudeSearchConfig = {
|
||||
system: SYSTEM_PROMPT,
|
||||
userPrompt: (today) => `Сегодня ${today}. Найди подходящие стажировки и передай их через ${SUBMIT_TOOL}.`,
|
||||
reminder: `Передай найденные стажировки вызовом ${SUBMIT_TOOL} (пустой список, если ничего не нашлось).`,
|
||||
toolName: SUBMIT_TOOL,
|
||||
toolDescription: "Передать итоговый список найденных стажировок. Вызывается один раз в конце работы.",
|
||||
schema: SUBMIT_TOOL_SCHEMA,
|
||||
resultKey: "internships",
|
||||
};
|
||||
|
||||
export function buildRequest(
|
||||
messages: BetaMessageParam[],
|
||||
config: ClaudeSearchConfig = internshipSearchConfig,
|
||||
): BetaMessageStreamParams {
|
||||
return {
|
||||
model: SEARCH_MODEL,
|
||||
max_tokens: 64000,
|
||||
@ -112,14 +139,14 @@ export function buildRequest(messages: BetaMessageParam[]): BetaMessageStreamPar
|
||||
output_config: { effort: "medium" },
|
||||
betas: ["server-side-fallback-2026-07-01"],
|
||||
fallbacks: "default",
|
||||
system: SYSTEM_PROMPT,
|
||||
system: config.system,
|
||||
tools: [
|
||||
{ type: "web_search_20260209", name: "web_search", max_uses: 15 },
|
||||
{ type: "web_fetch_20260209", name: "web_fetch", max_uses: 10 },
|
||||
{
|
||||
name: SUBMIT_TOOL,
|
||||
description: "Передать итоговый список найденных стажировок. Вызывается один раз в конце работы.",
|
||||
input_schema: SUBMIT_TOOL_SCHEMA as unknown as BetaTool["input_schema"],
|
||||
name: config.toolName,
|
||||
description: config.toolDescription,
|
||||
input_schema: config.schema as unknown as BetaTool["input_schema"],
|
||||
strict: true,
|
||||
},
|
||||
],
|
||||
@ -127,17 +154,20 @@ export function buildRequest(messages: BetaMessageParam[]): BetaMessageStreamPar
|
||||
};
|
||||
}
|
||||
|
||||
/** Поиск стажировок моделью Claude с серверным веб-поиском. Нужен ANTHROPIC_API_KEY. */
|
||||
/** Поиск моделью Claude с серверным веб-поиском (по умолчанию — стажировки). Нужен ANTHROPIC_API_KEY. */
|
||||
export class ClaudeSearchProvider implements SearchProvider {
|
||||
readonly name = "claude";
|
||||
|
||||
constructor(private readonly messagesApi: MessagesStreamer = new Anthropic().beta.messages) {}
|
||||
constructor(
|
||||
private readonly messagesApi: MessagesStreamer = new Anthropic().beta.messages,
|
||||
private readonly config: ClaudeSearchConfig = internshipSearchConfig,
|
||||
) {}
|
||||
|
||||
async search(): Promise<unknown[]> {
|
||||
const messages: BetaMessageParam[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: `Сегодня ${new Date().toISOString().slice(0, 10)}. Найди подходящие стажировки и передай их через ${SUBMIT_TOOL}.`,
|
||||
content: this.config.userPrompt(new Date().toISOString().slice(0, 10)),
|
||||
},
|
||||
];
|
||||
let reminded = false;
|
||||
@ -145,7 +175,7 @@ export class ClaudeSearchProvider implements SearchProvider {
|
||||
for (let step = 0; step < MAX_STEPS; step++) {
|
||||
let message: BetaMessage;
|
||||
try {
|
||||
message = await this.messagesApi.stream(buildRequest(messages)).finalMessage();
|
||||
message = await this.messagesApi.stream(buildRequest(messages, this.config)).finalMessage();
|
||||
} catch (error) {
|
||||
throw new SearchProviderError(`Claude API: ${(error as Error).message}`, { cause: error });
|
||||
}
|
||||
@ -156,17 +186,17 @@ export class ClaudeSearchProvider implements SearchProvider {
|
||||
}
|
||||
|
||||
const submit = message.content.find(
|
||||
(block): block is BetaToolUseBlock => block.type === "tool_use" && block.name === SUBMIT_TOOL,
|
||||
(block): block is BetaToolUseBlock => block.type === "tool_use" && block.name === this.config.toolName,
|
||||
);
|
||||
if (submit) {
|
||||
if (message.stop_reason === "max_tokens") {
|
||||
throw new SearchProviderError("Ответ модели обрезан (max_tokens)");
|
||||
}
|
||||
const input = submit.input as { internships?: unknown };
|
||||
if (!Array.isArray(input.internships)) {
|
||||
const result = (submit.input as Record<string, unknown>)[this.config.resultKey];
|
||||
if (!Array.isArray(result)) {
|
||||
throw new SearchProviderError("Модель вернула результат в неверном формате");
|
||||
}
|
||||
return input.internships;
|
||||
return result;
|
||||
}
|
||||
|
||||
messages.push({ role: "assistant", content: message.content });
|
||||
@ -175,7 +205,7 @@ export class ClaudeSearchProvider implements SearchProvider {
|
||||
reminded = true;
|
||||
messages.push({
|
||||
role: "user",
|
||||
content: `Передай найденные стажировки вызовом ${SUBMIT_TOOL} (пустой список, если ничего не нашлось).`,
|
||||
content: this.config.reminder,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
117
src/search/mockTrainingProvider.ts
Normal file
117
src/search/mockTrainingProvider.ts
Normal file
@ -0,0 +1,117 @@
|
||||
import { addMonths, type RawTraining } from "../domain/training.js";
|
||||
import { type SearchProvider, SearchProviderError } from "./provider.js";
|
||||
|
||||
/** Дата через days дней от today (YYYY-MM-DD). */
|
||||
function addDays(today: string, days: number): string {
|
||||
const date = new Date(`${today}T00:00:00Z`);
|
||||
date.setUTCDate(date.getUTCDate() + days);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* МОК поиска программ: вымышленные программы (домены example.org) в формате ответа Claude, даты —
|
||||
* относительно today. Первые две проходят отбор, остальные проверяют его.
|
||||
*/
|
||||
export function mockTrainings(today: string): RawTraining[] {
|
||||
const base = {
|
||||
format: "in_person",
|
||||
participantCost: "free",
|
||||
paymentConfirmed: true,
|
||||
coverage: { tuition: true, travel: false, accommodation: false, meals: false },
|
||||
customerService: true,
|
||||
applyMethod: "Анкета на сайте организатора",
|
||||
} as const;
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
title: "Школа клиентского сервиса",
|
||||
organization: "Mock Фонд развития сервиса",
|
||||
country: "Казахстан",
|
||||
city: "Алматы",
|
||||
startDate: addDays(today, 40),
|
||||
endDate: addDays(today, 44),
|
||||
deadline: addDays(today, 20),
|
||||
participantCost: "host_paid",
|
||||
coverage: { tuition: true, travel: true, accommodation: true, meals: false },
|
||||
paymentDetails: "Организатор оплачивает обучение, проезд и проживание в гостинице",
|
||||
applyMethod: "Анкета и мотивационное письмо на сайте фонда",
|
||||
sourceUrl: "https://example.org/mock/almaty-service-school",
|
||||
rationale: "Очный интенсив по клиентскому сервису, участие и дорогу оплачивает фонд.",
|
||||
},
|
||||
{
|
||||
...base,
|
||||
title: "Интенсив «Клиентский опыт в гостеприимстве»",
|
||||
organization: "Mock Ассоциация отельеров",
|
||||
country: "Армения",
|
||||
city: "Ереван",
|
||||
startDate: addMonths(today, 4),
|
||||
endDate: addDays(addMonths(today, 4), 2),
|
||||
deadline: null,
|
||||
paymentDetails: "Участие бесплатное, проезд и жильё за свой счёт",
|
||||
applyMethod: "Письмо организатору с резюме",
|
||||
sourceUrl: "https://example.org/mock/yerevan-cx-intensive",
|
||||
rationale: "Бесплатный очный интенсив по сервису для гостиниц.",
|
||||
},
|
||||
{
|
||||
...base,
|
||||
title: "Платный курс администратора",
|
||||
organization: "Mock Академия",
|
||||
country: "Россия",
|
||||
city: "Москва",
|
||||
startDate: addDays(today, 30),
|
||||
endDate: addDays(today, 60),
|
||||
deadline: null,
|
||||
participantCost: "paid",
|
||||
paymentDetails: "Стоимость 45 000 ₽",
|
||||
sourceUrl: "https://example.org/mock/moscow-paid-course",
|
||||
rationale: "Отбрасывается: платно для участницы.",
|
||||
},
|
||||
{
|
||||
...base,
|
||||
title: "Онлайн-марафон по сервису",
|
||||
organization: "Mock Онлайн-школа",
|
||||
country: "Беларусь",
|
||||
city: null,
|
||||
startDate: addDays(today, 15),
|
||||
endDate: addDays(today, 20),
|
||||
deadline: null,
|
||||
format: "online",
|
||||
paymentDetails: "Бесплатно",
|
||||
sourceUrl: "https://example.org/mock/online-marathon",
|
||||
rationale: "Отбрасывается: полностью онлайн.",
|
||||
},
|
||||
{
|
||||
...base,
|
||||
title: "Тренинг для операторов поддержки",
|
||||
organization: "Mock Колл-центр",
|
||||
country: "Узбекистан",
|
||||
city: "Ташкент",
|
||||
startDate: addDays(today, 25),
|
||||
endDate: addDays(today, 26),
|
||||
deadline: null,
|
||||
participantCost: "unknown",
|
||||
paymentConfirmed: false,
|
||||
paymentDetails: "Условия оплаты не указаны",
|
||||
sourceUrl: "https://example.org/mock/tashkent-support-training",
|
||||
rationale: "Отбрасывается: оплата не подтверждена.",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export interface MockTrainingOptions {
|
||||
fail?: boolean;
|
||||
delayMs?: number;
|
||||
/** Сегодня (YYYY-MM-DD); по умолчанию — текущая дата. */
|
||||
today?: () => string;
|
||||
}
|
||||
|
||||
export function mockTrainingProvider(options: MockTrainingOptions = {}): SearchProvider {
|
||||
return {
|
||||
name: "mock",
|
||||
async search() {
|
||||
if (options.delayMs) await new Promise((resolve) => setTimeout(resolve, options.delayMs));
|
||||
if (options.fail) throw new SearchProviderError("Сервис поиска недоступен (мок)");
|
||||
return mockTrainings(options.today?.() ?? new Date().toISOString().slice(0, 10));
|
||||
},
|
||||
};
|
||||
}
|
||||
102
src/search/trainingSearchConfig.ts
Normal file
102
src/search/trainingSearchConfig.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import { TRAINING_COUNTRIES } from "../domain/training.js";
|
||||
import type { ClaudeSearchConfig } from "./claudeSearchProvider.js";
|
||||
|
||||
const TOOL = "submit_trainings";
|
||||
|
||||
export const TRAINING_SYSTEM_PROMPT = `Ты — исследователь, который ищет очное обучение для специалистки по клиентскому сервису. Она не может платить за участие.
|
||||
|
||||
Найди в интернете (на русском и английском) очные программы обучения и повышения квалификации по клиентскому сервису — школы, интенсивы, курсы, тренинги, летние школы, программы стажировок с обучением — в странах: ${TRAINING_COUNTRIES.join(", ")}. Подходят программы, которые:
|
||||
1. Проходят очно (или смешанно с очной частью). Полностью онлайн программы не подходят.
|
||||
2. Бесплатны для участницы (free), либо участие оплачивает принимающая сторона — организатор, фонд, грант, работодатель (host_paid). Бесплатное участие с самостоятельной оплатой дороги и жилья тоже подходит.
|
||||
3. Связаны с клиентским сервисом: обслуживание клиентов, клиентский опыт, поддержка, сервис в гостиничном деле и туризме, продажи и консультирование.
|
||||
4. Начинаются в ближайшие 6 месяцев.
|
||||
|
||||
Как работать:
|
||||
- Ищи веб-поиском, затем открывай страницу организатора, чтобы проверить даты и условия. Не выдумывай программы и условия: каждая программа должна опираться на страницу организатора (первоисточник), её адрес — в sourceUrl. Агрегаторы и новости — только чтобы найти первоисточник.
|
||||
- paymentConfirmed = true, только если на странице организатора прямо написано, что участие бесплатно или что организатор оплачивает участие. Иначе false.
|
||||
- В coverage отметь, что именно оплачивает организатор: tuition — обучение, travel — проезд, accommodation — жильё, meals — питание.
|
||||
- Пропускай прошедшие программы и закрытые наборы.
|
||||
- Если условие не указано, пиши честно (participantCost "unknown", paymentConfirmed false) — отбор сделает программа.
|
||||
- Даты — в формате YYYY-MM-DD. Страну пиши по-русски одним словом из списка выше. Условия оплаты, способ подачи и обоснование — по-русски.
|
||||
|
||||
Когда закончишь, обязательно вызови инструмент ${TOOL} один раз со всеми найденными программами (до 20). Это единственный способ передать результат.`;
|
||||
|
||||
const nullableString = { type: ["string", "null"] } as const;
|
||||
|
||||
export const TRAINING_TOOL_SCHEMA = {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["trainings"],
|
||||
properties: {
|
||||
trainings: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: [
|
||||
"title",
|
||||
"organization",
|
||||
"country",
|
||||
"city",
|
||||
"startDate",
|
||||
"endDate",
|
||||
"deadline",
|
||||
"format",
|
||||
"participantCost",
|
||||
"paymentConfirmed",
|
||||
"coverage",
|
||||
"paymentDetails",
|
||||
"applyMethod",
|
||||
"customerService",
|
||||
"sourceUrl",
|
||||
"rationale",
|
||||
],
|
||||
properties: {
|
||||
title: { type: "string", description: "Название программы" },
|
||||
organization: { type: "string", description: "Организатор" },
|
||||
country: { type: "string", description: "Страна по-русски, из списка" },
|
||||
city: nullableString,
|
||||
startDate: { ...nullableString, description: "Дата начала YYYY-MM-DD" },
|
||||
endDate: { ...nullableString, description: "Дата окончания YYYY-MM-DD" },
|
||||
deadline: { ...nullableString, description: "Дедлайн заявки YYYY-MM-DD" },
|
||||
format: { type: "string", enum: ["in_person", "hybrid", "online"] },
|
||||
participantCost: {
|
||||
type: "string",
|
||||
enum: ["free", "host_paid", "paid", "unknown"],
|
||||
description: "free — бесплатно; host_paid — оплачивает принимающая сторона; paid — платит участница",
|
||||
},
|
||||
paymentConfirmed: {
|
||||
type: "boolean",
|
||||
description: "true — условия оплаты прямо написаны на странице организатора",
|
||||
},
|
||||
coverage: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["tuition", "travel", "accommodation", "meals"],
|
||||
properties: {
|
||||
tuition: { type: "boolean" },
|
||||
travel: { type: "boolean" },
|
||||
accommodation: { type: "boolean" },
|
||||
meals: { type: "boolean" },
|
||||
},
|
||||
},
|
||||
paymentDetails: { type: "string", description: "Условия оплаты словами, по-русски" },
|
||||
applyMethod: { type: "string", description: "Как подать заявку: форма, письмо, конкурс…" },
|
||||
customerService: { type: "boolean" },
|
||||
sourceUrl: { ...nullableString, description: "Страница организатора" },
|
||||
rationale: { type: "string", description: "Почему подходит, 1–2 предложения по-русски" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const trainingSearchConfig: ClaudeSearchConfig = {
|
||||
system: TRAINING_SYSTEM_PROMPT,
|
||||
userPrompt: (today) => `Сегодня ${today}. Найди подходящие очные программы обучения и передай их через ${TOOL}.`,
|
||||
reminder: `Передай найденные программы вызовом ${TOOL} (пустой список, если ничего не нашлось).`,
|
||||
toolName: TOOL,
|
||||
toolDescription: "Передать итоговый список найденных программ обучения. Вызывается один раз в конце работы.",
|
||||
schema: TRAINING_TOOL_SCHEMA,
|
||||
resultKey: "trainings",
|
||||
};
|
||||
@ -3,16 +3,20 @@ import { fileURLToPath } from "node:url";
|
||||
import fastifyStatic from "@fastify/static";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { OwnerAuth, readCookie, SESSION_COOKIE, sessionCookie } from "./auth/session.js";
|
||||
import { sortForDisplay, withoutExamples } from "./domain/internship.js";
|
||||
import { isExampleSource, sortForDisplay, withoutExamples } from "./domain/internship.js";
|
||||
import { sortTrainings, type TrainingCatalog } from "./domain/training.js";
|
||||
import { Notifier, NotifierError } from "./notify/notifier.js";
|
||||
import { SearchAlreadyRunningError, type SearchService } from "./search/searchService.js";
|
||||
import type { CatalogStore } from "./store/catalogStore.js";
|
||||
import type { CatalogStore, Store } from "./store/catalogStore.js";
|
||||
import type { TrainingSearch } from "./training/trainingSearch.js";
|
||||
|
||||
export interface ServerOptions {
|
||||
store: CatalogStore;
|
||||
search: SearchService;
|
||||
/** Привязка Телеграма и регулярный поиск; без него эндпоинты настроек не регистрируются. */
|
||||
notifier?: Notifier;
|
||||
/** Поиск очного обучения по клиентскому сервису в СНГ (FRTVL-44); без него вид поиска недоступен. */
|
||||
trainings?: { search: TrainingSearch; store: Store<TrainingCatalog>; providerName?: string };
|
||||
/** Вход владельца: без него (или без пароля) поиск и настройки Телеграма закрыты. */
|
||||
auth?: OwnerAuth;
|
||||
/** Ставить cookie сессии с флагом Secure (стенды по https). */
|
||||
@ -57,13 +61,30 @@ export async function buildServer(options: ServerOptions): Promise<FastifyInstan
|
||||
return { internships: sortForDisplay(catalog), lastRun: catalog.lastRun };
|
||||
});
|
||||
|
||||
const { trainings } = options;
|
||||
const realTrainingSearch = trainings?.providerName !== undefined && trainings.providerName !== "mock";
|
||||
const isTrainings = (request: { query: unknown }) => (request.query as { kind?: string } | undefined)?.kind === "trainings";
|
||||
|
||||
if (trainings) {
|
||||
app.get("/api/trainings", async () => {
|
||||
const catalog = await trainings.store.load();
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const shown = sortTrainings(catalog, today).filter((item) => !realTrainingSearch || !isExampleSource(item.sourceUrl));
|
||||
return { trainings: shown, lastRun: catalog.lastRun };
|
||||
});
|
||||
}
|
||||
|
||||
app.get("/api/search/status", async (request) => {
|
||||
const catalog = await options.store.load();
|
||||
const kindTrainings = trainings !== undefined && isTrainings(request);
|
||||
const service = kindTrainings ? trainings.search : options.search;
|
||||
const catalog = kindTrainings ? await trainings.store.load() : await options.store.load();
|
||||
return {
|
||||
state: options.search.running ? "running" : "idle",
|
||||
runningSince: options.search.runningSince,
|
||||
kind: kindTrainings ? "trainings" : "internships",
|
||||
trainingsAvailable: trainings !== undefined,
|
||||
state: service.running ? "running" : "idle",
|
||||
runningSince: service.runningSince,
|
||||
lastRun: catalog.lastRun,
|
||||
provider: options.providerName ?? "unknown",
|
||||
provider: (kindTrainings ? trainings.providerName : options.providerName) ?? "unknown",
|
||||
signedIn: signedIn(request),
|
||||
loginAvailable: auth.available,
|
||||
};
|
||||
@ -106,8 +127,9 @@ export async function buildServer(options: ServerOptions): Promise<FastifyInstan
|
||||
|
||||
app.post("/api/search", async (request, reply) => {
|
||||
if (!signedIn(request)) return reply.code(401).send(deny);
|
||||
const service = trainings && isTrainings(request) ? trainings.search : options.search;
|
||||
try {
|
||||
options.search.start().catch((error: unknown) => request.log.error(error, "search run failed"));
|
||||
service.start().catch((error: unknown) => request.log.error(error, "search run failed"));
|
||||
} catch (error) {
|
||||
if (error instanceof SearchAlreadyRunningError) {
|
||||
return reply.code(409).send({ error: error.message });
|
||||
|
||||
@ -2,33 +2,46 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { type Catalog, emptyCatalog } from "../domain/internship.js";
|
||||
|
||||
export interface CatalogStore {
|
||||
load(): Promise<Catalog>;
|
||||
save(catalog: Catalog): Promise<void>;
|
||||
export interface Store<T> {
|
||||
load(): Promise<T>;
|
||||
save(value: T): Promise<void>;
|
||||
}
|
||||
|
||||
/** Каталог в `<dir>/catalog.json`; запись атомарная (временный файл + rename). */
|
||||
export class JsonCatalogStore implements CatalogStore {
|
||||
export type CatalogStore = Store<Catalog>;
|
||||
|
||||
/** Объект в `<dir>/<file>`; нет файла — пустое значение; запись атомарная (временный файл + rename). */
|
||||
export class JsonFileStore<T extends object> implements Store<T> {
|
||||
private readonly file: string;
|
||||
|
||||
constructor(private readonly dir: string) {
|
||||
this.file = path.join(dir, "catalog.json");
|
||||
constructor(
|
||||
private readonly dir: string,
|
||||
file: string,
|
||||
private readonly empty: () => T,
|
||||
) {
|
||||
this.file = path.join(dir, file);
|
||||
}
|
||||
|
||||
async load(): Promise<Catalog> {
|
||||
async load(): Promise<T> {
|
||||
try {
|
||||
const data = JSON.parse(await readFile(this.file, "utf8")) as Partial<Catalog>;
|
||||
return { ...emptyCatalog(), ...data };
|
||||
const data = JSON.parse(await readFile(this.file, "utf8")) as Partial<T>;
|
||||
return { ...this.empty(), ...data };
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return emptyCatalog();
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return this.empty();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async save(catalog: Catalog): Promise<void> {
|
||||
async save(value: T): Promise<void> {
|
||||
await mkdir(this.dir, { recursive: true });
|
||||
const tmp = `${this.file}.${process.pid}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(catalog, null, 2), "utf8");
|
||||
await writeFile(tmp, JSON.stringify(value, null, 2), "utf8");
|
||||
await rename(tmp, this.file);
|
||||
}
|
||||
}
|
||||
|
||||
/** Каталог стажировок в `<dir>/catalog.json`. */
|
||||
export class JsonCatalogStore extends JsonFileStore<Catalog> {
|
||||
constructor(dir: string) {
|
||||
super(dir, "catalog.json", emptyCatalog);
|
||||
}
|
||||
}
|
||||
|
||||
54
src/training/trainingMessage.ts
Normal file
54
src/training/trainingMessage.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import type { Training } from "../domain/training.js";
|
||||
import { MAX_MESSAGE_LENGTH } from "../notify/message.js";
|
||||
|
||||
const COVERAGE_LABELS: Array<[keyof Training["coverage"], string]> = [
|
||||
["tuition", "обучение"],
|
||||
["travel", "проезд"],
|
||||
["accommodation", "жильё"],
|
||||
["meals", "питание"],
|
||||
];
|
||||
|
||||
/** Что оплачивает организатор: «обучение, жильё»; ничего — пустая строка. */
|
||||
export function coveredByHost(item: Pick<Training, "coverage">): string {
|
||||
return COVERAGE_LABELS.filter(([key]) => item.coverage[key]).map(([, label]) => label).join(", ");
|
||||
}
|
||||
|
||||
/** «Алматы, Казахстан». */
|
||||
export function trainingPlace(item: Pick<Training, "city" | "country">): string {
|
||||
return [item.city, item.country].filter(Boolean).join(", ");
|
||||
}
|
||||
|
||||
/** «2027-01-20 — 2027-01-24». */
|
||||
export function trainingDates(item: Pick<Training, "startDate" | "endDate">): string {
|
||||
if (!item.startDate) return "не указаны";
|
||||
return item.endDate && item.endDate !== item.startDate ? `${item.startDate} — ${item.endDate}` : item.startDate;
|
||||
}
|
||||
|
||||
export function formatTraining(item: Training): string {
|
||||
const host = coveredByHost(item);
|
||||
return [
|
||||
item.title,
|
||||
`Где: ${trainingPlace(item)}`,
|
||||
`Даты: ${trainingDates(item)}`,
|
||||
`Дедлайн: ${item.deadline ?? "не указан"}`,
|
||||
`Оплачивает организатор: ${host || "только участие (бесплатно)"}`,
|
||||
item.sourceUrl,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Сообщения о новых программах; делит по границам карточек, чтобы уложиться в лимит Телеграма. */
|
||||
export function formatTrainingMessages(items: readonly Training[]): string[] {
|
||||
const messages: string[] = [];
|
||||
let current = `Новое обучение по клиентскому сервису (СНГ): ${items.length}`;
|
||||
for (const item of items) {
|
||||
const block = formatTraining(item).slice(0, MAX_MESSAGE_LENGTH - 100);
|
||||
if (current.length + block.length + 2 > MAX_MESSAGE_LENGTH) {
|
||||
messages.push(current);
|
||||
current = block;
|
||||
} else {
|
||||
current += `\n\n${block}`;
|
||||
}
|
||||
}
|
||||
messages.push(current);
|
||||
return messages;
|
||||
}
|
||||
122
src/training/trainingSearch.ts
Normal file
122
src/training/trainingSearch.ts
Normal file
@ -0,0 +1,122 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { RunReport } from "../domain/internship.js";
|
||||
import { mergeTrainings, type TrainingCatalog, unnotifiedTrainings } from "../domain/training.js";
|
||||
import type { SettingsStore } from "../notify/settingsStore.js";
|
||||
import type { TelegramClient } from "../notify/telegram.js";
|
||||
import type { SearchProvider } from "../search/provider.js";
|
||||
import { SearchAlreadyRunningError } from "../search/searchService.js";
|
||||
import type { Store } from "../store/catalogStore.js";
|
||||
import { formatTrainingMessages } from "./trainingMessage.js";
|
||||
|
||||
export interface TrainingSearchOptions {
|
||||
store: Store<TrainingCatalog>;
|
||||
provider: SearchProvider;
|
||||
/** Привязка Телеграма (тот же чат, что и для стажировок); без неё уведомлений нет. */
|
||||
settings?: SettingsStore;
|
||||
telegram?: TelegramClient;
|
||||
now?: () => Date;
|
||||
onError?: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** Итог уведомления после поиска. */
|
||||
export type TrainingNotifyResult = { status: "sent"; sent: number } | { status: "nothing_new" | "not_linked" | "error" };
|
||||
|
||||
/** Поиск очных программ обучения (не более одного одновременно), каталог и уведомления в Телеграм. */
|
||||
export class TrainingSearch {
|
||||
private current: Promise<RunReport> | null = null;
|
||||
private currentStartedAt: string | null = null;
|
||||
|
||||
constructor(private readonly options: TrainingSearchOptions) {}
|
||||
|
||||
private now(): Date {
|
||||
return (this.options.now ?? (() => new Date()))();
|
||||
}
|
||||
|
||||
get running(): boolean {
|
||||
return this.current !== null;
|
||||
}
|
||||
|
||||
get runningSince(): string | null {
|
||||
return this.currentStartedAt;
|
||||
}
|
||||
|
||||
/** Начинает поиск; бросает SearchAlreadyRunningError, если поиск программ уже идёт. */
|
||||
start(): Promise<RunReport> {
|
||||
if (this.current) throw new SearchAlreadyRunningError();
|
||||
this.currentStartedAt = this.now().toISOString();
|
||||
this.current = this.run()
|
||||
.then(async (report) => {
|
||||
if (report.status === "ok") await this.notify();
|
||||
return report;
|
||||
})
|
||||
.finally(() => {
|
||||
this.current = null;
|
||||
this.currentStartedAt = null;
|
||||
});
|
||||
return this.current;
|
||||
}
|
||||
|
||||
private async run(): Promise<RunReport> {
|
||||
const { store, provider, onError } = this.options;
|
||||
const id = randomUUID();
|
||||
const startedAt = this.currentStartedAt ?? this.now().toISOString();
|
||||
let candidates: unknown[];
|
||||
try {
|
||||
candidates = await provider.search();
|
||||
} catch (error) {
|
||||
onError?.(error);
|
||||
const report: RunReport = {
|
||||
id,
|
||||
startedAt,
|
||||
finishedAt: this.now().toISOString(),
|
||||
status: "error",
|
||||
found: 0,
|
||||
added: 0,
|
||||
rejected: 0,
|
||||
error: (error as Error).message || "Неизвестная ошибка",
|
||||
};
|
||||
await store.save({ ...(await store.load()), lastRun: report });
|
||||
return report;
|
||||
}
|
||||
const finishedAt = this.now().toISOString();
|
||||
// Настоящий поиск не оставляет в каталоге примеров (как у стажировок, FRTVL-47).
|
||||
const merged = mergeTrainings(await store.load(), candidates, id, finishedAt, provider.name !== "mock");
|
||||
const report: RunReport = {
|
||||
id,
|
||||
startedAt,
|
||||
finishedAt,
|
||||
status: "ok",
|
||||
found: merged.found,
|
||||
added: merged.added,
|
||||
rejected: merged.rejected,
|
||||
};
|
||||
await store.save({ ...merged.catalog, lastRun: report, lastSuccessfulRunId: id });
|
||||
return report;
|
||||
}
|
||||
|
||||
/** Отправляет в привязанный Телеграм программы, о которых ещё не сообщали. */
|
||||
async notify(): Promise<TrainingNotifyResult> {
|
||||
const { settings, telegram, store, onError } = this.options;
|
||||
if (!settings || !telegram) return { status: "not_linked" };
|
||||
const { chatId } = await settings.load();
|
||||
if (chatId === null) return { status: "not_linked" };
|
||||
const at = this.now().toISOString();
|
||||
const catalog = await store.load();
|
||||
const fresh = unnotifiedTrainings(catalog, at.slice(0, 10));
|
||||
if (fresh.length === 0) return { status: "nothing_new" };
|
||||
try {
|
||||
for (const text of formatTrainingMessages(fresh)) await telegram.sendMessage(chatId, text);
|
||||
} catch (error) {
|
||||
// Не отмечаем отправленными — уйдут после следующего поиска.
|
||||
onError?.(error);
|
||||
return { status: "error" };
|
||||
}
|
||||
const sent = new Set(fresh.map((item) => item.id));
|
||||
const latest = await store.load();
|
||||
await store.save({
|
||||
...latest,
|
||||
trainings: latest.trainings.map((item) => (sent.has(item.id) ? { ...item, notifiedAt: at } : item)),
|
||||
});
|
||||
return { status: "sent", sent: fresh.length };
|
||||
}
|
||||
}
|
||||
317
test/training.test.ts
Normal file
317
test/training.test.ts
Normal file
@ -0,0 +1,317 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { OwnerAuth } from "../src/auth/session.js";
|
||||
import {
|
||||
emptyTrainingCatalog,
|
||||
isEligibleTraining,
|
||||
mergeTrainings,
|
||||
parseRawTraining,
|
||||
type RawTraining,
|
||||
sortTrainings,
|
||||
type TrainingCatalog,
|
||||
} from "../src/domain/training.js";
|
||||
import { Notifier } from "../src/notify/notifier.js";
|
||||
import { emptySettings, type NotificationSettings, type SettingsStore } from "../src/notify/settingsStore.js";
|
||||
import { MockTelegramClient } from "../src/notify/telegram.js";
|
||||
import { ClaudeSearchProvider, buildRequest } from "../src/search/claudeSearchProvider.js";
|
||||
import { mockSearchProvider } from "../src/search/mockSearchProvider.js";
|
||||
import { mockTrainingProvider, mockTrainings } from "../src/search/mockTrainingProvider.js";
|
||||
import type { SearchProvider } from "../src/search/provider.js";
|
||||
import { SearchService } from "../src/search/searchService.js";
|
||||
import { trainingSearchConfig } from "../src/search/trainingSearchConfig.js";
|
||||
import { buildServer } from "../src/server.js";
|
||||
import { JsonFileStore, type Store } from "../src/store/catalogStore.js";
|
||||
import { formatTrainingMessages } from "../src/training/trainingMessage.js";
|
||||
import { TrainingSearch } from "../src/training/trainingSearch.js";
|
||||
import { MemoryStore } from "./helpers.js";
|
||||
|
||||
/** Сценарии training-search (FRTVL-44). */
|
||||
|
||||
const TODAY = "2026-11-25";
|
||||
const NOW = new Date(`${TODAY}T12:00:00.000Z`);
|
||||
|
||||
function training(overrides: Partial<RawTraining> = {}): RawTraining {
|
||||
return {
|
||||
title: "Школа клиентского сервиса",
|
||||
organization: "Фонд сервиса",
|
||||
country: "Казахстан",
|
||||
city: "Алматы",
|
||||
startDate: "2027-01-20",
|
||||
endDate: "2027-01-24",
|
||||
deadline: "2026-12-20",
|
||||
format: "in_person",
|
||||
participantCost: "host_paid",
|
||||
paymentConfirmed: true,
|
||||
coverage: { tuition: true, travel: false, accommodation: true, meals: false },
|
||||
paymentDetails: "Обучение и жильё оплачивает фонд",
|
||||
applyMethod: "Анкета на сайте",
|
||||
customerService: true,
|
||||
sourceUrl: "https://org.kz/school",
|
||||
rationale: "Подходит",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
class MemoryTrainingStore implements Store<TrainingCatalog> {
|
||||
constructor(public catalog: TrainingCatalog = emptyTrainingCatalog()) {}
|
||||
async load() {
|
||||
return structuredClone(this.catalog);
|
||||
}
|
||||
async save(value: TrainingCatalog) {
|
||||
this.catalog = structuredClone(value);
|
||||
}
|
||||
}
|
||||
|
||||
class MemorySettings implements SettingsStore {
|
||||
constructor(public value: NotificationSettings = emptySettings()) {}
|
||||
async load() {
|
||||
return structuredClone(this.value);
|
||||
}
|
||||
async save(value: NotificationSettings) {
|
||||
this.value = structuredClone(value);
|
||||
}
|
||||
}
|
||||
|
||||
const provider = (items: unknown[], name = "test"): SearchProvider => ({ name, search: async () => items });
|
||||
|
||||
describe("Карточка программы обучения", () => {
|
||||
it("Scenario: Полная карточка программы", () => {
|
||||
const { catalog, added } = mergeTrainings(emptyTrainingCatalog(), [training()], "run-1", NOW.toISOString());
|
||||
expect(added).toBe(1);
|
||||
expect(catalog.trainings[0]).toMatchObject({
|
||||
country: "Казахстан",
|
||||
city: "Алматы",
|
||||
startDate: "2027-01-20",
|
||||
endDate: "2027-01-24",
|
||||
deadline: "2026-12-20",
|
||||
coverage: { tuition: true, travel: false, accommodation: true, meals: false },
|
||||
applyMethod: "Анкета на сайте",
|
||||
sourceUrl: "https://org.kz/school",
|
||||
notifiedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("Scenario: Программа без ссылки на организатора отбрасывается", () => {
|
||||
const result = mergeTrainings(emptyTrainingCatalog(), [training({ sourceUrl: null })], "run-1", NOW.toISOString());
|
||||
expect(result.catalog.trainings).toHaveLength(0);
|
||||
expect(result.rejected).toBe(1);
|
||||
});
|
||||
|
||||
it("синонимы стран приводятся к названию из списка", () => {
|
||||
expect(parseRawTraining(training({ country: "Республика Беларусь" }))?.country).toBe("Беларусь");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Отбор программ", () => {
|
||||
const cases: Array<[string, Partial<RawTraining>]> = [
|
||||
["участие платное для участницы", { participantCost: "paid" }],
|
||||
["стоимость неизвестна", { participantCost: "unknown" }],
|
||||
["формат полностью онлайн", { format: "online" }],
|
||||
["оплата на странице организатора не подтверждена", { paymentConfirmed: false }],
|
||||
["страна «Грузия»", { country: "Грузия" }],
|
||||
["начало через 8 месяцев", { startDate: "2027-07-25", endDate: "2027-07-30", deadline: null }],
|
||||
["дедлайн уже прошёл", { deadline: "2026-11-01" }],
|
||||
["программа уже прошла", { startDate: "2026-11-01", endDate: "2026-11-05", deadline: null }],
|
||||
["не про клиентский сервис", { customerService: false }],
|
||||
["нет даты начала", { startDate: null }],
|
||||
];
|
||||
it.each(cases)("Scenario Outline: Неподходящая программа отбрасывается — %s", (_name, overrides) => {
|
||||
expect(isEligibleTraining(training(overrides), TODAY)).toBe(false);
|
||||
});
|
||||
|
||||
it("Scenario: Подходящая программа с оплатой от организатора", () => {
|
||||
const item = training({ country: "Армения", city: "Ереван", startDate: "2027-01-25", endDate: null });
|
||||
expect(isEligibleTraining(item, TODAY)).toBe(true);
|
||||
const { catalog } = mergeTrainings(emptyTrainingCatalog(), [item], "run-1", NOW.toISOString());
|
||||
expect(sortTrainings(catalog, TODAY)[0].soon).toBe(true);
|
||||
});
|
||||
|
||||
it("смешанный формат и бесплатное участие подходят; дальше 3 месяцев — не «скоро»", () => {
|
||||
const item = training({ format: "hybrid", participantCost: "free", startDate: "2027-04-10", endDate: null, deadline: null });
|
||||
expect(isEligibleTraining(item, TODAY)).toBe(true);
|
||||
const { catalog } = mergeTrainings(emptyTrainingCatalog(), [item], "run-1", NOW.toISOString());
|
||||
expect(sortTrainings(catalog, TODAY)[0].soon).toBe(false);
|
||||
});
|
||||
|
||||
it("мок: подходят ровно две программы из пяти", () => {
|
||||
const result = mergeTrainings(emptyTrainingCatalog(), mockTrainings(TODAY), "run-1", NOW.toISOString());
|
||||
expect(result).toMatchObject({ found: 2, added: 2, rejected: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Порядок программ", () => {
|
||||
it("Scenario: Ближайший дедлайн первым", () => {
|
||||
const items = [
|
||||
training({ title: "Январь", deadline: "2027-01-10", sourceUrl: "https://a.ru/1" }),
|
||||
training({ title: "Без дедлайна", deadline: null, sourceUrl: "https://a.ru/2" }),
|
||||
training({ title: "Декабрь", deadline: "2026-12-15", sourceUrl: "https://a.ru/3" }),
|
||||
];
|
||||
const { catalog } = mergeTrainings(emptyTrainingCatalog(), items, "run-1", NOW.toISOString());
|
||||
expect(sortTrainings(catalog, TODAY).map((item) => item.title)).toEqual(["Декабрь", "Январь", "Без дедлайна"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Уведомление о новой программе", () => {
|
||||
function setup(linked = true, items: unknown[] = [training()]) {
|
||||
const store = new MemoryTrainingStore();
|
||||
const settings = new MemorySettings({ ...emptySettings(), chatId: linked ? 555 : null });
|
||||
const telegram = new MockTelegramClient();
|
||||
const search = new TrainingSearch({ store, provider: provider(items), settings, telegram, now: () => NOW });
|
||||
return { store, settings, telegram, search };
|
||||
}
|
||||
|
||||
it("Scenario: Новая программа приходит в Телеграм", async () => {
|
||||
const { search, telegram, store } = setup();
|
||||
await search.start();
|
||||
expect(telegram.sent).toHaveLength(1);
|
||||
const text = telegram.sent[0].text;
|
||||
for (const part of ["Школа клиентского сервиса", "Алматы, Казахстан", "Дедлайн: 2026-12-20", "https://org.kz/school"]) {
|
||||
expect(text).toContain(part);
|
||||
}
|
||||
expect(store.catalog.trainings[0].notifiedAt).toBe(NOW.toISOString());
|
||||
});
|
||||
|
||||
it("Scenario: О программе не сообщают повторно", async () => {
|
||||
const { search, telegram } = setup();
|
||||
await search.start();
|
||||
await search.start();
|
||||
expect(telegram.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("Scenario: Телеграм не привязан", async () => {
|
||||
const { search, telegram, store } = setup(false);
|
||||
const report = await search.start();
|
||||
expect(report.status).toBe("ok");
|
||||
expect(store.catalog.trainings).toHaveLength(1);
|
||||
expect(telegram.sent).toHaveLength(0);
|
||||
expect(store.catalog.trainings[0].notifiedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("сбой отправки не отмечает программу отправленной", async () => {
|
||||
const { search, telegram, store } = setup();
|
||||
telegram.failSend = true;
|
||||
const report = await search.start();
|
||||
expect(report.status).toBe("ok");
|
||||
expect(store.catalog.trainings[0].notifiedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("ошибка поиска сохраняется в отчёте", async () => {
|
||||
const store = new MemoryTrainingStore();
|
||||
const search = new TrainingSearch({ store, provider: mockTrainingProvider({ fail: true }), now: () => NOW });
|
||||
const report = await search.start();
|
||||
expect(report.status).toBe("error");
|
||||
expect(store.catalog.lastRun?.status).toBe("error");
|
||||
});
|
||||
|
||||
it("сообщение со многими программами делится по лимиту", () => {
|
||||
const { catalog } = mergeTrainings(
|
||||
emptyTrainingCatalog(),
|
||||
Array.from({ length: 40 }, (_, i) => training({ sourceUrl: `https://a.ru/${i}`, title: "Программа ".repeat(20) })),
|
||||
"run-1",
|
||||
NOW.toISOString(),
|
||||
);
|
||||
const messages = formatTrainingMessages(catalog.trainings);
|
||||
expect(messages.length).toBeGreaterThan(1);
|
||||
for (const m of messages) expect(m.length).toBeLessThanOrEqual(4000);
|
||||
});
|
||||
|
||||
it("ежедневный поиск ищет и программы", async () => {
|
||||
const trainingStore = new MemoryTrainingStore();
|
||||
const settings = new MemorySettings({ ...emptySettings(), chatId: 555, enabled: true });
|
||||
const telegram = new MockTelegramClient();
|
||||
const trainings = new TrainingSearch({ store: trainingStore, provider: provider([training()]), settings, telegram, now: () => NOW });
|
||||
const catalog = new MemoryStore();
|
||||
const search = new SearchService({ store: catalog, provider: provider([]), now: () => NOW });
|
||||
const notifier = new Notifier({ settings, catalog, search, telegram, trainings, now: () => NOW });
|
||||
expect(await notifier.tick()).toBe(true);
|
||||
expect(trainingStore.catalog.trainings).toHaveLength(1);
|
||||
expect(telegram.sent.some((m) => m.text.includes("Новое обучение"))).toBe(true);
|
||||
expect(settings.value.lastRun?.status).toBe("nothing_new");
|
||||
});
|
||||
|
||||
it("настоящий поиск убирает примеры из каталога", async () => {
|
||||
const store = new MemoryTrainingStore();
|
||||
await new TrainingSearch({ store, provider: provider(mockTrainings(TODAY), "mock"), now: () => NOW }).start();
|
||||
expect(store.catalog.trainings).toHaveLength(2);
|
||||
await new TrainingSearch({ store, provider: provider([training()], "claude"), now: () => NOW }).start();
|
||||
expect(store.catalog.trainings.map((item) => item.sourceUrl)).toEqual(["https://org.kz/school"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Поиск программ моделью", () => {
|
||||
it("запрос использует инструмент submit_trainings и промпт про СНГ", () => {
|
||||
const request = buildRequest([{ role: "user", content: "x" }], trainingSearchConfig);
|
||||
expect(request.tools?.map((tool) => tool.name)).toContain("submit_trainings");
|
||||
expect(String(request.system)).toContain("Казахстан");
|
||||
});
|
||||
|
||||
it("результат берётся из поля trainings", async () => {
|
||||
const streamer = {
|
||||
stream: () => ({
|
||||
finalMessage: async () =>
|
||||
({
|
||||
stop_reason: "tool_use",
|
||||
content: [{ type: "tool_use", id: "t1", name: "submit_trainings", input: { trainings: [training()] } }],
|
||||
}) as never,
|
||||
}),
|
||||
};
|
||||
expect(await new ClaudeSearchProvider(streamer, trainingSearchConfig).search()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTTP API программ", () => {
|
||||
let dir: string | null = null;
|
||||
afterEach(async () => {
|
||||
if (dir) await rm(dir, { recursive: true, force: true });
|
||||
dir = null;
|
||||
});
|
||||
|
||||
async function setup() {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "trainings-"));
|
||||
const store = new MemoryStore();
|
||||
const search = new SearchService({ store, provider: mockSearchProvider() });
|
||||
const trainingStore = new JsonFileStore(dir, "trainings.json", emptyTrainingCatalog);
|
||||
const trainingSearch = new TrainingSearch({ store: trainingStore, provider: mockTrainingProvider() });
|
||||
const app = await buildServer({
|
||||
store,
|
||||
search,
|
||||
auth: new OwnerAuth("pw"),
|
||||
providerName: "mock",
|
||||
trainings: { search: trainingSearch, store: trainingStore, providerName: "mock" },
|
||||
});
|
||||
const login = await app.inject({ method: "POST", url: "/api/session", payload: { password: "pw" } });
|
||||
const cookie = String(login.headers["set-cookie"]).split(";")[0];
|
||||
return { app, search, trainingSearch, cookie };
|
||||
}
|
||||
|
||||
it("поиск программ без входа → 401", async () => {
|
||||
const { app, trainingSearch } = await setup();
|
||||
const response = await app.inject({ method: "POST", url: "/api/search?kind=trainings" });
|
||||
expect(response.statusCode).toBe(401);
|
||||
expect(trainingSearch.running).toBe(false);
|
||||
});
|
||||
|
||||
it("поиск программ после входа: запускается только он, результат в /api/trainings", async () => {
|
||||
const { app, search, trainingSearch, cookie } = await setup();
|
||||
const response = await app.inject({ method: "POST", url: "/api/search?kind=trainings", headers: { cookie } });
|
||||
expect(response.statusCode).toBe(202);
|
||||
expect(search.running).toBe(false);
|
||||
const status = await app.inject({ method: "GET", url: "/api/search/status?kind=trainings" });
|
||||
expect(status.json()).toMatchObject({ kind: "trainings", trainingsAvailable: true });
|
||||
while (trainingSearch.running) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
const list = (await app.inject({ method: "GET", url: "/api/trainings" })).json();
|
||||
expect(list.trainings).toHaveLength(2);
|
||||
expect(list.lastRun).toMatchObject({ status: "ok", found: 2 });
|
||||
});
|
||||
|
||||
it("поиск стажировок по-прежнему без вида", async () => {
|
||||
const { app, search, trainingSearch, cookie } = await setup();
|
||||
await app.inject({ method: "POST", url: "/api/search", headers: { cookie } });
|
||||
expect(trainingSearch.running).toBe(false);
|
||||
while (search.running) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
const status = (await app.inject({ method: "GET", url: "/api/search/status" })).json();
|
||||
expect(status).toMatchObject({ kind: "internships", lastRun: { status: "ok" } });
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user