Files
ismc-hamchin/apps/web/app/planner.ts
Meghdad d14b2b98c4
CI / python (push) Canceled after 0s
CI / web (push) Canceled after 0s
init
2026-09-12 22:59:58 +03:30

307 lines
13 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export type Semester = 'نیمسال اول' | 'نیمسال دوم' | 'نامشخص';
export type Meeting = {
day: string;
start: number;
end: number;
label: string;
approximate?: boolean;
};
export type ClassOption = {
id: string;
lesson: string;
teacher: string;
semester: Semester;
hours: number;
capacity: number;
availability: string;
location: string;
classTitle: string;
scope: string;
meetings: Meeting[];
};
export type LockRule = { id: string; lesson: string; teacher: string };
export type Priority = 'کم' | 'متوسط' | 'زیاد';
export type PlannerWeights = { compact: Priority; fewerDays: Priority; location: Priority; capacity: Priority };
export type PlanMetrics = {
hours: number;
gapMinutes: number;
activeDays: number;
locationSwitches: number;
minCapacity: number;
approximateTimes: number;
};
export type ScheduleSuggestion = {
id: string;
name: string;
note: string;
score: number;
classes: ClassOption[];
metrics: PlanMetrics;
};
const persianDigits = '۰۱۲۳۴۵۶۷۸۹';
const arabicDigits = '٠١٢٣٤٥٦٧٨٩';
export const weekDays = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه'];
function scalarText(value: unknown): string {
if (value == null) return '';
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'bigint') return value.toString();
if (typeof value === 'boolean') return value ? 'true' : 'false';
return '';
}
export function toEnglishDigits(value: unknown): string {
return scalarText(value)
.replace(/[۰-۹]/g, (digit) => String(persianDigits.indexOf(digit)))
.replace(/[٠-٩]/g, (digit) => String(arabicDigits.indexOf(digit)));
}
const normalizeText = (value: unknown) => scalarText(value).replace(/\s+/g, ' ').trim();
function parseClock(value: string): { start: number; end: number; label: string; approximate?: boolean } | null {
const normalized = toEnglishDigits(value);
const range = normalized.match(/(\d{1,2}):(\d{2})\s*[-–]\s*(\d{1,2}):(\d{2})/);
if (range) {
const start = Number(range[1]) * 60 + Number(range[2]);
const end = Number(range[3]) * 60 + Number(range[4]);
return { start, end, label: value };
}
if (normalized.includes('بعد از نماز عصر')) {
return { start: 16 * 60, end: 17 * 60, label: 'بعد از نماز عصر', approximate: true };
}
return null;
}
function parseSemester(value: unknown): Semester {
const text = normalizeText(value);
if (/نیمسال\s*اول/.test(text)) return 'نیمسال اول';
if (/نیمسال\s*دوم/.test(text)) return 'نیمسال دوم';
return 'نامشخص';
}
function field(raw: Record<string, unknown>, snake: string, camel: string): unknown {
return raw[snake] ?? raw[camel];
}
export function normalizeExport(payload: unknown): ClassOption[] {
const root = payload as { classes?: unknown };
const rows = Array.isArray(payload) ? payload : root && Array.isArray(root.classes) ? root.classes : [];
return rows.map((entry, index) => {
const raw = entry as Record<string, unknown>;
const lesson = normalizeText(field(raw, 'lesson', 'lesson'));
const classTitle = normalizeText(field(raw, 'class_title', 'classTitle'));
const semester = parseSemester(field(raw, 'semester', 'semester') || classTitle);
const scheduleRaw = normalizeText(field(raw, 'schedule_raw', 'scheduleRaw'));
const rawDays = field(raw, 'days', 'days');
const days = Array.isArray(rawDays) ? rawDays.map(normalizeText).filter(Boolean) : [];
const timeText = normalizeText(field(raw, 'time', 'time')) || scheduleRaw;
const clock = parseClock(timeText);
const meetings = clock ? days.map((day) => ({ day, ...clock })) : [];
return {
id: normalizeText(field(raw, 'id', 'id')) || `imported-${index}`,
lesson,
teacher: normalizeText(field(raw, 'teacher', 'teacher')) || 'بدون استاد',
semester,
hours: Number(toEnglishDigits(field(raw, 'hours', 'hours')).replace(/[^\d.]/g, '')) || 0,
capacity: Number(toEnglishDigits(field(raw, 'remaining_capacity', 'remainingCapacity')).replace(/[^\d-]/g, '')) || 0,
availability: normalizeText(field(raw, 'availability', 'availability')),
location: normalizeText(field(raw, 'location', 'location')),
classTitle,
scope: normalizeText(field(raw, 'scope', 'scope')),
meetings,
};
}).filter((item) => item.lesson && item.hours > 0);
}
function conflicts(classes: ClassOption[], candidate: ClassOption): boolean {
return candidate.meetings.some((meeting) => classes.some((chosen) =>
chosen.semester === candidate.semester && chosen.meetings.some((other) =>
other.day === meeting.day && meeting.start < other.end && other.start < meeting.end,
),
));
}
export function calculateMetrics(classes: ClassOption[]): PlanMetrics {
const meetings = classes.flatMap((item) => item.meetings.map((meeting) => ({ ...meeting, semester: item.semester, location: item.location })));
let gapMinutes = 0;
let locationSwitches = 0;
const dayGroups = new Map<string, typeof meetings>();
meetings.forEach((meeting) => {
const key = `${meeting.semester}-${meeting.day}`;
dayGroups.set(key, [...(dayGroups.get(key) ?? []), meeting]);
});
dayGroups.forEach((items) => {
items.sort((a, b) => a.start - b.start);
for (let index = 1; index < items.length; index += 1) {
gapMinutes += Math.max(0, items[index].start - items[index - 1].end);
if (items[index].location && items[index - 1].location && items[index].location !== items[index - 1].location) locationSwitches += 1;
}
});
const capacities = classes.filter((item) => item.capacity >= 0).map((item) => item.capacity);
return {
hours: classes.reduce((sum, item) => sum + item.hours, 0),
gapMinutes,
activeDays: new Set(meetings.map((meeting) => meeting.day)).size,
locationSwitches,
minCapacity: capacities.length ? Math.min(...capacities) : 0,
approximateTimes: meetings.filter((meeting) => meeting.approximate).length,
};
}
const priorityValue: Record<Priority, number> = { کم: .55, متوسط: 1, زیاد: 1.75 };
function scorePlan(metrics: PlanMetrics, weights: PlannerWeights, range: number[], profile: string): number {
const center = (range[0] + range[1]) / 2;
const hourPenalty = Math.abs(metrics.hours - center) / 15;
const profileWeights = {
compact: profile === 'compact' ? 2.4 : priorityValue[weights.compact],
days: profile === 'days' ? 2.8 : priorityValue[weights.fewerDays],
capacity: profile === 'safe' ? 2.6 : priorityValue[weights.capacity],
location: priorityValue[weights.location],
};
const penalty = hourPenalty +
(metrics.gapMinutes / 60) * 3.3 * profileWeights.compact +
Math.max(0, metrics.activeDays - 4) * 3.8 * profileWeights.days +
metrics.locationSwitches * 1.35 * profileWeights.location +
Math.max(0, 12 - metrics.minCapacity) * .55 * profileWeights.capacity +
metrics.approximateTimes * 1.5;
return Math.max(45, Math.min(99, Math.round(99 - penalty)));
}
type BeamState = { classes: ClassOption[]; hours: number; minCapacity: number; gapMinutes: number; days: string[] };
const MAX_CHOICES_PER_LESSON = 32;
const MAX_BEAM_STATES = 720;
function behaviorKey(option: ClassOption): string {
const meetings = option.meetings
.map((meeting) => `${meeting.day}:${meeting.start}-${meeting.end}`)
.sort()
.join('|');
return `${option.semester}::${option.hours}::${option.location}::${meetings}`;
}
/** Keep useful schedule/location diversity without letting one lesson create hundreds of equivalent branches. */
function representativeChoices(choices: ClassOption[]): ClassOption[] {
if (choices.length <= MAX_CHOICES_PER_LESSON) return choices;
const buckets = new Map<string, ClassOption[]>();
for (const choice of choices) {
const key = behaviorKey(choice);
buckets.set(key, [...(buckets.get(key) ?? []), choice]);
}
let queues = [...buckets.values()]
.map((items) => items.sort((a, b) => b.capacity - a.capacity))
.sort((a, b) => b[0].capacity - a[0].capacity);
const selected: ClassOption[] = [];
while (selected.length < MAX_CHOICES_PER_LESSON && queues.length) {
const remaining: ClassOption[][] = [];
for (const queue of queues) {
const choice = queue.shift();
if (choice) selected.push(choice);
if (queue.length) remaining.push(queue);
if (selected.length === MAX_CHOICES_PER_LESSON) break;
}
queues = remaining;
}
return selected;
}
function beamRank(state: BeamState, range: number[]): number {
const distance = state.hours < range[0] ? range[0] - state.hours : state.hours - range[1];
return Math.max(0, distance) * 100 + state.gapMinutes * .2 + state.days.length * 10 - Math.min(50, state.minCapacity);
}
function addedGap(classes: ClassOption[], candidate: ClassOption): number {
let delta = 0;
for (const meeting of candidate.meetings) {
const adjacent = classes
.filter((item) => item.semester === candidate.semester)
.flatMap((item) => item.meetings)
.filter((item) => item.day === meeting.day);
const previous = adjacent.filter((item) => item.end <= meeting.start).sort((a, b) => b.end - a.end)[0];
const next = adjacent.filter((item) => item.start >= meeting.end).sort((a, b) => a.start - b.start)[0];
if (previous && next) delta += meeting.start - previous.end + next.start - meeting.end - (next.start - previous.end);
else if (previous) delta += meeting.start - previous.end;
else if (next) delta += next.start - meeting.end;
}
return delta;
}
export function buildSuggestions(
options: ClassOption[],
locks: LockRule[],
range: number[],
weights: PlannerWeights,
includeFull = false,
): ScheduleSuggestion[] {
const usable = options.filter((item) => includeFull || item.capacity > 0);
const byLesson = new Map<string, ClassOption[]>();
usable.forEach((item) => byLesson.set(item.lesson, [...(byLesson.get(item.lesson) ?? []), item]));
const groups = [...byLesson.entries()]
.map(([lesson, choices]) => {
const lock = locks.find((rule) => rule.lesson === lesson);
const allowed = lock ? choices.filter((item) => item.teacher === lock.teacher) : choices;
return { lesson, lock, choices: representativeChoices(allowed) };
})
.filter((group) => group.choices.length)
.sort((a, b) => Number(Boolean(b.lock)) - Number(Boolean(a.lock)) || a.choices.length - b.choices.length);
let beam: BeamState[] = [{ classes: [], hours: 0, minCapacity: Number.POSITIVE_INFINITY, gapMinutes: 0, days: [] }];
for (const { lock, choices } of groups) {
const variants: (ClassOption | null)[] = lock ? choices : [null, ...choices];
const next: BeamState[] = [];
for (const state of beam) {
for (const choice of variants) {
if (!choice) { next.push(state); continue; }
if (state.hours + choice.hours > range[1]) continue;
if (conflicts(state.classes, choice)) continue;
next.push({
classes: [...state.classes, choice],
hours: state.hours + choice.hours,
minCapacity: Math.min(state.minCapacity, choice.capacity),
gapMinutes: state.gapMinutes + addedGap(state.classes, choice),
days: [...new Set([...state.days, ...choice.meetings.map((meeting) => meeting.day)])],
});
}
}
beam = next
.sort((a, b) => beamRank(a, range) - beamRank(b, range))
.slice(0, MAX_BEAM_STATES);
}
const valid = beam.filter((state) => state.hours >= range[0] && state.hours <= range[1] && locks.every((rule) =>
state.classes.some((item) => item.lesson === rule.lesson && item.teacher === rule.teacher),
));
if (!valid.length) return [];
const rankedStates = valid.map((state) => ({ state, metrics: calculateMetrics(state.classes) }));
const profiles = [
{ id: 'balanced', name: 'متعادل', note: 'تعادل خوب بین فشردگی، ظرفیت و تعداد روزها' },
{ id: 'compact', name: 'فشرده‌ترین', note: 'کمترین فاصلهٔ خالی بین کلاس‌های هر روز' },
{ id: 'days', name: 'روزهای کمتر', note: 'کمترین تعداد روز حضور در طول هفته' },
{ id: 'safe', name: 'ظرفیت مطمئن', note: 'ظرفیت باقی‌ماندهٔ بیشتر و ریسک انتخاب کمتر' },
];
const used = new Set<string>();
const suggestions: ScheduleSuggestion[] = [];
for (const profile of profiles) {
const ranked = [...rankedStates]
.sort((a, b) => scorePlan(b.metrics, weights, range, profile.id) - scorePlan(a.metrics, weights, range, profile.id));
const winner = ranked.find(({ state }) => !used.has(state.classes.map((item) => item.id).sort().join('|'))) ?? ranked[0];
const key = winner.state.classes.map((item) => item.id).sort().join('|');
used.add(key);
suggestions.push({
...profile,
score: scorePlan(winner.metrics, weights, range, profile.id),
classes: winner.state.classes,
metrics: winner.metrics,
});
}
return suggestions;
}