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 { 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 = { Россия: ["россия", "российская федерация", "рф"], Беларусь: ["беларусь", "белоруссия", "республика беларусь"], Казахстан: ["казахстан", "республика казахстан"], Кыргызстан: ["кыргызстан", "киргизия", "кыргызская республика"], Узбекистан: ["узбекистан", "республика узбекистан"], Таджикистан: ["таджикистан", "республика таджикистан"], Армения: ["армения", "республика армения"], Азербайджан: ["азербайджан", "азербайджанская республика"], }; 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; 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; 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(); 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)); }