All checks were successful
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
228 lines
9.0 KiB
TypeScript
228 lines
9.0 KiB
TypeScript
/** Требование к языку работы. */
|
||
export type LanguageRequirement = "russian" | "not_required" | "required";
|
||
|
||
/** Покрытие расходов участника. */
|
||
export type Funding = "full" | "partial" | "unknown";
|
||
|
||
/** Уверенность агента в том, что условия найдены и поняты верно. */
|
||
export type Confidence = "high" | "medium" | "low";
|
||
|
||
/** Стажировка в том виде, в каком её вернул провайдер поиска (ещё не отобрана). */
|
||
export interface RawInternship {
|
||
title: string;
|
||
organization: string;
|
||
/** Страна по-русски, например «Швейцария». */
|
||
country: string;
|
||
city: string | null;
|
||
/** Сфера: отель, ресепшн, поддержка клиентов… */
|
||
field: string;
|
||
funding: Funding;
|
||
/** Что именно оплачивается, по-русски. */
|
||
coveredExpenses: string;
|
||
/** Плата за участие; null — участие бесплатное. */
|
||
participationFee: string | null;
|
||
language: LanguageRequirement;
|
||
/** Пояснение к требованию по языку, по-русски. */
|
||
languageDetails: string;
|
||
customerService: boolean;
|
||
/** Смежная сфера (поддержка, колл-центр, гостиничный сервис), а не чисто клиентский сервис. */
|
||
adjacent: boolean;
|
||
confidence: Confidence;
|
||
deadline: string | null;
|
||
sourceUrl: string | null;
|
||
/** Почему подходит — по-русски. */
|
||
rationale: string;
|
||
}
|
||
|
||
/** Карточка каталога. */
|
||
export interface Internship extends Omit<RawInternship, "sourceUrl"> {
|
||
/** Нормализованная ссылка — ключ дедупликации. */
|
||
id: string;
|
||
sourceUrl: string;
|
||
firstSeenAt: string;
|
||
checkedAt: string;
|
||
/** Запуск поиска, в котором карточка появилась. */
|
||
addedInRun: string;
|
||
/**
|
||
* Когда карточка показана пользователю (в уведомлении или ручном запуске); null — ещё нет.
|
||
* Нет поля (каталог первой версии) — считается показанной.
|
||
*/
|
||
shownAt?: string | null;
|
||
}
|
||
|
||
export type RunTrigger = "manual" | "scheduled";
|
||
|
||
export interface RunReport {
|
||
id: string;
|
||
startedAt: string;
|
||
finishedAt: string;
|
||
status: "ok" | "error";
|
||
found: number;
|
||
added: number;
|
||
rejected: number;
|
||
error?: string;
|
||
}
|
||
|
||
export interface Catalog {
|
||
internships: Internship[];
|
||
lastRun: RunReport | null;
|
||
/** Последний успешный запуск — его карточки помечаются «новое». */
|
||
lastSuccessfulRunId: string | null;
|
||
}
|
||
|
||
export const emptyCatalog = (): Catalog => ({ internships: [], lastRun: null, lastSuccessfulRunId: null });
|
||
|
||
const LANGUAGES: readonly LanguageRequirement[] = ["russian", "not_required", "required"];
|
||
const CONFIDENCES: readonly Confidence[] = ["high", "medium", "low"];
|
||
const FUNDINGS: readonly Funding[] = ["full", "partial", "unknown"];
|
||
|
||
const isStr = (v: unknown): v is string => typeof v === "string";
|
||
const optStr = (v: unknown): string | null => (isStr(v) && v.trim() !== "" ? v.trim() : null);
|
||
|
||
/**
|
||
* Приводит недоверенный объект (ответ модели или мока) к RawInternship.
|
||
* Возвращает null, если не хватает обязательных полей.
|
||
*/
|
||
export function parseRawInternship(value: unknown): RawInternship | 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 (!LANGUAGES.includes(v.language as LanguageRequirement)) return null;
|
||
if (!FUNDINGS.includes(v.funding as Funding)) return null;
|
||
if (typeof v.customerService !== "boolean") return null;
|
||
const fee = optStr(v.participationFee);
|
||
return {
|
||
title,
|
||
organization,
|
||
country,
|
||
city: optStr(v.city),
|
||
field: optStr(v.field) ?? "",
|
||
funding: v.funding as Funding,
|
||
coveredExpenses: optStr(v.coveredExpenses) ?? "",
|
||
participationFee: fee && !/^(none|нет|0|free|бесплатно)$/i.test(fee) ? fee : null,
|
||
language: v.language as LanguageRequirement,
|
||
languageDetails: optStr(v.languageDetails) ?? "",
|
||
customerService: v.customerService,
|
||
adjacent: v.adjacent === true,
|
||
confidence: CONFIDENCES.includes(v.confidence as Confidence) ? (v.confidence as Confidence) : "low",
|
||
deadline: optStr(v.deadline),
|
||
sourceUrl: optStr(v.sourceUrl),
|
||
rationale: optStr(v.rationale) ?? "",
|
||
};
|
||
}
|
||
|
||
/** Ссылка http(s), иначе null. */
|
||
function validUrl(raw: string | null): URL | null {
|
||
if (!raw) return null;
|
||
try {
|
||
const url = new URL(raw);
|
||
return url.protocol === "http:" || url.protocol === "https:" ? url : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Нормализует ссылку для дедупликации: без схемы, `www.`, завершающего `/`, якоря и UTM-параметров.
|
||
* Возвращает null для невалидной ссылки.
|
||
*/
|
||
export function normalizeUrl(raw: string | null): string | null {
|
||
const url = validUrl(raw);
|
||
if (!url) return null;
|
||
const params = [...url.searchParams.entries()]
|
||
.filter(([key]) => !key.toLowerCase().startsWith("utm_"))
|
||
.sort(([a], [b]) => a.localeCompare(b));
|
||
const query = params.length ? "?" + new URLSearchParams(params).toString() : "";
|
||
const host = url.hostname.toLowerCase().replace(/^www\./, "");
|
||
const path = url.pathname.replace(/\/+$/, "");
|
||
return `${host}${url.port ? ":" + url.port : ""}${path}${query}`;
|
||
}
|
||
|
||
/** Критерии отбора из спеки internship-search. */
|
||
export function isEligible(item: RawInternship): boolean {
|
||
return (
|
||
normalizeUrl(item.sourceUrl) !== null &&
|
||
item.participationFee === null &&
|
||
item.funding === "full" &&
|
||
(item.language === "russian" || item.language === "not_required") &&
|
||
item.customerService
|
||
);
|
||
}
|
||
|
||
export interface MergeResult {
|
||
catalog: Catalog;
|
||
found: number;
|
||
added: number;
|
||
rejected: number;
|
||
}
|
||
|
||
/**
|
||
* Отбирает подходящие стажировки и вливает их в каталог. Известные (по нормализованной ссылке)
|
||
* обновляют данные и дату проверки, но сохраняют дату и запуск появления.
|
||
*/
|
||
export function mergeIntoCatalog(
|
||
catalog: Catalog,
|
||
candidates: readonly unknown[],
|
||
runId: string,
|
||
now: string,
|
||
trigger: RunTrigger = "manual",
|
||
): MergeResult {
|
||
const byId = new Map(catalog.internships.map((item) => [item.id, item]));
|
||
const seenThisRun = new Set<string>();
|
||
let found = 0;
|
||
let added = 0;
|
||
let rejected = 0;
|
||
|
||
for (const candidate of candidates) {
|
||
const raw = parseRawInternship(candidate);
|
||
const id = raw ? normalizeUrl(raw.sourceUrl) : null;
|
||
if (!raw || !id || !isEligible(raw)) {
|
||
rejected++;
|
||
continue;
|
||
}
|
||
if (seenThisRun.has(id)) continue;
|
||
seenThisRun.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,
|
||
// Ручной запуск показывает список целиком; запуск по расписанию сообщает о новом через уведомление.
|
||
shownAt: trigger === "manual" ? (existing?.shownAt ?? now) : existing ? existing.shownAt : null,
|
||
});
|
||
}
|
||
|
||
return {
|
||
catalog: { ...catalog, internships: [...byId.values()] },
|
||
found,
|
||
added,
|
||
rejected,
|
||
};
|
||
}
|
||
|
||
/** Карточки для показа: новые первыми, затем по дате появления (свежие выше). */
|
||
export function sortForDisplay(catalog: Catalog): Array<Internship & { isNew: boolean }> {
|
||
return catalog.internships
|
||
.map((item) => ({ ...item, isNew: item.addedInRun === catalog.lastSuccessfulRunId }))
|
||
.sort((a, b) => Number(b.isNew) - Number(a.isNew) || b.firstSeenAt.localeCompare(a.firstSeenAt));
|
||
}
|
||
|
||
/** Срок подачи уже прошёл (формат YYYY-MM-DD); неизвестный или не разобранный срок — не прошёл. */
|
||
export function isExpired(deadline: string | null | undefined, today: string): boolean {
|
||
const match = deadline?.match(/^\d{4}-\d{2}-\d{2}/);
|
||
return match !== null && match !== undefined && match[0] < today;
|
||
}
|
||
|
||
/** Карточки, о которых ещё не сообщали и подача на которые не закрыта. */
|
||
export function unseenActive(catalog: Catalog, today: string): Internship[] {
|
||
return catalog.internships.filter((item) => item.shownAt === null && !isExpired(item.deadline, today));
|
||
}
|