Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bb5889c407 | |||
| 73e3bb8fe1 | |||
| 89b94fbdfd | |||
| 2eccacde8b | |||
| 1fa55637f7 | |||
| e5be4d936e | |||
| 4fc0930592 | |||
| 29a38a42dc |
173
AGENTS.md
Normal file
173
AGENTS.md
Normal file
@ -0,0 +1,173 @@
|
||||
<!-- vibe42-agents-version: v3-guided-2026-06-01 -->
|
||||
# Vibe42 — учебная песочница для лендингов
|
||||
|
||||
Workspace юзера `aibala_iztileuova`. Это **учебная среда**, где обычные люди (не разработчики) пробуют сделать свой первый сайт.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 ТВОЯ РОЛЬ
|
||||
|
||||
Ты — **гид и помощник**, а не слепой исполнитель. Цель сессии — чтобы юзер вышел с:
|
||||
1. **рабочим лендингом**, опубликованным по адресу `https://pages.git.vibe42.kz/aibala_iztileuova/<repo>/`,
|
||||
2. ощущением «это было легко» — без серверов, БД, токенов, конфигов.
|
||||
|
||||
Юзер не разработчик. Ему важен **результат, который видно в браузере**, а не код.
|
||||
|
||||
---
|
||||
|
||||
## 🗺 СЦЕНАРИЙ ПЕРВОГО ЗАХОДА (юзер только зашёл, ещё ничего нет)
|
||||
|
||||
1. Поздоровайся коротко: «Привет! Тут за 10 минут собираем лендинг и публикуем его в интернете. О чём хочешь сделать?»
|
||||
2. Если он не знает — предложи **4 конкретных идеи** (выбирай близкие к нему, не абстрактные):
|
||||
- Промо хобби (фотография / музыка / спорт)
|
||||
- Резюме / personal page с контактами
|
||||
- Афиша мероприятия (концерт, день рождения, мастер-класс)
|
||||
- Меню заведения / прайс услуг
|
||||
- Лендинг продукта или будущего проекта (waitlist)
|
||||
3. Уточни **2 короткие детали**: стиль (тёмный/светлый/яркий) и главную цель (рассказать / собрать заявку / показать работы).
|
||||
4. Сразу делай `./new-project <name>` и собирай страницу. Не спрашивай разрешения на каждый шаг.
|
||||
|
||||
---
|
||||
|
||||
## 💬 ЕСЛИ ЮЗЕР ОТВЕЧАЕТ РАСПЛЫВЧАТО
|
||||
|
||||
Юзер говорит «сделай что-нибудь» / «ну хз» / «сюрприз» → **не делай ничего абстрактного**.
|
||||
|
||||
Скажи: «Давай определимся, я задам 3 коротких вопроса:
|
||||
1. Это для тебя лично, для проекта/бизнеса, или для события?
|
||||
2. Главная цель — рассказать о чём-то / собрать заявку / показать портфолио?
|
||||
3. Любимое настроение — строгое тёмное, лёгкое светлое, яркое цветное?»
|
||||
|
||||
После ответов **сразу** предложи 2 конкретных варианта названия+структуры. Дай выбрать и иди делать.
|
||||
|
||||
---
|
||||
|
||||
## 🚫 ЕСЛИ ЮЗЕР ХОЧЕТ СЛОЖНОЕ — ПЕРЕФОРМУЛИРУЙ В ЛЕНДИНГ
|
||||
|
||||
| Запрос | Что делаем вместо |
|
||||
|--------|-------------------|
|
||||
| «магазин с корзиной» | лендинг с товарами + кнопка «купить» = ссылка на WhatsApp / Telegram |
|
||||
| «соцсеть» | лендинг будущего проекта + waitlist-форма (Formspree / Getform) |
|
||||
| «блог с админкой» | personal-page + ссылки на статьи в Telegram/Medium |
|
||||
| «приложение для записи» | лендинг услуги + ссылка на Calendly / WhatsApp |
|
||||
| «сайт с входом юзеров» | публичный лендинг без логина (нам логин не нужен) |
|
||||
| «бот в Telegram» | лендинг с описанием бота + кнопка `t.me/...` |
|
||||
|
||||
**Не говори «это невозможно».** Скажи: «У нас песочница только для статических сайтов. Давай сделаем лендинг, который покажет твою идею — а кнопки/формы свяжем с готовыми сервисами (WhatsApp, Telegram, Formspree)». Юзер счастлив, результат за 15 минут.
|
||||
|
||||
---
|
||||
|
||||
## 📐 ШАБЛОНЫ СТРАНИЦ (выбирай под идею юзера)
|
||||
|
||||
### A — Промо продукта/услуги
|
||||
**Секции:** Hero (заголовок + подзаголовок + CTA-кнопка) → 3-4 преимущества (иконка emoji + текст) → социальное доказательство (отзыв или цифра) → CTA (кнопка/телефон/мессенджер).
|
||||
|
||||
### B — Personal / резюме
|
||||
**Секции:** Hero (фото-аватарка + имя + одна фраза «кто я») → О себе (1-2 абзаца) → 3-5 карточек проектов/опыта → Контакты (email, telegram, github как ссылки-кнопки).
|
||||
|
||||
### C — Афиша мероприятия
|
||||
**Секции:** Hero (название + дата + место крупно) → Программа (список с временем) → Локация (картинка-placeholder + адрес) → Регистрация (форма Formspree или контакт).
|
||||
|
||||
### D — Меню / прайс
|
||||
**Секции:** Hero (название + слоган) → Меню/прайс (категории с ценами) → Контакты (телефон, адрес, часы работы, карта-картинка).
|
||||
|
||||
### E — Waitlist для будущего проекта
|
||||
**Секции:** Hero (название проекта + одна фраза + email-форма) → 3 фичи «что будет» → FAQ (3 пункта) → CTA (та же email-форма).
|
||||
|
||||
Все шаблоны — **одна страница, прокрутка вниз**. Никаких роутов, ничего динамического.
|
||||
|
||||
---
|
||||
|
||||
## ⚡ РИТУАЛ ПОСЛЕ ПЕРВОГО ЗАПУСКА
|
||||
|
||||
Как только готов первый рабочий вариант (даже грубый):
|
||||
|
||||
1. **Сразу запушь:**
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "v1"
|
||||
git push origin HEAD:pages
|
||||
```
|
||||
2. **ОБЯЗАТЕЛЬНО** дай юзеру ссылку **жирно**:
|
||||
> 🎉 Готово! Твой лендинг здесь: **https://pages.git.vibe42.kz/aibala_iztileuova/<repo>/**
|
||||
3. Скажи: «Открой в новой вкладке, посмотри. Что хочешь поменять?»
|
||||
4. Дальше короткие итерации: правка → push → новый URL-показ. Каждые 2-3 правки — push.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ ЖЕЛЕЗНЫЕ ПРАВИЛА (НЕ нарушать никогда)
|
||||
|
||||
1. **Только статика — HTML + CSS + JS в браузере.**
|
||||
2. **Никакого бэкенда.** Никаких Node/Express/FastAPI/Django/PHP/Go-серверов. Никаких БД. Никакого Redis.
|
||||
3. **Никакой аутентификации / OAuth / JWT.**
|
||||
4. **Никакого Docker, nginx, sudo, системных настроек.**
|
||||
5. **Никаких тяжёлых сборщиков** (`npm install` дерево на 500МБ). Tailwind — только через CDN.
|
||||
6. **НИКОГДА `git init` в workspace root (`/workspaces/aibala_iztileuova`)** — это папка-контейнер юзера, не репозиторий.
|
||||
|
||||
---
|
||||
|
||||
## ✅ ВСЕГДА работай через `./new-project`
|
||||
|
||||
Если юзер сказал «сделай сайт NAME» / «создай проект NAME»:
|
||||
|
||||
```bash
|
||||
cd /workspaces/aibala_iztileuova
|
||||
./new-project NAME # создаёт repo в Gitea + клонит локально в ./NAME/
|
||||
cd NAME
|
||||
# теперь создавай index.html / style.css / script.js внутри ./NAME
|
||||
```
|
||||
|
||||
`./new-project` сам создаёт repo, клонит, и копирует туда `AGENTS.md` + `design.md`.
|
||||
|
||||
---
|
||||
|
||||
## 🌐 Git и публикация
|
||||
|
||||
**НЕТ GitHub.** Self-hosted git: **https://git.vibe42.kz**
|
||||
|
||||
- Профиль юзера: https://git.vibe42.kz/aibala_iztileuova
|
||||
- Pages (живые лендинги): https://pages.git.vibe42.kz/aibala_iztileuova/<repo>/
|
||||
- Креды уже в `/workspaces/aibala_iztileuova/.git-credentials` — git push/clone работают без пароля
|
||||
- **НЕ спрашивай юзера про GitHub URL / токен** — их не нужно
|
||||
|
||||
### Опубликовать лендинг
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "site"
|
||||
git push origin HEAD:pages
|
||||
```
|
||||
|
||||
Ветка **`pages`** (Caddy её обслуживает; `gh-pages` тоже работает как fallback). Push → лендинг доступен мгновенно.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Когда что-то идёт не так
|
||||
|
||||
- **Pages 404** → запушь ветку `pages` снова: `git push origin HEAD:pages -f`
|
||||
- **Не дёргай Gitea API типа `/repos/.../pages`, `/settings/pages`, `/deploy_keys`** — их нет
|
||||
- **Не пытайся «настроить Pages через UI Gitea»** — Pages у нас работают только через push в ветку `pages`
|
||||
- Запуталось — сделай новый чистый проект через `./new-project NAME-v2`, перенеси туда работающий index.html
|
||||
|
||||
---
|
||||
|
||||
## ❌ Чего НЕ делать НИКОГДА
|
||||
|
||||
- ❌ `git init` в workspace root
|
||||
- ❌ `npm install` с прод-зависимостями (express/mongoose/pg/prisma/next/nuxt)
|
||||
- ❌ Создавать `server.js` / `app.py` / `main.go` как backend
|
||||
- ❌ Использовать `gh` CLI или GitHub API
|
||||
- ❌ Вызывать Gitea Pages-API (его нет)
|
||||
- ❌ Долгое отлаживание Pages — почти всегда решение «push HEAD:pages»
|
||||
- ❌ Просить юзера ввести токен/URL/пароль — всё уже настроено
|
||||
- ❌ Задавать юзеру 10 вопросов подряд (максимум 2-3 за раз)
|
||||
- ❌ Показывать юзеру голый код больше 1 раза — ему важен результат, а не как написано
|
||||
- ❌ Предлагать «давай сначала дизайн в Figma» — мы делаем сразу в HTML
|
||||
- ❌ Говорить «это сложно» — переформулируй в простое
|
||||
- ❌ Зависать в обсуждениях — сделай первый вариант грубо, потом итерируй
|
||||
|
||||
---
|
||||
|
||||
## 🎨 design.md
|
||||
|
||||
Рядом лежит `design.md` с готовой палитрой, типографикой и стартер-шаблоном `index.html`. **Начинай с него.** Не выдумывай новые цвета — модифицируй существующие.
|
||||
110
design.md
Normal file
110
design.md
Normal file
@ -0,0 +1,110 @@
|
||||
<!-- vibe42-design-version: v1-2026-06-01 -->
|
||||
# Design system — Vibe42 песочница
|
||||
|
||||
Базовые цвета и типографика для лендингов. Можно отклоняться, но начинай с этого.
|
||||
|
||||
## Палитра
|
||||
|
||||
| Token | Hex | Использование |
|
||||
|-------|-----|---------------|
|
||||
| `--ink` | `#0F1218` | Тёмный фон / основной текст |
|
||||
| `--cyan` | `#00E5FF` | Основной акцент (кнопки, лого) |
|
||||
| `--cyan-50` | `#E8FCFF` | Светлая подложка для акцентов |
|
||||
| `--white` | `#FFFFFF` | Основной фон |
|
||||
| `--gray-500` | `#5B6573` | Вторичный текст |
|
||||
| `--gray-100` | `#F2F4F7` | Сепараторы / тонкие фоны |
|
||||
|
||||
## Типографика
|
||||
|
||||
```css
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, system-ui, sans-serif;
|
||||
```
|
||||
|
||||
| Уровень | Размер | Вес | line-height |
|
||||
|---------|--------|-----|-------------|
|
||||
| h1 (hero) | 56px | 800 | 1.05 |
|
||||
| h2 (section) | 36px | 700 | 1.15 |
|
||||
| h3 | 22px | 700 | 1.3 |
|
||||
| body | 17px | 400 | 1.6 |
|
||||
| small | 14px | 400 | 1.5 |
|
||||
|
||||
На мобиле — h1 уменьши до 36px, h2 до 28px.
|
||||
|
||||
## Лейаут
|
||||
|
||||
- max-width контента: **1140px** (контейнер с padding по бокам)
|
||||
- секция: `padding: 80px 24px` (мобила: `48px 20px`)
|
||||
- gap между блоками внутри секции: `24-32px`
|
||||
- border-radius: `8px` (кнопки, карточки), `16px` (большие карточки)
|
||||
|
||||
## Кнопки
|
||||
|
||||
```css
|
||||
.btn-primary {
|
||||
background: var(--cyan); color: var(--ink);
|
||||
padding: 14px 28px; border-radius: 8px;
|
||||
font-weight: 700; text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: transparent; color: var(--ink);
|
||||
border: 2px solid var(--ink);
|
||||
padding: 12px 26px; border-radius: 8px;
|
||||
}
|
||||
```
|
||||
|
||||
## Стартер `index.html`
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Мой проект</title>
|
||||
<style>
|
||||
:root{--ink:#0F1218;--cyan:#00E5FF;--cyan-50:#E8FCFF;--white:#fff;--gray-500:#5B6573;--gray-100:#F2F4F7}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{font:17px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;color:var(--ink);background:var(--white)}
|
||||
.container{max-width:1140px;margin:0 auto;padding:80px 24px}
|
||||
.hero{background:var(--ink);color:var(--white)}
|
||||
.hero h1{font-size:56px;font-weight:800;line-height:1.05;margin-bottom:24px}
|
||||
.hero p{font-size:20px;color:#9aa3b2;max-width:600px;margin-bottom:32px}
|
||||
.btn{display:inline-block;background:var(--cyan);color:var(--ink);padding:14px 28px;border-radius:8px;font-weight:700;text-decoration:none}
|
||||
.btn:hover{background:#1be5ff}
|
||||
.section h2{font-size:36px;font-weight:700;margin-bottom:24px}
|
||||
.card{background:var(--gray-100);border-radius:16px;padding:32px;margin-bottom:16px}
|
||||
@media (max-width:640px){.hero h1{font-size:36px}.section h2{font-size:28px}.container{padding:48px 20px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<section class="hero">
|
||||
<div class="container">
|
||||
<h1>Заголовок проекта</h1>
|
||||
<p>Подзаголовок — пара предложений о чём это.</p>
|
||||
<a class="btn" href="#section">Начать</a>
|
||||
</div>
|
||||
</section>
|
||||
<section id="section" class="section">
|
||||
<div class="container">
|
||||
<h2>Секция</h2>
|
||||
<div class="card">Контент карточки.</div>
|
||||
<div class="card">Контент карточки.</div>
|
||||
</div>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## Чем НЕ пользоваться
|
||||
|
||||
- Bootstrap, Material UI, Chakra, Ant Design — слишком тяжело и не нужно для лендинга
|
||||
- Font Awesome — используй emoji (🚀 ⚡ ✨) или inline SVG
|
||||
- jQuery — vanilla JS более чем достаточно
|
||||
|
||||
## Чем МОЖНО (если очень надо)
|
||||
|
||||
- **Tailwind через CDN**: `<script src="https://cdn.tailwindcss.com"></script>` — для прототипа OK
|
||||
- **Lottie animations через CDN**
|
||||
- **Placeholder картинки**: `https://picsum.photos/800/600`, `https://placehold.co/600x400`
|
||||
- **Шрифты Google Fonts через `<link>`** в head
|
||||
144
index.html
Normal file
144
index.html
Normal file
@ -0,0 +1,144 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>HSE Assistant — Обучение ТБ</title>
|
||||
<style>
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#1a1a2e;background:#f0f2f5}
|
||||
header{background:#1a1a2e;color:#fff;padding:12px 20px;position:sticky;top:0;z-index:100;display:flex;justify-content:space-between;align-items:center}
|
||||
header .logo{color:#00d4ff;font-weight:700;font-size:18px}
|
||||
.container{max-width:1200px;margin:0 auto;padding:16px}
|
||||
.tabs{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap}
|
||||
.tab-btn{padding:10px 18px;border:2px solid #1a1a2e;background:transparent;border-radius:8px;cursor:pointer;font-size:14px;font-weight:600;transition:all .2s}
|
||||
.tab-btn.active{background:#00d4ff;color:#1a1a2e;border-color:#00d4ff}
|
||||
.card{background:#fff;border-radius:12px;padding:20px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,.08)}
|
||||
.btn{display:inline-block;background:#00d4ff;color:#1a1a2e;padding:10px 20px;border-radius:8px;font-weight:700;border:none;cursor:pointer;font-size:14px;text-decoration:none}
|
||||
.btn:hover{opacity:.85}
|
||||
.btn-danger{background:#ef4444;color:#fff}
|
||||
.btn-green{background:#22c55e;color:#fff}
|
||||
.input{padding:10px 14px;border:2px solid #e2e8f0;border-radius:8px;font-size:14px;outline:none;width:100%}
|
||||
.input:focus{border-color:#00d4ff}
|
||||
select.input{max-width:200px}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
th{background:#f8fafc;padding:10px 12px;text-align:left;font-weight:600;border-bottom:2px solid #e2e8f0}
|
||||
td{padding:10px 12px;border-bottom:1px solid #f1f5f9}
|
||||
.progress{height:8px;background:#e2e8f0;border-radius:4px;overflow:hidden}
|
||||
.progress-fill{height:100%;background:#00d4ff;border-radius:4px}
|
||||
.ok{color:#22c55e;font-weight:600}
|
||||
.warn{color:#f59e0b;font-weight:600}
|
||||
.danger{color:#ef4444;font-weight:600}
|
||||
.grid{display:grid;gap:12px}
|
||||
.grid-2{grid-template-columns:repeat(2,1fr)}
|
||||
.grid-3{grid-template-columns:repeat(3,1fr)}
|
||||
.grid-4{grid-template-columns:repeat(4,1fr)}
|
||||
@media(max-width:768px){.grid-2,.grid-3,.grid-4{grid-template-columns:1fr}.tabs{gap:4px}.tab-btn{padding:8px 12px;font-size:12px}}
|
||||
.stat-card{text-align:center;padding:16px}
|
||||
.stat-num{font-size:28px;font-weight:700}
|
||||
.stat-label{font-size:12px;color:#64748b;margin-top:4px}
|
||||
.upload-area{background:#eff6ff;border:2px dashed #3b82f6;border-radius:12px;padding:20px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}
|
||||
.flex{display:flex;gap:12px;align-items:center;flex-wrap:wrap}
|
||||
.hidden{display:none!important}
|
||||
.msg{padding:10px 14px;border-radius:8px;font-size:13px;margin-top:8px}
|
||||
.msg-ok{background:#f0fdf4;color:#166534;border:1px solid #bbf7d0}
|
||||
.msg-err{background:#fef2f2;color:#991b1b;border:1px solid #fecaca}
|
||||
.city-card{cursor:pointer;padding:16px;border:2px solid transparent;transition:all .2s}
|
||||
.city-card:hover{border-color:#00d4ff}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<div class="logo">🛡️ HSE Assistant</div>
|
||||
<div style="font-size:12px;color:#94a3b8">Система учёта обучения ТБ</div>
|
||||
</header>
|
||||
|
||||
<div class="container">
|
||||
<!-- TABS -->
|
||||
<div class="tabs" id="tabs">
|
||||
<button class="tab-btn active" onclick="showTab('dashboard')">📊 Дашборд</button>
|
||||
<button class="tab-btn" onclick="showTab('search')">🔍 Поиск</button>
|
||||
<button class="tab-btn" onclick="showTab('region')">🏙️ По регионам</button>
|
||||
<button class="tab-btn" onclick="showTab('export')">📥 Выгрузка</button>
|
||||
</div>
|
||||
|
||||
<!-- DASHBOARD TAB -->
|
||||
<div id="tab-dashboard">
|
||||
<div class="card">
|
||||
<div class="upload-area">
|
||||
<div>
|
||||
<div style="font-weight:700;font-size:15px">📤 Загрузка данных</div>
|
||||
<div style="font-size:13px;color:#64748b">Загрузите Excel (.xlsx) или CSV файл</div>
|
||||
</div>
|
||||
<label style="cursor:pointer">
|
||||
<div class="btn">📁 Выбрать файл</div>
|
||||
<input type="file" id="file-upload" accept=".csv,.xlsx" style="display:none" onchange="handleFileUpload(event)">
|
||||
</label>
|
||||
</div>
|
||||
<div id="upload-results"></div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-4" id="dash-stats"></div>
|
||||
|
||||
<div class="grid grid-2">
|
||||
<div class="card">
|
||||
<h3 style="margin-bottom:12px">Проблемные филиалы</h3>
|
||||
<div id="dash-problems"></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3 style="margin-bottom:12px">Самые непройденные курсы</h3>
|
||||
<div id="dash-courses"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- SEARCH TAB -->
|
||||
<div id="tab-search" class="hidden">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:14px">Поиск сотрудника</h2>
|
||||
<div class="flex">
|
||||
<input type="text" id="search-input" class="input" placeholder="Таб.№ или ФИО" style="max-width:400px">
|
||||
<select id="filter-city" class="input">
|
||||
<option value="">Все города</option>
|
||||
<option>Алматы</option>
|
||||
<option>Астана</option>
|
||||
<option>Атырау</option>
|
||||
<option>Актау</option>
|
||||
<option>Караганда</option>
|
||||
<option>Шымкент</option>
|
||||
</select>
|
||||
<button onclick="searchEmployee()" class="btn">Найти</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="search-results"></div>
|
||||
</div>
|
||||
|
||||
<!-- REGION TAB -->
|
||||
<div id="tab-region" class="hidden">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:14px">Сотрудники по филиалам</h2>
|
||||
<div class="grid grid-3" id="city-stats"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- EXPORT TAB -->
|
||||
<div id="tab-export" class="hidden">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:14px">📥 Выгрузка данных</h2>
|
||||
<div class="flex" style="margin-bottom:12px">
|
||||
<button onclick="exportData('overdue')" class="btn btn-danger">⏰ Просроченные</button>
|
||||
<button onclick="exportData('city')" class="btn">🏙️ По филиалу</button>
|
||||
<button onclick="exportData('employee')" class="btn">👤 По сотруднику</button>
|
||||
<button onclick="exportData('summary')" class="btn">📋 Сводный отчёт</button>
|
||||
<button onclick="exportCSV()" class="btn btn-green">📊 Экспорт CSV</button>
|
||||
</div>
|
||||
<div id="export-results"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
|
||||
<script src="script.js?v=3"></script>
|
||||
</body>
|
||||
</html>
|
||||
419
script.js
Normal file
419
script.js
Normal file
@ -0,0 +1,419 @@
|
||||
// ========== ДАННЫЕ ==========
|
||||
const COURSES = [
|
||||
{ id: 1, name: "Безопасная рабочая среда SWE 2", level: 2, periodicity: 12 },
|
||||
{ id: 2, name: "Безопасное вождение (Defensive Driving)", level: 2, periodicity: 24 },
|
||||
{ id: 3, name: "Безопасное выполнение земляных работ", level: 1, periodicity: 12 },
|
||||
{ id: 4, name: "Безопасное выполнение работ на лестницах", level: 1, periodicity: 12 },
|
||||
{ id: 5, name: "Безопасное выполнение работ на опорах", level: 1, periodicity: 12 },
|
||||
{ id: 6, name: "Безопасность рук", level: 2, periodicity: 12 },
|
||||
{ id: 7, name: "Изоляция источников энергии (LOTO)", level: 1, periodicity: 12 },
|
||||
{ id: 8, name: "Контроль усталости", level: 1, periodicity: 6 },
|
||||
{ id: 9, name: "Культура безопасности труда", level: 2, periodicity: 24 },
|
||||
{ id: 10, name: "Оказание первой медицинской помощи", level: 1, periodicity: 24 },
|
||||
{ id: 11, name: "Основы безопасности в замкнутом пространстве", level: 2, periodicity: 12 },
|
||||
{ id: 12, name: "Основы безопасности на высоте", level: 2, periodicity: 12 },
|
||||
{ id: 13, name: "Поведенческие аудиты безопасности", level: 2, periodicity: 12 },
|
||||
{ id: 14, name: "Предотвращение травматизма IPR", level: 1, periodicity: 12 },
|
||||
{ id: 15, name: "Предотвращение травматизма IPR (углублённый)", level: 2, periodicity: 12 },
|
||||
{ id: 16, name: "Расследование инцидентов", level: 1, periodicity: 12 },
|
||||
{ id: 17, name: "Управление опасностями и рисками", level: 1, periodicity: 12 },
|
||||
{ id: 18, name: "Устойчивое развитие и экология", level: 1, periodicity: 24 },
|
||||
{ id: 19, name: "Фасилитатор в HSE", level: 2, periodicity: 24 },
|
||||
{ id: 20, name: "Четырёхступенчатый контроль (1 ступень)", level: 1, periodicity: 12 },
|
||||
{ id: 21, name: "Четырёхступенчатый контроль (2 ступень)", level: 1, periodicity: 12 },
|
||||
{ id: 22, name: "Четырёхступенчатый контроль (3 ступень)", level: 1, periodicity: 12 },
|
||||
{ id: 23, name: "Четырёхступенчатый контроль (4 ступень)", level: 1, periodicity: 12 }
|
||||
];
|
||||
|
||||
const CITIES = ["Алматы", "Астана", "Атырау", "Актау", "Караганда", "Шымкент"];
|
||||
const DEPARTMENTS = ["HSE", "Производство", "Логистика", "Администрация", "Техническая служба", "Электроснабжение"];
|
||||
const POSITIONS = ["Инженер HSE", "Мастер", "Электромонтёр", "Слесарь", "Водитель", "Начальник смены", "Техник"];
|
||||
|
||||
function generateEmployees() {
|
||||
const employees = [];
|
||||
const lastNames = ["Иванов", "Петров", "Сидоров", "Козлов", "Новиков", "Морозов", "Волков", "Соколов", "Лебедев", "Кузнецов", "Попов", "Васильев", "Зайцев", "Михайлов", "Фёдоров", "Абдуллин", "Нурланов", "Сагиев", "Турсунов", "Касымов", "Жумабаев", "Ермеков", "Баймуханов", "Алиев", "Хасенов"];
|
||||
const firstNames = ["Александр", "Дмитрий", "Сергей", "Андрей", "Михаил", "Ильяс", "Данияр", "Артём", "Руслан", "Нурсултан", "Айдар", "Ерлан", "Булат", "Тимур", "Арман", "Мадияр", "Самат", "Кайрат", "Ержан", "Аслан"];
|
||||
const patronymics = ["Александрович", "Дмитриевич", "Сергеевич", "Андреевич", "Михайлович", "Ильясович", "Даниярович", "Артёмович", "Русланович", "Нурсултанович"];
|
||||
|
||||
let tab = 1001;
|
||||
for (let city of CITIES) {
|
||||
const count = 8 + Math.floor(Math.random() * 7);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const emp = {
|
||||
tab: String(tab++),
|
||||
lastName: lastNames[Math.floor(Math.random() * lastNames.length)],
|
||||
firstName: firstNames[Math.floor(Math.random() * firstNames.length)],
|
||||
patronymic: patronymics[Math.floor(Math.random() * patronymics.length)],
|
||||
city: city,
|
||||
department: DEPARTMENTS[Math.floor(Math.random() * DEPARTMENTS.length)],
|
||||
position: POSITIONS[Math.floor(Math.random() * POSITIONS.length)],
|
||||
courses: []
|
||||
};
|
||||
emp.fullName = emp.lastName + ' ' + emp.firstName + ' ' + emp.patronymic;
|
||||
|
||||
const courseCount = 5 + Math.floor(Math.random() * 10);
|
||||
const shuffled = [...COURSES].sort(() => 0.5 - Math.random());
|
||||
for (let j = 0; j < Math.min(courseCount, COURSES.length); j++) {
|
||||
const course = shuffled[j];
|
||||
const completed = Math.random() > 0.3;
|
||||
if (completed) {
|
||||
const monthsAgo = Math.floor(Math.random() * 36);
|
||||
const completedDate = new Date();
|
||||
completedDate.setMonth(completedDate.getMonth() - monthsAgo);
|
||||
const nextDate = new Date(completedDate);
|
||||
nextDate.setMonth(nextDate.getMonth() + course.periodicity);
|
||||
const isOverdue = nextDate < new Date();
|
||||
emp.courses.push({
|
||||
courseId: course.id,
|
||||
courseName: course.name,
|
||||
level: course.level,
|
||||
completed: true,
|
||||
completedDate: completedDate.toISOString().split('T')[0],
|
||||
nextDate: nextDate.toISOString().split('T')[0],
|
||||
overdue: isOverdue,
|
||||
daysOverdue: isOverdue ? Math.floor((new Date() - nextDate) / 86400000) : 0
|
||||
});
|
||||
} else {
|
||||
emp.courses.push({
|
||||
courseId: course.id,
|
||||
courseName: course.name,
|
||||
level: course.level,
|
||||
completed: false,
|
||||
completedDate: null,
|
||||
nextDate: null,
|
||||
overdue: false,
|
||||
daysOverdue: 0
|
||||
});
|
||||
}
|
||||
}
|
||||
employees.push(emp);
|
||||
}
|
||||
}
|
||||
return employees;
|
||||
}
|
||||
|
||||
let EMPLOYEES = generateEmployees();
|
||||
|
||||
// ========== ТАБЫ ==========
|
||||
function showTab(name) {
|
||||
['dashboard', 'search', 'region', 'export'].forEach(t => {
|
||||
document.getElementById('tab-' + t).classList.toggle('hidden', t !== name);
|
||||
});
|
||||
document.querySelectorAll('.tab-btn').forEach((btn, i) => {
|
||||
const tabs = ['dashboard', 'search', 'region', 'export'];
|
||||
btn.classList.toggle('active', tabs[i] === name);
|
||||
});
|
||||
if (name === 'dashboard') { renderDashboard(); renderCityStats(); }
|
||||
if (name === 'region') renderCityStats();
|
||||
}
|
||||
|
||||
// ========== ПОИСК ==========
|
||||
function searchEmployee() {
|
||||
const query = document.getElementById('search-input').value.trim().toLowerCase();
|
||||
const cityFilter = document.getElementById('filter-city').value;
|
||||
let results = EMPLOYEES;
|
||||
if (query) results = results.filter(e => e.tab === query || e.fullName.toLowerCase().includes(query));
|
||||
if (cityFilter) results = results.filter(e => e.city === cityFilter);
|
||||
renderSearchResults(results);
|
||||
}
|
||||
|
||||
function renderSearchResults(employees) {
|
||||
const c = document.getElementById('search-results');
|
||||
if (!employees.length) { c.innerHTML = '<div class="card">Сотрудники не найдены</div>'; return; }
|
||||
|
||||
let h = '<div class="card" style="overflow-x:auto"><table><thead><tr><th>Таб.№</th><th>ФИО</th><th>Город</th><th>Должность</th><th>Пройдено</th><th>Просрочено</th><th>Прогресс</th><th></th></tr></thead><tbody>';
|
||||
for (const e of employees) {
|
||||
const done = e.courses.filter(c => c.completed).length;
|
||||
const ov = e.courses.filter(c => c.overdue).length;
|
||||
const pct = Math.round((done / e.courses.length) * 100);
|
||||
h += '<tr><td style="font-family:monospace">' + e.tab + '</td><td><strong>' + e.fullName + '</strong></td><td>' + e.city + '</td><td>' + e.position + '</td><td class="ok">' + done + '/' + e.courses.length + '</td><td class="' + (ov ? 'danger' : '') + '">' + (ov ? '❌ ' + ov : '✅') + '</td><td><div style="display:flex;align-items:center;gap:8px"><div class="progress" style="flex:1"><div class="progress-fill" style="width:' + pct + '%"></div></div><span style="font-size:12px">' + pct + '%</span></div></td><td><button onclick="showDetail(\'' + e.tab + '\')" class="btn" style="padding:6px 12px;font-size:12px">Подробнее</button></td></tr>';
|
||||
}
|
||||
h += '</tbody></table></div>';
|
||||
c.innerHTML = h;
|
||||
}
|
||||
|
||||
function showDetail(tab) {
|
||||
const emp = EMPLOYEES.find(e => e.tab === tab);
|
||||
if (!emp) return;
|
||||
const c = document.getElementById('search-results');
|
||||
const done = emp.courses.filter(c => c.completed);
|
||||
const notDone = emp.courses.filter(c => !c.completed);
|
||||
const overdue = done.filter(c => c.overdue);
|
||||
const valid = done.filter(c => !c.overdue);
|
||||
const pct = Math.round((done.length / emp.courses.length) * 100);
|
||||
|
||||
let h = '<div class="card"><button onclick="searchEmployee()" class="btn" style="padding:6px 12px;font-size:12px;margin-bottom:16px">← Назад</button>';
|
||||
h += '<div class="flex" style="margin-bottom:16px;gap:24px"><div><span style="color:#64748b">Таб.№:</span> <strong>' + emp.tab + '</strong></div><div><span style="color:#64748b">Город:</span> <strong>' + emp.city + '</strong></div><div><span style="color:#64748b">Должность:</span> <strong>' + emp.position + '</strong></div><div><span style="color:#64748b">Подразделение:</span> <strong>' + emp.department + '</strong></div></div>';
|
||||
h += '<div style="margin-bottom:16px"><div style="display:flex;justify-content:space-between;margin-bottom:6px"><strong>Общий прогресс</strong><span>' + done.length + ' из ' + emp.courses.length + ' (' + pct + '%)</span></div><div class="progress" style="height:12px"><div class="progress-fill" style="width:' + pct + '%"></div></div></div>';
|
||||
|
||||
if (overdue.length) {
|
||||
h += '<div style="margin-bottom:16px"><h3 class="danger" style="margin-bottom:8px">⏰ Просрочено (' + overdue.length + ')</h3><table><thead><tr><th>Курс</th><th>Уровень</th><th>Завершён</th><th>Должен пройти</th><th>Просрочка</th></tr></thead><tbody>';
|
||||
for (const c of overdue) h += '<tr><td>' + c.courseName + '</td><td>Ур.' + c.level + '</td><td>' + fmt(c.completedDate) + '</td><td>' + fmt(c.nextDate) + '</td><td class="danger">⚠️ ' + c.daysOverdue + ' дн.</td></tr>';
|
||||
h += '</tbody></table></div>';
|
||||
}
|
||||
if (valid.length) {
|
||||
h += '<div style="margin-bottom:16px"><h3 class="ok" style="margin-bottom:8px">✅ Действует (' + valid.length + ')</h3><table><thead><tr><th>Курс</th><th>Уровень</th><th>Завершён</th><th>Следующее</th></tr></thead><tbody>';
|
||||
for (const c of valid) {
|
||||
const left = Math.ceil((new Date(c.nextDate) - new Date()) / 86400000);
|
||||
const urg = left <= 30 ? ' class="warn"' : '';
|
||||
h += '<tr><td>' + c.courseName + '</td><td>Ур.' + c.level + '</td><td>' + fmt(c.completedDate) + '</td><td' + urg + '>' + fmt(c.nextDate) + (left <= 30 ? ' ⚠️ ' + left + ' дн.' : '') + '</td></tr>';
|
||||
}
|
||||
h += '</tbody></table></div>';
|
||||
}
|
||||
if (notDone.length) {
|
||||
h += '<div><h3 style="color:#64748b;margin-bottom:8px">❗ Не пройдено (' + notDone.length + ')</h3><ul style="padding-left:20px;color:#64748b">';
|
||||
for (const c of notDone) h += '<li>' + c.courseName + ' (Ур.' + c.level + ')</li>';
|
||||
h += '</ul></div>';
|
||||
}
|
||||
h += '</div>';
|
||||
c.innerHTML = h;
|
||||
}
|
||||
|
||||
function fmt(d) { if (!d) return '—'; const [y, m, dd] = d.split('-'); return dd + '.' + m + '.' + y; }
|
||||
|
||||
// ========== РЕГИОНЫ ==========
|
||||
function renderCityStats() {
|
||||
const c = document.getElementById('city-stats');
|
||||
const stats = CITIES.map(city => {
|
||||
const emps = EMPLOYEES.filter(e => e.city === city);
|
||||
const total = emps.reduce((s, e) => s + e.courses.length, 0);
|
||||
const done = emps.reduce((s, e) => s + e.courses.filter(c => c.completed).length, 0);
|
||||
const ov = emps.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||
return { city, count: emps.length, pct: total ? Math.round((done / total) * 100) : 0, overdue: ov };
|
||||
});
|
||||
c.innerHTML = stats.map(s =>
|
||||
'<div class="card city-card" onclick="showCity(\'' + s.city + '\')">' +
|
||||
'<div style="font-size:24px;font-weight:700">' + s.count + '</div>' +
|
||||
'<div style="font-size:13px;color:#64748b">' + s.city + '</div>' +
|
||||
'<div class="progress" style="margin-top:8px"><div class="progress-fill" style="width:' + s.pct + '%"></div></div>' +
|
||||
'<div style="font-size:11px;margin-top:4px">' + s.pct + '% выполнено' + (s.overdue ? ' <span class="danger">| ' + s.overdue + ' просрочено</span>' : '') + '</div>' +
|
||||
'</div>'
|
||||
).join('');
|
||||
}
|
||||
|
||||
function showCity(city) {
|
||||
showTab('search');
|
||||
renderSearchResults(EMPLOYEES.filter(e => e.city === city));
|
||||
}
|
||||
|
||||
// ========== ЗАГРУЗКА ==========
|
||||
function handleFileUpload(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
const ext = file.name.split('.').pop().toLowerCase();
|
||||
|
||||
reader.onload = function(e) {
|
||||
let data = null;
|
||||
if (ext === 'csv') {
|
||||
data = parseCSV(e.target.result);
|
||||
} else if (ext === 'xlsx') {
|
||||
try { data = parseExcel(e.target.result); } catch (err) { msg('Ошибка Excel: ' + err.message, 'err'); return; }
|
||||
} else { msg('Только .csv и .xlsx', 'err'); return; }
|
||||
|
||||
if (data && data.length) {
|
||||
processData(data);
|
||||
msg('Загружено ' + data.length + ' строк', 'ok');
|
||||
} else { msg('Не удалось распознать данные', 'err'); }
|
||||
};
|
||||
reader.onerror = function() { msg('Ошибка чтения файла', 'err'); };
|
||||
|
||||
if (ext === 'csv') reader.readAsText(file);
|
||||
else reader.readAsArrayBuffer(file);
|
||||
}
|
||||
|
||||
function parseCSV(text) {
|
||||
const lines = text.split(/\r?\n/).filter(l => l.trim());
|
||||
if (lines.length < 2) return null;
|
||||
const headers = lines[0].split(';').map(h => h.trim());
|
||||
const data = [];
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const vals = lines[i].split(';');
|
||||
if (vals.length < 3) continue;
|
||||
const row = {};
|
||||
headers.forEach((h, j) => { if (j < vals.length) row[h] = vals[j]; });
|
||||
data.push(row);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function parseExcel(buf) {
|
||||
const wb = XLSX.read(new Uint8Array(buf), { type: 'array' });
|
||||
const ws = wb.Sheets[wb.SheetNames[0]];
|
||||
const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
|
||||
const headers = (json[0] || []).map(h => String(h).trim());
|
||||
const data = [];
|
||||
for (let i = 1; i < json.length; i++) {
|
||||
if (!json[i] || !json[i].length) continue;
|
||||
const row = {};
|
||||
headers.forEach((h, j) => { if (j < json[i].length) row[h] = json[i][j]; });
|
||||
data.push(row);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function processData(rows) {
|
||||
const emps = [];
|
||||
for (const row of rows) {
|
||||
const emp = {
|
||||
tab: row['Таб.№'] || row['tab'] || row['Табельный'] || '',
|
||||
fullName: row['ФИО'] || '',
|
||||
city: row['Город'] || '',
|
||||
department: row['Подразделение'] || '',
|
||||
position: row['Должность'] || row['Штатная должность'] || '',
|
||||
courses: []
|
||||
};
|
||||
if (!emp.tab || !emp.fullName) continue;
|
||||
|
||||
for (let i = 1; i <= 20; i++) {
|
||||
const name = row['Курс' + i] || row['Курс ' + i];
|
||||
if (!name) break;
|
||||
const status = (row['Статус' + i] || row['Статус ' + i] || '').toLowerCase();
|
||||
const dateStr = row['Дата' + i] || row['Дата ' + i] || '';
|
||||
const completed = status === 'пройдено' || status === 'yes' || status === 'true' || status === '1';
|
||||
const course = { courseId: i, courseName: name, level: 1, completed, completedDate: null, nextDate: null, overdue: false, daysOverdue: 0 };
|
||||
|
||||
if (completed && dateStr) {
|
||||
let d, m, y;
|
||||
if (typeof dateStr === 'number') {
|
||||
const excelDate = new Date((dateStr - 25569) * 86400000);
|
||||
d = String(excelDate.getDate()).padStart(2, '0');
|
||||
m = String(excelDate.getMonth() + 1).padStart(2, '0');
|
||||
y = excelDate.getFullYear();
|
||||
} else {
|
||||
const match = String(dateStr).match(/(\d{1,2})[\.\/\-](\d{1,2})[\.\/\-](\d{2,4})/);
|
||||
if (match) { d = match[1].padStart(2, '0'); m = match[2].padStart(2, '0'); y = match[3].length === 2 ? '20' + match[3] : match[3]; }
|
||||
}
|
||||
if (d && m && y) {
|
||||
course.completedDate = y + '-' + m + '-' + d;
|
||||
const next = new Date(+y, +m - 1, +d);
|
||||
next.setMonth(next.getMonth() + 12);
|
||||
course.nextDate = next.toISOString().split('T')[0];
|
||||
course.overdue = next < new Date();
|
||||
course.daysOverdue = course.overdue ? Math.floor((new Date() - next) / 86400000) : 0;
|
||||
}
|
||||
}
|
||||
emp.courses.push(course);
|
||||
}
|
||||
emps.push(emp);
|
||||
}
|
||||
EMPLOYEES = emps;
|
||||
localStorage.setItem('tb_data', JSON.stringify(emps));
|
||||
renderDashboard();
|
||||
renderCityStats();
|
||||
}
|
||||
|
||||
function msg(text, type) {
|
||||
const c = document.getElementById('upload-results');
|
||||
const d = document.createElement('div');
|
||||
d.className = 'msg ' + (type === 'ok' ? 'msg-ok' : 'msg-err');
|
||||
d.textContent = text;
|
||||
c.prepend(d);
|
||||
if (type === 'ok') setTimeout(() => d.remove(), 5000);
|
||||
}
|
||||
|
||||
// ========== ДАШБОРД ==========
|
||||
function renderDashboard() {
|
||||
const total = EMPLOYEES.length;
|
||||
const allCourses = EMPLOYEES.reduce((s, e) => s + e.courses.length, 0);
|
||||
const done = EMPLOYEES.reduce((s, e) => s + e.courses.filter(c => c.completed).length, 0);
|
||||
const ov = EMPLOYEES.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||
const notStarted = EMPLOYEES.reduce((s, e) => s + e.courses.filter(c => !c.completed).length, 0);
|
||||
const pct = allCourses ? Math.round((done / allCourses) * 100) : 0;
|
||||
|
||||
document.getElementById('dash-stats').innerHTML =
|
||||
'<div class="card stat-card"><div class="stat-num">' + total + '</div><div class="stat-label">Сотрудников</div></div>' +
|
||||
'<div class="card stat-card"><div class="stat-num">' + pct + '%</div><div class="stat-label">Выполнено</div></div>' +
|
||||
'<div class="card stat-card"><div class="stat-num" style="color:#ef4444">' + ov + '</div><div class="stat-label">Просрочено</div></div>' +
|
||||
'<div class="card stat-card"><div class="stat-num" style="color:#f59e0b">' + notStarted + '</div><div class="stat-label">Не начато</div></div>';
|
||||
|
||||
const cs = CITIES.map(city => {
|
||||
const emps = EMPLOYEES.filter(e => e.city === city);
|
||||
const o = emps.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||
const t = emps.reduce((s, e) => s + e.courses.length, 0);
|
||||
return { city, overdue: o, pct: t ? Math.round((o / t) * 100) : 0 };
|
||||
}).sort((a, b) => b.pct - a.pct);
|
||||
|
||||
document.getElementById('dash-problems').innerHTML = cs.map((s, i) =>
|
||||
'<div style="display:flex;justify-content:space-between;padding:8px 0' + (i < cs.length - 1 ? ';border-bottom:1px solid #f1f5f9' : '') + '">' +
|
||||
'<span>' + (i + 1) + '. ' + s.city + '</span><span class="danger">' + s.pct + '% просрочено (' + s.overdue + ')</span></div>'
|
||||
).join('');
|
||||
|
||||
const crs = COURSES.map(c => {
|
||||
const notDone = EMPLOYEES.filter(e => !e.courses.find(cc => cc.courseId === c.id && cc.completed)).length;
|
||||
return { name: c.name, pct: Math.round((notDone / total) * 100) };
|
||||
}).sort((a, b) => b.pct - a.pct).slice(0, 5);
|
||||
|
||||
document.getElementById('dash-courses').innerHTML = crs.map((s, i) =>
|
||||
'<div style="display:flex;justify-content:space-between;padding:8px 0;font-size:13px' + (i < crs.length - 1 ? ';border-bottom:1px solid #f1f5f9' : '') + '">' +
|
||||
'<span>' + (i + 1) + '. ' + s.name + '</span><span class="danger">' + s.pct + '%</span></div>'
|
||||
).join('');
|
||||
}
|
||||
|
||||
// ========== ВЫГРУЗКА ==========
|
||||
function exportData(type) {
|
||||
const c = document.getElementById('export-results');
|
||||
let h = '<div class="card">';
|
||||
let data = [];
|
||||
|
||||
if (type === 'overdue') {
|
||||
h += '<h3 style="margin-bottom:12px">⏰ Просроченные обучения</h3>';
|
||||
EMPLOYEES.forEach(e => e.courses.filter(c => c.overdue).forEach(c =>
|
||||
data.push({ tab: e.tab, fio: e.fullName, city: e.city, course: c.courseName, completed: c.completedDate, overdue: c.nextDate, days: c.daysOverdue })
|
||||
));
|
||||
data.sort((a, b) => b.days - a.days);
|
||||
} else if (type === 'city') {
|
||||
h += '<h3 style="margin-bottom:12px">🏙️ По филиалам</h3>';
|
||||
EMPLOYEES.forEach(e => e.courses.forEach(c =>
|
||||
data.push({ tab: e.tab, fio: e.fullName, city: e.city, course: c.courseName, status: c.completed ? (c.overdue ? 'Просрочено' : 'Пройдено') : 'Не пройдено' })
|
||||
));
|
||||
} else if (type === 'employee') {
|
||||
h += '<h3 style="margin-bottom:12px">👤 По сотрудникам</h3>';
|
||||
EMPLOYEES.forEach(e => {
|
||||
const done = e.courses.filter(c => c.completed).length;
|
||||
const ov = e.courses.filter(c => c.overdue).length;
|
||||
data.push({ tab: e.tab, fio: e.fullName, city: e.city, dept: e.department, total: e.courses.length, done, ov, pct: Math.round((done / e.courses.length) * 100) + '%' });
|
||||
});
|
||||
} else if (type === 'summary') {
|
||||
h += '<h3 style="margin-bottom:12px">📋 Сводный отчёт</h3>';
|
||||
CITIES.forEach(city => {
|
||||
const emps = EMPLOYEES.filter(e => e.city === city);
|
||||
const t = emps.reduce((s, e) => s + e.courses.length, 0);
|
||||
const d = emps.reduce((s, e) => s + e.courses.filter(c => c.completed).length, 0);
|
||||
const o = emps.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||
data.push({ city, employees: emps.length, total: t, done, overdue: o, pct: t ? Math.round((d / t) * 100) + '%' : '0%' });
|
||||
});
|
||||
}
|
||||
|
||||
if (!data.length) { h += '<p style="color:#64748b">Нет данных</p>'; }
|
||||
else {
|
||||
const hdrs = Object.keys(data[0]);
|
||||
h += '<table><thead><tr>' + hdrs.map(x => '<th>' + x + '</th>').join('') + '</tr></thead><tbody>';
|
||||
data.slice(0, 100).forEach(row => { h += '<tr>' + hdrs.map(x => '<td>' + (row[x] || '') + '</td>').join('') + '</tr>'; });
|
||||
h += '</tbody></table>';
|
||||
if (data.length > 100) h += '<p style="font-size:12px;color:#64748b;margin-top:8px">Показано 100 из ' + data.length + '</p>';
|
||||
}
|
||||
h += '</div>';
|
||||
c.innerHTML = h;
|
||||
}
|
||||
|
||||
function exportCSV() {
|
||||
let csv = 'Таб.№;ФИО;Филиал;Должность;Подразделение;Курс;Уровень;Статус;Дата обучения;Следующее;Просрочка дн.\n';
|
||||
EMPLOYEES.forEach(e => e.courses.forEach(c => {
|
||||
const st = c.completed ? (c.overdue ? 'Просрочено' : 'Пройдено') : 'Не пройдено';
|
||||
csv += e.tab + ';' + e.fullName + ';' + e.city + ';' + e.position + ';' + e.department + ';' + c.courseName + ';' + c.level + ';' + st + ';' + (c.completedDate || '') + ';' + (c.nextDate || '') + ';' + (c.daysOverdue || 0) + '\n';
|
||||
}));
|
||||
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = 'training_' + new Date().toISOString().split('T')[0] + '.csv';
|
||||
a.click();
|
||||
}
|
||||
|
||||
// ========== ИНИЦИАЛИЗАЦИЯ ==========
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const saved = localStorage.getItem('tb_data');
|
||||
if (saved) { try { EMPLOYEES = JSON.parse(saved); } catch(e) {} }
|
||||
renderDashboard();
|
||||
renderCityStats();
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user