This commit is contained in:
49 files changed
+13268
No files matched your search
@@ -0,0 +1,277 @@
|
||||
@import 'tailwindcss';
|
||||
@import 'tw-animate-css';
|
||||
@import 'shadcn/tailwind.css';
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--radius-sm: calc(var(--radius) * .65);
|
||||
--radius-md: calc(var(--radius) * .82);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.35);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: #f4f7f9;
|
||||
--foreground: #122530;
|
||||
--card: #ffffff;
|
||||
--card-foreground: #122530;
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: #122530;
|
||||
--primary: #0b6673;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #e7f0f1;
|
||||
--secondary-foreground: #174a52;
|
||||
--muted: #edf2f4;
|
||||
--muted-foreground: #647780;
|
||||
--accent: #e2f2ef;
|
||||
--accent-foreground: #0d5a63;
|
||||
--destructive: #c64145;
|
||||
--border: #dce5e8;
|
||||
--input: #cfdadd;
|
||||
--ring: #2c929a;
|
||||
--radius: .8rem;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* { @apply border-border outline-ring/50; }
|
||||
body { @apply bg-background text-foreground; }
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { min-width: 320px; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: Vazirmatn, Tahoma, Arial, sans-serif;
|
||||
font-size: 16px;
|
||||
background: radial-gradient(circle at 82% 0%, rgba(32, 151, 150, .08), transparent 28rem), #f4f7f9;
|
||||
}
|
||||
button, input { font: inherit; }
|
||||
.spin { animation:spin .8s linear infinite; }
|
||||
@keyframes spin { to { transform:rotate(360deg); } }
|
||||
|
||||
.topbar { height:76px; display:flex; align-items:center; gap:12px; padding:0 24px; border-bottom:1px solid var(--border); background:rgba(255,255,255,.92); backdrop-filter:blur(18px); position:sticky; top:0; z-index:40; }
|
||||
.brand-mark { width:42px; height:42px; border-radius:13px; display:grid; place-items:center; color:#fff; background:linear-gradient(145deg,#0b6673,#119a91); box-shadow:0 8px 24px rgba(11,102,115,.22); }
|
||||
.brand-mark svg { width:22px; }
|
||||
.brand-copy { display:flex; flex-direction:column; line-height:1.25; }
|
||||
.brand-copy strong { font-size:1.1rem; letter-spacing:-.02em; }
|
||||
.brand-copy span { color:var(--muted-foreground); font-size:.78rem; margin-top:4px; }
|
||||
.topbar-status { margin-inline-start:auto; font-size:.85rem; color:#536a73; display:flex; align-items:center; gap:8px; background:#f4f7f7; border:1px solid #e4ebed; padding:8px 12px; border-radius:999px; }
|
||||
.status-dot { width:8px; height:8px; border-radius:50%; background:#24a77c; box-shadow:0 0 0 4px rgba(36,167,124,.12); }
|
||||
.status-dot.is-empty { background:#9aabb1; box-shadow:0 0 0 4px rgba(115,137,145,.12); }
|
||||
.data-button { height:40px; padding-inline:14px; }
|
||||
|
||||
.empty-start { min-height:calc(100vh - 76px); display:grid; place-items:center; padding:32px 20px; }
|
||||
.empty-start-card { width:min(590px,100%); display:flex; flex-direction:column; align-items:center; text-align:center; padding:52px 46px 42px; border:1px dashed #afc8cd; border-radius:28px; background:rgba(255,255,255,.9); box-shadow:0 24px 70px rgba(29,67,77,.08); }
|
||||
.empty-start-icon { width:70px; height:70px; display:grid; place-items:center; margin-bottom:18px; border-radius:22px; color:#fff; background:linear-gradient(145deg,#0b6673,#15978d); box-shadow:0 14px 34px rgba(11,102,115,.24); }
|
||||
.empty-start-icon svg { width:31px; height:31px; }
|
||||
.empty-start-card h1 { margin:6px 0 10px; font-size:1.7rem; letter-spacing:-.035em; }
|
||||
.empty-start-card > p:not(.eyebrow) { max-width:470px; margin:0 0 24px; color:#667b83; font-size:.9rem; line-height:1.95; }
|
||||
.empty-start-card > button { min-width:190px; height:46px; background:linear-gradient(135deg,#0b6673,#128f87); box-shadow:0 10px 25px rgba(11,102,115,.18); }
|
||||
.privacy-note { width:100%; display:grid; grid-template-columns:36px 1fr; align-items:center; gap:11px; margin-top:28px; padding:13px 15px; text-align:right; border:1px solid #d9ece8; border-radius:14px; background:#eef8f6; }
|
||||
.privacy-note > svg { width:34px; height:34px; padding:8px; border-radius:10px; color:#138374; background:#fff; }
|
||||
.privacy-note div { display:flex; flex-direction:column; gap:3px; }
|
||||
.privacy-note strong { font-size:.79rem; }
|
||||
.privacy-note span { color:#6e837f; font-size:.7rem; }
|
||||
|
||||
.workspace-grid { max-width:1800px; margin:0 auto; padding:20px; display:grid; grid-template-columns:300px minmax(720px,1fr) 280px; gap:16px; align-items:start; }
|
||||
.control-panel,.schedule-panel,.suggestions-panel { background:rgba(255,255,255,.88); border:1px solid var(--border); box-shadow:0 16px 45px rgba(38,64,74,.05); }
|
||||
.control-panel,.suggestions-panel { border-radius:20px; padding:18px; position:sticky; top:96px; }
|
||||
.schedule-panel { border-radius:22px; padding:22px; min-width:0; }
|
||||
.panel-heading,.suggestions-head,.schedule-head,.section-title,.eyebrow-row,.calendar-title-row { display:flex; align-items:center; justify-content:space-between; gap:12px; }
|
||||
.panel-heading h1,.suggestions-head h2,.schedule-head h2 { margin:3px 0 0; font-size:1.12rem; letter-spacing:-.025em; }
|
||||
.eyebrow { margin:0; color:#768991; font-size:.74rem; font-weight:700; }
|
||||
.source-card { margin-top:18px; display:grid; grid-template-columns:38px 1fr 18px; align-items:center; gap:10px; padding:12px; border-radius:14px; background:#eef8f6; border:1px solid #d9eeea; }
|
||||
.source-icon { width:36px;height:36px;border-radius:11px;background:#fff;display:grid;place-items:center;color:#148377;box-shadow:0 4px 12px rgba(15,92,85,.08); }
|
||||
.source-icon svg,.source-check { width:17px; }
|
||||
.source-card div:nth-child(2) { display:flex; flex-direction:column; gap:3px; }
|
||||
.source-card strong { font-size:.83rem; }
|
||||
.source-card span { font-size:.7rem; color:#68817d; }
|
||||
.source-check { color:#1b9b73; }
|
||||
.rule-section { margin-top:22px; padding-top:20px; border-top:1px solid #e8eef0; }
|
||||
.section-title { margin-bottom:11px; font-size:.83rem; font-weight:700; }
|
||||
.section-title svg { width:16px; color:#6d8189; }
|
||||
.section-title > strong { color:#0b6673; font-size:.76rem; }
|
||||
.lock-card { display:grid; grid-template-columns:34px 1fr 20px; gap:9px; align-items:center; padding:10px; border:1px solid #dce7e9; border-radius:12px; margin-bottom:8px; background:#fbfdfd; }
|
||||
.lock-icon { width:32px; height:32px; border-radius:9px; background:#e0f0ef; color:#0b6673; display:grid; place-items:center; }
|
||||
.lock-icon svg { width:15px; }
|
||||
.lock-card div { display:flex; flex-direction:column; gap:2px; }
|
||||
.lock-card strong { font-size:.82rem; }
|
||||
.lock-card span { font-size:.72rem; color:#6d7f86; }
|
||||
.lock-card button { border:0; background:transparent; color:#93a1a6; font-size:1.1rem; cursor:pointer; }
|
||||
.range-labels { display:flex; justify-content:space-between; color:#89999f; font-size:.68rem; margin-top:8px; direction:ltr; }
|
||||
.priorities { display:grid; gap:10px; }
|
||||
.priorities .section-title { margin-bottom:0; }
|
||||
.priorities > button { display:flex; align-items:center; justify-content:space-between; gap:8px; width:100%; font-size:.78rem; }
|
||||
.priorities > button { border:0; padding:2px 0; background:transparent; color:inherit; cursor:pointer; text-align:right; }
|
||||
.priorities > button:hover > span { color:#0b6673; }
|
||||
.priorities > button > span { display:flex; align-items:center; gap:7px; }
|
||||
.priorities svg { width:15px; color:#5f747d; }
|
||||
.include-full { display:flex; align-items:center; gap:8px; color:#657981; line-height:1.5; padding-top:3px; }
|
||||
.include-full label { font-size:.78rem; cursor:pointer; }
|
||||
.generate-button { margin-top:20px; width:100%; height:44px; background:linear-gradient(135deg,#0b6673,#128f87); box-shadow:0 10px 25px rgba(11,102,115,.18); }
|
||||
.generate-button:disabled { opacity:.72; }
|
||||
|
||||
.view-tabs-row { display:flex; align-items:center; justify-content:space-between; gap:14px; margin-bottom:20px; }
|
||||
.view-tabs-row > span { color:#7b8e95; font-size:.72rem; }
|
||||
.schedule-head { align-items:flex-start; padding-bottom:18px; }
|
||||
.schedule-head h2 { font-size:1.45rem; }
|
||||
.schedule-head p { margin:7px 0 0; color:#687b83; font-size:.82rem; max-width:580px; }
|
||||
.eyebrow-row { justify-content:flex-start; }
|
||||
.score-badge { background:#e5f5ec; color:#197552; box-shadow:none; }
|
||||
.semester-tabs { direction:rtl; height:40px; padding:4px; }
|
||||
.metrics-row { display:grid; grid-template-columns:repeat(4,1fr); border:1px solid #e0e8ea; border-radius:16px; overflow:hidden; background:#fff; }
|
||||
.metrics-row > div { padding:14px 16px; display:grid; gap:3px; border-inline-start:1px solid #e8edef; }
|
||||
.metrics-row > div:first-child { border-inline-start:0; }
|
||||
.metrics-row span { color:#72858c; font-size:.72rem; }
|
||||
.metrics-row strong { font-size:1.18rem; }
|
||||
.metrics-row small { color:#97a5aa; font-size:.66rem; }
|
||||
.calendar-shell { margin-top:18px; border:1px solid #dde6e8; border-radius:17px; overflow:hidden; background:#fff; }
|
||||
.calendar-title-row { padding:14px 16px; border-bottom:1px solid #e4ebed; }
|
||||
.calendar-title-row > div:first-child { display:flex; align-items:baseline; gap:9px; }
|
||||
.calendar-title-row strong { font-size:.9rem; }
|
||||
.calendar-title-row span { color:#819197; font-size:.7rem; }
|
||||
.legend { display:flex; gap:12px; }
|
||||
.legend span { display:flex; align-items:center; gap:5px; }
|
||||
.legend i { width:8px;height:8px;border-radius:3px; }
|
||||
.legend-lock { background:#14978d; }
|
||||
.legend-normal { background:#9caeb4; }
|
||||
.week-grid { display:grid; grid-template-columns:58px repeat(6,minmax(92px,1fr)); overflow:auto; direction:rtl; }
|
||||
.contents { display:contents; }
|
||||
.time-corner,.day-head,.time-cell,.calendar-cell { min-height:74px; border-inline-start:1px solid #e7edef; border-bottom:1px solid #e7edef; }
|
||||
.time-corner,.day-head { min-height:42px; display:grid; place-items:center; background:#f8fafb; color:#60747c; font-size:.72rem; font-weight:700; position:sticky; top:0; z-index:2; }
|
||||
.time-cell { direction:ltr; padding-top:9px; text-align:center; color:#89989e; font-size:.66rem; background:#fbfcfc; }
|
||||
.calendar-cell { padding:4px; background-image:linear-gradient(to bottom,transparent 49%,rgba(225,232,235,.5) 50%,transparent 51%); }
|
||||
.course-block { height:65px; border-radius:10px; padding:7px 8px; display:flex; flex-direction:column; justify-content:space-between; border:1px solid transparent; overflow:hidden; transition:.18s ease; }
|
||||
.course-block:hover { transform:translateY(-1px); filter:saturate(1.1); }
|
||||
.course-block div { display:flex; align-items:center; justify-content:space-between; gap:4px; }
|
||||
.course-block strong { font-size:.72rem; white-space:nowrap; }
|
||||
.course-block span { font-size:.61rem; opacity:.72; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.course-block small { font-size:.58rem; opacity:.72; direction:ltr; text-align:right; }
|
||||
.course-block svg { width:12px; }
|
||||
.tone-blue { background:#e7f0fc; color:#275e93; border-color:#d2e3f7; }
|
||||
.tone-teal { background:#e3f5f1; color:#126a66; border-color:#cce9e3; }
|
||||
.tone-amber { background:#fff1d9; color:#8b5e17; border-color:#f5dfb9; }
|
||||
.tone-violet { background:#eee9fb; color:#665095; border-color:#ddd4f4; }
|
||||
.tone-rose { background:#fbe8e8; color:#8e4a50; border-color:#f2d4d6; }
|
||||
.tone-indigo { background:#e7ebfb; color:#4f5f9c; border-color:#d6ddf7; }
|
||||
.is-locked { box-shadow:inset -3px 0 #14978d; }
|
||||
|
||||
.selected-lessons { margin-top:16px; border:1px solid #dde6e8; border-radius:17px; background:#fff; overflow:hidden; }
|
||||
.lesson-chip-list { display:flex; flex-wrap:wrap; gap:8px; padding:14px 16px 16px; }
|
||||
.lesson-chip-list > span { display:grid; grid-template-columns:8px auto; align-items:center; gap:1px 7px; padding:8px 10px; border:1px solid #e2e9eb; border-radius:11px; background:#fbfcfc; font-size:.72rem; font-weight:700; }
|
||||
.lesson-chip-list small { grid-column:2; color:#84949a; font-size:.62rem; font-weight:400; }
|
||||
.tone-dot { width:7px; height:7px; border-radius:50%; grid-row:1 / span 2; }
|
||||
.tone-bg-blue { background:#5590c9; }.tone-bg-teal { background:#1e958a; }.tone-bg-amber { background:#d59a35; }
|
||||
.tone-bg-violet { background:#826db5; }.tone-bg-rose { background:#bd6a70; }.tone-bg-indigo { background:#6878b9; }
|
||||
|
||||
.classes-head { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin:4px 0 18px; }
|
||||
.classes-head h2 { margin:3px 0 6px; font-size:1.42rem; letter-spacing:-.025em; }
|
||||
.classes-head p:not(.eyebrow) { margin:0; color:#687b83; font-size:.8rem; }
|
||||
.filters-row { display:grid; grid-template-columns:minmax(280px,1fr) 190px; gap:10px; margin-bottom:14px; }
|
||||
.data-warning { display:grid; grid-template-columns:34px 1fr; gap:10px; align-items:center; margin:-4px 0 14px; padding:12px 14px; border:1px solid #efd8ad; border-radius:13px; background:#fff8e9; color:#76501b; }
|
||||
.data-warning > svg { width:32px; height:32px; padding:7px; border-radius:9px; background:#fff; }
|
||||
.data-warning div { display:grid; gap:3px; }
|
||||
.data-warning strong { font-size:.78rem; }
|
||||
.data-warning span { color:#876a3e; font-size:.69rem; line-height:1.7; }
|
||||
.search-box { position:relative; }
|
||||
.search-box > svg { position:absolute; z-index:1; top:50%; right:12px; width:16px; transform:translateY(-50%); color:#829299; }
|
||||
.search-box input { padding-right:38px; background:#fff; }
|
||||
.table-shell { border:1px solid #dde6e8; border-radius:16px; background:#fff; overflow:auto; }
|
||||
.table-shell table { min-width:820px; }
|
||||
.table-shell th { background:#f7f9fa; color:#667a82; font-size:.72rem; }
|
||||
.table-shell td { vertical-align:middle; font-size:.75rem; }
|
||||
.table-shell td:first-child { min-width:150px; }
|
||||
.table-shell td strong,.table-shell td small { display:block; }
|
||||
.table-shell td small { margin-top:3px; color:#89999f; font-size:.64rem; }
|
||||
.table-shell td button { white-space:nowrap; }
|
||||
.location-cell { max-width:160px; color:#667a82; }
|
||||
.no-results { min-height:540px; display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; color:#72858c; }
|
||||
.no-results > svg { width:42px; height:42px; padding:10px; border-radius:13px; color:#b06b25; background:#fff0db; }
|
||||
.no-results h2 { margin:14px 0 5px; color:#2b414a; font-size:1.05rem; }
|
||||
.no-results p,.empty-hint { margin:0; color:#83949a; font-size:.75rem; line-height:1.8; }
|
||||
.no-results .empty-generate { margin-top:18px; }
|
||||
.empty-hint { padding:10px 2px 12px; }
|
||||
.lock-dialog { max-width:430px; }
|
||||
.dialog-fields { display:grid; gap:8px; margin:8px 0; }
|
||||
.dialog-fields label { color:#536a73; font-size:.75rem; font-weight:700; margin-top:4px; }
|
||||
|
||||
.suggestions-head svg { width:18px; color:#8a999e; }
|
||||
.suggestion-list { display:grid; gap:9px; margin-top:16px; }
|
||||
.suggestion-empty { padding:18px 12px; border:1px dashed #cfdbde; border-radius:13px; color:#7a8c93; background:#f9fbfb; font-size:.72rem; line-height:1.8; text-align:center; }
|
||||
.suggestion-card { border:1px solid #e0e8ea; border-radius:14px; padding:12px; text-align:right; background:#fff; cursor:pointer; transition:.18s ease; }
|
||||
.suggestion-card:hover { border-color:#b9ced2; transform:translateY(-1px); }
|
||||
.suggestion-card.active { border-color:#3c9b9c; box-shadow:0 0 0 3px rgba(34,137,139,.09); background:#fbfefe; }
|
||||
.suggestion-top { display:grid; grid-template-columns:28px 1fr auto; align-items:center; gap:7px; }
|
||||
.rank { font-size:.7rem; color:#9aa7ac; font-variant-numeric:tabular-nums; }
|
||||
.suggestion-top strong { font-size:.85rem; }
|
||||
.suggestion-card p { font-size:.69rem; color:#71848b; margin:8px 0 10px; line-height:1.7; }
|
||||
.mini-metrics { display:flex; gap:9px; margin-bottom:9px; }
|
||||
.mini-metrics span { font-size:.64rem; color:#89989d; }
|
||||
.mini-metrics b { color:#405861; }
|
||||
.why-card { display:grid; grid-template-columns:36px 1fr; gap:10px; padding:13px; margin-top:18px; border-radius:14px; background:#0f3440; color:#fff; }
|
||||
.why-icon { width:34px;height:34px;border-radius:10px;background:rgba(255,255,255,.1);display:grid;place-items:center; }
|
||||
.why-icon svg { width:16px; color:#66d5c6; }
|
||||
.why-card strong { font-size:.82rem; }
|
||||
.why-card p { color:#c8d6da; font-size:.7rem; line-height:1.8; margin:5px 0 0; }
|
||||
.quick-filter { margin-top:18px; padding-top:18px; border-top:1px solid #e6ecee; display:grid; gap:9px; }
|
||||
.quick-filter label { font-size:.75rem; font-weight:700; }
|
||||
.quick-title { display:grid; grid-template-columns:30px 1fr; align-items:center; gap:9px; }
|
||||
.quick-title > svg { width:28px; height:28px; padding:6px; border-radius:9px; color:#0b6673; background:#e7f3f2; }
|
||||
.quick-title div { display:flex; flex-direction:column; gap:2px; }
|
||||
.quick-title strong { font-size:.77rem; }
|
||||
.quick-title span { color:#819197; font-size:.65rem; }
|
||||
.table-limit-note { margin:10px 3px 0; color:#7e9097; font-size:.68rem; line-height:1.7; }
|
||||
.notice { position:fixed; right:50%; bottom:22px; z-index:80; transform:translateX(50%); display:flex; align-items:center; gap:9px; min-width:280px; padding:11px 13px; color:#fff; background:#153e49; border:1px solid rgba(255,255,255,.12); border-radius:13px; box-shadow:0 18px 55px rgba(17,46,56,.26); font-size:.78rem; }
|
||||
.notice > svg { width:16px; color:#72d6b1; }
|
||||
.notice button { margin-inline-start:auto; border:0; background:transparent; color:#aec1c7; cursor:pointer; }
|
||||
.notice button svg { width:15px; }
|
||||
|
||||
@media (max-width: 1260px) {
|
||||
.workspace-grid { grid-template-columns:280px minmax(660px,1fr); }
|
||||
.suggestions-panel { grid-column:1 / -1; position:static; display:grid; grid-template-columns:160px 1fr 280px; gap:16px; align-items:start; }
|
||||
.suggestion-list { grid-template-columns:repeat(3,1fr); margin-top:0; }
|
||||
.why-card,.quick-filter { margin-top:0; }
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.topbar-status { display:none; }
|
||||
.workspace-grid { display:flex; flex-direction:column; padding:12px; }
|
||||
.control-panel,.schedule-panel,.suggestions-panel { width:100%; position:static; }
|
||||
.suggestions-panel { display:block; }
|
||||
.suggestion-list { grid-template-columns:1fr; }
|
||||
.metrics-row { grid-template-columns:repeat(2,1fr); }
|
||||
.schedule-head { flex-direction:column; }
|
||||
.filters-row { grid-template-columns:1fr; }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.topbar { padding:0 12px; height:68px; }
|
||||
.brand-copy span,.data-button { display:none; }
|
||||
.topbar-status { display:flex; margin-inline-start:auto; }
|
||||
.schedule-panel { padding:14px; }
|
||||
.metrics-row { grid-template-columns:1fr 1fr; }
|
||||
.metrics-row > div:nth-child(3),.metrics-row > div:nth-child(4) { border-top:1px solid #e8edef; }
|
||||
.view-tabs-row { align-items:flex-start; flex-direction:column; }
|
||||
.classes-head { align-items:flex-start; flex-direction:column; }
|
||||
.notice { width:calc(100% - 24px); min-width:0; bottom:12px; }
|
||||
.empty-start { min-height:calc(100vh - 68px); padding:16px 12px; }
|
||||
.empty-start-card { padding:38px 20px 28px; border-radius:22px; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Metadata } from 'next';
|
||||
import './globals.css';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'همچین | دستیار برنامهریزی دروس',
|
||||
description: 'فیلتر، مقایسه و چینش هوشمند کلاسهای قابل انتخاب',
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||
return (
|
||||
<html lang="fa" dir="rtl">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
'use client';
|
||||
|
||||
import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
AlertCircle,
|
||||
CalendarDays,
|
||||
Check,
|
||||
ChevronLeft,
|
||||
Clock3,
|
||||
Database,
|
||||
FileJson,
|
||||
ListFilter,
|
||||
LoaderCircle,
|
||||
LockKeyhole,
|
||||
MapPin,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
ShieldCheck,
|
||||
SlidersHorizontal,
|
||||
Sparkles,
|
||||
Upload,
|
||||
Users,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import {
|
||||
buildSuggestions,
|
||||
ClassOption,
|
||||
LockRule,
|
||||
normalizeExport,
|
||||
PlannerWeights,
|
||||
Priority,
|
||||
ScheduleSuggestion,
|
||||
Semester,
|
||||
weekDays,
|
||||
} from './planner';
|
||||
|
||||
type WebMcpContext = {
|
||||
registerTool: (tool: Record<string, unknown>, options?: { signal?: AbortSignal }) => void | Promise<void>;
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Document { modelContext?: WebMcpContext }
|
||||
}
|
||||
|
||||
const fa = new Intl.NumberFormat('fa-IR');
|
||||
const formatNumber = (value: number) => fa.format(value);
|
||||
const formatGap = (minutes: number) => minutes < 60 ? `${formatNumber(minutes)} دقیقه` : `${formatNumber(Number((minutes / 60).toFixed(1)))} ساعت`;
|
||||
const priorities: Priority[] = ['کم', 'متوسط', 'زیاد'];
|
||||
const MAX_IMPORT_BYTES = 25 * 1024 * 1024;
|
||||
const nextPaint = () => new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
|
||||
|
||||
function toneFor(lesson: string) {
|
||||
const tones = ['blue', 'teal', 'amber', 'violet', 'rose', 'indigo'];
|
||||
const total = Array.from(lesson).reduce((sum, letter) => sum + letter.charCodeAt(0), 0);
|
||||
return tones[total % tones.length];
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const [dataset, setDataset] = useState<ClassOption[]>([]);
|
||||
const [dataLabel, setDataLabel] = useState('فایلی وارد نشده');
|
||||
const [locks, setLocks] = useState<LockRule[]>([]);
|
||||
const [hourRange, setHourRange] = useState<number[]>([500, 600]);
|
||||
const [weights, setWeights] = useState<PlannerWeights>({ compact: 'زیاد', fewerDays: 'متوسط', location: 'متوسط', capacity: 'متوسط' });
|
||||
const [includeFull, setIncludeFull] = useState(false);
|
||||
const [suggestions, setSuggestions] = useState<ScheduleSuggestion[]>([]);
|
||||
const [activePlanId, setActivePlanId] = useState('');
|
||||
const [semester, setSemester] = useState<Semester>('نیمسال اول');
|
||||
const [mainTab, setMainTab] = useState('plans');
|
||||
const [query, setQuery] = useState('');
|
||||
const [semesterFilter, setSemesterFilter] = useState('همه');
|
||||
const [draftLesson, setDraftLesson] = useState('');
|
||||
const [draftTeacher, setDraftTeacher] = useState('');
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [isPlanning, setIsPlanning] = useState(false);
|
||||
const [hasGenerated, setHasGenerated] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
|
||||
const activePlan = suggestions.find((item) => item.id === activePlanId) ?? suggestions[0];
|
||||
const lessons = useMemo(() => [...new Set(dataset.map((item) => item.lesson))].sort((a, b) => a.localeCompare(b, 'fa')), [dataset]);
|
||||
const teachersForDraft = useMemo(() => [...new Set(dataset.filter((item) => item.lesson === draftLesson).map((item) => item.teacher))], [dataset, draftLesson]);
|
||||
const timedClassCount = useMemo(() => dataset.filter((item) => item.meetings.length).length, [dataset]);
|
||||
const filteredClasses = useMemo(() => dataset.filter((item) => {
|
||||
const needle = deferredQuery.trim().toLocaleLowerCase('fa');
|
||||
const matchesText = !needle || `${item.lesson} ${item.teacher} ${item.location}`.toLocaleLowerCase('fa').includes(needle);
|
||||
const matchesSemester = semesterFilter === 'همه' || item.semester === semesterFilter;
|
||||
return matchesText && matchesSemester && (includeFull || item.capacity > 0);
|
||||
}), [dataset, deferredQuery, semesterFilter, includeFull]);
|
||||
|
||||
const visibleClasses = useMemo(
|
||||
() => activePlan?.classes.filter((item) => item.semester === semester) ?? [],
|
||||
[activePlan, semester],
|
||||
);
|
||||
const hourSlots = useMemo(() => {
|
||||
const meetings = visibleClasses.flatMap((item) => item.meetings);
|
||||
if (!meetings.length) return [7, 8, 9, 10, 11];
|
||||
const min = Math.max(6, Math.floor(Math.min(...meetings.map((item) => item.start)) / 60));
|
||||
const max = Math.min(19, Math.ceil(Math.max(...meetings.map((item) => item.end)) / 60));
|
||||
return Array.from({ length: Math.max(1, max - min) }, (_, index) => min + index);
|
||||
}, [visibleClasses]);
|
||||
|
||||
const regenerate = async (nextDataset = dataset, nextLocks = locks, nextRange = hourRange, nextWeights = weights) => {
|
||||
if (isPlanning) return;
|
||||
setIsPlanning(true);
|
||||
setMainTab('plans');
|
||||
await nextPaint();
|
||||
try {
|
||||
const plans = buildSuggestions(nextDataset, nextLocks, nextRange, nextWeights, includeFull);
|
||||
setSuggestions(plans);
|
||||
setActivePlanId(plans[0]?.id ?? '');
|
||||
setHasGenerated(true);
|
||||
setNotice(plans.length ? `${formatNumber(plans.length)} برنامهٔ متفاوت آماده شد` : 'با این شرطها برنامهای پیدا نشد');
|
||||
window.setTimeout(() => setNotice(null), 3200);
|
||||
} finally {
|
||||
setIsPlanning(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const context = document.modelContext;
|
||||
if (!context?.registerTool) return;
|
||||
const lifecycle = new AbortController();
|
||||
const register = context.registerTool({
|
||||
name: 'configure_schedule_planner',
|
||||
title: 'تنظیم برنامهریز درسی',
|
||||
description: 'بازه ساعت و میزان اهمیت فشردگی برنامه را در رابط تنظیم میکند و پیشنهادهای تازه میسازد.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
minHours: { type: 'number', minimum: 300, maximum: 700 },
|
||||
maxHours: { type: 'number', minimum: 300, maximum: 700 },
|
||||
compactness: { type: 'string', enum: ['کم', 'متوسط', 'زیاد'] },
|
||||
},
|
||||
required: ['minHours', 'maxHours'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: false, untrustedContentHint: false },
|
||||
execute: async (input: unknown) => {
|
||||
const value = input as { minHours: number; maxHours: number; compactness?: Priority };
|
||||
if (!Number.isFinite(value.minHours) || !Number.isFinite(value.maxHours) || value.minHours > value.maxHours) throw new Error('بازه ساعت معتبر نیست.');
|
||||
const nextRange = [value.minHours, value.maxHours];
|
||||
const nextWeights = { ...weights, compact: value.compactness ?? weights.compact };
|
||||
setHourRange(nextRange);
|
||||
setWeights(nextWeights);
|
||||
await nextPaint();
|
||||
const plans = buildSuggestions(dataset, locks, nextRange, nextWeights, includeFull);
|
||||
setSuggestions(plans);
|
||||
setActivePlanId(plans[0]?.id ?? '');
|
||||
setHasGenerated(true);
|
||||
return { suggestionCount: plans.length, minHours: value.minHours, maxHours: value.maxHours };
|
||||
},
|
||||
}, { signal: lifecycle.signal });
|
||||
Promise.resolve(register).catch(() => undefined);
|
||||
return () => lifecycle.abort();
|
||||
}, [dataset, includeFull, locks, weights]);
|
||||
|
||||
const importJson = async (file?: File) => {
|
||||
if (!file) return;
|
||||
if (file.size > MAX_IMPORT_BYTES) {
|
||||
setNotice('حجم فایل بیشتر از ۲۵ مگابایت است؛ خروجی را به چند فایل کوچکتر تقسیم کنید.');
|
||||
window.setTimeout(() => setNotice(null), 5000);
|
||||
if (inputRef.current) inputRef.current.value = '';
|
||||
return;
|
||||
}
|
||||
setIsImporting(true);
|
||||
await nextPaint();
|
||||
try {
|
||||
const parsed = JSON.parse(await file.text());
|
||||
const normalized = normalizeExport(parsed);
|
||||
if (!normalized.length) throw new Error('هیچ کلاس معتبری در فایل پیدا نشد.');
|
||||
setDataset(normalized);
|
||||
setDataLabel(file.name);
|
||||
setLocks([]);
|
||||
setSuggestions([]);
|
||||
setActivePlanId('');
|
||||
setHasGenerated(false);
|
||||
setMainTab('classes');
|
||||
setNotice(`${formatNumber(normalized.length)} کلاس آمادهٔ فیلتر است`);
|
||||
window.setTimeout(() => setNotice(null), 3200);
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : 'فایل خوانده نشد');
|
||||
window.setTimeout(() => setNotice(null), 4000);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
if (inputRef.current) inputRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
setDataset([]);
|
||||
setDataLabel('فایلی وارد نشده');
|
||||
setLocks([]);
|
||||
setHourRange([500, 600]);
|
||||
setWeights({ compact: 'زیاد', fewerDays: 'متوسط', location: 'متوسط', capacity: 'متوسط' });
|
||||
setIncludeFull(false);
|
||||
setSuggestions([]);
|
||||
setActivePlanId('');
|
||||
setHasGenerated(false);
|
||||
setQuery('');
|
||||
setSemesterFilter('همه');
|
||||
};
|
||||
|
||||
const addLock = (lesson = draftLesson, teacher = draftTeacher) => {
|
||||
if (!lesson || !teacher) return;
|
||||
setLocks((current) => [...current.filter((item) => item.lesson !== lesson), { id: `lock-${Date.now()}`, lesson, teacher }]);
|
||||
setDraftLesson('');
|
||||
setDraftTeacher('');
|
||||
};
|
||||
|
||||
const cyclePriority = (key: keyof PlannerWeights) => {
|
||||
setWeights((current) => ({ ...current, [key]: priorities[(priorities.indexOf(current[key]) + 1) % priorities.length] }));
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-background text-foreground" dir="rtl">
|
||||
<header className="topbar">
|
||||
<div className="brand-mark" aria-hidden="true"><CalendarDays /></div>
|
||||
<div className="brand-copy"><strong>همچین</strong><span>دستیار برنامهریزی دروس حوزه</span></div>
|
||||
<div className="topbar-status"><span className={`status-dot ${dataset.length ? '' : 'is-empty'}`} />{dataLabel}</div>
|
||||
<Button variant="outline" className="data-button" disabled={isImporting} onClick={() => inputRef.current?.click()}>{isImporting ? <LoaderCircle className="spin" /> : <Upload />}{isImporting ? 'در حال خواندن…' : 'ورود فایل کلاسها'}</Button>
|
||||
<input ref={inputRef} type="file" accept="application/json,.json" className="hidden" onChange={(event) => { void importJson(event.target.files?.[0]); }} />
|
||||
</header>
|
||||
|
||||
{!dataset.length ? (
|
||||
<section
|
||||
className="empty-start"
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={(event) => { event.preventDefault(); void importJson(event.dataTransfer.files?.[0]); }}
|
||||
>
|
||||
<div className="empty-start-card">
|
||||
<div className="empty-start-icon"><FileJson /></div>
|
||||
<p className="eyebrow">شروع کاملاً خالی</p>
|
||||
<h1>فایل کلاسها را وارد کن</h1>
|
||||
<p>فایل JSON خروجی اسکرپر را انتخاب کن یا همینجا رها کن. تا قبل از ورود فایل، هیچ کلاس یا استاد پیشفرضی وجود ندارد.</p>
|
||||
<Button size="lg" disabled={isImporting} onClick={() => inputRef.current?.click()}>{isImporting ? <LoaderCircle className="spin" /> : <Upload />} {isImporting ? 'در حال خواندن…' : 'انتخاب فایل JSON'}</Button>
|
||||
<div className="privacy-note"><ShieldCheck /><div><strong>پردازش فقط در همین مرورگر</strong><span>محتوای فایل به سرور ارسال یا ذخیره نمیشود.</span></div></div>
|
||||
</div>
|
||||
</section>
|
||||
) : <section className="workspace-grid">
|
||||
<aside className="control-panel">
|
||||
<div className="panel-heading">
|
||||
<div><p className="eyebrow">قواعد برنامه</p><h1>اولویتهای من</h1></div>
|
||||
<Button variant="ghost" size="icon" aria-label="بازنشانی قواعد" onClick={reset}><RefreshCw /></Button>
|
||||
</div>
|
||||
<div className="source-card">
|
||||
<div className="source-icon"><Database /></div>
|
||||
<div><strong>{formatNumber(dataset.length)} کلاس آمادهٔ بررسی</strong><span>{formatNumber(lessons.length)} درس · فقط برای تصمیمگیری</span></div>
|
||||
<Check className="source-check" />
|
||||
</div>
|
||||
|
||||
<div className="rule-section">
|
||||
<div className="section-title"><span>شرطهای قطعی</span><Badge variant="secondary">{formatNumber(locks.length)} قفل</Badge></div>
|
||||
{locks.length ? locks.map((rule) => (
|
||||
<div className="lock-card" key={rule.id}>
|
||||
<span className="lock-icon"><LockKeyhole /></span>
|
||||
<div><strong>{rule.lesson}</strong><span>استاد {rule.teacher}</span></div>
|
||||
<button aria-label={`حذف شرط ${rule.lesson}`} onClick={() => setLocks((current) => current.filter((item) => item.id !== rule.id))}>×</button>
|
||||
</div>
|
||||
)) : <p className="empty-hint">هنوز درس یا استادی را قطعی نکردهاید.</p>}
|
||||
<Dialog>
|
||||
<DialogTrigger render={<Button variant="outline" className="w-full border-dashed" />}><Plus /> افزودن شرط قطعی</DialogTrigger>
|
||||
<DialogContent dir="rtl" className="lock-dialog">
|
||||
<DialogHeader><DialogTitle>قفلکردن درس و استاد</DialogTitle><DialogDescription>پیشنهادهایی که این انتخاب را نداشته باشند حذف میشوند.</DialogDescription></DialogHeader>
|
||||
<div className="dialog-fields">
|
||||
<label htmlFor="locked-lesson">درس</label>
|
||||
<Select value={draftLesson} onValueChange={(value) => { setDraftLesson(value as string); setDraftTeacher(''); }}>
|
||||
<SelectTrigger id="locked-lesson" className="w-full"><SelectValue placeholder="یک درس را انتخاب کنید" /></SelectTrigger>
|
||||
<SelectContent>{lessons.map((lesson) => <SelectItem key={lesson} value={lesson}>{lesson}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
<label htmlFor="locked-teacher">استاد</label>
|
||||
<Select value={draftTeacher} onValueChange={(value) => setDraftTeacher(value as string)} disabled={!draftLesson}>
|
||||
<SelectTrigger id="locked-teacher" className="w-full"><SelectValue placeholder="استاد مورد نظر" /></SelectTrigger>
|
||||
<SelectContent>{teachersForDraft.map((teacher) => <SelectItem key={teacher} value={teacher}>{teacher}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button onClick={() => addLock()} disabled={!draftLesson || !draftTeacher} />}>ثبت شرط قطعی</DialogClose>
|
||||
<DialogClose render={<Button variant="outline" />}>انصراف</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="rule-section">
|
||||
<div className="section-title"><span>مجموع ساعت مطلوب</span><strong>{formatNumber(hourRange[0])} تا {formatNumber(hourRange[1])}</strong></div>
|
||||
<Slider min={400} max={700} step={10} value={hourRange} onValueChange={(value) => setHourRange(value as number[])} aria-label="بازه ساعت مطلوب" />
|
||||
<div className="range-labels"><span>۴۰۰</span><span>۷۰۰ ساعت</span></div>
|
||||
</div>
|
||||
|
||||
<div className="rule-section priorities">
|
||||
<div className="section-title"><span>شیوهٔ چینش</span><SlidersHorizontal /></div>
|
||||
<button onClick={() => cyclePriority('compact')}><span><Clock3 />کلاسهای پشتسرهم</span><Badge>{weights.compact}</Badge></button>
|
||||
<button onClick={() => cyclePriority('fewerDays')}><span><CalendarDays />روزهای حضور کمتر</span><Badge variant="outline">{weights.fewerDays}</Badge></button>
|
||||
<button onClick={() => cyclePriority('location')}><span><MapPin />جابهجایی مکانی کمتر</span><Badge variant="outline">{weights.location}</Badge></button>
|
||||
<button onClick={() => cyclePriority('capacity')}><span><Users />ظرفیت مطمئنتر</span><Badge variant="outline">{weights.capacity}</Badge></button>
|
||||
<div className="include-full"><Checkbox id="include-full" checked={includeFull} onCheckedChange={(checked) => setIncludeFull(Boolean(checked))} /><label htmlFor="include-full">کلاسهای تکمیلظرفیت هم بررسی شوند</label></div>
|
||||
</div>
|
||||
<Button size="lg" className="generate-button" disabled={isPlanning} onClick={() => { void regenerate(); }}>{isPlanning ? <LoaderCircle className="spin" /> : <Sparkles />}{isPlanning ? 'در حال ساخت…' : 'ساخت پیشنهادهای تازه'}</Button>
|
||||
</aside>
|
||||
|
||||
<section className="schedule-panel">
|
||||
<Tabs value={mainTab} onValueChange={setMainTab}>
|
||||
<div className="view-tabs-row">
|
||||
<TabsList><TabsTrigger value="plans">پیشنهادها</TabsTrigger><TabsTrigger value="classes">همهٔ کلاسها</TabsTrigger></TabsList>
|
||||
<span>هیچ تغییری در سامانه ثبت نمیشود</span>
|
||||
</div>
|
||||
<TabsContent value="plans">
|
||||
{activePlan ? (
|
||||
<>
|
||||
<div className="schedule-head">
|
||||
<div>
|
||||
<div className="eyebrow-row"><p className="eyebrow">پیشنهاد انتخابشده</p><Badge className="score-badge">امتیاز {formatNumber(activePlan.score)} از ۱۰۰</Badge></div>
|
||||
<h2>برنامهٔ {activePlan.name}</h2><p>{activePlan.note}؛ تمام شرطهای قطعی رعایت شدهاند.</p>
|
||||
</div>
|
||||
<Tabs value={semester} onValueChange={(value) => setSemester(value as Semester)}>
|
||||
<TabsList className="semester-tabs"><TabsTrigger value="نیمسال اول">نیمسال اول</TabsTrigger><TabsTrigger value="نیمسال دوم">نیمسال دوم</TabsTrigger></TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
<div className="metrics-row">
|
||||
<div><span>مجموع ساعت</span><strong>{formatNumber(activePlan.metrics.hours)}</strong><small>در بازهٔ مطلوب</small></div>
|
||||
<div><span>فاصلهٔ خالی</span><strong>{formatGap(activePlan.metrics.gapMinutes)}</strong><small>در دو نیمسال</small></div>
|
||||
<div><span>روزهای حضور</span><strong>{formatNumber(activePlan.metrics.activeDays)} روز</strong><small>در هر هفته</small></div>
|
||||
<div><span>کمترین ظرفیت</span><strong>{formatNumber(activePlan.metrics.minCapacity)} نفر</strong><small>{activePlan.metrics.minCapacity < 10 ? 'نیازمند توجه' : 'وضعیت مناسب'}</small></div>
|
||||
</div>
|
||||
<div className="calendar-shell">
|
||||
<div className="calendar-title-row"><div><strong>نمای هفتگی</strong><span>{formatNumber(visibleClasses.length)} درس در {semester}</span></div><div className="legend"><span><i className="legend-lock" />قطعی</span><span><i className="legend-normal" />پیشنهادی</span></div></div>
|
||||
<div className="week-grid">
|
||||
<div className="time-corner">ساعت</div>{weekDays.map((day) => <div key={day} className="day-head">{day}</div>)}
|
||||
{hourSlots.map((hour) => <div className="contents" key={hour}>
|
||||
<div className="time-cell">{String(hour).padStart(2, '0')}:۰۰</div>
|
||||
{weekDays.map((day) => {
|
||||
const entries = visibleClasses.filter((course) => course.meetings.some((meeting) => meeting.day === day && Math.floor(meeting.start / 60) === hour));
|
||||
return <div key={`${day}-${hour}`} className="calendar-cell">{entries.map((item) => {
|
||||
const meeting = item.meetings.find((entry) => entry.day === day)!;
|
||||
const locked = locks.some((rule) => rule.lesson === item.lesson && rule.teacher === item.teacher);
|
||||
return <article key={item.id} className={`course-block tone-${toneFor(item.lesson)} ${locked ? 'is-locked' : ''}`} title={`${item.teacher} · ${item.location}`}>
|
||||
<div><strong>{item.lesson}</strong>{locked && <LockKeyhole />}</div><span>{item.teacher}</span><small>{meeting.label}</small>
|
||||
</article>;
|
||||
})}</div>;
|
||||
})}
|
||||
</div>)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="selected-lessons">
|
||||
<div className="calendar-title-row"><div><strong>درسهای این پیشنهاد</strong><span>{formatNumber(activePlan.classes.length)} انتخاب پیشنهادی</span></div></div>
|
||||
<div className="lesson-chip-list">{activePlan.classes.map((item) => <span key={item.id}><i className={`tone-dot tone-bg-${toneFor(item.lesson)}`} />{item.lesson}<small>{item.teacher}</small></span>)}</div>
|
||||
</div>
|
||||
</>
|
||||
) : <div className="no-results">{isPlanning ? <LoaderCircle className="spin" /> : <AlertCircle />}<h2>{isPlanning ? 'در حال بررسی کلاسها…' : hasGenerated ? 'برنامهای با این شرطها پیدا نشد' : 'هنوز پیشنهادی ساخته نشده'}</h2><p>{isPlanning ? 'این مرحله برای فایلهای بزرگ هم باید کوتاه باشد.' : hasGenerated ? 'بازهٔ ساعت را کمی بازتر کنید یا یکی از شرطهای قطعی را بردارید.' : 'اول شرطها را تنظیم کنید، سپس پیشنهادها را بسازید.'}</p>{!hasGenerated && !isPlanning && <Button className="empty-generate" onClick={() => { void regenerate(); }}><Sparkles />ساخت پیشنهادها</Button>}</div>}
|
||||
</TabsContent>
|
||||
<TabsContent value="classes">
|
||||
<div className="classes-head"><div><p className="eyebrow">فهرست دادهها</p><h2>همهٔ کلاسها</h2><p>جستوجو کنید، ظرفیت و زمان را ببینید و هر استاد را مستقیماً قفل کنید.</p></div><Badge variant="secondary">{formatNumber(filteredClasses.length)} نتیجه</Badge></div>
|
||||
{timedClassCount === 0 && <div className="data-warning"><AlertCircle /><div><strong>زمان کلاسها در این فایل خالی است</strong><span>فیلتر و شرط استاد کار میکند، اما تداخل زمانی و فشردگی برنامه تا وقتی days و time در خروجی نباشد محاسبه نمیشود.</span></div></div>}
|
||||
<div className="filters-row">
|
||||
<div className="search-box"><Search /><Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="نام درس، استاد یا مکان…" /></div>
|
||||
<Select value={semesterFilter} onValueChange={(value) => setSemesterFilter(value as string)}><SelectTrigger><ListFilter /><SelectValue /></SelectTrigger><SelectContent><SelectItem value="همه">هر دو نیمسال</SelectItem><SelectItem value="نیمسال اول">نیمسال اول</SelectItem><SelectItem value="نیمسال دوم">نیمسال دوم</SelectItem></SelectContent></Select>
|
||||
</div>
|
||||
<div className="table-shell"><Table><TableHeader><TableRow><TableHead>درس و نیمسال</TableHead><TableHead>استاد</TableHead><TableHead>زمان</TableHead><TableHead>مکان</TableHead><TableHead>ساعت</TableHead><TableHead>ظرفیت</TableHead><TableHead /></TableRow></TableHeader><TableBody>
|
||||
{filteredClasses.slice(0, 100).map((item) => {
|
||||
const locked = locks.some((rule) => rule.lesson === item.lesson && rule.teacher === item.teacher);
|
||||
return <TableRow key={item.id}><TableCell><strong>{item.lesson}</strong><small>{item.semester}</small></TableCell><TableCell>{item.teacher}</TableCell><TableCell>{item.meetings[0] ? `${item.meetings.map((meeting) => meeting.day).join('، ')} · ${item.meetings[0].label}` : 'زمان نامشخص'}</TableCell><TableCell className="location-cell">{item.location || '—'}</TableCell><TableCell>{formatNumber(item.hours)}</TableCell><TableCell><Badge variant={item.capacity > 10 ? 'secondary' : item.capacity > 0 ? 'outline' : 'destructive'}>{item.capacity > 0 ? formatNumber(item.capacity) : 'تکمیل'}</Badge></TableCell><TableCell><Button size="sm" variant={locked ? 'secondary' : 'ghost'} onClick={() => locked ? setLocks((current) => current.filter((rule) => !(rule.lesson === item.lesson && rule.teacher === item.teacher))) : addLock(item.lesson, item.teacher)}>{locked ? <><Check />قفل شد</> : <><LockKeyhole />قفل</>}</Button></TableCell></TableRow>;
|
||||
})}
|
||||
</TableBody></Table></div>
|
||||
{filteredClasses.length > 100 && <p className="table-limit-note">برای سبک ماندن صفحه، ۱۰۰ نتیجهٔ اول نمایش داده شده است؛ با جستوجو یا فیلتر نیمسال به کلاس موردنظر برسید.</p>}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</section>
|
||||
|
||||
<aside className="suggestions-panel">
|
||||
<div className="suggestions-head"><div><p className="eyebrow">{formatNumber(suggestions.length)} انتخاب خوب</p><h2>پیشنهادها</h2></div><ChevronLeft /></div>
|
||||
<div className="suggestion-list">{suggestions.length === 0 && <div className="suggestion-empty">پس از تنظیم شرطها، پیشنهادها را بسازید.</div>}{suggestions.map((item, index) => <button key={item.id} onClick={() => { setActivePlanId(item.id); setMainTab('plans'); }} className={`suggestion-card ${activePlan?.id === item.id ? 'active' : ''}`}>
|
||||
<div className="suggestion-top"><span className="rank">۰{formatNumber(index + 1)}</span><strong>{item.name}</strong><Badge variant={activePlan?.id === item.id ? 'default' : 'secondary'}>{formatNumber(item.score)}٪</Badge></div>
|
||||
<p>{item.note}</p><div className="mini-metrics"><span><b>{formatNumber(item.metrics.hours)}</b> ساعت</span><span><b>{formatGap(item.metrics.gapMinutes)}</b> فاصله</span><span><b>{formatNumber(item.metrics.activeDays)}</b> روز</span></div><Progress value={item.score} />
|
||||
</button>)}</div>
|
||||
{activePlan && <div className="why-card"><div className="why-icon"><Sparkles /></div><div><strong>چرا این برنامه؟</strong><p>{locks.length ? `${locks.map((item) => `${item.lesson} با ${item.teacher}`).join(' و ')} قطعی است. ` : ''}{activePlan.metrics.gapMinutes ? `مجموع فاصلهٔ خالی فقط ${formatGap(activePlan.metrics.gapMinutes)} است` : 'همهٔ کلاسهای هر روز پشتسرهماند'} و کمترین ظرفیت آن {formatNumber(activePlan.metrics.minCapacity)} نفر است.</p></div></div>}
|
||||
<div className="quick-filter"><div className="quick-title"><FileJson /><div><strong>دادهٔ واقعی خودت</strong><span>خروجی hamchin-scraper را اینجا بینداز</span></div></div><Button variant="outline" className="w-full" onClick={() => inputRef.current?.click()}>انتخاب فایل JSON <ChevronLeft /></Button></div>
|
||||
</aside>
|
||||
</section>}
|
||||
{notice && <output className="notice"><Check />{notice}<button onClick={() => setNotice(null)} aria-label="بستن"><X /></button></output>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
buildSuggestions,
|
||||
type ClassOption,
|
||||
normalizeExport,
|
||||
type PlannerWeights,
|
||||
} from './planner.ts';
|
||||
|
||||
const weights: PlannerWeights = {
|
||||
compact: 'زیاد',
|
||||
fewerDays: 'متوسط',
|
||||
location: 'متوسط',
|
||||
capacity: 'متوسط',
|
||||
};
|
||||
|
||||
function option(
|
||||
id: string,
|
||||
lesson: string,
|
||||
teacher: string,
|
||||
start: number,
|
||||
end: number,
|
||||
): ClassOption {
|
||||
return {
|
||||
id,
|
||||
lesson,
|
||||
teacher,
|
||||
semester: 'نیمسال اول',
|
||||
hours: 20,
|
||||
capacity: 15,
|
||||
availability: 'قابل انتخاب',
|
||||
location: 'مکان ساختگی',
|
||||
classTitle: lesson,
|
||||
scope: '',
|
||||
meetings: [{ day: 'شنبه', start, end, label: 'زمان ساختگی' }],
|
||||
};
|
||||
}
|
||||
|
||||
void test('normalizes scraper JSON and Persian digits', () => {
|
||||
const classes = normalizeExport({
|
||||
classes: [{
|
||||
lesson: 'درس ساختگی',
|
||||
class_title: 'درس ساختگی: نیمسال اول',
|
||||
hours: '۲۰',
|
||||
teacher: 'استاد ساختگی',
|
||||
remaining_capacity: '۱۵',
|
||||
days: ['شنبه'],
|
||||
time: '08:00-09:00',
|
||||
}],
|
||||
});
|
||||
|
||||
assert.equal(classes.length, 1);
|
||||
assert.equal(classes[0].hours, 20);
|
||||
assert.equal(classes[0].capacity, 15);
|
||||
assert.equal(classes[0].meetings[0].start, 480);
|
||||
});
|
||||
|
||||
void test('honors teacher locks and rejects time conflicts', () => {
|
||||
const classes = [
|
||||
option('lesson-1-a', 'درس یک', 'استاد الف', 480, 540),
|
||||
option('lesson-1-b', 'درس یک', 'استاد ب', 540, 600),
|
||||
option('lesson-2-c', 'درس دو', 'استاد ج', 510, 570),
|
||||
option('lesson-2-d', 'درس دو', 'استاد د', 600, 660),
|
||||
];
|
||||
|
||||
const plans = buildSuggestions(
|
||||
classes,
|
||||
[{ id: 'required', lesson: 'درس یک', teacher: 'استاد الف' }],
|
||||
[40, 40],
|
||||
weights,
|
||||
);
|
||||
|
||||
assert.ok(plans.length > 0);
|
||||
for (const plan of plans) {
|
||||
assert.ok(plan.classes.some((item) => item.id === 'lesson-1-a'));
|
||||
assert.ok(plan.classes.some((item) => item.id === 'lesson-2-d'));
|
||||
assert.ok(!plan.classes.some((item) => item.id === 'lesson-2-c'));
|
||||
}
|
||||
});
|
||||
|
||||
void test('keeps a locked teacher even when a lesson has many choices', () => {
|
||||
const crowdedLesson = Array.from({ length: 80 }, (_, index) =>
|
||||
option(`crowded-${index}`, 'درس پرتعداد', `استاد ${index}`, 480 + index, 540 + index));
|
||||
const required = crowdedLesson.at(-1)!;
|
||||
const plans = buildSuggestions(
|
||||
[...crowdedLesson, option('second', 'درس دوم', 'استاد دوم', 700, 760)],
|
||||
[{ id: 'required', lesson: required.lesson, teacher: required.teacher }],
|
||||
[40, 40],
|
||||
weights,
|
||||
);
|
||||
|
||||
assert.ok(plans.length > 0);
|
||||
assert.ok(plans.every((plan) => plan.classes.some((item) => item.id === required.id)));
|
||||
});
|
||||
|
||||
void test('handles a multi-thousand-class export without an exhaustive expansion', () => {
|
||||
const classes = Array.from({ length: 38 }, (_, lessonIndex) =>
|
||||
Array.from({ length: 60 }, (_, choiceIndex): ClassOption => ({
|
||||
...option(`large-${lessonIndex}-${choiceIndex}`, `درس ${lessonIndex}`, `استاد ${choiceIndex}`, 0, 0),
|
||||
hours: 20,
|
||||
capacity: 5 + (choiceIndex % 30),
|
||||
location: `مکان ${choiceIndex % 8}`,
|
||||
meetings: [],
|
||||
})),
|
||||
).flat();
|
||||
|
||||
const startedAt = performance.now();
|
||||
const plans = buildSuggestions(classes, [], [500, 600], weights);
|
||||
const elapsed = performance.now() - startedAt;
|
||||
|
||||
assert.ok(plans.length > 0);
|
||||
assert.ok(elapsed < 1500, `large dataset took ${elapsed.toFixed(0)}ms`);
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user