Compare commits

..

132 Commits

Author SHA1 Message Date
poignatov
60a0efafad 6.27.3: Фикс сброса автовыполнения и прогресс
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m28s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:21:45 +03:00
poignatov
48fa192cdc 6.27.2: Fitbit не меняет auto_complete в драфтах
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:13:33 +03:00
poignatov
06cc1a4b3b 6.27.1: Fitbit не меняет auto_complete в драфтах
Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:12:34 +03:00
poignatov
e2966aedd1 6.27.0: Автовыполнение и прогрессия по-умолчанию
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m32s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:04:45 +03:00
poignatov
d561683e12 6.26.1: Автовыполнение задач сортируется наверх
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m12s
2026-03-20 11:24:13 +03:00
poignatov
fdc3e01443 6.26.0: Объединённый диалог товаров
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m17s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 11:21:47 +03:00
poignatov
d4f0064aa7 6.25.5: Стиль остатка как у подзадач
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m10s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:38:23 +03:00
poignatov
87126a480a 6.25.4: Стиль остатка как у подзадач
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 38s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:36:22 +03:00
poignatov
837ddbe4ed 6.25.4: Карандаш вместо троеточия на карточках
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m8s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:28:56 +03:00
poignatov
44bbb46a1a 6.25.3: Остаток в скобках вместо тильды
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:23:40 +03:00
poignatov
1795a66ee1 6.25.2: Выравнивание текста в селекторе доски
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m7s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:22:06 +03:00
poignatov
84b5aa9390 6.25.1: Иконка архива в селекторе доски
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m9s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:20:37 +03:00
poignatov
e8a766205f 6.25.0: Меню действий для досок вместо кнопок
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m11s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:10:34 +03:00
poignatov
6e7ebb9aa3 6.24.0: Кнопка архива рядом с создать доску
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m11s
2026-03-19 19:22:10 +03:00
poignatov
101f4e27ed 6.23.0: Архивация досок желаний и товаров
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m26s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 18:27:19 +03:00
poignatov
f1c12fd81a 6.22.0: Авторасчёт сроков товаров по истории
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m23s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 11:37:39 +03:00
poignatov
664adcfaa5 6.21.3: Сортировка задач по алфавиту
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m11s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 09:36:45 +03:00
poignatov
8acfaf19ac 6.21.2: Увеличен градиент нижней панели желаний
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m7s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 21:49:33 +03:00
poignatov
2fde471076 6.21.1: Меню действий на экране желания
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m7s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 21:46:46 +03:00
poignatov
5f05b77d36 6.21.0: Копирование товаров и меню действий
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m20s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 21:43:04 +03:00
poignatov
eb68eca63f 6.20.0: Копирование задач и меню действий
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m23s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 21:39:15 +03:00
poignatov
b82db8d80f 6.19.13: Тест сборки
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m9s
2026-03-18 20:30:52 +03:00
poignatov
b3403ff23a 6.19.12: Тест сборки
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m36s
2026-03-18 20:28:05 +03:00
poignatov
b8373eb986 6.19.11: Тест сборки
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m18s
2026-03-18 20:23:45 +03:00
poignatov
df17ecf943 6.19.10: Увеличена область клика кнопки переноса
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m18s
2026-03-18 18:38:14 +03:00
poignatov
42ea241b7c 6.19.9: Ускорение run.sh с BuildKit
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m14s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 17:06:02 +03:00
poignatov
3a06d9148c 6.19.8: Кнопки сохранения досок внизу экрана
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m16s
2026-03-18 16:59:18 +03:00
poignatov
b1f4fdd449 6.19.7: Сброс скролла и загрузка при смене проекта
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m16s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 16:41:55 +03:00
poignatov
01cd0e9003 6.19.6: Кеш-first и отмена запросов при смене доски
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m17s
2026-03-18 16:24:32 +03:00
poignatov
6dc3ec828f 6.19.5: Поднятие патч версии
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m15s
2026-03-17 21:25:23 +03:00
poignatov
0a8ff4dfab 6.19.4: Поднятие патч версии
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m4s
2026-03-17 21:23:01 +03:00
poignatov
dff929c52c 6.19.3: Навигация на редактирование из диалога задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m15s
2026-03-17 10:37:02 +03:00
poignatov
2104fea5e2 6.19.2: Фикс кнопки сохранения в приоритетах
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m18s
2026-03-17 10:29:52 +03:00
poignatov
caa8ac6ebb 6.19.1: Фикс сброса скролла в статистике
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m16s
2026-03-17 10:19:31 +03:00
poignatov
49f67ec36d 6.19.0: Унификация кнопок сохранения в формах
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m18s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 10:08:23 +03:00
poignatov
171befdf05 6.18.17: Откат: скобки и без жирного в подзадачах
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m14s
2026-03-16 16:20:34 +03:00
poignatov
0c6ba5c8fb 6.18.16: Отступ между карточкой и кнопкой в задаче
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m17s
2026-03-16 16:19:08 +03:00
poignatov
1b7e2cd887 6.18.15: Фикс цвета кнопки и отступа снизу в задаче
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m13s
2026-03-16 13:59:29 +03:00
poignatov
53593fdc3d 6.18.14: Убран лишний отступ снизу в карточке задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m14s
2026-03-16 13:56:11 +03:00
poignatov
b888d056e4 Убран лишний отступ снизу в карточке задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 45s
2026-03-16 13:55:14 +03:00
poignatov
cbf20ce679 6.18.13: Фикс стилей кнопок в редактировании задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
2026-03-16 13:54:09 +03:00
poignatov
91bba98b65 6.18.12: Стили кнопок и отступ в редактировании задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m14s
2026-03-16 13:34:06 +03:00
poignatov
c927f55fd6 6.18.11: Фикс сброса скролла на статистике
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m15s
2026-03-16 13:29:55 +03:00
poignatov
ae13b2bcac 6.18.10: Горизонтальный скролл для чипсов на статистике
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m13s
2026-03-16 13:26:59 +03:00
poignatov
85e9a6f48b 6.18.9: Убраны скобки у счётчика подзадач
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m16s
2026-03-16 13:22:40 +03:00
poignatov
7309deb98f 6.18.8: Жирный счётчик выполненных подзадач
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m13s
2026-03-16 08:54:41 +03:00
poignatov
10f370b0da 6.18.7: Фикс замены $name в автовыполнении
Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
2026-03-16 08:53:21 +03:00
poignatov
f59453783a 6.18.6: Отступ снизу для кнопки в тесте и форме задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m16s
2026-03-16 08:48:32 +03:00
poignatov
5ea58476cb 6.18.5: Фиксированные кнопки в формах задачи и желания
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m19s
2026-03-16 07:49:56 +03:00
poignatov
1876595005 6.18.4: Фикс загрузки товаров при создании доски
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m14s
2026-03-15 20:00:12 +03:00
poignatov
a4dcc62a37 6.18.3: Фиксированная кнопка Начать/Завершить в тесте
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m15s
2026-03-15 19:55:50 +03:00
poignatov
8749f21ac8 6.18.2: Фикс навигации назад после создания задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m16s
2026-03-15 18:48:34 +03:00
poignatov
912ae7a857 6.18.1: Фикс логики минуса в полях прогрессии
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m15s
2026-03-15 18:14:41 +03:00
poignatov
7ec76ea59b 6.18.0: Улучшения диалога товара и кнопки прогрессии
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m13s
2026-03-15 18:13:20 +03:00
poignatov
4f69481efe 6.17.5: Кнопка выполнения и тайтл в диалоге товара
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m13s
2026-03-15 18:09:26 +03:00
poignatov
b85b85a27f 6.17.4: Фикс закрытия экрана закупки через history.back
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m14s
2026-03-15 18:04:54 +03:00
poignatov
710adff385 6.17.3: Фикс навигации при редактировании из закупки
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m14s
2026-03-15 18:01:28 +03:00
poignatov
9c915d4675 6.17.2: Навигация закупки и next_show_at для товара
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m29s
2026-03-15 17:54:23 +03:00
poignatov
7e0f979ae3 6.17.1: Общая стратегия по умолчанию в задаче-желании
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m30s
2026-03-15 17:41:56 +03:00
poignatov
d42535f36e 6.17.0: Счётчик подзадач с учётом драфта
Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
2026-03-15 17:41:46 +03:00
poignatov
95985f97f2 6.16.5: Оптимизация выполнения задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 1m39s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 13:14:25 +03:00
poignatov
7889922d9b 6.16.4: Синяя обводка для разблокированных желаний
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m4s
2026-03-13 22:05:05 +03:00
poignatov
97753f4465 6.16.3: Разблокировано вместо Готово
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m25s
2026-03-13 22:00:46 +03:00
poignatov
b1ffb7ba7d 6.16.2: В конце дня вместо скоро
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-13 21:58:21 +03:00
poignatov
c232bb40a3 6.16.1: Обновление статистики после редактирования задачи
Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
2026-03-13 21:57:11 +03:00
poignatov
3bd864d41a 6.16.0: Редактирование записей в статистике
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m24s
2026-03-13 21:48:11 +03:00
poignatov
193b4138d9 6.15.6: Открытие редактирования задачи из статистики
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
2026-03-13 15:49:09 +03:00
poignatov
06b7c614ed 6.15.5: Драфты в статистике текущей недели
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m29s
2026-03-13 15:41:10 +03:00
poignatov
b51b9421be 6.15.4: Подзадачи в драфтах авто-выполнения
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m28s
2026-03-13 15:28:50 +03:00
poignatov
0dca57964d 6.15.3: Фикс обновления данных при редактировании завершённого желания
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m7s
2026-03-13 15:15:01 +03:00
poignatov
95ed1b48fe 6.15.2: Общая стратегия по умолчанию для задач-желаний
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m2s
2026-03-13 14:54:16 +03:00
poignatov
6f76c4a25c 6.15.1: Фикс race condition при смене доски желаний
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m25s
2026-03-13 14:52:07 +03:00
poignatov
c8a47ff408 6.15.0: Драфты авто-выполнения в статистике
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m22s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 14:43:19 +03:00
poignatov
4ce8ba66cc 6.14.2: Фикс nginx маршрута /priorities/confirm на проде
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
2026-03-12 17:27:18 +03:00
poignatov
c42cdfe35b 6.14.1: Фикс nginx маршрута /priorities/confirm на проде
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 36s
2026-03-12 17:23:34 +03:00
poignatov
4971b2a305 6.14.1: Убран хинт 'Открыть статистику'
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m4s
2026-03-12 17:18:36 +03:00
poignatov
64493b9c1f 6.14.0: Еженедельное подтверждение приоритетов
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-12 17:16:57 +03:00
poignatov
1df00bbefd 6.13.1: Фикс обновления текущего дня в статистике
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-12 15:53:22 +03:00
poignatov
0b5106458a 6.13.0: Переменные $name и $subtaskName в сообщениях награды
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-12 15:28:25 +03:00
poignatov
02c8b7537a 6.12.1: Фикс диалога ошибки загрузки
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m8s
2026-03-12 15:20:27 +03:00
poignatov
2a61b17187 6.12.0: Улучшения блока выбора доски в товарах и желаниях
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-11 09:46:41 +03:00
poignatov
3624cfffbd 6.11.5: Стили блока выбора доски в товарах и желаниях
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-11 09:41:27 +03:00
poignatov
a35797a1f9 6.11.4: Товары перенесены из таба в профиль
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m7s
2026-03-11 09:34:36 +03:00
poignatov
20778d6d39 6.11.3: Настройки доски внутри селекта
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
2026-03-11 09:18:56 +03:00
poignatov
ac1f6c3a47 6.11.2: Фикс стилей блока особенностей задачи
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-11 09:14:07 +03:00
poignatov
25f193a061 6.11.1: Фикс моргания кнопки завершения закупки
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m3s
2026-03-11 09:08:40 +03:00
poignatov
ea1720506a 6.11.0: Фикс навигации и переключение типов задач
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m8s
2026-03-11 09:04:11 +03:00
poignatov
dc50433eb1 6.10.0: Синий блок настроек для задач
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 23:49:24 +03:00
poignatov
4b28d90d68 6.9.2: Фикс стилей чекбоксов закупки
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 2m5s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 23:31:25 +03:00
poignatov
fb1ccd7831 6.9.1: Фикс сброса типа задачи при создании
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m8s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 23:08:52 +03:00
poignatov
636f53eb04 6.9.0: Задачи-закупки
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m20s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 22:37:03 +03:00
poignatov
786a03bf86 6.8.3: Последний объём из истории в плейсхолдере
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m20s
2026-03-10 17:57:03 +03:00
poignatov
eb5e5a5476 6.8.2: Перестановка галочки и инпута объёма
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 17:50:55 +03:00
poignatov
ebd1398a81 6.8.1: Фикс истории навигации при закрытии крестиком
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-10 17:18:14 +03:00
poignatov
3cac8d0452 6.8.0: История покупок товаров
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m20s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 17:05:59 +03:00
poignatov
e962f49407 6.7.0: Описание товаров и редизайн выполнения
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m24s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 16:39:23 +03:00
poignatov
79fa0538f9 6.6.4: Очистка истории при закрытии диалога желания
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m3s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 16:17:03 +03:00
poignatov
99b0eba701 6.6.3: Фикс закрытия желания при выполнении задачи
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 16:12:39 +03:00
poignatov
23f16a8bef 6.6.2: Фикс навигации при создании задачи из желания
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
2026-03-10 15:59:05 +03:00
poignatov
a441a3d1e7 6.6.1: Скрытие прошедших дат в товарах
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 15:48:09 +03:00
poignatov
7957776f53 6.6.0: Извлечение ссылки из текста в желании
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-10 15:41:34 +03:00
poignatov
a693d3fa4b 6.5.0: Табы вместо селекта в форме цели
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 22:23:41 +03:00
poignatov
3a1b836ece 6.4.13: Фикс кнопки назад для диалога цели
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 22:08:24 +03:00
poignatov
17e6bbf9f1 6.4.12: Навигация назад по стеку после создания
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m4s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 21:42:18 +03:00
poignatov
c9a8b994eb 6.4.11: Фикс кнопки назад для диалога желания
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
2026-03-09 21:36:34 +03:00
poignatov
b47d50f51c 6.4.10: Фикс закрытия диалога желания при создании задачи
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m4s
2026-03-09 21:10:02 +03:00
poignatov
37d5c87a55 6.4.9: Скрытие даты для товаров с прошедшей датой
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m11s
2026-03-09 21:04:21 +03:00
poignatov
c911950cc1 6.4.8: Фикс кнопки назад при создании словаря
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m3s
2026-03-08 19:56:25 +03:00
poignatov
2ec5860d78 6.4.7: Фикс закрытия диалога желания при закрытии задачи
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-08 19:51:36 +03:00
poignatov
5d257cd0f8 6.4.6: Поднятие патч версии
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-08 19:37:39 +03:00
poignatov
e7ce7b2092 6.4.5: Фикс чипса Сегодня для товаров без даты
Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
2026-03-08 19:37:06 +03:00
poignatov
81de26e586 6.4.4: Логика чипсов и кнопки Без даты
Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
2026-03-08 19:36:45 +03:00
poignatov
4169285394 6.4.3: Фоновое обновление досок при наличии кеша
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m4s
2026-03-08 19:30:56 +03:00
poignatov
c8fead4034 6.4.2: Закрытие диалогов кнопкой назад (товары)
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-08 19:25:35 +03:00
poignatov
01631ff13b 6.4.1: Сброс формы товара при закрытии
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-08 19:20:33 +03:00
poignatov
60fca2d93c 6.4.0: Экран товаров (Shopping List)
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m22s
2026-03-08 16:11:08 +03:00
poignatov
cd51b097c8 6.3.10: Фикс зоны клика кнопок прогрессии
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m2s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:17:38 +03:00
poignatov
fd416b4bd5 6.3.9: Поднятие патч версии
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
2026-03-08 14:13:25 +03:00
poignatov
537ad9e06e 6.3.8: Фикс визуала кнопок прогрессии
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 34s
2026-03-08 14:00:27 +03:00
poignatov
b0155e6cbe 6.3.8: Увеличена зона клика кнопок +/- прогрессии
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m4s
2026-03-08 13:57:56 +03:00
poignatov
999fa15267 6.3.7: Поднятие патч версии
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
2026-03-08 13:53:54 +03:00
poignatov
67334dde3c 6.3.6: Фикс подстановки base_progress при авто-выполнении
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 58s
2026-03-08 13:52:06 +03:00
poignatov
7e51b0cb9f 6.3.6: Авто-подстановка base_progress в драфт
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-08 12:57:59 +03:00
poignatov
3a6f223aac 6.3.5: Фикс пустого таба и ошибки после авторизации
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m6s
2026-03-08 12:51:44 +03:00
poignatov
e1b6fcb918 6.3.4: Сброс на current при рестарте PWA
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m8s
2026-03-08 12:41:25 +03:00
poignatov
f54a0fff14 6.3.3: Фикс навигации при перезапуске PWA
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-07 20:13:16 +03:00
poignatov
80800da839 6.3.2: Буст × 1.2 для группы остальных приоритетов
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-07 19:35:36 +03:00
poignatov
c7b684491c 6.3.1: Буст Group2 × 1.2, max 120%
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m32s
2026-03-07 19:29:19 +03:00
poignatov
7f51411175 6.3.0: Готовые желания на экране прогресса недели
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m19s
2026-03-05 19:41:43 +03:00
poignatov
25317997e5 6.2.0: Срок разблокировки в днях в карточках желаний
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m4s
2026-03-05 18:34:40 +03:00
poignatov
7c5b80b314 6.1.0: Редизайн карточек желаний на экране прогресса
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m20s
2026-03-05 18:30:49 +03:00
poignatov
368f10bcdd 6.0.2: Учёт pending-баллов на желаниях, чёрный текст 2026-03-05 18:08:29 +03:00
69 changed files with 10884 additions and 1319 deletions

8
.claude/settings.json Normal file
View File

@@ -0,0 +1,8 @@
{
"permissions": {
"allow": [
"Bash(curl -s -o /dev/null -w \"%{http_code}\" http://localhost:8080/priorities/confirm)",
"Bash(curl -s -o /dev/null -w \"%{http_code}\" -X POST http://localhost:8080/priorities/confirm -H \"Content-Type: application/json\" -d '[]')"
]
}
}

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"claudeCode.allowDangerouslySkipPermissions": true
}

65
CLAUDE.md Normal file
View File

@@ -0,0 +1,65 @@
# Правила проекта
## Миграции базы данных
**ВАЖНО:** Если меняется структура базы данных — пиши НОВУЮ миграцию.
НИ В КОЕМ СЛУЧАЕ не меняй старые миграции, можно добавлять только новые.
Старой миграцией считается та, что была уже ранее закоммичена.
## Перезапуск приложения после изменений
После применения всех изменений в бэкенде (`play-life-backend/`) или фронтенде (`play-life-web/`), а также после изменений в `docker-compose.yml`, **ОБЯЗАТЕЛЬНО** выполни команду `./run.sh` для перезапуска всех сервисов.
Применяется при работе с:
- Go кодом в `play-life-backend/`
- Миграциями базы данных в `play-life-backend/migrations/`
- React компонентами и стилями в `play-life-web/src/`
- Docker конфигурациями (`docker-compose.yml`, `Dockerfile`)
При изменениях в `play-life-llm/` (если LLM запущен на этой машине) выполни `./runLLM.sh`.
**Команды:** `./run.sh` (web + backend + db) или `bash run.sh` в корне проекта. Для LLM: `./runLLM.sh`.
## Поднятие версии и пуш
Когда пользователь просит **поднять версию и запушить**:
### 1. Определи тип версии
- **major** — первая цифра (1.1.1 → 2.0.0), минор и патч обнуляются
- **minor** — вторая цифра (1.0.1 → 1.1.0), патч обнуляется
- **patch** — третья цифра (1.0.0 → 1.0.1)
Любая часть версии может быть больше 9 (10, 11, 12 и т.д.).
**Если тип версии непонятен из контекста — обязательно спроси у пользователя!**
### 2. Обнови версию в файлах
- `VERSION` (в корне проекта)
- `play-life-web/package.json` (поле `"version"`)
### 3. Составь commit message
Выполни `git diff --staged` и `git diff`, проанализируй изменения. Составь **короткий commit message** (максимум 50 символов) на русском языке. Формат: `"1.2.3: Описание изменений"`.
### 4. Закоммить и запушить
```bash
git add -A
git commit -m "<commit message>"
git push
```
## Пуш без поднятия версии
Когда пользователь просит просто запушить (без поднятия версии):
1. Выполни `git diff --staged` и `git diff`, составь короткий commit message на русском (максимум 50 символов)
2. `git add -A && git commit -m "<commit message>" && git push`
**Примеры:**
- "Подними патч и запушь" → поднять patch
- "Bump minor and push" → поднять minor
- "Подними версию и запушь" → спросить какой тип
- "Запушь изменения" → пушить без изменения версии

View File

@@ -1 +1 @@
6.0.1
6.27.3

View File

@@ -76,7 +76,7 @@ server {
}
# Proxy other API endpoints to backend
location ~ ^/(playlife-feed|d2dc349a-0d13-49b2-a8f0-1ab094bfba9b|projects|message/post|weekly_goals/setup|project_score_sample_mv/refresh)$ {
location ~ ^/(playlife-feed|d2dc349a-0d13-49b2-a8f0-1ab094bfba9b|projects|message/post|weekly_goals/setup|project_score_sample_mv/refresh|priorities/confirm)$ {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
DROP TABLE IF EXISTS shopping_items;
DROP TABLE IF EXISTS shopping_board_members;
DROP TABLE IF EXISTS shopping_boards;

View File

@@ -0,0 +1,50 @@
-- Shopping boards (аналог wishlist_boards)
CREATE TABLE shopping_boards (
id SERIAL PRIMARY KEY,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
invite_token VARCHAR(64) UNIQUE,
invite_enabled BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
deleted BOOLEAN DEFAULT FALSE
);
CREATE INDEX idx_shopping_boards_owner_id ON shopping_boards(owner_id);
CREATE INDEX idx_shopping_boards_invite_token ON shopping_boards(invite_token) WHERE invite_token IS NOT NULL;
CREATE INDEX idx_shopping_boards_owner_deleted ON shopping_boards(owner_id, deleted);
-- Shopping board members (аналог wishlist_board_members)
CREATE TABLE shopping_board_members (
id SERIAL PRIMARY KEY,
board_id INTEGER NOT NULL REFERENCES shopping_boards(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
joined_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT unique_shopping_board_member UNIQUE (board_id, user_id)
);
CREATE INDEX idx_shopping_board_members_board_id ON shopping_board_members(board_id);
CREATE INDEX idx_shopping_board_members_user_id ON shopping_board_members(user_id);
-- Shopping items (товары)
CREATE TABLE shopping_items (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
board_id INTEGER NOT NULL REFERENCES shopping_boards(id) ON DELETE CASCADE,
author_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
group_name VARCHAR(255),
volume_base NUMERIC(10,4) NOT NULL DEFAULT 1,
repetition_period INTERVAL,
next_show_at TIMESTAMP WITH TIME ZONE,
completed INTEGER DEFAULT 0,
last_completed_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
deleted BOOLEAN DEFAULT FALSE
);
CREATE INDEX idx_shopping_items_board_id ON shopping_items(board_id);
CREATE INDEX idx_shopping_items_user_id ON shopping_items(user_id);
CREATE INDEX idx_shopping_items_deleted ON shopping_items(deleted);
CREATE INDEX idx_shopping_items_next_show_at ON shopping_items(next_show_at);

View File

@@ -0,0 +1 @@
ALTER TABLE shopping_items DROP COLUMN description;

View File

@@ -0,0 +1 @@
ALTER TABLE shopping_items ADD COLUMN description TEXT;

View File

@@ -0,0 +1 @@
DROP TABLE IF EXISTS shopping_item_history;

View File

@@ -0,0 +1,10 @@
CREATE TABLE shopping_item_history (
id SERIAL PRIMARY KEY,
item_id INTEGER NOT NULL REFERENCES shopping_items(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id),
name VARCHAR(255) NOT NULL,
volume NUMERIC(10,4) NOT NULL DEFAULT 1,
completed_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_shopping_item_history_item_id ON shopping_item_history(item_id);

View File

@@ -0,0 +1,3 @@
ALTER TABLE tasks DROP COLUMN IF EXISTS purchase_config_id;
DROP TABLE IF EXISTS purchase_config_boards;
DROP TABLE IF EXISTS purchase_configs;

View File

@@ -0,0 +1,24 @@
-- Purchase task configurations
CREATE TABLE purchase_configs (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_purchase_configs_user_id ON purchase_configs(user_id);
-- Purchase config board/group associations
CREATE TABLE purchase_config_boards (
id SERIAL PRIMARY KEY,
purchase_config_id INTEGER NOT NULL REFERENCES purchase_configs(id) ON DELETE CASCADE,
board_id INTEGER NOT NULL REFERENCES shopping_boards(id) ON DELETE CASCADE,
group_name VARCHAR(255),
UNIQUE (purchase_config_id, board_id, group_name)
);
CREATE INDEX idx_purchase_config_boards_config_id ON purchase_config_boards(purchase_config_id);
CREATE INDEX idx_purchase_config_boards_board_id ON purchase_config_boards(board_id);
-- Add purchase_config_id to tasks
ALTER TABLE tasks ADD COLUMN purchase_config_id INTEGER REFERENCES purchase_configs(id) ON DELETE SET NULL;
CREATE INDEX idx_tasks_purchase_config_id ON tasks(purchase_config_id);

View File

@@ -0,0 +1,3 @@
ALTER TABLE users
DROP COLUMN IF EXISTS priorities_confirmed_year,
DROP COLUMN IF EXISTS priorities_confirmed_week;

View File

@@ -0,0 +1,3 @@
ALTER TABLE users
ADD COLUMN priorities_confirmed_year INTEGER NOT NULL DEFAULT 0,
ADD COLUMN priorities_confirmed_week INTEGER NOT NULL DEFAULT 0;

View File

@@ -0,0 +1 @@
DROP TABLE IF EXISTS shopping_volume_records;

View File

@@ -0,0 +1,19 @@
-- Отдельная таблица записей об остатках (создаётся при каждом выполнении и переносе)
CREATE TABLE shopping_volume_records (
id SERIAL PRIMARY KEY,
item_id INTEGER NOT NULL REFERENCES shopping_items(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id),
action_type VARCHAR(20) NOT NULL,
volume_remaining NUMERIC(10,4),
volume_purchased NUMERIC(10,4),
daily_consumption NUMERIC(10,4),
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_shopping_volume_records_item_id ON shopping_volume_records(item_id);
-- Создаём начальные записи для всех существующих товаров (остаток 0, дата = created_at)
INSERT INTO shopping_volume_records (item_id, user_id, action_type, volume_remaining, volume_purchased, created_at)
SELECT id, user_id, 'create', 0, 0, created_at
FROM shopping_items
WHERE deleted = FALSE;

View File

@@ -0,0 +1 @@
ALTER TABLE shopping_volume_records DROP COLUMN IF EXISTS next_show_at;

View File

@@ -0,0 +1 @@
ALTER TABLE shopping_volume_records ADD COLUMN next_show_at TIMESTAMP;

View File

@@ -0,0 +1 @@
DROP TABLE IF EXISTS board_archives;

View File

@@ -0,0 +1,10 @@
CREATE TABLE board_archives (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
board_type VARCHAR(20) NOT NULL, -- 'wishlist' or 'shopping'
board_id INTEGER NOT NULL,
archived_at TIMESTAMP NOT NULL DEFAULT NOW(),
UNIQUE(user_id, board_type, board_id)
);
CREATE INDEX idx_board_archives_user_type ON board_archives(user_id, board_type);

View File

@@ -0,0 +1,2 @@
ALTER TABLE tasks DROP COLUMN default_auto_complete;
ALTER TABLE tasks DROP COLUMN default_progress;

View File

@@ -0,0 +1,4 @@
ALTER TABLE tasks ADD COLUMN default_auto_complete BOOLEAN DEFAULT FALSE;
ALTER TABLE tasks ADD COLUMN default_progress NUMERIC(10,4);
-- Для существующих задач: default_progress = progression_base
UPDATE tasks SET default_progress = progression_base WHERE progression_base IS NOT NULL;

Binary file not shown.

View File

@@ -50,7 +50,7 @@ server {
}
# Proxy other API endpoints to backend
location ~ ^/(playlife-feed|d2dc349a-0d13-49b2-a8f0-1ab094bfba9b|projects|message/post|webhook/|weekly_goals/setup|project_score_sample_mv/refresh)$ {
location ~ ^/(playlife-feed|d2dc349a-0d13-49b2-a8f0-1ab094bfba9b|projects|message/post|webhook/|weekly_goals/setup|project_score_sample_mv/refresh|priorities/confirm)$ {
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;

View File

@@ -1,6 +1,6 @@
{
"name": "play-life-web",
"version": "6.0.1",
"version": "6.27.3",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -14,6 +14,12 @@ import WishlistForm from './components/WishlistForm'
import WishlistDetail from './components/WishlistDetail'
import BoardForm from './components/BoardForm'
import BoardJoinPreview from './components/BoardJoinPreview'
import ShoppingList from './components/ShoppingList'
import ShoppingItemForm from './components/ShoppingItemForm'
import ShoppingBoardForm from './components/ShoppingBoardForm'
import ShoppingBoardJoinPreview from './components/ShoppingBoardJoinPreview'
import ShoppingItemHistory from './components/ShoppingItemHistory'
import PurchaseScreen from './components/PurchaseScreen'
import TodoistIntegration from './components/TodoistIntegration'
import TelegramIntegration from './components/TelegramIntegration'
import FitbitIntegration from './components/FitbitIntegration'
@@ -30,7 +36,7 @@ const FULL_STATISTICS_API_URL = '/d2dc349a-0d13-49b2-a8f0-1ab094bfba9b'
// Определяем основные табы (без крестика) и глубокие табы (с крестиком)
const mainTabs = ['current', 'tasks', 'wishlist', 'profile']
const deepTabs = ['add-words', 'test', 'task-form', 'wishlist-form', 'wishlist-detail', 'board-form', 'board-join', 'words', 'dictionaries', 'todoist-integration', 'telegram-integration', 'fitbit-integration', 'full', 'priorities', 'tracking', 'tracking-access', 'tracking-invite']
const deepTabs = ['add-words', 'test', 'purchase', 'task-form', 'wishlist-form', 'wishlist-detail', 'board-form', 'board-join', 'words', 'dictionaries', 'todoist-integration', 'telegram-integration', 'fitbit-integration', 'full', 'priorities', 'tracking', 'tracking-access', 'tracking-invite', 'shopping', 'shopping-item-form', 'shopping-board-form', 'shopping-board-join', 'shopping-item-history']
/**
* Гарантирует базовую запись истории для главного экрана перед глубоким табом.
@@ -77,8 +83,14 @@ function AppContent() {
tracking: false,
'tracking-access': false,
'tracking-invite': false,
shopping: false,
'shopping-item-form': false,
'shopping-board-form': false,
'shopping-board-join': false,
'shopping-item-history': false,
purchase: false,
})
// Отслеживаем, какие табы уже были загружены (для предотвращения повторных загрузок)
const [tabsInitialized, setTabsInitialized] = useState({
current: false,
@@ -102,6 +114,12 @@ function AppContent() {
tracking: false,
'tracking-access': false,
'tracking-invite': false,
shopping: false,
'shopping-item-form': false,
'shopping-board-form': false,
'shopping-board-join': false,
'shopping-item-history': false,
purchase: false,
})
// Параметры для навигации между вкладками
@@ -110,12 +128,16 @@ function AppContent() {
// Предыдущий таб для возврата из модальных окон
const [previousTab, setPreviousTab] = useState(null)
// Модальное окно выбора типа задачи
const [showAddModal, setShowAddModal] = useState(false)
// Счётчик для сброса формы товара при каждом открытии
const [shoppingItemFormKey, setShoppingItemFormKey] = useState(0)
// Ref для функции открытия модала добавления записи в CurrentWeek
const currentWeekAddModalRef = useRef(null)
// Подтверждение приоритетов на текущей неделе (null = неизвестно, true/false = известно)
const [prioritiesConfirmed, setPrioritiesConfirmed] = useState(null)
const prioritiesOverlayPushedRef = useRef(false)
// Кеширование данных
const [currentWeekData, setCurrentWeekData] = useState(null)
const [fullStatisticsData, setFullStatisticsData] = useState(null)
@@ -149,26 +171,65 @@ function AppContent() {
const [dictionariesRefreshTrigger, setDictionariesRefreshTrigger] = useState(0)
const [wordsRefreshTrigger, setWordsRefreshTrigger] = useState(0)
const [wishlistRefreshTrigger, setWishlistRefreshTrigger] = useState(0)
const [shoppingRefreshTrigger, setShoppingRefreshTrigger] = useState(0)
// Восстанавливаем последний выбранный таб после перезагрузки
const [isInitialized, setIsInitialized] = useState(false)
// Управление историей для оверлея приоритетов
useEffect(() => {
const overlayVisible = activeTab === 'current' && prioritiesConfirmed === false
if (overlayVisible && !prioritiesOverlayPushedRef.current) {
prioritiesOverlayPushedRef.current = true
// Заменяем текущую запись { tab: 'current' } на { tab: 'tasks' },
// затем добавляем запись оверлея. Так системная кнопка "Назад" вернёт на tasks.
window.history.replaceState({ tab: 'tasks' }, '', '/')
window.history.pushState({ tab: 'current', prioritiesOverlay: true }, '', '/')
}
if (!overlayVisible) {
prioritiesOverlayPushedRef.current = false
}
}, [activeTab, prioritiesConfirmed])
// Переключение на экран прогрессии после успешной авторизации
useEffect(() => {
// Обновляем ref только после того, как authLoading стал false
if (!authLoading) {
const wasNotAuthenticated = prevIsAuthenticatedRef.current === false
prevIsAuthenticatedRef.current = isAuthenticated
// Обновляем ref только если инициализация завершена,
// чтобы не потерять переход false→true при ожидании isInitialized
if (isInitialized) {
prevIsAuthenticatedRef.current = isAuthenticated
}
// Проверяем, что это новая авторизация (переход с false на true)
// и что инициализация уже завершена (чтобы не конфликтовать с восстановлением из URL/localStorage)
if (wasNotAuthenticated && isAuthenticated && isInitialized) {
// Сбрасываем ошибки, кеш данных и состояние инициализации табов при повторной авторизации
setCurrentWeekError(null)
setFullStatisticsError(null)
setPrioritiesError(null)
setTasksError(null)
setTodayEntriesError(null)
setCurrentWeekData(null)
setFullStatisticsData(null)
setTasksData(null)
setTodayEntriesData(null)
setPrioritiesConfirmed(null)
// Сбрасываем инициализацию табов, чтобы данные загрузились заново
Object.keys(tabsInitializedRef.current).forEach(key => {
tabsInitializedRef.current[key] = false
})
cacheRef.current = { current: null, full: null, tasks: null, todayEntries: null }
lastLoadedTabRef.current = null
// Переключаемся на экран прогресса только если нет таба в URL
const urlParams = new URLSearchParams(window.location.search)
const tabFromUrl = urlParams.get('tab')
// Если в URL нет таба, переключаемся на current (экран прогресса)
if (!tabFromUrl) {
setActiveTab('current')
@@ -205,6 +266,20 @@ function AppContent() {
}
}
// Проверяем путь /shopping-invite/:token для присоединения к shopping доске
if (path.startsWith('/shopping-invite/')) {
const token = path.replace('/shopping-invite/', '')
if (token) {
const url = '/?tab=shopping-board-join&inviteToken=' + token
ensureBaseHistory('shopping-board-join', { inviteToken: token }, url)
setActiveTab('shopping-board-join')
setLoadedTabs(prev => ({ ...prev, 'shopping-board-join': true }))
setTabParams({ inviteToken: token })
setIsInitialized(true)
return
}
}
// Проверяем путь /tracking/invite/:token
if (path.startsWith('/tracking/invite/')) {
const token = path.replace('/tracking/invite/', '')
@@ -240,10 +315,10 @@ function AppContent() {
// Проверяем URL только для глубоких табов
const tabFromUrl = urlParams.get('tab')
const validTabs = ['current', 'priorities', 'full', 'words', 'add-words', 'dictionaries', 'test', 'tasks', 'task-form', 'wishlist', 'wishlist-form', 'wishlist-detail', 'board-form', 'board-join', 'profile', 'todoist-integration', 'telegram-integration', 'fitbit-integration', 'tracking', 'tracking-access', 'tracking-invite']
if (tabFromUrl && validTabs.includes(tabFromUrl) && deepTabs.includes(tabFromUrl)) {
// Восстанавливаем параметры из URL
const validTabs = ['current', 'priorities', 'full', 'words', 'add-words', 'dictionaries', 'test', 'purchase', 'tasks', 'task-form', 'wishlist', 'wishlist-form', 'wishlist-detail', 'board-form', 'board-join', 'profile', 'todoist-integration', 'telegram-integration', 'fitbit-integration', 'tracking', 'tracking-access', 'tracking-invite', 'shopping', 'shopping-item-form', 'shopping-board-form', 'shopping-board-join', 'shopping-item-history']
if (tabFromUrl && validTabs.includes(tabFromUrl) && deepTabs.includes(tabFromUrl) && window.history.length > 1) {
// Восстанавливаем глубокий таб из URL только если есть история (не рестарт PWA)
const params = {}
urlParams.forEach((value, key) => {
if (key !== 'tab') {
@@ -256,31 +331,42 @@ function AppContent() {
})
const deepTabUrl = window.location.pathname + window.location.search
ensureBaseHistory(tabFromUrl, params, deepTabUrl)
// Если в URL есть глубокий таб, восстанавливаем его
setActiveTab(tabFromUrl)
setLoadedTabs(prev => ({ ...prev, [tabFromUrl]: true }))
if (Object.keys(params).length > 0) {
setTabParams(params)
// Если это экран full с selectedProject, восстанавливаем его
if (tabFromUrl === 'full' && params.selectedProject) {
setSelectedProject(params.selectedProject)
}
}
} else {
// Если в URL нет глубокого таба, проверяем localStorage для основного таба
const savedTab = window.localStorage?.getItem('activeTab')
if (savedTab && validTabs.includes(savedTab)) {
setActiveTab(savedTab)
setLoadedTabs(prev => ({ ...prev, [savedTab]: true }))
}
// Очищаем URL от параметров таба, если это основной таб
if (tabFromUrl && mainTabs.includes(tabFromUrl)) {
const url = new URL(window.location)
url.searchParams.delete('tab')
url.searchParams.forEach((value, key) => {
url.searchParams.delete(key)
})
window.history.replaceState({}, '', url)
// При рестарте PWA (history.length <= 1) с deep tab в URL — сбрасываем на current
if (tabFromUrl && deepTabs.includes(tabFromUrl) && window.history.length <= 1) {
window.history.replaceState({ tab: 'current' }, '', '/')
setActiveTab('current')
setLoadedTabs(prev => ({ ...prev, 'current': true }))
} else {
// Проверяем localStorage для основного таба
const savedTab = window.localStorage?.getItem('activeTab')
if (savedTab && validTabs.includes(savedTab) && mainTabs.includes(savedTab)) {
setActiveTab(savedTab)
setLoadedTabs(prev => ({ ...prev, [savedTab]: true }))
// Сохраняем таб в history state для корректной работы кнопки "назад"
window.history.replaceState({ tab: savedTab }, '', window.location.href)
} else {
// Если нет сохранённого таба — активируем current по умолчанию
setLoadedTabs(prev => ({ ...prev, current: true }))
window.history.replaceState({ tab: 'current' }, '', window.location.href)
}
// Очищаем URL от параметров таба, если это основной таб
if (tabFromUrl && mainTabs.includes(tabFromUrl)) {
const url = new URL(window.location)
url.searchParams.delete('tab')
url.searchParams.forEach((value, key) => {
url.searchParams.delete(key)
})
window.history.replaceState({}, '', url)
}
}
}
setIsInitialized(true)
@@ -295,7 +381,7 @@ function AppContent() {
}, [])
// Функция для обновления URL (только для глубоких табов)
const updateUrl = useCallback((tab, params = {}, previousTab = null) => {
const updateUrl = useCallback((tab, params = {}, previousTab = null, replace = false) => {
if (!deepTabs.includes(tab)) {
// Для основных табов не обновляем URL
return
@@ -320,8 +406,17 @@ function AppContent() {
}
})
// Если стек пуст (после перезапуска PWA), добавляем базовую запись 'current'
if (window.history.length <= 1) {
window.history.replaceState({ tab: 'current' }, '', '/')
}
// Сохраняем предыдущий таб в state для восстановления при "Назад"
window.history.pushState({ tab, params, previousTab }, '', url)
if (replace) {
window.history.replaceState({ tab, params, previousTab }, '', url)
} else {
window.history.pushState({ tab, params, previousTab }, '', url)
}
}, []) // deepTabs - константа, не нужно в зависимостях
// Функция для очистки URL (при возврате к основному табу)
@@ -427,17 +522,26 @@ function AppContent() {
groupProgress0 = jsonData.group_progress_0 !== undefined ? jsonData.group_progress_0 : null
}
// Получаем желания из ответа
// Получаем желания и pending-баллы по проектам из ответа
const wishes = jsonData?.wishes || []
const pendingScoresByProject = jsonData?.pending_scores_by_project && typeof jsonData.pending_scores_by_project === 'object' ? jsonData.pending_scores_by_project : {}
const rootData = (Array.isArray(jsonData) && jsonData.length > 0) ? jsonData[0] : jsonData
const prioritiesConfirmedValue = rootData?.priorities_confirmed ?? null
setCurrentWeekData({
projects: Array.isArray(projects) ? projects : [],
total: total,
group_progress_1: groupProgress1,
group_progress_2: groupProgress2,
group_progress_0: groupProgress0,
wishes: wishes
wishes: wishes,
pending_scores_by_project: pendingScoresByProject
})
if (prioritiesConfirmedValue !== null) {
setPrioritiesConfirmed(prioritiesConfirmedValue)
}
} catch (err) {
setCurrentWeekError(err.message)
console.error('Ошибка загрузки данных текущей недели:', err)
@@ -573,6 +677,8 @@ function AppContent() {
// Refs для отслеживания активного таба
const prevActiveTabRef = useRef(null)
const lastLoadedTabRef = useRef(null) // Отслеживаем последний загруженный таб, чтобы избежать двойной загрузки
const fullStatisticsScrollRef = useRef(null)
const lastFullProjectRef = useRef(selectedProject)
// Обновляем ref при изменении данных
useEffect(() => {
@@ -702,12 +808,13 @@ function AppContent() {
// Проверяем, есть ли открытые модальные окна в DOM
const taskDetailModal = document.querySelector('.task-detail-modal-overlay')
const wishlistDetailModal = document.querySelector('.wishlist-detail-modal-overlay')
const conditionFormOverlay = document.querySelector('.condition-form-overlay')
// Если есть открытые модальные окна, не обрабатываем здесь - компоненты сами закроют их
if (taskDetailModal || wishlistDetailModal) {
if (taskDetailModal || wishlistDetailModal || conditionFormOverlay) {
return
}
// Если это модальное окно, не обрабатываем здесь - компоненты сами закроют его
if (event.state && event.state.modalOpen) {
// Если модальных окон нет в DOM, это устаревшая запись — пропускаем её
@@ -717,8 +824,8 @@ function AppContent() {
return
}
const validTabs = ['current', 'priorities', 'full', 'words', 'add-words', 'dictionaries', 'test', 'tasks', 'task-form', 'wishlist', 'wishlist-form', 'wishlist-detail', 'profile', 'todoist-integration', 'telegram-integration', 'tracking', 'tracking-access', 'tracking-invite']
const validTabs = ['current', 'priorities', 'full', 'words', 'add-words', 'dictionaries', 'test', 'purchase', 'tasks', 'task-form', 'wishlist', 'wishlist-form', 'wishlist-detail', 'profile', 'todoist-integration', 'telegram-integration', 'tracking', 'tracking-access', 'tracking-invite', 'shopping', 'shopping-item-form', 'shopping-board-form', 'shopping-board-join', 'shopping-item-history']
// Проверяем state текущей записи истории (куда мы вернулись)
if (event.state && event.state.tab) {
const { tab, params = {} } = event.state
@@ -769,9 +876,9 @@ function AppContent() {
setSelectedProject(null)
clearUrl(event.state.tab)
} else {
// Если state пустой, используем сохраненный таб из localStorage
// Если state пустой, используем сохраненный таб из localStorage (только основные табы)
const savedTab = window.localStorage?.getItem('activeTab')
const validMainTab = savedTab && validTabs.includes(savedTab) ? savedTab : 'current'
const validMainTab = savedTab && mainTabs.includes(savedTab) ? savedTab : 'current'
setActiveTab(validMainTab)
setTabParams({})
markTabAsLoaded(validMainTab)
@@ -815,14 +922,14 @@ function AppContent() {
setActiveTab('full')
}
const handleTabChange = (tab, params = {}) => {
const handleTabChange = (tab, params = {}, options = {}) => {
if (tab === 'full' && activeTab === 'full') {
// При повторном клике на "Полная статистика" сбрасываем выбранный проект
setSelectedProject(null)
setTabParams({})
updateUrl('full', {}, activeTab)
} else if (tab !== activeTab || tab === 'task-form' || tab === 'wishlist-form' || (tab === 'words' && Object.keys(params).length > 0)) {
// Для task-form и wishlist-form всегда обновляем параметры, даже если это тот же таб
} else if (tab !== activeTab || tab === 'task-form' || tab === 'wishlist-form' || tab === 'shopping-item-form' || (tab === 'words' && Object.keys(params).length > 0)) {
// Для task-form, wishlist-form и shopping-item-form всегда обновляем параметры, даже если это тот же таб
markTabAsLoaded(tab)
// Определяем, является ли текущий таб глубоким
@@ -833,8 +940,8 @@ function AppContent() {
{
// Для task-form и wishlist-form явно удаляем параметры, только если нет никаких параметров
// task-form может иметь taskId (редактирование), wishlistId (создание из желания), returnTo (возврат после создания), или isTest (создание теста)
const isTaskFormWithNoParams = tab === 'task-form' && params.taskId === undefined && params.wishlistId === undefined && params.returnTo === undefined && params.isTest === undefined
// task-form может иметь taskId (редактирование), wishlistId (создание из желания), returnTo (возврат после создания)
const isTaskFormWithNoParams = tab === 'task-form' && params.taskId === undefined && params.wishlistId === undefined && params.returnTo === undefined
// Проверяем, что boardId не null и не undefined (null означает "нет доски", но это валидное значение)
const hasBoardId = params.boardId !== null && params.boardId !== undefined
const isWishlistFormWithNoParams = tab === 'wishlist-form' && params.wishlistId === undefined && params.newTaskId === undefined && !hasBoardId
@@ -843,7 +950,19 @@ function AppContent() {
if (isNewTabMain) {
clearUrl()
} else if (isNewTabDeep) {
updateUrl(tab, {}, activeTab)
// Если текущая запись — модальное окно, заменяем её вместо push
const currentState = window.history.state || {}
const isFromModal = currentState.modalOpen === true || currentState.conditionForm === true
if (isFromModal) {
const url = new URL(window.location)
url.searchParams.set('tab', tab)
const keysToRemove = []
url.searchParams.forEach((value, key) => { if (key !== 'tab') keysToRemove.push(key) })
keysToRemove.forEach(key => url.searchParams.delete(key))
window.history.replaceState({ tab, params: {}, previousTab: activeTab }, '', url)
} else {
updateUrl(tab, {}, activeTab)
}
}
} else {
setTabParams(params)
@@ -851,8 +970,8 @@ function AppContent() {
if (isNewTabDeep) {
// Проверяем, была ли последняя запись в истории от модального окна
const currentState = window.history.state || {}
const isFromModal = currentState.modalOpen === true
const isNavigatingToForm = tab === 'task-form' || tab === 'wishlist-form'
const isFromModal = currentState.modalOpen === true || currentState.conditionForm === true
const isNavigatingToForm = tab === 'task-form' || tab === 'wishlist-form' || tab === 'shopping-item-form'
if (isFromModal && isNavigatingToForm) {
// Заменяем запись модального окна на запись формы редактирования
@@ -874,7 +993,7 @@ function AppContent() {
window.history.replaceState({ tab, params, previousTab: activeTab }, '', url)
} else {
// Сохраняем текущий таб как предыдущий при переходе на глубокий таб
updateUrl(tab, params, activeTab)
updateUrl(tab, params, activeTab, options.replace)
}
} else if (isNewTabMain && isCurrentTabDeep) {
// При переходе с глубокого таба на основной - очищаем URL и сохраняем таб в state
@@ -901,14 +1020,14 @@ function AppContent() {
}
// Обновляем список задач при возврате из экрана редактирования или теста
// Используем фоновую загрузку, чтобы не показывать индикатор загрузки
if ((activeTab === 'task-form' || activeTab === 'test') && tab === 'tasks') {
if ((activeTab === 'task-form' || activeTab === 'test' || activeTab === 'purchase') && tab === 'tasks') {
fetchTasksData(true)
}
// Сохраняем предыдущий таб при открытии wishlist-form или wishlist-detail
if ((tab === 'wishlist-form' || tab === 'wishlist-detail') && activeTab !== tab) {
setPreviousTab(activeTab)
}
// Обновляем список желаний при возврате из экрана редактирования
if (activeTab === 'wishlist-form' && tab !== 'wishlist-form') {
// Сохраняем boardId из параметров или текущих tabParams
@@ -921,35 +1040,40 @@ function AppContent() {
setWishlistRefreshTrigger(prev => prev + 1)
}
}
// Обновляем список желаний при возврате из экрана детализации
if (activeTab === 'wishlist-detail' && tab !== 'wishlist-detail') {
if (tab === 'wishlist') {
setWishlistRefreshTrigger(prev => prev + 1)
}
}
// Сохраняем предыдущий таб при открытии shopping-item-form
if (tab === 'shopping-item-form' && activeTab !== tab) {
setPreviousTab(activeTab)
setShoppingItemFormKey(prev => prev + 1)
}
// Обновляем список товаров при возврате из экрана редактирования
if ((activeTab === 'shopping-item-form' || activeTab === 'shopping-board-form') && (tab === 'shopping' || tab === 'purchase')) {
const savedBoardId = params.boardId || tabParams.boardId
if (savedBoardId) {
setTabParams(prev => ({ ...prev, boardId: savedBoardId }))
}
setShoppingRefreshTrigger(prev => prev + 1)
}
// Загрузка данных произойдет в useEffect при изменении activeTab
}
}
// Обработчики для кнопки добавления задачи
// Обработчик для кнопки добавления задачи
const handleAddClick = () => {
setShowAddModal(true)
}
const handleAddTask = () => {
setShowAddModal(false)
handleNavigate('task-form', { taskId: undefined, isTest: false })
}
const handleAddTest = () => {
setShowAddModal(false)
handleNavigate('task-form', { taskId: undefined, isTest: true })
handleNavigate('task-form', { taskId: undefined })
}
// Обработчик навигации для компонентов
const handleNavigate = (tab, params = {}) => {
handleTabChange(tab, params)
const handleNavigate = (tab, params = {}, options = {}) => {
handleTabChange(tab, params, options)
}
// Загружаем данные при открытии таба (когда таб становится активным)
@@ -970,16 +1094,25 @@ function AppContent() {
setWordsRefreshTrigger(prev => prev + 1)
}
// Обновляем список желаний при возврате из формы редактирования
if (prevActiveTabRef.current === 'wishlist-form' && activeTab === 'wishlist') {
setWishlistRefreshTrigger(prev => prev + 1)
}
if (isFirstLoad) {
// Первая загрузка таба
lastLoadedTabRef.current = tabKey
const projectName = activeTab === 'full' ? selectedProject : null
loadTabData(activeTab, false, projectName)
if (activeTab === 'full') lastFullProjectRef.current = selectedProject
} else if (isReturningToTab) {
// Возврат на таб - фоновая загрузка
// Возврат на таб
lastLoadedTabRef.current = tabKey
const projectName = activeTab === 'full' ? selectedProject : null
loadTabData(activeTab, true, projectName)
// Если проект изменился - загрузка с индикатором, иначе фоновая
const isBackground = activeTab === 'full' && lastFullProjectRef.current !== selectedProject ? false : true
loadTabData(activeTab, isBackground, projectName)
if (activeTab === 'full') lastFullProjectRef.current = selectedProject
}
prevActiveTabRef.current = activeTab
@@ -1001,6 +1134,13 @@ function AppContent() {
const isAnyLoading = currentWeekLoading || fullStatisticsLoading || prioritiesLoading || isRefreshing
const hasAnyError = currentWeekError || fullStatisticsError || prioritiesError
// Сбрасываем скролл экрана статистики при его открытии
useEffect(() => {
if (activeTab === 'full' && fullStatisticsScrollRef.current) {
fullStatisticsScrollRef.current.scrollTop = 0
}
}, [activeTab])
// Сохраняем выбранный таб, чтобы восстановить его после перезагрузки
useEffect(() => {
try {
@@ -1026,7 +1166,7 @@ function AppContent() {
}
// Определяем, нужно ли скрывать нижнюю панель (для fullscreen экранов)
const isFullscreenTab = activeTab === 'test' || activeTab === 'add-words' || activeTab === 'task-form' || activeTab === 'wishlist-form' || activeTab === 'wishlist-detail' || activeTab === 'todoist-integration' || activeTab === 'telegram-integration' || activeTab === 'fitbit-integration' || activeTab === 'full' || activeTab === 'priorities' || activeTab === 'words' || activeTab === 'dictionaries' || activeTab === 'tracking' || activeTab === 'tracking-access' || activeTab === 'tracking-invite'
const isFullscreenTab = activeTab === 'test' || activeTab === 'purchase' || activeTab === 'add-words' || activeTab === 'task-form' || activeTab === 'wishlist-form' || activeTab === 'wishlist-detail' || activeTab === 'todoist-integration' || activeTab === 'telegram-integration' || activeTab === 'fitbit-integration' || activeTab === 'full' || activeTab === 'priorities' || activeTab === 'words' || activeTab === 'dictionaries' || activeTab === 'tracking' || activeTab === 'tracking-access' || activeTab === 'tracking-invite' || activeTab === 'shopping' || activeTab === 'shopping-item-form' || activeTab === 'shopping-board-form' || activeTab === 'shopping-board-join' || activeTab === 'shopping-item-history' || activeTab === 'board-form'
// Функция для получения классов скролл-контейнера для каждого таба
// Каждый таб имеет свой изолированный скролл-контейнер для автоматического сохранения позиции скролла
@@ -1040,7 +1180,7 @@ function AppContent() {
let paddingClasses = ''
if (tabName === 'current' || tabName === 'tasks' || tabName === 'wishlist' || tabName === 'profile') {
paddingClasses = 'pb-20'
} else if (tabName === 'words' || tabName === 'dictionaries') {
} else if (tabName === 'words' || tabName === 'dictionaries' || tabName === 'shopping') {
paddingClasses = 'pb-16'
}
@@ -1055,7 +1195,10 @@ function AppContent() {
if (tabName === 'current') {
return 'max-w-7xl mx-auto p-4 md:p-6'
}
if (tabName === 'full' || tabName === 'priorities' || tabName === 'dictionaries' || tabName === 'words') {
if (tabName === 'priorities') {
return 'max-w-2xl mx-auto px-4 h-full'
}
if (tabName === 'full' || tabName === 'dictionaries' || tabName === 'words' || tabName === 'shopping' || tabName === 'shopping-item-history' || tabName === 'purchase') {
return 'max-w-7xl mx-auto px-4 md:px-8 py-0'
}
// Fullscreen табы без отступов
@@ -1088,7 +1231,7 @@ function AppContent() {
{loadedTabs.priorities && (
<div className={getTabContainerClasses('priorities')}>
<div className={getInnerContainerClasses('priorities')}>
<ProjectPriorityManager
<ProjectPriorityManager
allProjectsData={fullStatisticsData}
currentWeekData={currentWeekData}
shouldLoad={activeTab === 'priorities' && loadedTabs.priorities}
@@ -1096,13 +1239,19 @@ function AppContent() {
onErrorChange={setPrioritiesError}
refreshTrigger={prioritiesRefreshTrigger}
onNavigate={handleNavigate}
onConfirmed={async () => {
await fetchCurrentWeekData(false)
setPrioritiesConfirmed(true)
markTabAsLoaded('current')
setActiveTab('current')
}}
/>
</div>
</div>
)}
{loadedTabs.full && (
<div className={getTabContainerClasses('full')}>
<div ref={fullStatisticsScrollRef} className={getTabContainerClasses('full')}>
<div className={getInnerContainerClasses('full')}>
<FullStatistics
selectedProject={selectedProject}
@@ -1115,12 +1264,13 @@ function AppContent() {
loading={fullStatisticsLoading}
error={fullStatisticsError}
todayEntries={todayEntriesData}
todayEntriesLoading={todayEntriesLoading || todayEntriesBackgroundLoading}
todayEntriesLoading={todayEntriesLoading}
todayEntriesError={todayEntriesError}
onRetryTodayEntries={() => fetchTodayEntries(false, selectedProject, null)}
fetchTodayEntries={fetchTodayEntries}
onRetry={fetchFullStatisticsData}
currentWeekData={currentWeekData}
fetchCurrentWeekData={fetchCurrentWeekData}
onNavigate={handleNavigate}
activeTab={activeTab}
/>
@@ -1167,12 +1317,26 @@ function AppContent() {
{loadedTabs.test && (
<div className={getTabContainerClasses('test')}>
<div className={getInnerContainerClasses('test')}>
<TestWords
<TestWords
onNavigate={handleNavigate}
wordCount={tabParams.wordCount}
configId={tabParams.configId}
maxCards={tabParams.maxCards}
taskId={tabParams.taskId}
isActive={activeTab === 'test'}
/>
</div>
</div>
)}
{loadedTabs.purchase && (
<div className={getTabContainerClasses('purchase')}>
<div className={getInnerContainerClasses('purchase')}>
<PurchaseScreen
onNavigate={handleNavigate}
purchaseConfigId={tabParams.purchaseConfigId}
taskId={tabParams.taskId}
taskName={tabParams.taskName}
/>
</div>
</div>
@@ -1188,7 +1352,13 @@ function AppContent() {
backgroundLoading={tasksBackgroundLoading}
error={tasksError}
onRetry={() => fetchTasksData(false)}
onRefresh={(isBackground = false) => fetchTasksData(isBackground)}
onRefresh={(tasksOrBackground) => {
if (Array.isArray(tasksOrBackground)) {
setTasksData(tasksOrBackground)
} else {
fetchTasksData(tasksOrBackground === true)
}
}}
/>
</div>
</div>
@@ -1197,14 +1367,14 @@ function AppContent() {
{loadedTabs['task-form'] && (
<div className={getTabContainerClasses('task-form')}>
<div className={getInnerContainerClasses('task-form')}>
<TaskForm
key={tabParams.taskId || 'new'}
<TaskForm
key={tabParams.taskId || 'new-task'}
onNavigate={handleNavigate}
taskId={tabParams.taskId}
wishlistId={tabParams.wishlistId}
isTest={tabParams.isTest}
returnTo={tabParams.returnTo}
returnWishlistId={tabParams.returnWishlistId}
isActive={activeTab === 'task-form'}
/>
</div>
</div>
@@ -1234,6 +1404,7 @@ function AppContent() {
editConditionIndex={tabParams.editConditionIndex}
newTaskId={tabParams.newTaskId}
boardId={tabParams.boardId}
isActive={activeTab === 'wishlist-form'}
/>
</div>
</div>
@@ -1247,6 +1418,7 @@ function AppContent() {
onNavigate={handleNavigate}
boardId={tabParams.boardId}
onSaved={() => setWishlistRefreshTrigger(prev => prev + 1)}
isActive={activeTab === 'board-form'}
/>
</div>
</div>
@@ -1264,6 +1436,74 @@ function AppContent() {
</div>
)}
{loadedTabs.shopping && (
<div className={getTabContainerClasses('shopping')}>
<div className={getInnerContainerClasses('shopping')}>
<ShoppingList
onNavigate={handleNavigate}
refreshTrigger={shoppingRefreshTrigger}
isActive={activeTab === 'shopping'}
initialBoardId={tabParams.boardId}
boardDeleted={tabParams.boardDeleted}
/>
</div>
</div>
)}
{loadedTabs['shopping-item-form'] && (
<div className={getTabContainerClasses('shopping-item-form')}>
<div className={getInnerContainerClasses('shopping-item-form')}>
<ShoppingItemForm
key={tabParams.itemId || `new-${shoppingItemFormKey}`}
onNavigate={handleNavigate}
itemId={tabParams.itemId}
boardId={tabParams.boardId}
previousTab={previousTab}
onSaved={() => setShoppingRefreshTrigger(prev => prev + 1)}
isActive={activeTab === 'shopping-item-form'}
/>
</div>
</div>
)}
{loadedTabs['shopping-board-form'] && (
<div className={getTabContainerClasses('shopping-board-form')}>
<div className={getInnerContainerClasses('shopping-board-form')}>
<ShoppingBoardForm
key={tabParams.boardId || 'new'}
onNavigate={handleNavigate}
boardId={tabParams.boardId}
onSaved={() => setShoppingRefreshTrigger(prev => prev + 1)}
isActive={activeTab === 'shopping-board-form'}
/>
</div>
</div>
)}
{loadedTabs['shopping-board-join'] && (
<div className={getTabContainerClasses('shopping-board-join')}>
<div className={getInnerContainerClasses('shopping-board-join')}>
<ShoppingBoardJoinPreview
key={tabParams.inviteToken}
onNavigate={handleNavigate}
inviteToken={tabParams.inviteToken}
/>
</div>
</div>
)}
{loadedTabs['shopping-item-history'] && (
<div className={getTabContainerClasses('shopping-item-history')}>
<div className={getInnerContainerClasses('shopping-item-history')}>
<ShoppingItemHistory
key={tabParams.itemId}
itemId={tabParams.itemId}
onNavigate={handleNavigate}
/>
</div>
</div>
)}
{loadedTabs.profile && (
<div className={getTabContainerClasses('profile')}>
<div className={getInnerContainerClasses('profile')}>
@@ -1386,6 +1626,42 @@ function AppContent() {
</button>
)}
{/* Кнопка добавления товара (только для таба shopping) */}
{activeTab === 'shopping' && (
<button
onClick={() => {
let boardId = tabParams.boardId
if (!boardId) {
try {
const saved = localStorage.getItem('shopping_selected_board_id')
if (saved) {
const parsed = parseInt(saved, 10)
if (!isNaN(parsed)) boardId = parsed
}
} catch (err) {
console.error('Error loading boardId from localStorage:', err)
}
}
handleNavigate('shopping-item-form', { itemId: undefined, boardId: boardId })
}}
className="fixed bottom-4 right-4 z-20 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white w-[61px] h-[61px] rounded-2xl shadow-lg transition-all duration-200 hover:scale-105 flex items-center justify-center"
title="Добавить товар"
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M12 5v14M5 12h14" />
</svg>
</button>
)}
{/* Кнопка добавления записи (только для таба current - экран прогресса) */}
{!isFullscreenTab && activeTab === 'current' && (
<button
@@ -1546,40 +1822,31 @@ function AppContent() {
</div>
)}
{/* Модальное окно выбора типа задачи */}
{showAddModal && (
<div className="task-add-modal-overlay" onClick={() => setShowAddModal(false)}>
<div className="task-add-modal" onClick={(e) => e.stopPropagation()}>
<div className="task-add-modal-header">
<h3>Что добавить?</h3>
</div>
<div className="task-add-modal-buttons">
<button
className="task-add-modal-button task-add-modal-button-task"
onClick={handleAddTask}
>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M9 11l3 3L22 4"></path>
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path>
</svg>
Задача
</button>
<button
className="task-add-modal-button task-add-modal-button-test"
onClick={handleAddTest}
>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path>
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path>
<path d="M8 7h6"></path>
<path d="M8 11h4"></path>
</svg>
Тест
</button>
</div>
{/* Оверлей подтверждения приоритетов — показывается поверх экрана прогресса недели */}
{activeTab === 'current' && prioritiesConfirmed === false && (
<div className="fixed inset-0 bg-white z-50 overflow-y-auto">
<div className="max-w-2xl mx-auto px-4 h-full">
<ProjectPriorityManager
allProjectsData={fullStatisticsData}
currentWeekData={currentWeekData}
shouldLoad={true}
onLoadingChange={setPrioritiesLoading}
onErrorChange={setPrioritiesError}
refreshTrigger={Math.max(prioritiesRefreshTrigger, 1)}
onNavigate={handleNavigate}
onConfirmed={async () => {
await fetchCurrentWeekData(false)
setPrioritiesConfirmed(true)
}}
onClose={() => {
// history.back() переходит к { tab: 'tasks' }, popstate обработает переключение
window.history.back()
}}
/>
</div>
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,101 @@
.archived-boards {
padding: 1rem;
max-width: 800px;
margin: 0 auto;
position: relative;
}
.archived-boards h2 {
font-size: 1.5rem;
font-weight: 600;
color: #1f2937;
margin: 0 0 1.5rem 0;
}
.archived-boards-loading {
display: flex;
justify-content: center;
padding: 3rem 0;
}
.archived-boards-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
padding: 3rem 0;
color: #9ca3af;
font-size: 0.95rem;
}
.archived-boards-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.archived-board-card {
display: flex;
align-items: center;
background: white;
border-radius: 0.5rem;
padding: 0.875rem 1rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
gap: 0.75rem;
}
.archived-board-info {
flex: 1;
min-width: 0;
cursor: pointer;
}
.archived-board-name {
font-weight: 500;
color: #1f2937;
font-size: 0.95rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.archived-board-meta {
font-size: 0.8rem;
color: #9ca3af;
margin-top: 0.15rem;
}
.archived-board-actions {
display: flex;
gap: 0.25rem;
flex-shrink: 0;
}
.archived-board-btn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border: none;
border-radius: 0.375rem;
cursor: pointer;
transition: background 0.15s;
background: transparent;
}
.archived-board-restore {
color: #6366f1;
}
.archived-board-restore:hover {
background: #eef2ff;
}
.archived-board-delete {
color: #ef4444;
}
.archived-board-delete:hover {
background: #fef2f2;
}

View File

@@ -0,0 +1,171 @@
import React, { useState, useEffect } from 'react'
import { useAuth } from './auth/AuthContext'
import Toast from './Toast'
import './ArchivedBoards.css'
function ArchivedBoards({ boardType, onNavigate, onSaved }) {
const { authFetch } = useAuth()
const [boards, setBoards] = useState([])
const [loading, setLoading] = useState(true)
const [toastMessage, setToastMessage] = useState(null)
const isWishlist = boardType === 'wishlist'
const apiBase = isWishlist ? '/api/wishlist' : '/api/shopping'
const returnTab = isWishlist ? 'wishlist' : 'shopping'
useEffect(() => {
fetchArchivedBoards()
}, [])
const fetchArchivedBoards = async () => {
setLoading(true)
try {
const res = await authFetch(`${apiBase}/boards/archived`)
if (res.ok) {
const data = await res.json()
setBoards(Array.isArray(data) ? data : [])
}
} catch (err) {
console.error('Error fetching archived boards:', err)
} finally {
setLoading(false)
}
}
const handleUnarchive = async (boardId) => {
try {
const res = await authFetch(`${apiBase}/boards/${boardId}/unarchive`, {
method: 'POST'
})
if (res.ok) {
setBoards(prev => prev.filter(b => b.id !== boardId))
setToastMessage({ text: 'Доска восстановлена', type: 'success' })
onSaved?.()
} else {
setToastMessage({ text: 'Ошибка восстановления', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка восстановления', type: 'error' })
}
}
const handleDelete = async (board) => {
if (board.is_owner) {
if (!window.confirm(`Удалить доску "${board.name}"? Все ${isWishlist ? 'желания' : 'товары'} на ней будут удалены.`)) return
try {
const res = await authFetch(`${apiBase}/boards/${board.id}`, {
method: 'DELETE'
})
if (res.ok) {
setBoards(prev => prev.filter(b => b.id !== board.id))
setToastMessage({ text: 'Доска удалена', type: 'success' })
onSaved?.()
} else {
setToastMessage({ text: 'Ошибка удаления', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка удаления', type: 'error' })
}
} else {
if (!window.confirm(`Покинуть доску "${board.name}"?`)) return
try {
const res = await authFetch(`${apiBase}/boards/${board.id}/leave`, {
method: 'POST'
})
if (res.ok) {
// Также убираем из архива
await authFetch(`${apiBase}/boards/${board.id}/unarchive`, { method: 'POST' })
setBoards(prev => prev.filter(b => b.id !== board.id))
setToastMessage({ text: 'Вы покинули доску', type: 'success' })
onSaved?.()
} else {
setToastMessage({ text: 'Ошибка', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка', type: 'error' })
}
}
}
const handleOpenBoard = (boardId) => {
onNavigate(returnTab, { boardId })
}
const handleClose = () => {
window.history.back()
}
return (
<div className="archived-boards">
<button className="close-x-button" onClick={handleClose}>
</button>
<h2>Архив</h2>
{loading ? (
<div className="archived-boards-loading">
<div className="w-8 h-8 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
</div>
) : boards.length === 0 ? (
<div className="archived-boards-empty">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#d1d5db" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<polyline points="21 8 21 21 3 21 3 8"></polyline>
<rect x="1" y="3" width="22" height="5"></rect>
<line x1="10" y1="12" x2="14" y2="12"></line>
</svg>
<p>Архив пуст</p>
</div>
) : (
<div className="archived-boards-list">
{boards.map(board => (
<div key={board.id} className="archived-board-card">
<div className="archived-board-info" onClick={() => handleOpenBoard(board.id)}>
<div className="archived-board-name">{board.name}</div>
<div className="archived-board-meta">
{board.is_owner ? 'Моя доска' : `Доска ${board.owner_name}`}
{' · '}
{board.member_count + 1} {board.member_count + 1 === 1 ? 'участник' : 'участников'}
</div>
</div>
<div className="archived-board-actions">
<button
className="archived-board-btn archived-board-restore"
onClick={() => handleUnarchive(board.id)}
title="Восстановить"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="1 4 1 10 7 10"></polyline>
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path>
</svg>
</button>
<button
className="archived-board-btn archived-board-delete"
onClick={() => handleDelete(board)}
title={board.is_owner ? 'Удалить' : 'Покинуть'}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
</button>
</div>
</div>
))}
</div>
)}
{toastMessage && (
<Toast
message={toastMessage.text}
type={toastMessage.type}
onClose={() => setToastMessage(null)}
/>
)}
</div>
)
}
export default ArchivedBoards

View File

@@ -130,3 +130,38 @@
font-size: 0.85rem;
color: #6b7280;
}
/* Board action buttons (for archive, leave) */
.board-actions-list {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.board-action-button {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.875rem 0.5rem;
background: none;
border: none;
border-radius: 0.375rem;
font-size: 0.95rem;
color: #374151;
cursor: pointer;
transition: background 0.15s;
text-align: left;
}
.board-action-button:hover {
background: #f3f4f6;
}
.board-action-button.board-action-danger {
color: #ef4444;
}
.board-action-button.board-action-danger:hover {
background: #fef2f2;
}

View File

@@ -1,13 +1,13 @@
import React, { useState, useEffect } from 'react'
import React, { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import BoardMembers from './BoardMembers'
import Toast from './Toast'
import SubmitButton from './SubmitButton'
import DeleteButton from './DeleteButton'
import './Buttons.css'
import './BoardForm.css'
import './Wishlist.css'
function BoardForm({ boardId, onNavigate, onSaved }) {
function BoardForm({ boardId, onNavigate, onSaved, isActive }) {
const { authFetch } = useAuth()
const [name, setName] = useState('')
const [inviteEnabled, setInviteEnabled] = useState(false)
@@ -17,15 +17,20 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
const [isDeleting, setIsDeleting] = useState(false)
const [copied, setCopied] = useState(false)
const [toastMessage, setToastMessage] = useState(null)
const [isOwner, setIsOwner] = useState(true)
const [isArchived, setIsArchived] = useState(false)
const [showActionMenu, setShowActionMenu] = useState(false)
const actionMenuHistoryRef = useRef(false)
const savedHistoryStateRef = useRef(null)
const isEdit = !!boardId
useEffect(() => {
if (boardId) {
fetchBoard()
}
}, [boardId])
const fetchBoard = async () => {
setLoadingBoard(true)
try {
@@ -35,6 +40,8 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
setName(data.name)
setInviteEnabled(data.invite_enabled)
setInviteURL(data.invite_url || '')
setIsOwner(data.is_owner)
setIsArchived(data.is_archived || false)
} else {
setToastMessage({ text: 'Ошибка загрузки доски', type: 'error' })
}
@@ -44,7 +51,7 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
setLoadingBoard(false)
}
}
const handleSave = async () => {
if (!name.trim()) {
setToastMessage({ text: 'Введите название доски', type: 'error' })
@@ -53,19 +60,19 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
setLoading(true)
try {
const url = boardId
? `/api/wishlist/boards/${boardId}`
const url = boardId
? `/api/wishlist/boards/${boardId}`
: '/api/wishlist/boards'
const res = await authFetch(url, {
method: boardId ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: name.trim(),
invite_enabled: inviteEnabled
body: JSON.stringify({
name: name.trim(),
invite_enabled: inviteEnabled
})
})
if (res.ok) {
const data = await res.json()
if (data.invite_url) {
@@ -89,7 +96,7 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
setLoading(false)
}
}
// Функция для автоматической генерации ссылки при включении доступа
const generateInviteLink = async () => {
try {
@@ -105,7 +112,7 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
console.error('Error generating invite link:', err)
}
}
const handleCopyLink = () => {
navigator.clipboard.writeText(inviteURL)
setCopied(true)
@@ -115,7 +122,7 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
const handleToggleInvite = async (enabled) => {
setInviteEnabled(enabled)
if (boardId && enabled && !inviteURL) {
// Автоматически генерируем ссылку при включении
await generateInviteLink()
@@ -132,10 +139,21 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
}
}
}
// Навигация после действия из action menu: убрать обе записи (action menu + board-form)
const navigateBackFromActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.go(-2)
} else {
window.history.back()
}
}
const handleDelete = async () => {
if (!window.confirm('Удалить доску? Все желания на ней будут удалены.')) return
setIsDeleting(true)
try {
const res = await authFetch(`/api/wishlist/boards/${boardId}`, {
@@ -143,8 +161,7 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
})
if (res.ok) {
onSaved?.()
// Передаём флаг, что доска удалена, чтобы Wishlist выбрал первую доступную
onNavigate('wishlist', { boardDeleted: true })
navigateBackFromActionMenu()
} else {
setToastMessage({ text: 'Ошибка удаления', type: 'error' })
setIsDeleting(false)
@@ -155,10 +172,98 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
}
}
const handleLeave = async () => {
if (!window.confirm('Покинуть доску? Вы больше не будете видеть её желания.')) return
try {
const res = await authFetch(`/api/wishlist/boards/${boardId}/leave`, {
method: 'POST'
})
if (res.ok) {
onSaved?.()
onNavigate('wishlist', { boardDeleted: true }, { replace: true })
} else {
setToastMessage({ text: 'Ошибка выхода', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка выхода', type: 'error' })
}
}
const handleArchive = async () => {
if (!window.confirm('Архивировать доску? Она переместится в архив.')) return
try {
const res = await authFetch(`/api/wishlist/boards/${boardId}/archive`, {
method: 'POST'
})
if (res.ok) {
onSaved?.()
navigateBackFromActionMenu()
} else {
setToastMessage({ text: 'Ошибка архивации', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка архивации', type: 'error' })
}
}
const handleUnarchive = async () => {
try {
const res = await authFetch(`/api/wishlist/boards/${boardId}/unarchive`, {
method: 'POST'
})
if (res.ok) {
onSaved?.()
navigateBackFromActionMenu()
} else {
setToastMessage({ text: 'Ошибка разархивации', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка разархивации', type: 'error' })
}
}
const openActionMenu = () => {
setShowActionMenu(true)
savedHistoryStateRef.current = window.history.state
window.history.pushState({ actionMenu: true }, '')
actionMenuHistoryRef.current = true
}
const closeActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.back()
}
}
// Закрыть меню без popstate — заменяем запись в истории на сохранённое состояние
const dismissActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.replaceState(savedHistoryStateRef.current, '', window.location.href)
}
}
// Обработка popstate для закрытия action menu кнопкой назад
useEffect(() => {
const handlePopState = () => {
if (showActionMenu) {
actionMenuHistoryRef.current = false
setShowActionMenu(false)
}
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
}, [showActionMenu])
const handleClose = () => {
window.history.back()
}
if (loadingBoard) {
return (
<div className="board-form">
@@ -171,19 +276,19 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
</div>
)
}
return (
<div className="board-form">
<button className="close-x-button" onClick={handleClose}>
</button>
<h2>{isEdit ? 'Настройки доски' : 'Новая доска'}</h2>
<div className="form-card">
<div className="form-group">
<label htmlFor="board-name">Название</label>
<input
<input
id="board-name"
type="text"
className="form-input"
@@ -192,13 +297,13 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
placeholder="Название доски"
/>
</div>
{isEdit && (
<>
{/* Настройки доступа */}
<div className="form-section">
<h3>Доступ по ссылке</h3>
<label className="toggle-field">
<input
type="checkbox"
@@ -208,17 +313,17 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
<span className="toggle-slider"></span>
<span className="toggle-label">Разрешить присоединение по ссылке</span>
</label>
{inviteEnabled && inviteURL && (
<div className="invite-link-section">
<div className="invite-url-row">
<input
type="text"
<input
type="text"
className="invite-url-input"
value={inviteURL}
readOnly
value={inviteURL}
readOnly
/>
<button
<button
className="copy-btn"
onClick={handleCopyLink}
title="Копировать ссылку"
@@ -241,36 +346,20 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
</div>
)}
</div>
{/* Список участников */}
<BoardMembers
boardId={boardId}
<BoardMembers
boardId={boardId}
onMemberRemoved={() => {
setToastMessage({ text: 'Участник удалён', type: 'success' })
}}
/>
</>
)}
<div className="form-actions">
<SubmitButton
onClick={handleSave}
loading={loading}
disabled={!name.trim()}
>
Сохранить
</SubmitButton>
{isEdit && (
<DeleteButton
onClick={handleDelete}
loading={isDeleting}
disabled={loading}
title="Удалить доску"
/>
)}
</div>
</div>
{toastMessage && (
<Toast
message={toastMessage.text}
@@ -278,9 +367,100 @@ function BoardForm({ boardId, onNavigate, onSaved }) {
onClose={() => setToastMessage(null)}
/>
)}
{isActive ? createPortal(
<div style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '0.75rem 1rem',
paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))',
background: 'linear-gradient(to top, white 60%, rgba(255,255,255,0))',
zIndex: 1500,
display: 'flex',
justifyContent: 'center',
gap: '0.75rem',
}}>
<button
onClick={handleSave}
disabled={loading || isDeleting || !name.trim()}
style={{
flex: 1,
maxWidth: '42rem',
padding: '0.875rem',
background: (loading || !name.trim()) ? undefined : 'linear-gradient(to right, #10b981, #059669)',
backgroundColor: (loading || !name.trim()) ? '#9ca3af' : undefined,
color: 'white',
border: 'none',
borderRadius: '0.5rem',
fontSize: '1rem',
fontWeight: 600,
cursor: (loading || isDeleting || !name.trim()) ? 'not-allowed' : 'pointer',
opacity: loading ? 0.6 : 1,
transition: 'all 0.2s',
}}
>
{loading ? 'Сохранение...' : 'Сохранить'}
</button>
{isEdit && (
<button
type="button"
onClick={openActionMenu}
disabled={loading || isDeleting}
style={{
width: '52px',
height: '52px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'transparent',
color: '#059669',
border: '2px solid #059669',
borderRadius: '0.5rem',
fontSize: '1.25rem',
fontWeight: 700,
cursor: (loading || isDeleting) ? 'not-allowed' : 'pointer',
lineHeight: 1,
flexShrink: 0,
padding: 0,
boxSizing: 'border-box',
transition: 'all 0.2s',
}}
title="Действия"
>
</button>
)}
</div>,
document.body
) : null}
{showActionMenu && createPortal(
<div className="wishlist-modal-overlay" style={{ zIndex: 2000 }} onClick={closeActionMenu}>
<div className="wishlist-modal" onClick={(e) => e.stopPropagation()}>
<div className="wishlist-modal-header">
<h3>{name}</h3>
</div>
<div className="wishlist-modal-actions">
{isArchived ? (
<button className="wishlist-modal-copy" onClick={handleUnarchive}>
Разархивировать
</button>
) : (
<button className="wishlist-modal-copy" onClick={handleArchive}>
Архивировать
</button>
)}
<button className="wishlist-modal-delete" onClick={handleDelete}>
Удалить
</button>
</div>
</div>
</div>,
document.body
)}
</div>
)
}
export default BoardForm

View File

@@ -2,21 +2,21 @@ import React, { useState, useEffect } from 'react'
import { useAuth } from './auth/AuthContext'
import './BoardMembers.css'
function BoardMembers({ boardId, onMemberRemoved }) {
function BoardMembers({ boardId, onMemberRemoved, apiBase = '/api/wishlist' }) {
const { authFetch } = useAuth()
const [members, setMembers] = useState([])
const [loading, setLoading] = useState(true)
const [removingId, setRemovingId] = useState(null)
useEffect(() => {
if (boardId) {
fetchMembers()
}
}, [boardId])
const fetchMembers = async () => {
try {
const res = await authFetch(`/api/wishlist/boards/${boardId}/members`)
const res = await authFetch(`${apiBase}/boards/${boardId}/members`)
if (res.ok) {
const data = await res.json()
setMembers(data || [])
@@ -27,13 +27,13 @@ function BoardMembers({ boardId, onMemberRemoved }) {
setLoading(false)
}
}
const handleRemoveMember = async (userId) => {
if (!window.confirm('Удалить участника из доски?')) return
setRemovingId(userId)
try {
const res = await authFetch(`/api/wishlist/boards/${boardId}/members/${userId}`, {
const res = await authFetch(`${apiBase}/boards/${boardId}/members/${userId}`, {
method: 'DELETE'
})
if (res.ok) {

View File

@@ -15,7 +15,6 @@
.board-header {
display: flex;
gap: 12px;
align-items: center;
}
@@ -25,12 +24,12 @@
display: flex;
align-items: center;
gap: 10px;
height: 52px;
padding: 0 20px;
height: 40px;
padding: 0 10px 0 16px;
background: white;
border: 1px solid #e5e7eb;
border-radius: 26px;
font-size: 17px;
border-radius: 20px;
font-size: 15px;
font-weight: 500;
color: #1f2937;
cursor: pointer;
@@ -68,50 +67,42 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1;
}
.chevron {
.board-label-archived {
color: #9ca3af;
}
.board-label-archive-icon {
flex-shrink: 0;
transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
color: #9ca3af;
}
.chevron.rotated {
transform: rotate(180deg);
}
/* Кнопка действия (настройки/выход) */
.board-action-btn {
/* Иконка настроек/выхода внутри pill */
.pill-action-btn {
display: flex;
align-items: center;
justify-content: center;
width: 52px;
height: 52px;
padding: 0;
background: white;
border: 1px solid #e5e7eb;
border-radius: 50%;
cursor: pointer;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
color: #6b7280;
width: 18px;
height: 18px;
margin-left: 6px;
border-left: 1px solid #e5e7eb;
padding-left: 6px;
color: #9ca3af;
flex-shrink: 0;
cursor: pointer;
transition: color 0.15s ease;
box-sizing: content-box;
}
.board-action-btn:hover {
background: #f9fafb;
color: #374151;
border-color: #6366f1;
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
transform: translateY(-1px);
.board-pill:hover:not(:disabled) .pill-action-btn,
.board-pill.open .pill-action-btn {
border-left-color: rgba(99, 102, 241, 0.3);
}
.board-action-btn:active {
transform: translateY(0);
}
.board-action-btn svg {
width: 22px;
height: 22px;
.pill-action-btn:hover {
color: #4f46e5;
}
/* Выпадающий список */
@@ -238,11 +229,26 @@
color: #4f46e5;
}
/* Строка с кнопками добавления и архива */
.board-actions-row {
display: flex;
align-items: center;
margin-top: 6px;
border-top: 1px solid #f3f4f6;
}
.board-actions-separator {
width: 1px;
height: 24px;
background: #e5e7eb;
flex-shrink: 0;
}
/* Кнопка добавления доски */
.dropdown-item.add-board {
margin-top: 6px;
flex: 1;
padding-top: 14px;
border-top: 1px solid #f3f4f6;
padding-bottom: 14px;
border-radius: 0 0 12px 12px;
color: #667eea;
font-weight: 500;
@@ -250,6 +256,10 @@
justify-content: flex-start;
}
.board-actions-row .dropdown-item.add-board:not(:last-child) {
border-radius: 0 0 0 12px;
}
.dropdown-item.add-board:hover {
background: linear-gradient(135deg, #667eea08 0%, #764ba208 100%);
}
@@ -259,3 +269,86 @@
width: 20px;
height: 20px;
}
/* Кнопка настроек/выхода в дропдауне */
.dropdown-item.board-action-item {
margin-top: 2px;
padding-top: 14px;
border-top: 1px solid #f3f4f6;
border-radius: 0 0 12px 12px;
color: #6b7280;
font-weight: 500;
gap: 12px;
justify-content: flex-start;
}
.dropdown-item.board-action-item:hover {
background: #f3f4f6;
color: #374151;
}
.dropdown-item.board-action-item svg {
flex-shrink: 0;
width: 20px;
height: 20px;
}
/* Кнопка архива в строке действий */
.dropdown-item.archive-toggle {
flex-shrink: 0;
width: auto;
padding: 14px 14px;
border-radius: 0 0 12px 0;
color: #6b7280;
font-weight: 500;
gap: 6px;
justify-content: center;
}
.dropdown-item.archive-toggle:hover {
background: #f3f4f6;
color: #374151;
}
.dropdown-item.archive-toggle svg {
flex-shrink: 0;
width: 20px;
height: 20px;
}
.archive-toggle-icon {
font-size: 8px;
color: #9ca3af;
}
.archive-list {
padding: 0 4px 4px;
border-top: 1px solid #f3f4f6;
}
.archive-loading {
display: flex;
justify-content: center;
padding: 12px 0;
}
.archive-empty {
padding: 10px 16px;
text-align: center;
color: #9ca3af;
font-size: 14px;
}
.dropdown-item.archive-item {
padding: 14px 16px;
color: #9ca3af;
}
.dropdown-item.archive-item:hover {
background: #f3f4f6;
color: #6b7280;
}
.archive-item-name {
font-weight: 500;
}

View File

@@ -1,17 +1,22 @@
import React, { useState, useEffect, useRef } from 'react'
import React, { useState, useEffect, useRef, useMemo } from 'react'
import './BoardSelector.css'
function BoardSelector({
boards,
selectedBoardId,
onBoardChange,
function BoardSelector({
boards,
selectedBoardId,
onBoardChange,
onBoardEdit,
onAddBoard,
loading
loading,
showBoardAction = true
}) {
const [isOpen, setIsOpen] = useState(false)
const [archiveExpanded, setArchiveExpanded] = useState(false)
const dropdownRef = useRef(null)
const activeBoards = useMemo(() => boards.filter(b => !b.is_archived), [boards])
const archivedBoards = useMemo(() => boards.filter(b => b.is_archived), [boards])
const selectedBoard = boards.find(b => b.id === selectedBoardId)
// Закрытие при клике снаружи
@@ -25,71 +30,69 @@ function BoardSelector({
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [])
useEffect(() => {
if (!isOpen) {
setArchiveExpanded(false)
}
}, [isOpen])
const handleSelectBoard = (board) => {
onBoardChange(board.id)
setIsOpen(false)
}
const handleBoardAction = (e) => {
e.stopPropagation()
setIsOpen(false)
onBoardEdit()
}
return (
<div className="board-selector" ref={dropdownRef}>
<div className="board-header">
<button
<button
className={`board-pill ${isOpen ? 'open' : ''}`}
onClick={() => setIsOpen(!isOpen)}
disabled={loading}
>
<span className="board-label">
{!loading && selectedBoard?.is_archived && (
<svg className="board-label-archive-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="21 8 21 21 3 21 3 8"></polyline>
<rect x="1" y="3" width="22" height="5"></rect>
<line x1="10" y1="12" x2="14" y2="12"></line>
</svg>
)}
<span className={`board-label ${selectedBoard?.is_archived ? 'board-label-archived' : ''}`}>
{loading ? 'Загрузка...' : (selectedBoard?.name || 'Выберите доску')}
</span>
<svg
className={`chevron ${isOpen ? 'rotated' : ''}`}
width="14"
height="14"
viewBox="0 0 12 12"
>
<path
d="M2.5 4.5L6 8L9.5 4.5"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
{selectedBoard && (
<button
className="board-action-btn"
onClick={onBoardEdit}
title={selectedBoard.is_owner ? 'Настройки доски' : 'Покинуть доску'}
>
{selectedBoard.is_owner ? (
{selectedBoard && (
<span
className="pill-action-btn"
role="button"
tabIndex={0}
title="Настройки доски"
onClick={handleBoardAction}
onKeyDown={(e) => e.key === 'Enter' && handleBoardAction(e)}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="1.5"></circle>
<circle cx="19" cy="12" r="1.5"></circle>
<circle cx="5" cy="12" r="1.5"></circle>
</svg>
) : (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line>
</svg>
)}
</button>
)}
</span>
)}
</button>
</div>
<div className={`board-dropdown ${isOpen ? 'visible' : ''}`}>
<div className="dropdown-content">
{boards.length === 0 ? (
{activeBoards.length === 0 && archivedBoards.length === 0 ? (
<div className="dropdown-empty">
Нет досок
</div>
) : (
<div className="dropdown-list">
{boards.map(board => (
{activeBoards.map(board => (
<button
key={board.id}
className={`dropdown-item ${board.id === selectedBoardId ? 'selected' : ''}`}
@@ -103,15 +106,53 @@ function BoardSelector({
))}
</div>
)}
<button className="dropdown-item add-board" onClick={onAddBoard}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="16"></line>
<line x1="8" y1="12" x2="16" y2="12"></line>
</svg>
<span>Создать доску</span>
</button>
<div className="board-actions-row">
<button className="dropdown-item add-board" onClick={onAddBoard}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="16"></line>
<line x1="8" y1="12" x2="16" y2="12"></line>
</svg>
<span>Создать доску</span>
</button>
{archivedBoards.length > 0 && (
<>
<div className="board-actions-separator" />
<button
className="dropdown-item archive-toggle"
onClick={() => setArchiveExpanded(!archiveExpanded)}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="21 8 21 21 3 21 3 8"></polyline>
<rect x="1" y="3" width="22" height="5"></rect>
<line x1="10" y1="12" x2="14" y2="12"></line>
</svg>
<span className="archive-toggle-icon">
{archiveExpanded ? '▼' : '▶'}
</span>
</button>
</>
)}
</div>
{archiveExpanded && archivedBoards.length > 0 && (
<div className="archive-list">
{archivedBoards.map(board => (
<button
key={board.id}
className={`dropdown-item archive-item ${board.id === selectedBoardId ? 'selected' : ''}`}
onClick={() => handleSelectBoard(board)}
>
<span className="item-name archive-item-name">{board.name}</span>
<div className="item-meta">
<span className={`item-members ${board.is_owner ? 'filled' : 'outline'}`}>{board.member_count + 1}</span>
</div>
</button>
))}
</div>
)}
</div>
</div>
</div>

View File

@@ -7,17 +7,17 @@
}
.submit-button {
background: linear-gradient(to right, #6366f1, #8b5cf6);
background: linear-gradient(to right, #10b981, #059669);
color: white;
padding: 0.75rem 1.5rem;
padding: 0.875rem 1.5rem;
border: none;
border-radius: 0.375rem;
border-radius: 0.5rem;
font-size: 1rem;
font-weight: 500;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
flex: 1;
height: 44px;
height: 52px;
box-sizing: border-box;
display: flex;
align-items: center;
@@ -26,7 +26,7 @@
.submit-button:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}
.submit-button:disabled {
@@ -39,7 +39,7 @@
color: white;
padding: 0;
border: none;
border-radius: 0.375rem;
border-radius: 0.5rem;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
@@ -47,9 +47,9 @@
display: flex;
align-items: center;
justify-content: center;
min-width: 44px;
width: 44px;
height: 44px;
width: 52px;
height: 52px;
flex-shrink: 0;
box-sizing: border-box;
}

View File

@@ -271,7 +271,7 @@
justify-content: center;
width: calc(100% - 8px);
max-width: calc(100% - 8px);
color: #5b6b8a;
color: #000;
/* font-size задаётся в JS по количеству цифр (auto-size) */
font-weight: 700;
line-height: 1.2;
@@ -306,3 +306,118 @@
white-space: nowrap;
text-align: center;
}
/* Вертикальный список желаний (для 1-2 элементов) */
.project-wishes-vertical {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
/* Карточка желания в виде строки */
.wish-row-card {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 1rem;
background-color: #fff;
cursor: pointer;
transition: background-color 0.2s;
box-shadow: 0 1px 3px 0 rgb(99 102 241 / 0.08);
}
.wish-row-card:hover {
background-color: #f9fafb;
}
.wish-row-card:active {
background-color: #f3f4f6;
}
/* Логика скруглений: карточка проекта всегда сверху, последнее желание - снизу */
.wish-row-card-last {
border-radius: 0 0 1.5rem 1.5rem;
}
.wish-row-card-middle {
border-radius: 0;
}
/* Изображение желания */
.wish-row-image {
flex-shrink: 0;
width: 50px;
height: 60px;
margin-top: 0.25rem;
margin-bottom: 0.25rem;
background: #f0f0f0;
border-radius: 8px;
overflow: hidden;
position: relative;
}
.wish-row-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.wish-row-overlay {
position: absolute;
inset: 0;
z-index: 1;
background: rgba(255, 255, 255, 0.65);
pointer-events: none;
}
.wish-row-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.25rem;
background: white;
border: 1px solid #e5e7eb;
border-radius: 8px;
}
/* Блок с информацией о желании */
.wish-row-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.wish-row-title {
font-size: 1rem;
font-weight: 600;
color: #1f2937;
line-height: 1.3;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wish-row-unlock {
font-size: 0.875rem;
color: #6b7280;
}
/* Текст "Готово!" синим для WishRowCard */
.wish-row-unlock.ready {
color: #3b82f6;
font-weight: 600;
}
/* Синяя обводка для готового MiniWishCard */
.mini-wish-image.ready {
border: 2px solid #3b82f6;
}
/* Синяя обводка для готового WishRowCard */
.wish-row-image.ready {
border: 2px solid #3b82f6;
}

View File

@@ -96,7 +96,7 @@ function CircularProgressBar({ progress, size = 120, strokeWidth = 8, showCheckm
}
// Компонент мини-карточки желания для отображения внутри карточки проекта
function MiniWishCard({ wish, onClick }) {
function MiniWishCard({ wish, onClick, pendingScoresByProject = {} }) {
const handleClick = (e) => {
e.stopPropagation()
if (onClick) {
@@ -104,11 +104,19 @@ function MiniWishCard({ wish, onClick }) {
}
}
const cond = wish.first_locked_condition
// Желание помечено как готовое на бэкенде
const isReady = wish.is_ready === true
// Для готовых желаний берём условие из unlock_conditions, иначе из first_locked_condition
const cond = isReady
? wish.unlock_conditions?.find(c => c.type === 'project_points')
: wish.first_locked_condition
const isPointsCondition = cond?.type === 'project_points'
const required = cond?.required_points ?? 0
const current = cond?.current_points ?? 0
const remaining = isPointsCondition ? Math.max(0, required - current) : 0
const projectId = cond?.project_id
const pending = (projectId != null && pendingScoresByProject[projectId] != null) ? Number(pendingScoresByProject[projectId]) : 0
const remaining = isPointsCondition ? (required - current - pending) : 0
const showUnlockPoints = remaining > 0
// Auto-size: уменьшаем шрифт при большом количестве цифр, чтобы текст влезал
@@ -117,14 +125,14 @@ function MiniWishCard({ wish, onClick }) {
return (
<div className="mini-wish-card" onClick={handleClick}>
<div className="mini-wish-image">
<div className={`mini-wish-image ${isReady ? 'ready' : ''}`}>
{wish.image_url ? (
<img src={wish.image_url} alt={wish.name} />
) : (
<div className="mini-wish-placeholder">🎁</div>
)}
<div className="mini-wish-overlay" aria-hidden="true" />
{showUnlockPoints && (
{!isReady && <div className="mini-wish-overlay" aria-hidden="true" />}
{showUnlockPoints && !isReady && (
<div
className="mini-wish-unlock-points"
style={{ fontSize: `${fontSizePx}px` }}
@@ -138,8 +146,86 @@ function MiniWishCard({ wish, onClick }) {
)
}
// Компонент карточки желания в виде строки (для отображения 1-2 желаний)
function WishRowCard({ wish, onClick, pendingScoresByProject = {}, position, minGoalScore }) {
const handleClick = (e) => {
e.stopPropagation()
if (onClick) {
onClick(wish)
}
}
// Желание помечено как готовое на бэкенде
const isReady = wish.is_ready === true
// Для готовых желаний берём условие из unlock_conditions, иначе из first_locked_condition
const cond = isReady
? wish.unlock_conditions?.find(c => c.type === 'project_points')
: wish.first_locked_condition
const isPointsCondition = cond?.type === 'project_points'
const required = cond?.required_points ?? 0
const current = cond?.current_points ?? 0
const projectId = cond?.project_id
const pending = (projectId != null && pendingScoresByProject[projectId] != null) ? Number(pendingScoresByProject[projectId]) : 0
const remaining = isPointsCondition ? (required - current - pending) : 0
const formatDaysText = (days) => {
if (days < 1) return '<1 дня'
const daysRounded = Math.round(days)
const lastDigit = daysRounded % 10
const lastTwoDigits = daysRounded % 100
let dayWord
if (lastTwoDigits >= 11 && lastTwoDigits <= 14) {
dayWord = 'дней'
} else if (lastDigit === 1) {
dayWord = 'день'
} else if (lastDigit >= 2 && lastDigit <= 4) {
dayWord = 'дня'
} else {
dayWord = 'дней'
}
return `${daysRounded} ${dayWord}`
}
const getUnlockText = () => {
if (isReady) {
return 'Разблокировано!'
}
if (remaining <= 0) {
return 'в конце дня'
}
const pointsText = `${Math.round(remaining)} баллов`
const safeMinGoal = Number.isFinite(minGoalScore) && minGoalScore > 0 ? minGoalScore : 0
if (safeMinGoal > 0) {
const weeks = remaining / safeMinGoal
const days = weeks * 7
return `${pointsText} (${formatDaysText(days)})`
}
return pointsText
}
const positionClass = position === 'last' ? 'wish-row-card-last' : 'wish-row-card-middle'
return (
<div className={`wish-row-card ${positionClass}`} onClick={handleClick}>
<div className={`wish-row-image ${isReady ? 'ready' : ''}`}>
{wish.image_url ? (
<img src={wish.image_url} alt={wish.name} />
) : (
<div className="wish-row-placeholder">🎁</div>
)}
{!isReady && <div className="wish-row-overlay" aria-hidden="true" />}
</div>
<div className="wish-row-info">
<div className="wish-row-title">{wish.name}</div>
<div className={`wish-row-unlock ${isReady ? 'ready' : ''}`}>{getUnlockText()}</div>
</div>
</div>
)
}
// Компонент карточки проекта с круглым прогрессбаром
function ProjectCard({ project, projectColor, onProjectClick, wishes = [], onWishClick }) {
function ProjectCard({ project, projectColor, onProjectClick, wishes = [], onWishClick, pendingScoresByProject = {} }) {
const { project_name, total_score, min_goal_score, max_goal_score, priority, today_change } = project
// Вычисляем прогресс по оригинальной логике из ProjectProgressBar
@@ -265,26 +351,46 @@ function ProjectCard({ project, projectColor, onProjectClick, wishes = [], onWis
</div>
</div>
{/* Горизонтальный список желаний в отдельном белом блоке */}
{/* Список желаний: горизонтальный скролл для 3+, вертикальный список для 1-2 */}
{hasWishes && (
<div className="project-wishes-block">
<div className="project-wishes-scroll">
{wishes.map((wish) => (
<MiniWishCard
key={wish.id}
wish={wish}
onClick={onWishClick}
/>
))}
wishes.length >= 3 ? (
<div className="project-wishes-block">
<div className="project-wishes-scroll">
{wishes.map((wish) => (
<MiniWishCard
key={wish.id}
wish={wish}
onClick={onWishClick}
pendingScoresByProject={pendingScoresByProject || {}}
/>
))}
</div>
</div>
</div>
) : (
<div className="project-wishes-vertical">
{wishes.map((wish, index) => {
const isLast = index === wishes.length - 1
const position = isLast ? 'last' : 'middle'
return (
<WishRowCard
key={wish.id}
wish={wish}
onClick={onWishClick}
pendingScoresByProject={pendingScoresByProject || {}}
position={position}
minGoalScore={min_goal_score}
/>
)
})}
</div>
)
)}
</div>
)
}
// Компонент группы проектов по приоритету
function PriorityGroup({ title, subtitle, projects, allProjects, onProjectClick, getWishesForProject, onWishClick }) {
function PriorityGroup({ title, subtitle, projects, allProjects, onProjectClick, getWishesForProject, onWishClick, pendingScoresByProject = {} }) {
if (projects.length === 0) return null
return (
@@ -312,6 +418,7 @@ function PriorityGroup({ title, subtitle, projects, allProjects, onProjectClick,
onProjectClick={onProjectClick}
wishes={projectWishes}
onWishClick={onWishClick}
pendingScoresByProject={pendingScoresByProject}
/>
)
})}
@@ -577,8 +684,9 @@ function CurrentWeek({ onProjectClick, data, loading, error, onRetry, allProject
const [toastMessage, setToastMessage] = useState(null)
const [selectedWishlistId, setSelectedWishlistId] = useState(null)
// Желания приходят вместе с данными проектов
// Желания и pending-баллы по проектам приходят вместе с данными
const wishes = data?.wishes || []
const pendingScoresByProject = data?.pending_scores_by_project && typeof data.pending_scores_by_project === 'object' ? data.pending_scores_by_project : {}
// Функция для получения числового значения срока из текста
const getWeeksValue = (weeksText) => {
@@ -590,19 +698,31 @@ function CurrentWeek({ onProjectClick, data, loading, error, onRetry, allProject
}
// Функция фильтрации желаний для проекта
// Фильтрация уже выполнена на бэкенде, здесь только группируем по проекту
const getWishesForProject = (projectId) => {
// Вспомогательная функция для получения projectId из желания
const getWishProjectId = (wish) => {
// Сначала пробуем first_locked_condition
if (wish.first_locked_condition?.project_id) {
return wish.first_locked_condition.project_id
}
// Иначе ищем в unlock_conditions (для готовых/разблокированных желаний)
if (wish.unlock_conditions) {
const cond = wish.unlock_conditions.find(c => c.type === 'project_points')
return cond?.project_id
}
return null
}
const filtered = wishes.filter(wish => {
if (wish.unlocked || wish.completed) return false
if (wish.locked_conditions_count !== 1) return false
const condition = wish.first_locked_condition
if (!condition || condition.project_id !== projectId) return false
const weeksText = condition.weeks_text
if (!weeksText) return false
return weeksText === '1 неделя' || weeksText === '<1 недели'
return getWishProjectId(wish) === projectId
})
// Сортируем по сроку разблокировки (от меньшего к большему)
// Сортируем: готовые желания первыми, затем по сроку разблокировки
return filtered.sort((a, b) => {
// Готовые желания показываем первыми
if (a.is_ready && !b.is_ready) return -1
if (!a.is_ready && b.is_ready) return 1
const weeksA = getWeeksValue(a.first_locked_condition?.weeks_text)
const weeksB = getWeeksValue(b.first_locked_condition?.weeks_text)
return weeksA - weeksB
@@ -759,12 +879,6 @@ function CurrentWeek({ onProjectClick, data, loading, error, onRetry, allProject
showCheckmark={true}
displayProgress={displayOverallProgress}
/>
{/* Подсказка при наведении */}
<div className="absolute inset-0 rounded-full opacity-0 hover:opacity-100 transition-opacity duration-200 bg-black bg-opacity-10 flex items-center justify-center">
<span className="text-xs text-gray-600 font-medium bg-white px-2 py-1 rounded shadow-sm">
Открыть статистику
</span>
</div>
</div>
</div>
@@ -778,6 +892,7 @@ function CurrentWeek({ onProjectClick, data, loading, error, onRetry, allProject
onProjectClick={onProjectClick}
getWishesForProject={getWishesForProject}
onWishClick={handleWishClick}
pendingScoresByProject={pendingScoresByProject}
/>
<PriorityGroup
@@ -788,6 +903,7 @@ function CurrentWeek({ onProjectClick, data, loading, error, onRetry, allProject
onProjectClick={onProjectClick}
getWishesForProject={getWishesForProject}
onWishClick={handleWishClick}
pendingScoresByProject={pendingScoresByProject}
/>
<PriorityGroup
@@ -798,6 +914,7 @@ function CurrentWeek({ onProjectClick, data, loading, error, onRetry, allProject
onProjectClick={onProjectClick}
getWishesForProject={getWishesForProject}
onWishClick={handleWishClick}
pendingScoresByProject={pendingScoresByProject}
/>
</div>

View File

@@ -37,21 +37,32 @@ const formatDate = (date) => {
// Названия дней недели
const dayNames = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс']
function FullStatistics({ selectedProject, onClearSelection, data, loading, error, onRetry, currentWeekData, onNavigate, todayEntries, todayEntriesLoading, todayEntriesError, onRetryTodayEntries, fetchTodayEntries, activeTab }) {
function FullStatistics({ selectedProject, onClearSelection, data, loading, error, onRetry, currentWeekData, onNavigate, todayEntries, todayEntriesLoading, todayEntriesError, onRetryTodayEntries, fetchTodayEntries, fetchCurrentWeekData, activeTab }) {
const [selectedDate, setSelectedDate] = useState(null)
const prevActiveTabRef = React.useRef(activeTab)
const componentJustOpenedRef = React.useRef(false)
const lastActiveProjectRef = React.useRef(selectedProject)
const [projectChanged, setProjectChanged] = React.useState(false)
// Пересчитываем текущий день и даты недели при каждом открытии экрана
const [now, setNow] = useState(() => new Date())
useEffect(() => {
if (activeTab === 'full') {
setNow(new Date())
}
}, [activeTab])
// Получаем даты текущей недели
const weekDates = getCurrentWeekDates()
// Определяем текущий день (используем useMemo для стабильности)
const weekDates = React.useMemo(() => getCurrentWeekDates(), [now]) // eslint-disable-line react-hooks/exhaustive-deps
// Определяем текущий день
const today = React.useMemo(() => {
const date = new Date()
const date = new Date(now)
date.setHours(0, 0, 0, 0)
return date
}, [])
}, [now])
// Получаем строковое представление сегодняшней даты
const todayDateStr = React.useMemo(() => formatDate(today), [today])
@@ -90,23 +101,39 @@ function FullStatistics({ selectedProject, onClearSelection, data, loading, erro
// Когда компонент открывается (activeTab становится 'full'), помечаем это
if (activeTab === 'full' && prevActiveTabRef.current !== 'full') {
componentJustOpenedRef.current = true
// Проверяем, изменился ли проект с прошлого открытия
if (lastActiveProjectRef.current !== selectedProject) {
setProjectChanged(true)
}
}
// Запоминаем текущий проект при закрытии экрана
if (prevActiveTabRef.current === 'full' && activeTab !== 'full') {
lastActiveProjectRef.current = selectedProject
}
prevActiveTabRef.current = activeTab
}, [activeTab])
}, [activeTab, selectedProject])
// Загружаем данные при открытии экрана, при изменении selectedDate или selectedProject
useEffect(() => {
if (activeTab === 'full' && selectedDate && fetchTodayEntries) {
// Если компонент только что открылся - используем фоновую загрузку
// Если компонент только что открылся
if (componentJustOpenedRef.current) {
componentJustOpenedRef.current = false
fetchTodayEntries(true, selectedProject, selectedDate)
// Если проект изменился - показываем загрузку (не фоновую)
if (projectChanged) {
setProjectChanged(false)
lastActiveProjectRef.current = selectedProject
fetchTodayEntries(false, selectedProject, selectedDate)
} else {
// Тот же проект - фоновая загрузка
fetchTodayEntries(true, selectedProject, selectedDate)
}
} else {
// При изменении даты или проекта - используем обычную загрузку (не фоновую)
fetchTodayEntries(false, selectedProject, selectedDate)
}
}
}, [activeTab, selectedDate, selectedProject, fetchTodayEntries])
}, [activeTab, selectedDate, selectedProject, fetchTodayEntries, projectChanged])
// Обработчик выбора дня
const handleDaySelect = useCallback((date) => {
@@ -153,7 +180,7 @@ function FullStatistics({ selectedProject, onClearSelection, data, loading, erro
{/* Чипсы дней недели */}
{pastDays.length > 0 && (
<div className="mt-3 mb-2">
<div className="flex flex-wrap gap-2.5">
<div className="flex flex-nowrap gap-2.5 overflow-x-auto" style={{scrollbarWidth: 'none', msOverflowStyle: 'none'}}>
{pastDays.map((date, index) => {
const dateStr = formatDate(date)
const dayOfWeek = index + 1 // 1 = понедельник
@@ -190,7 +217,12 @@ function FullStatistics({ selectedProject, onClearSelection, data, loading, erro
loading={todayEntriesLoading}
error={todayEntriesError}
onRetry={() => fetchTodayEntries && fetchTodayEntries(false, selectedProject, selectedDate)}
onDelete={() => fetchTodayEntries && fetchTodayEntries(false, selectedProject, selectedDate)}
onDelete={() => {
fetchTodayEntries && fetchTodayEntries(true, selectedProject, selectedDate)
fetchCurrentWeekData && fetchCurrentWeekData(true)
onRetry && onRetry(true)
}}
onNavigate={onNavigate}
/>
</>
)}

View File

@@ -1,28 +1,11 @@
.loading-error-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 80px; /* Отступ для нижнего бара */
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
}
/* Учитываем safe-area для мобильных устройств */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
.loading-error-container {
bottom: calc(80px + env(safe-area-inset-bottom, 0px));
}
padding: 0.5rem 0;
}
.loading-error-content {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 1rem;
gap: 0.75rem;
}
.loading-error-text {
@@ -32,6 +15,7 @@
}
.loading-error-button {
width: 100%;
padding: 0.75rem 1.5rem;
background: linear-gradient(to right, #4f46e5, #9333ea);
color: white;

View File

@@ -5,7 +5,6 @@ function LoadingError({ onRetry }) {
return (
<div className="loading-error-container">
<div className="loading-error-content">
<div className="loading-error-text">Ошибка, повторите позже</div>
{onRetry && (
<button
onClick={onRetry}

View File

@@ -120,6 +120,29 @@ function Profile({ onNavigate }) {
</svg>
</div>
</button>
<button
onClick={() => onNavigate?.('shopping')}
className="w-full p-4 bg-white rounded-xl shadow-sm hover:shadow-md transition-all text-left border border-gray-100 hover:border-indigo-200 group"
>
<div className="flex items-center justify-between">
<span className="text-gray-800 font-medium group-hover:text-indigo-600 transition-colors">
Товары
</span>
<svg
className="w-5 h-5 text-gray-400 group-hover:text-indigo-500 transition-colors"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5l7 7-7 7"
/>
</svg>
</div>
</button>
</div>
</div>

View File

@@ -27,10 +27,10 @@ import './Integrations.css'
// API endpoints (используем относительные пути, проксирование настроено в nginx/vite)
const PROJECTS_API_URL = '/projects'
const PRIORITY_UPDATE_API_URL = '/project/priority'
const PROJECT_COLOR_API_URL = '/project/color'
const PROJECT_MOVE_API_URL = '/project/move'
const PROJECT_CREATE_API_URL = '/project/create'
const PRIORITIES_CONFIRM_API_URL = '/priorities/confirm'
// Компонент экрана добавления проекта
function AddProjectScreen({ onClose, onSuccess, onError }) {
@@ -387,13 +387,14 @@ function PrioritySlot({ title, projects, allProjects, onMenuClick, maxItems = nu
)
}
function ProjectPriorityManager({ allProjectsData, currentWeekData, shouldLoad, onLoadingChange, onErrorChange, refreshTrigger, onNavigate }) {
function ProjectPriorityManager({ allProjectsData, currentWeekData, shouldLoad, onLoadingChange, onErrorChange, refreshTrigger, onNavigate, onConfirmed, onClose }) {
const { authFetch } = useAuth()
const [projectsLoading, setProjectsLoading] = useState(false)
const [projectsError, setProjectsError] = useState(null)
const [hasDataCache, setHasDataCache] = useState(false) // Отслеживаем наличие кеша
const [toastMessage, setToastMessage] = useState(null)
const [isSaving, setIsSaving] = useState(false)
// Уведомляем родительский компонент об изменении состояния загрузки
useEffect(() => {
if (onLoadingChange) {
@@ -421,9 +422,8 @@ function ProjectPriorityManager({ allProjectsData, currentWeekData, shouldLoad,
const scrollContainerRef = useRef(null)
const hasFetchedRef = useRef(false)
const skipNextEffectRef = useRef(false)
const lastRefreshTriggerRef = useRef(0) // Отслеживаем последний обработанный refreshTrigger
const isLoadingRef = useRef(false) // Отслеживаем, идет ли сейчас загрузка
const lastRefreshTriggerRef = useRef(0)
const isLoadingRef = useRef(false)
const sensors = useSensors(
useSensor(PointerSensor, {
@@ -608,60 +608,30 @@ function ProjectPriorityManager({ allProjectsData, currentWeekData, shouldLoad,
return map
}, [lowPriority, maxPriority, mediumPriority])
const prevAssignmentsRef = useRef(new Map())
const initializedAssignmentsRef = useRef(false)
const handleSave = useCallback(async () => {
const assignments = buildAssignments()
const changes = []
assignments.forEach(({ id, priority }) => {
if (id) changes.push({ id, priority })
})
const sendPriorityChanges = useCallback(async (changes) => {
if (!changes.length) return
setIsSaving(true)
try {
await authFetch(PRIORITY_UPDATE_API_URL, {
const response = await authFetch(PRIORITIES_CONFIRM_API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(changes),
})
} catch (e) {
console.error('Ошибка отправки изменений приоритета', e)
}
}, [])
useEffect(() => {
const current = buildAssignments()
if (!initializedAssignmentsRef.current) {
prevAssignmentsRef.current = current
initializedAssignmentsRef.current = true
return
}
if (skipNextEffectRef.current) {
skipNextEffectRef.current = false
prevAssignmentsRef.current = current
return
}
const prev = prevAssignmentsRef.current
const allKeys = new Set([...prev.keys(), ...current.keys()])
const changes = []
allKeys.forEach(key => {
const prevItem = prev.get(key)
const currItem = current.get(key)
const prevPriority = prevItem?.priority ?? null
const currPriority = currItem?.priority ?? null
const id = currItem?.id ?? prevItem?.id
if (!id) return
if (prevPriority !== currPriority) {
changes.push({ id, priority: currPriority })
if (!response.ok) {
const errText = await response.text().catch(() => '')
throw new Error(`Ошибка сохранения (${response.status})${errText ? ': ' + errText : ''}`)
}
})
if (changes.length) {
sendPriorityChanges(changes)
if (onConfirmed) onConfirmed()
} catch (e) {
setToastMessage({ text: e.message || 'Ошибка сохранения', type: 'error' })
setIsSaving(false)
}
prevAssignmentsRef.current = current
}, [buildAssignments, sendPriorityChanges])
}, [authFetch, buildAssignments, onConfirmed])
const findProjectContainer = (projectName) => {
if (maxPriority.find(p => p.name === projectName)) return 'max'
@@ -919,9 +889,9 @@ function ProjectPriorityManager({ allProjectsData, currentWeekData, shouldLoad,
return (
<div className="max-w-2xl mx-auto flex flex-col h-full">
{onNavigate && (
{(onNavigate || onClose) && (
<button
onClick={() => window.history.back()}
onClick={() => onClose ? onClose() : window.history.back()}
className="close-x-button"
title="Закрыть"
>
@@ -1090,6 +1060,40 @@ function ProjectPriorityManager({ allProjectsData, currentWeekData, shouldLoad,
/>
)}
{!(projectsLoading && !maxPriority.length && !mediumPriority.length && !lowPriority.length) && <div style={{
position: 'sticky',
bottom: 0,
left: 0,
right: 0,
padding: '0.75rem 0',
paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))',
background: 'linear-gradient(to top, white 60%, rgba(255,255,255,0))',
display: 'flex',
justifyContent: 'center',
}}>
<button
onClick={handleSave}
disabled={isSaving}
style={{
width: '100%',
maxWidth: '42rem',
padding: '0.875rem',
background: isSaving ? undefined : 'linear-gradient(to right, #10b981, #059669)',
backgroundColor: isSaving ? '#9ca3af' : undefined,
color: 'white',
border: 'none',
borderRadius: '0.5rem',
fontSize: '1rem',
fontWeight: 600,
cursor: isSaving ? 'not-allowed' : 'pointer',
opacity: isSaving ? 0.6 : 1,
transition: 'all 0.2s',
}}
>
{isSaving ? 'Сохранение...' : 'Сохранить'}
</button>
</div>}
{toastMessage && (
<Toast
message={toastMessage.text}

View File

@@ -0,0 +1,383 @@
import React, { useState, useEffect, useRef, useMemo } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import ShoppingItemDetail from './ShoppingItemDetail'
import Toast from './Toast'
import './TaskList.css'
import './TaskDetail.css'
import './ShoppingList.css'
// Форматирование даты для отображения
const formatDateForDisplay = (dateStr) => {
if (!dateStr) return ''
const date = new Date(dateStr)
if (isNaN(date.getTime())) return ''
const now = new Date()
now.setHours(0, 0, 0, 0)
const target = new Date(date.getFullYear(), date.getMonth(), date.getDate())
const diffDays = Math.round((target - now) / (1000 * 60 * 60 * 24))
if (diffDays === 0) return 'Сегодня'
if (diffDays === 1) return 'Завтра'
const months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря']
return `${date.getDate()} ${months[date.getMonth()]}`
}
function PurchaseScreen({ onNavigate, purchaseConfigId, taskId, taskName }) {
const { authFetch } = useAuth()
const [items, setItems] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
const [selectedItemForDetail, setSelectedItemForDetail] = useState(null)
const [toast, setToast] = useState(null)
const [expandedFuture, setExpandedFuture] = useState({})
const [isCompleting, setIsCompleting] = useState(false)
const historyPushedForDetailRef = useRef(false)
const selectedItemForDetailRef = useRef(null)
const fetchItems = async () => {
if (!purchaseConfigId) return
try {
setLoading(true)
setError(false)
const response = await authFetch(`/api/purchase/items/${purchaseConfigId}`)
if (response.ok) {
const data = await response.json()
setItems(Array.isArray(data) ? data : [])
} else {
setError(true)
}
} catch (err) {
console.error('Error loading purchase items:', err)
setError(true)
} finally {
setLoading(false)
}
}
useEffect(() => {
fetchItems()
}, [purchaseConfigId])
const handleRefresh = () => {
fetchItems()
}
const handleClose = () => {
window.history.back()
}
const handleCompleteTask = async () => {
if (!taskId || isCompleting) return
setIsCompleting(true)
try {
const response = await authFetch(`/api/tasks/${taskId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
})
if (response.ok) {
setTimeout(() => window.history.back(), 500)
return
} else {
const errorData = await response.json().catch(() => ({}))
setToast({ message: errorData.error || 'Ошибка выполнения', type: 'error' })
}
} catch (err) {
setToast({ message: 'Ошибка выполнения', type: 'error' })
}
setIsCompleting(false)
}
// Синхронизация refs для диалогов
useEffect(() => {
selectedItemForDetailRef.current = selectedItemForDetail
}, [selectedItemForDetail])
// Пуш в историю при открытии модалок и обработка popstate
useEffect(() => {
if (selectedItemForDetail && !historyPushedForDetailRef.current) {
window.history.pushState({ modalOpen: true, type: 'purchase-detail' }, '', window.location.href)
historyPushedForDetailRef.current = true
} else if (!selectedItemForDetail) {
historyPushedForDetailRef.current = false
}
if (!selectedItemForDetail) return
const handlePopState = () => {
const currentDetail = selectedItemForDetailRef.current
if (currentDetail) {
setSelectedItemForDetail(null)
historyPushedForDetailRef.current = false
}
}
window.addEventListener('popstate', handlePopState)
return () => {
window.removeEventListener('popstate', handlePopState)
}
}, [selectedItemForDetail])
// Фильтрация и группировка
const groupedItems = useMemo(() => {
const now = new Date()
now.setHours(0, 0, 0, 0)
const todayEnd = new Date(now)
todayEnd.setHours(23, 59, 59, 999)
const groups = {}
items.forEach(item => {
const groupKey = item.group_name || 'Остальные'
if (!groups[groupKey]) {
groups[groupKey] = { active: [], future: [] }
}
if (!item.next_show_at) {
groups[groupKey].future.push(item)
return
}
const showAt = new Date(item.next_show_at)
if (showAt > todayEnd) {
groups[groupKey].future.push(item)
return
}
groups[groupKey].active.push(item)
})
Object.values(groups).forEach(group => {
group.future.sort((a, b) => {
if (!a.next_show_at) return 1
if (!b.next_show_at) return -1
return new Date(a.next_show_at) - new Date(b.next_show_at)
})
})
return groups
}, [items])
const groupNames = useMemo(() => {
const names = Object.keys(groupedItems)
return names.sort((a, b) => {
const groupA = groupedItems[a]
const groupB = groupedItems[b]
const hasActiveA = groupA.active.length > 0
const hasActiveB = groupB.active.length > 0
if (hasActiveA && !hasActiveB) return -1
if (!hasActiveA && hasActiveB) return 1
if (a === 'Остальные') return 1
if (b === 'Остальные') return -1
return a.localeCompare(b, 'ru')
})
}, [groupedItems])
const toggleFuture = (groupName) => {
setExpandedFuture(prev => ({
...prev,
[groupName]: !prev[groupName]
}))
}
const handleCloseDetail = (skipHistoryBack) => {
if (!skipHistoryBack && historyPushedForDetailRef.current) {
window.history.back()
} else {
setSelectedItemForDetail(null)
historyPushedForDetailRef.current = false
}
}
const renderItem = (item) => {
let dateDisplay = null
if (item.next_show_at) {
const itemDate = new Date(item.next_show_at)
const now = new Date()
now.setHours(0, 0, 0, 0)
const target = new Date(itemDate.getFullYear(), itemDate.getMonth(), itemDate.getDate())
if (target > now) {
dateDisplay = formatDateForDisplay(item.next_show_at)
}
}
return (
<div
key={item.id}
className="task-item"
onClick={() => setSelectedItemForDetail(item.id)}
>
<div className="task-item-content">
<div
className="task-checkmark"
onClick={(e) => {
e.stopPropagation()
setSelectedItemForDetail(item.id)
}}
title="Выполнить"
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="10" cy="10" r="9" stroke="currentColor" strokeWidth="2" fill="none" className="checkmark-circle" />
<path d="M6 10 L9 13 L14 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="checkmark-check" />
</svg>
</div>
<div className="task-name-container">
<div className="task-name-wrapper">
<div className="task-name">
{item.name}
{item.estimated_remaining > 0 && (
<span className="task-subtasks-count">
({Math.round(item.estimated_remaining * 10) / 10})
</span>
)}
</div>
{dateDisplay && (
<div className="task-next-show-date">{dateDisplay}</div>
)}
</div>
</div>
</div>
</div>
)
}
return (
<div className="max-w-2xl mx-auto" style={{ paddingBottom: taskId ? '5rem' : '2.5rem' }}>
<button className="close-x-button" onClick={handleClose}></button>
<h2 className="text-2xl font-semibold text-gray-800 mb-6" style={{ marginTop: '1.25rem' }}>{taskName || 'Закупка'}</h2>
{loading && items.length === 0 && (
<div className="shopping-loading">
<div className="w-8 h-8 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
</div>
)}
{error && (
<div className="shopping-empty">
<p>Ошибка загрузки</p>
<button onClick={handleRefresh} style={{ marginTop: '8px', color: 'var(--accent-color)' }}>
Повторить
</button>
</div>
)}
{!loading && !error && items.length === 0 && (
<div className="shopping-empty">
<p>Нет товаров</p>
</div>
)}
{groupNames.map(groupName => {
const group = groupedItems[groupName]
const hasActive = group.active.length > 0
const hasFuture = group.future.length > 0
const isFutureExpanded = expandedFuture[groupName]
return (
<div key={groupName} className={`project-group ${!hasActive ? 'project-group-no-tasks' : ''}`}>
<div
className={`project-group-header ${hasFuture ? 'project-group-header-clickable' : ''}`}
onClick={hasFuture ? () => toggleFuture(groupName) : undefined}
>
<h3 className={`project-group-title ${!hasActive ? 'project-group-title-empty' : ''}`}>{groupName}</h3>
{hasFuture ? (
<button
className="completed-toggle-header"
onClick={(e) => {
e.stopPropagation()
toggleFuture(groupName)
}}
title={isFutureExpanded ? 'Скрыть ожидающие' : 'Показать ожидающие'}
>
<span className="completed-toggle-icon">
{isFutureExpanded ? '▼' : '▶'}
</span>
</button>
) : (
<div className="completed-toggle-header" style={{ visibility: 'hidden', pointerEvents: 'none' }}>
<span className="completed-toggle-icon"></span>
</div>
)}
</div>
{hasActive && (
<div className="task-group">
{group.active.map(item => renderItem(item))}
</div>
)}
{hasFuture && isFutureExpanded && (
<div className="task-group completed-tasks">
{group.future.map(item => renderItem(item))}
</div>
)}
</div>
)
})}
{/* Кнопка завершения задачи — фиксированная внизу */}
{!loading && !error && taskId && createPortal(
<div style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '0.75rem 1rem',
paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))',
background: 'linear-gradient(to top, white 60%, rgba(255,255,255,0))',
zIndex: 1500,
display: 'flex',
justifyContent: 'center',
}}>
<button
onClick={handleCompleteTask}
disabled={isCompleting}
style={{
width: '100%',
maxWidth: '42rem',
padding: '0.875rem',
background: 'linear-gradient(to right, #10b981, #059669)',
color: 'white',
border: 'none',
borderRadius: '0.5rem',
fontSize: '1rem',
fontWeight: 600,
cursor: isCompleting ? 'not-allowed' : 'pointer',
opacity: isCompleting ? 0.6 : 1,
transition: 'all 0.2s',
}}
>
{isCompleting ? 'Выполняется...' : 'Завершить'}
</button>
</div>,
document.body
)}
{/* Модалка выполнения */}
{selectedItemForDetail && (
<ShoppingItemDetail
itemId={selectedItemForDetail}
onClose={handleCloseDetail}
onRefresh={handleRefresh}
onItemCompleted={() => setToast({ message: 'Товар выполнен', type: 'success' })}
onNavigate={onNavigate}
/>
)}
{toast && (
<Toast
message={toast.message}
type={toast.type}
onClose={() => setToast(null)}
/>
)}
</div>
)
}
export default PurchaseScreen

View File

@@ -0,0 +1,460 @@
import React, { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import BoardMembers from './BoardMembers'
import Toast from './Toast'
import './Buttons.css'
import './BoardForm.css'
import './Wishlist.css'
function ShoppingBoardForm({ boardId, onNavigate, onSaved, isActive }) {
const { authFetch } = useAuth()
const [name, setName] = useState('')
const [inviteEnabled, setInviteEnabled] = useState(false)
const [inviteURL, setInviteURL] = useState('')
const [loading, setLoading] = useState(false)
const [loadingBoard, setLoadingBoard] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [copied, setCopied] = useState(false)
const [toastMessage, setToastMessage] = useState(null)
const [isOwner, setIsOwner] = useState(true)
const [isArchived, setIsArchived] = useState(false)
const [showActionMenu, setShowActionMenu] = useState(false)
const actionMenuHistoryRef = useRef(false)
const savedHistoryStateRef = useRef(null)
const isEdit = !!boardId
useEffect(() => {
if (boardId) {
fetchBoard()
}
}, [boardId])
const fetchBoard = async () => {
setLoadingBoard(true)
try {
const res = await authFetch(`/api/shopping/boards/${boardId}`)
if (res.ok) {
const data = await res.json()
setName(data.name)
setInviteEnabled(data.invite_enabled)
setInviteURL(data.invite_url || '')
setIsOwner(data.is_owner)
setIsArchived(data.is_archived || false)
} else {
setToastMessage({ text: 'Ошибка загрузки доски', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка загрузки', type: 'error' })
} finally {
setLoadingBoard(false)
}
}
const handleSave = async () => {
if (!name.trim()) {
setToastMessage({ text: 'Введите название доски', type: 'error' })
return
}
setLoading(true)
try {
const url = boardId
? `/api/shopping/boards/${boardId}`
: '/api/shopping/boards'
const res = await authFetch(url, {
method: boardId ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: name.trim(),
invite_enabled: inviteEnabled
})
})
if (res.ok) {
const data = await res.json()
if (data.invite_url) {
setInviteURL(data.invite_url)
}
onSaved?.()
if (!boardId) {
onNavigate('shopping', { boardId: data.id })
} else {
onNavigate('shopping', { boardId: boardId })
}
} else {
const err = await res.json()
setToastMessage({ text: err.error || 'Ошибка сохранения', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка сохранения', type: 'error' })
} finally {
setLoading(false)
}
}
const generateInviteLink = async () => {
try {
const res = await authFetch(`/api/shopping/boards/${boardId}/regenerate-invite`, {
method: 'POST'
})
if (res.ok) {
const data = await res.json()
setInviteURL(data.invite_url)
setInviteEnabled(true)
}
} catch (err) {
console.error('Error generating invite link:', err)
}
}
const handleCopyLink = () => {
navigator.clipboard.writeText(inviteURL)
setCopied(true)
setToastMessage({ text: 'Ссылка скопирована', type: 'success' })
setTimeout(() => setCopied(false), 2000)
}
const handleToggleInvite = async (enabled) => {
setInviteEnabled(enabled)
if (boardId && enabled && !inviteURL) {
await generateInviteLink()
} else if (boardId) {
try {
await authFetch(`/api/shopping/boards/${boardId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ invite_enabled: enabled })
})
} catch (err) {
console.error('Error updating invite status:', err)
}
}
}
// Навигация после действия из action menu: убрать обе записи (action menu + board-form)
const navigateBackFromActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.go(-2)
} else {
window.history.back()
}
}
const handleDelete = async () => {
if (!window.confirm('Удалить доску? Все товары на ней будут удалены.')) return
setIsDeleting(true)
try {
const res = await authFetch(`/api/shopping/boards/${boardId}`, {
method: 'DELETE'
})
if (res.ok) {
onSaved?.()
navigateBackFromActionMenu()
} else {
setToastMessage({ text: 'Ошибка удаления', type: 'error' })
setIsDeleting(false)
}
} catch (err) {
setToastMessage({ text: 'Ошибка удаления', type: 'error' })
setIsDeleting(false)
}
}
const handleLeave = async () => {
if (!window.confirm('Покинуть доску? Вы больше не будете видеть её товары.')) return
try {
const res = await authFetch(`/api/shopping/boards/${boardId}/leave`, {
method: 'POST'
})
if (res.ok) {
onSaved?.()
onNavigate('shopping', { boardDeleted: true }, { replace: true })
} else {
setToastMessage({ text: 'Ошибка выхода', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка выхода', type: 'error' })
}
}
const handleArchive = async () => {
if (!window.confirm('Архивировать доску? Она переместится в архив.')) return
try {
const res = await authFetch(`/api/shopping/boards/${boardId}/archive`, {
method: 'POST'
})
if (res.ok) {
onSaved?.()
navigateBackFromActionMenu()
} else {
setToastMessage({ text: 'Ошибка архивации', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка архивации', type: 'error' })
}
}
const handleUnarchive = async () => {
try {
const res = await authFetch(`/api/shopping/boards/${boardId}/unarchive`, {
method: 'POST'
})
if (res.ok) {
onSaved?.()
navigateBackFromActionMenu()
} else {
setToastMessage({ text: 'Ошибка разархивации', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка разархивации', type: 'error' })
}
}
const openActionMenu = () => {
setShowActionMenu(true)
savedHistoryStateRef.current = window.history.state
window.history.pushState({ actionMenu: true }, '')
actionMenuHistoryRef.current = true
}
const closeActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.back()
}
}
// Закрыть меню без popstate — заменяем запись в истории на сохранённое состояние
const dismissActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.replaceState(savedHistoryStateRef.current, '', window.location.href)
}
}
// Обработка popstate для закрытия action menu кнопкой назад
useEffect(() => {
const handlePopState = () => {
if (showActionMenu) {
actionMenuHistoryRef.current = false
setShowActionMenu(false)
}
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
}, [showActionMenu])
const handleClose = () => {
window.history.back()
}
if (loadingBoard) {
return (
<div className="board-form">
<div className="fixed inset-0 bottom-20 flex justify-center items-center">
<div className="flex flex-col items-center">
<div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-4"></div>
<div className="text-gray-600 font-medium">Загрузка...</div>
</div>
</div>
</div>
)
}
return (
<div className="board-form">
<button className="close-x-button" onClick={handleClose}>
</button>
<h2>{isEdit ? 'Настройки доски' : 'Новая доска'}</h2>
<div className="form-card">
<div className="form-group">
<label htmlFor="board-name">Название</label>
<input
id="board-name"
type="text"
className="form-input"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Название доски"
/>
</div>
{isEdit && (
<>
<div className="form-section">
<h3>Доступ по ссылке</h3>
<label className="toggle-field">
<input
type="checkbox"
checked={inviteEnabled}
onChange={e => handleToggleInvite(e.target.checked)}
/>
<span className="toggle-slider"></span>
<span className="toggle-label">Разрешить присоединение по ссылке</span>
</label>
{inviteEnabled && inviteURL && (
<div className="invite-link-section">
<div className="invite-url-row">
<input
type="text"
className="invite-url-input"
value={inviteURL}
readOnly
/>
<button
className="copy-btn"
onClick={handleCopyLink}
title="Копировать ссылку"
>
{copied ? (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M20 6L9 17l-5-5"></path>
</svg>
) : (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
)}
</button>
</div>
<p className="invite-hint">
Пользователь, открывший ссылку, сможет присоединиться к доске
</p>
</div>
)}
</div>
<BoardMembers
boardId={boardId}
apiBase="/api/shopping"
onMemberRemoved={() => {
setToastMessage({ text: 'Участник удалён', type: 'success' })
}}
/>
</>
)}
</div>
{toastMessage && (
<Toast
message={toastMessage.text}
type={toastMessage.type}
onClose={() => setToastMessage(null)}
/>
)}
{isActive ? createPortal(
<div style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '0.75rem 1rem',
paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))',
background: 'linear-gradient(to top, white 60%, rgba(255,255,255,0))',
zIndex: 1500,
display: 'flex',
justifyContent: 'center',
gap: '0.75rem',
}}>
<button
onClick={handleSave}
disabled={loading || isDeleting || !name.trim()}
style={{
flex: 1,
maxWidth: '42rem',
padding: '0.875rem',
background: (loading || !name.trim()) ? undefined : 'linear-gradient(to right, #10b981, #059669)',
backgroundColor: (loading || !name.trim()) ? '#9ca3af' : undefined,
color: 'white',
border: 'none',
borderRadius: '0.5rem',
fontSize: '1rem',
fontWeight: 600,
cursor: (loading || isDeleting || !name.trim()) ? 'not-allowed' : 'pointer',
opacity: loading ? 0.6 : 1,
transition: 'all 0.2s',
}}
>
{loading ? 'Сохранение...' : 'Сохранить'}
</button>
{isEdit && (
<button
type="button"
onClick={openActionMenu}
disabled={loading || isDeleting}
style={{
width: '52px',
height: '52px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'transparent',
color: '#059669',
border: '2px solid #059669',
borderRadius: '0.5rem',
fontSize: '1.25rem',
fontWeight: 700,
cursor: (loading || isDeleting) ? 'not-allowed' : 'pointer',
lineHeight: 1,
flexShrink: 0,
padding: 0,
boxSizing: 'border-box',
transition: 'all 0.2s',
}}
title="Действия"
>
</button>
)}
</div>,
document.body
) : null}
{showActionMenu && createPortal(
<div className="wishlist-modal-overlay" style={{ zIndex: 2000 }} onClick={closeActionMenu}>
<div className="wishlist-modal" onClick={(e) => e.stopPropagation()}>
<div className="wishlist-modal-header">
<h3>{name}</h3>
</div>
<div className="wishlist-modal-actions">
{isArchived ? (
<button className="wishlist-modal-copy" onClick={handleUnarchive}>
Разархивировать
</button>
) : (
<button className="wishlist-modal-copy" onClick={handleArchive}>
Архивировать
</button>
)}
<button className="wishlist-modal-delete" onClick={handleDelete}>
Удалить
</button>
</div>
</div>
</div>,
document.body
)}
</div>
)
}
export default ShoppingBoardForm

View File

@@ -0,0 +1,149 @@
import React, { useState, useEffect } from 'react'
import { useAuth } from './auth/AuthContext'
import './BoardJoinPreview.css'
function ShoppingBoardJoinPreview({ inviteToken, onNavigate }) {
const { authFetch, user } = useAuth()
const [board, setBoard] = useState(null)
const [loading, setLoading] = useState(true)
const [joining, setJoining] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
if (inviteToken) {
fetchBoardInfo()
}
}, [inviteToken])
const fetchBoardInfo = async () => {
try {
const res = await authFetch(`/api/shopping/invite/${inviteToken}`)
if (res.ok) {
setBoard(await res.json())
} else {
const err = await res.json()
setError(err.error || 'Ссылка недействительна или устарела')
}
} catch (err) {
setError('Ошибка загрузки')
} finally {
setLoading(false)
}
}
const handleJoin = async () => {
if (!user) {
sessionStorage.setItem('pendingShoppingInviteToken', inviteToken)
onNavigate('login')
return
}
setJoining(true)
setError('')
try {
const res = await authFetch(`/api/shopping/invite/${inviteToken}/join`, {
method: 'POST'
})
if (res.ok) {
const data = await res.json()
onNavigate('shopping', { boardId: data.board.id })
} else {
const err = await res.json()
setError(err.error || 'Ошибка при присоединении')
}
} catch (err) {
setError('Ошибка при присоединении')
} finally {
setJoining(false)
}
}
const handleGoBack = () => {
onNavigate('shopping')
}
if (loading) {
return (
<div className="board-join-preview">
<div className="preview-loading">
<div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
<p>Загрузка...</p>
</div>
</div>
)
}
if (error && !board) {
return (
<div className="board-join-preview">
<div className="preview-card error-card">
<div className="error-icon">X</div>
<h2>Ошибка</h2>
<p className="error-text">{error}</p>
<button className="back-btn" onClick={handleGoBack}>
Вернуться к товарам
</button>
</div>
</div>
)
}
return (
<div className="board-join-preview">
<div className="preview-card">
<h2>Приглашение на доску</h2>
<div className="board-info">
<div className="board-name">{board.name}</div>
<div className="board-owner">
<span className="label">Владелец:</span>
<span className="value">{board.owner_name}</span>
</div>
{board.member_count > 0 && (
<div className="board-members">
<span className="label">Участников:</span>
<span className="value">{board.member_count}</span>
</div>
)}
</div>
{error && (
<div className="join-error">{error}</div>
)}
{user ? (
<button
className="join-btn"
onClick={handleJoin}
disabled={joining}
>
{joining ? (
<>
<span className="spinner-small"></span>
<span>Присоединение...</span>
</>
) : (
<span>Присоединиться</span>
)}
</button>
) : (
<div className="login-prompt">
<p>Для присоединения необходимо войти в аккаунт</p>
<button className="login-btn" onClick={() => onNavigate('login')}>
Войти
</button>
</div>
)}
<button className="cancel-link" onClick={handleGoBack}>
Отмена
</button>
</div>
</div>
)
}
export default ShoppingBoardJoinPreview

View File

@@ -0,0 +1,395 @@
import React, { useState, useEffect, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import LoadingError from './LoadingError'
import Toast from './Toast'
import { DayPicker } from 'react-day-picker'
import { ru } from 'react-day-picker/locale'
import 'react-day-picker/style.css'
import './TaskDetail.css'
import './TaskList.css'
const formatDateToLocal = (date) => {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
const formatShortDate = (dateStr) => {
if (!dateStr) return ''
const date = new Date(dateStr + 'T00:00:00')
if (isNaN(date.getTime())) return ''
const now = new Date()
now.setHours(0, 0, 0, 0)
const target = new Date(date.getFullYear(), date.getMonth(), date.getDate())
const diffDays = Math.floor((target - now) / (1000 * 60 * 60 * 24))
if (diffDays === 0) return 'Сегодня'
if (diffDays === 1) return 'Завтра'
const monthNames = ['янв.', 'фев.', 'мар.', 'апр.', 'мая', 'июн.', 'июл.', 'авг.', 'сен.', 'окт.', 'ноя.', 'дек.']
return `${target.getDate()} ${monthNames[target.getMonth()]}`
}
function ShoppingItemDetail({ itemId, onClose, onRefresh, onItemCompleted, onNavigate }) {
const { authFetch } = useAuth()
const [item, setItem] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [volumeRemaining, setVolumeRemaining] = useState('')
const [volumePurchased, setVolumePurchased] = useState('')
const [selectedDate, setSelectedDate] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [toastMessage, setToastMessage] = useState(null)
const fetchItem = useCallback(async () => {
try {
setLoading(true)
setError(null)
const response = await authFetch(`/api/shopping/items/${itemId}`)
if (!response.ok) throw new Error('Ошибка загрузки товара')
const data = await response.json()
setItem(data)
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}, [itemId, authFetch])
useEffect(() => {
if (itemId) {
fetchItem()
} else {
setItem(null)
setLoading(true)
setError(null)
setVolumeRemaining('')
setVolumePurchased('')
setSelectedDate('')
}
}, [itemId, fetchItem])
const calculateDate = useCallback((itm, remaining, purchased) => {
if (itm.daily_consumption > 0) {
const rem = remaining.trim() ? parseFloat(remaining) : (itm.estimated_remaining ?? 0)
const pur = purchased.trim() ? parseFloat(purchased) : 0
if (!isNaN(rem) && !isNaN(pur) && rem >= 0) {
const total = rem + pur
const daily = itm.daily_consumption
const daysUntilEmpty = total / daily
const daysUntilShow = Math.max(1, Math.ceil(daysUntilEmpty) - 3)
const target = new Date()
target.setHours(0, 0, 0, 0)
target.setDate(target.getDate() + daysUntilShow)
return formatDateToLocal(target)
}
}
const tomorrow = new Date()
tomorrow.setHours(0, 0, 0, 0)
tomorrow.setDate(tomorrow.getDate() + 1)
return formatDateToLocal(tomorrow)
}, [])
// Auto-update calendar when volumes change
useEffect(() => {
if (!item) return
setSelectedDate(calculateDate(item, volumeRemaining, volumePurchased))
}, [volumeRemaining, volumePurchased, item, calculateDate])
const handleSubmit = async (dateOverride) => {
if (!item) return
setIsSubmitting(true)
try {
const remaining = volumeRemaining.trim() ? parseFloat(volumeRemaining) : (item.estimated_remaining ?? 0)
const purchased = volumePurchased.trim() ? parseFloat(volumePurchased) : 0
const date = dateOverride || selectedDate
if (isNaN(remaining)) throw new Error('Неверное значение остатка')
if (isNaN(purchased)) throw new Error('Неверное значение докупки')
if (purchased > 0) {
const response = await authFetch(`/api/shopping/items/${itemId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ volume_remaining: remaining, volume_purchased: purchased }),
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.error || 'Ошибка при выполнении')
}
onItemCompleted?.()
} else {
const payload = {
next_show_at: date ? new Date(date + 'T00:00:00').toISOString() : null,
}
if (volumeRemaining.trim()) {
payload.volume_remaining = remaining
}
const response = await authFetch(`/api/shopping/items/${itemId}/postpone`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
if (!response.ok) throw new Error('Ошибка переноса')
}
onRefresh?.()
onClose?.()
} catch (err) {
setToastMessage({ text: err.message || 'Ошибка', type: 'error' })
} finally {
setIsSubmitting(false)
}
}
const byRemainingDate = item && item.daily_consumption > 0 ? calculateDate(item, volumeRemaining, volumePurchased) : null
const handleByRemainingClick = () => {
if (byRemainingDate) submitWithDate(byRemainingDate)
}
const handleTodayClick = () => {
submitWithDate(formatDateToLocal(new Date()))
}
const handleTomorrowClick = () => {
const tomorrow = new Date()
tomorrow.setHours(0, 0, 0, 0)
tomorrow.setDate(tomorrow.getDate() + 1)
submitWithDate(formatDateToLocal(tomorrow))
}
const handleDayClick = (date) => {
if (date) submitWithDate(formatDateToLocal(date))
}
const submitWithDate = (dateStr) => {
setSelectedDate(dateStr)
handleSubmit(dateStr)
}
if (!itemId) return null
const today = new Date()
today.setHours(0, 0, 0, 0)
const modalContent = (
<div className="task-detail-modal-overlay" onClick={() => onClose?.()}>
<div className="task-detail-modal task-detail-modal-fit" onClick={(e) => e.stopPropagation()}>
<div className="task-detail-modal-header">
<h2
className="task-detail-title"
onClick={item ? () => {
onClose?.(true)
onNavigate?.('shopping-item-form', { itemId: itemId, boardId: item.board_id })
} : undefined}
style={{ cursor: item ? 'pointer' : 'default' }}
>
{loading ? 'Загрузка...' : error ? 'Ошибка' : item ? (
<>
{item.name}
<svg
className="task-detail-edit-icon"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
</svg>
</>
) : 'Товар'}
</h2>
<button onClick={() => onClose?.()} className="task-detail-close-button">
</button>
</div>
<div className="task-detail-modal-content">
{loading && (
<div className="loading">Загрузка...</div>
)}
{error && !loading && (
<LoadingError onRetry={fetchItem} />
)}
{!loading && !error && item && (
<>
<div className="shopping-item-description-card">
<div className="shopping-item-description">
{item.description ? (
item.description.split(/(https?:\/\/[^\s<>"'`,;!)\]]+)/gi).map((part, i) => {
if (/^https?:\/\//i.test(part)) {
let host
try {
host = new URL(part).host.replace(/^www\./, '')
} catch {
host = 'Открыть ссылку'
}
return (
<a key={i} href={part} target="_blank" rel="noopener noreferrer" className="shopping-item-description-link">
{host}
</a>
)
}
return <span key={i}>{part}</span>
})
) : (
<span style={{ color: '#9ca3af' }}>Описание отсутствует</span>
)}
</div>
<button
type="button"
className="shopping-item-history-button"
onClick={() => {
onClose?.(true)
onNavigate?.('shopping-item-history', { itemId: itemId })
}}
title="История"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
</button>
</div>
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'flex-end', marginBottom: '0.75rem' }}>
<div style={{ flex: 1 }}>
<label className="progression-label">Остаток</label>
<div className="progression-input-wrapper">
<input
type="number"
step="any"
value={volumeRemaining}
onChange={(e) => setVolumeRemaining(e.target.value)}
placeholder={item.estimated_remaining != null ? Math.round(item.estimated_remaining * 10) / 10 + '' : '0'}
className="progression-input"
/>
{volumeRemaining && (
<button
type="button"
onClick={() => setVolumeRemaining('')}
style={{
position: 'absolute',
right: '8px',
top: '50%',
transform: 'translateY(-50%)',
background: 'none',
border: 'none',
color: '#9ca3af',
cursor: 'pointer',
fontSize: '1.1rem',
padding: '4px',
lineHeight: 1,
}}
>
</button>
)}
</div>
</div>
<div style={{ flex: 1 }}>
<label className="progression-label">Докуплено</label>
<div className="progression-input-wrapper">
<input
type="number"
step="any"
value={volumePurchased}
onChange={(e) => setVolumePurchased(e.target.value)}
placeholder="0"
className="progression-input"
/>
<div className="progression-controls-capsule">
<button
type="button"
className="progression-control-btn progression-control-minus"
onClick={() => {
const current = volumePurchased.trim() ? parseFloat(volumePurchased) : 0
const step = item.volume_base || 1
setVolumePurchased(Math.max(0, current - step).toString())
}}
>
</button>
<button
type="button"
className="progression-control-btn progression-control-plus"
onClick={() => {
const current = volumePurchased.trim() ? parseFloat(volumePurchased) : 0
const step = item.volume_base || 1
setVolumePurchased((current + step).toString())
}}
>
+
</button>
</div>
</div>
</div>
</div>
<div className="task-postpone-calendar">
<DayPicker
mode="single"
selected={selectedDate ? new Date(selectedDate + 'T00:00:00') : undefined}
onSelect={(date) => { if (date) setSelectedDate(formatDateToLocal(date)) }}
onDayClick={handleDayClick}
disabled={{ before: today }}
locale={ru}
/>
</div>
<div className="task-postpone-quick-buttons">
{item.daily_consumption > 0 && byRemainingDate && (
<button
onClick={handleByRemainingClick}
className="task-postpone-quick-button task-postpone-quick-button-primary"
disabled={isSubmitting}
>
{formatShortDate(byRemainingDate)}
</button>
)}
{item.next_show_at && new Date(item.next_show_at) > today && (
<button
onClick={handleTodayClick}
className="task-postpone-quick-button"
disabled={isSubmitting}
>
Сегодня
</button>
)}
<button
onClick={handleTomorrowClick}
className="task-postpone-quick-button"
disabled={isSubmitting}
>
Завтра
</button>
</div>
</>
)}
</div>
{toastMessage && (
<Toast
message={toastMessage.text}
type={toastMessage.type}
onClose={() => setToastMessage(null)}
/>
)}
</div>
</div>
)
return typeof document !== 'undefined'
? createPortal(modalContent, document.body)
: modalContent
}
export default ShoppingItemDetail

View File

@@ -0,0 +1,19 @@
.shopping-item-form {
padding: 20px;
max-width: 600px;
margin: 0 auto;
position: relative;
padding-bottom: 5rem;
}
.shopping-item-form h2 {
font-size: 1.5rem;
font-weight: 700;
color: #1e293b;
margin-bottom: 24px;
}
.shopping-item-form .repetition-label {
font-size: 1rem;
white-space: nowrap;
}

View File

@@ -0,0 +1,369 @@
import React, { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import Toast from './Toast'
import SubmitButton from './SubmitButton'
import './Wishlist.css'
import './ShoppingItemForm.css'
function ShoppingItemForm({ onNavigate, itemId, boardId, previousTab, onSaved, isActive }) {
const { authFetch } = useAuth()
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [groupName, setGroupName] = useState('')
const [groupSuggestions, setGroupSuggestions] = useState([])
const [volumeBase, setVolumeBase] = useState('')
const [loading, setLoading] = useState(false)
const [loadingItem, setLoadingItem] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [isCopying, setIsCopying] = useState(false)
const [showActionMenu, setShowActionMenu] = useState(false)
const actionMenuHistoryRef = useRef(false)
const [toastMessage, setToastMessage] = useState(null)
const isEdit = !!itemId
useEffect(() => {
loadGroupSuggestions()
}, [])
useEffect(() => {
if (itemId) {
fetchItem()
}
}, [itemId])
const loadGroupSuggestions = async () => {
try {
const res = await authFetch('/api/shopping/groups')
if (res.ok) {
const data = await res.json()
setGroupSuggestions(Array.isArray(data) ? data : [])
}
} catch (err) {
console.error('Error loading group suggestions:', err)
}
}
const fetchItem = async () => {
setLoadingItem(true)
try {
const res = await authFetch(`/api/shopping/items/${itemId}`)
if (res.ok) {
const data = await res.json()
setName(data.name)
setDescription(data.description || '')
setGroupName(data.group_name || '')
if (data.volume_base && data.volume_base !== 1) {
setVolumeBase(data.volume_base.toString())
}
} else {
setToastMessage({ text: 'Ошибка загрузки товара', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка загрузки', type: 'error' })
} finally {
setLoadingItem(false)
}
}
const handleSave = async () => {
if (!name.trim()) {
setToastMessage({ text: 'Введите название товара', type: 'error' })
return
}
setLoading(true)
try {
const vb = volumeBase.trim() ? parseFloat(volumeBase.trim()) : null
const payload = {
name: name.trim(),
description: description.trim() || null,
group_name: groupName.trim() || null,
volume_base: vb && vb > 0 ? vb : null,
}
let url, method
if (isEdit) {
url = `/api/shopping/items/${itemId}`
method = 'PUT'
} else {
url = `/api/shopping/boards/${boardId}/items`
method = 'POST'
}
const res = await authFetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
if (res.ok) {
onSaved?.()
window.history.back()
} else {
const err = await res.json()
setToastMessage({ text: err.error || 'Ошибка сохранения', type: 'error' })
}
} catch (err) {
setToastMessage({ text: 'Ошибка сохранения', type: 'error' })
} finally {
setLoading(false)
}
}
const openActionMenu = () => {
setShowActionMenu(true)
window.history.pushState({ actionMenu: true }, '')
actionMenuHistoryRef.current = true
}
const closeActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.back()
}
}
// Обработка popstate для закрытия action menu кнопкой назад
useEffect(() => {
const handlePopState = () => {
if (showActionMenu) {
actionMenuHistoryRef.current = false
setShowActionMenu(false)
}
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
}, [showActionMenu])
const handleDelete = async () => {
if (!itemId) return
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.go(-2)
} else {
window.history.back()
}
setIsDeleting(true)
try {
const res = await authFetch(`/api/shopping/items/${itemId}`, { method: 'DELETE' })
if (res.ok) {
onSaved?.()
}
} catch (err) {
console.error('Error deleting item:', err)
}
}
const handleCopy = async () => {
if (!itemId) return
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.go(-2)
} else {
window.history.back()
}
setIsCopying(true)
try {
const res = await authFetch(`/api/shopping/items/${itemId}/copy`, { method: 'POST' })
if (!res.ok) {
const errorText = await res.text().catch(() => '')
throw new Error(errorText || 'Ошибка при копировании товара')
}
onSaved?.()
} catch (err) {
console.error('Error copying item:', err)
}
}
const handleClose = () => {
window.history.back()
}
if (loadingItem) {
return (
<div className="shopping-item-form">
<div className="fixed inset-0 bottom-20 flex justify-center items-center">
<div className="flex flex-col items-center">
<div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-4"></div>
<div className="text-gray-600 font-medium">Загрузка...</div>
</div>
</div>
</div>
)
}
return (
<>
<div className="shopping-item-form">
<button className="close-x-button" onClick={handleClose}>
</button>
<h2>{isEdit ? 'Редактировать товар' : 'Новый товар'}</h2>
<div className="form-card">
<div className="form-group">
<label htmlFor="item-name">Название</label>
<input
id="item-name"
type="text"
className="form-input"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Название товара"
/>
</div>
<div className="form-group">
<label htmlFor="item-description">Описание</label>
<textarea
id="item-description"
className="form-input"
value={description}
onChange={e => setDescription(e.target.value)}
placeholder="Описание товара"
rows={3}
/>
</div>
<div className="form-group">
<label htmlFor="item-group">Группа</label>
<input
id="item-group"
type="text"
className="form-input"
value={groupName}
onChange={e => setGroupName(e.target.value)}
placeholder="Группа товара"
list="shopping-group-suggestions"
/>
<datalist id="shopping-group-suggestions">
{groupSuggestions.map((g, i) => (
<option key={i} value={g} />
))}
</datalist>
</div>
<div className="form-group">
<label htmlFor="item-volume">Шаги объёма</label>
<input
id="item-volume"
type="number"
step="any"
min="0"
className="form-input"
value={volumeBase}
onChange={e => setVolumeBase(e.target.value)}
placeholder="1"
/>
</div>
</div>
{toastMessage && (
<Toast
message={toastMessage.text}
type={toastMessage.type}
onClose={() => setToastMessage(null)}
/>
)}
</div>
{isActive ? createPortal(
<div style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '0.75rem 1rem',
paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))',
background: 'linear-gradient(to top, white 60%, rgba(255,255,255,0))',
zIndex: 1500,
display: 'flex',
justifyContent: 'center',
gap: '0.75rem',
}}>
<button
onClick={handleSave}
disabled={loading || isDeleting || isCopying || !name.trim()}
style={{
flex: 1,
maxWidth: '42rem',
padding: '0.875rem',
background: loading ? undefined : 'linear-gradient(to right, #10b981, #059669)',
backgroundColor: loading ? '#9ca3af' : undefined,
color: 'white',
border: 'none',
borderRadius: '0.5rem',
fontSize: '1rem',
fontWeight: 600,
cursor: (loading || isDeleting || isCopying) ? 'not-allowed' : 'pointer',
opacity: loading ? 0.6 : 1,
transition: 'all 0.2s',
}}
>
{loading ? 'Сохранение...' : 'Сохранить'}
</button>
{isEdit && (
<button
type="button"
onClick={openActionMenu}
disabled={loading || isDeleting || isCopying}
style={{
width: '52px',
height: '52px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'transparent',
color: '#059669',
border: '2px solid #059669',
borderRadius: '0.5rem',
fontSize: '1.25rem',
fontWeight: 700,
cursor: (loading || isDeleting || isCopying) ? 'not-allowed' : 'pointer',
lineHeight: 1,
flexShrink: 0,
padding: 0,
boxSizing: 'border-box',
transition: 'all 0.2s',
}}
title="Действия"
>
</button>
)}
</div>,
document.body
) : null}
{showActionMenu && createPortal(
<div className="wishlist-modal-overlay" style={{ zIndex: 2000 }} onClick={closeActionMenu}>
<div className="wishlist-modal" onClick={(e) => e.stopPropagation()}>
<div className="wishlist-modal-header">
<h3>{name}</h3>
</div>
<div className="wishlist-modal-actions">
<button className="wishlist-modal-copy" onClick={handleCopy}>
Копировать
</button>
<button className="wishlist-modal-delete" onClick={handleDelete}>
Удалить
</button>
</div>
</div>
</div>,
document.body
)}
</>
)
}
export default ShoppingItemForm

View File

@@ -0,0 +1,157 @@
import React, { useState, useEffect, useCallback } from 'react'
import { useAuth } from './auth/AuthContext'
import LoadingError from './LoadingError'
import './Integrations.css'
function ShoppingItemHistory({ itemId, onNavigate }) {
const { authFetch } = useAuth()
const [records, setRecords] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const fetchRecords = useCallback(async () => {
if (!itemId) return
try {
setLoading(true)
setError(null)
const response = await authFetch(`/api/shopping/items/${itemId}/volume-records`)
if (!response.ok) {
throw new Error('Ошибка загрузки истории')
}
const data = await response.json()
setRecords(Array.isArray(data) ? data : [])
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}, [itemId, authFetch])
useEffect(() => {
fetchRecords()
}, [fetchRecords])
const formatDate = (dateStr) => {
const date = new Date(dateStr)
const day = date.getDate()
const months = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек']
const month = months[date.getMonth()]
const year = date.getFullYear()
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${day} ${month} ${year}, ${hours}:${minutes}`
}
const formatVolume = (volume) => {
if (volume == null) return '—'
const rounded = Math.round(volume * 10) / 10
return rounded.toString()
}
const getActionLabel = (actionType) => {
switch (actionType) {
case 'purchase': return 'Закупка'
case 'postpone': return 'Перенос'
case 'create': return 'Создание'
default: return actionType
}
}
const getActionColor = (actionType) => {
switch (actionType) {
case 'purchase': return '#059669'
case 'postpone': return '#d97706'
case 'create': return '#6b7280'
default: return '#6b7280'
}
}
return (
<div className="max-w-2xl mx-auto">
{onNavigate && (
<button
onClick={() => window.history.back()}
className="close-x-button"
title="Закрыть"
>
</button>
)}
{loading ? (
<div className="fixed inset-0 flex justify-center items-center">
<div className="flex flex-col items-center">
<div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-4"></div>
<div className="text-gray-600 font-medium">Загрузка...</div>
</div>
</div>
) : error ? (
<LoadingError onRetry={fetchRecords} />
) : records.length === 0 ? (
<>
<h2 className="text-2xl font-semibold text-gray-800 mb-6" style={{ marginTop: '1.25rem' }}>История</h2>
<div className="flex justify-center items-center py-16">
<div className="text-gray-500 text-lg">История пуста</div>
</div>
</>
) : (
<div>
<h2 className="text-2xl font-semibold text-gray-800 mb-6" style={{ marginTop: '1.25rem' }}>История</h2>
<div className="space-y-3">
{records.map((record) => {
const total = (record.volume_remaining || 0) + (record.volume_purchased || 0)
return (
<div
key={record.id}
className="bg-white rounded-lg p-4 shadow-sm border border-gray-200"
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ color: getActionColor(record.action_type), fontWeight: 600, fontSize: '0.9rem' }}>
{getActionLabel(record.action_type)}
</span>
<span className="text-xs text-gray-500">
{formatDate(record.created_at)}
</span>
</div>
{record.action_type === 'purchase' && (
<div className="text-gray-800 mt-2">
{formatVolume(record.volume_remaining)} {formatVolume(total)}
</div>
)}
{record.action_type === 'postpone' && (
<div className="text-gray-800 mt-2">
{record.next_show_at ? (() => {
const d = new Date(record.next_show_at)
const day = d.getDate()
const months = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек']
return `на ${day} ${months[d.getMonth()]}`
})() : 'Без даты'}
{record.volume_remaining != null && (
<span className="text-gray-500" style={{ marginLeft: '8px' }}>
(остаток: {formatVolume(record.volume_remaining)})
</span>
)}
</div>
)}
{record.action_type === 'create' && (
<div className="text-gray-500 text-sm mt-1">
Остаток: {formatVolume(record.volume_remaining)}
</div>
)}
{record.daily_consumption != null && record.daily_consumption > 0 && (
<div className="text-gray-500 text-xs mt-1">
~{formatVolume(record.daily_consumption)}/день
</div>
)}
</div>
)
})}
</div>
</div>
)}
</div>
)
}
export default ShoppingItemHistory

View File

@@ -0,0 +1,72 @@
.shopping-list {
max-width: 42rem;
margin: 0 auto;
padding-bottom: 2.5rem;
}
.shopping-header {
display: flex;
align-items: flex-start;
gap: 8px;
max-width: 42rem;
margin: 0 auto;
padding-top: 1rem;
}
.shopping-header .board-selector {
flex: 1;
max-width: none;
margin: 0;
padding-left: 0;
padding-right: 0;
}
.shopping-close-btn {
flex-shrink: 0;
background: rgba(255, 255, 255, 0.9);
border: none;
font-size: 1.5rem;
color: #7f8c8d;
cursor: pointer;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
transition: background-color 0.2s, color 0.2s;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.shopping-close-btn:hover {
background-color: #ffffff;
color: #2c3e50;
}
.shopping-header .board-pill {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-color: transparent;
}
.shopping-empty {
text-align: center;
padding: 3rem 1rem;
color: #94a3b8;
}
.shopping-empty p:first-child {
font-size: 1.125rem;
font-weight: 600;
color: #64748b;
margin-bottom: 0.5rem;
}
.shopping-empty-hint {
font-size: 0.875rem;
}
.shopping-loading {
display: flex;
justify-content: center;
padding: 3rem 0;
}

View File

@@ -0,0 +1,660 @@
import React, { useState, useEffect, useRef, useMemo } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import BoardSelector from './BoardSelector'
import ShoppingItemDetail from './ShoppingItemDetail'
import LoadingError from './LoadingError'
import Toast from './Toast'
import './TaskList.css'
import './TaskDetail.css'
import './ShoppingList.css'
import './Wishlist.css'
const BOARDS_CACHE_KEY = 'shopping_boards_cache'
const ITEMS_CACHE_KEY = 'shopping_items_cache'
const SELECTED_BOARD_KEY = 'shopping_selected_board_id'
// Форматирование даты для отображения
const formatDateForDisplay = (dateStr) => {
if (!dateStr) return ''
const date = new Date(dateStr)
if (isNaN(date.getTime())) return ''
const now = new Date()
now.setHours(0, 0, 0, 0)
const target = new Date(date.getFullYear(), date.getMonth(), date.getDate())
const diffDays = Math.floor((target - now) / (1000 * 60 * 60 * 24))
if (diffDays === 0) return 'Сегодня'
if (diffDays === 1) return 'Завтра'
if (diffDays === -1) return 'Вчера'
if (diffDays > 0 && diffDays <= 7) {
const dayNames = ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота']
return dayNames[target.getDay()]
}
const monthNames = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря']
if (target.getFullYear() === now.getFullYear()) {
return `${target.getDate()} ${monthNames[target.getMonth()]}`
}
return `${target.getDate()} ${monthNames[target.getMonth()]} ${target.getFullYear()}`
}
function ShoppingList({ onNavigate, refreshTrigger = 0, isActive = false, initialBoardId = null, boardDeleted = false }) {
const { authFetch } = useAuth()
const [boards, setBoards] = useState([])
const getInitialBoardId = () => {
if (initialBoardId) return initialBoardId
try {
const saved = localStorage.getItem(SELECTED_BOARD_KEY)
if (saved) {
const boardId = parseInt(saved, 10)
if (!isNaN(boardId)) return boardId
}
} catch (err) {}
return null
}
const hasBoardsCache = () => {
try {
const cached = localStorage.getItem(BOARDS_CACHE_KEY)
if (cached) {
const data = JSON.parse(cached)
return !!(data.boards && data.boards.length >= 0)
}
} catch (err) {}
return false
}
const [selectedBoardId, setSelectedBoardIdState] = useState(getInitialBoardId)
const [items, setItems] = useState([])
const [loading, setLoading] = useState(true)
const [boardsLoading, setBoardsLoading] = useState(!hasBoardsCache())
const [error, setError] = useState('')
const [selectedItemForDetail, setSelectedItemForDetail] = useState(null)
const [toast, setToast] = useState(null)
const [showBoardActionMenu, setShowBoardActionMenu] = useState(false)
const initialFetchDoneRef = useRef(false)
const prevIsActiveRef = useRef(isActive)
const itemsAbortRef = useRef(null)
// Refs для закрытия диалогов кнопкой "Назад"
const historyPushedForDetailRef = useRef(false)
const selectedItemForDetailRef = useRef(selectedItemForDetail)
const setSelectedBoardId = (boardId) => {
setSelectedBoardIdState(boardId)
try {
if (boardId) {
localStorage.setItem(SELECTED_BOARD_KEY, String(boardId))
} else {
localStorage.removeItem(SELECTED_BOARD_KEY)
}
} catch (err) {}
}
// Загрузка досок
const fetchBoards = async (showLoading = true, preferBoardId = null) => {
if (showLoading) setBoardsLoading(true)
try {
const res = await authFetch('/api/shopping/boards')
if (res.ok) {
const data = await res.json()
const boardsList = Array.isArray(data) ? data : []
setBoards(boardsList)
try {
localStorage.setItem(BOARDS_CACHE_KEY, JSON.stringify({ boards: boardsList }))
} catch (err) {}
const effectiveBoardId = preferBoardId || selectedBoardId
if (boardDeleted || !boardsList.some(b => b.id === effectiveBoardId)) {
if (boardsList.length > 0) {
setSelectedBoardId(boardsList[0].id)
} else {
setSelectedBoardId(null)
}
} else if (preferBoardId && preferBoardId !== selectedBoardId) {
setSelectedBoardId(preferBoardId)
}
}
} catch (err) {
setError('Ошибка загрузки досок')
} finally {
setBoardsLoading(false)
}
}
// Загрузка товаров
const fetchItems = async (boardId, { background = false } = {}) => {
if (!boardId) return
// Отменяем предыдущий запрос если есть
if (itemsAbortRef.current) {
itemsAbortRef.current.abort()
}
const abortController = new AbortController()
itemsAbortRef.current = abortController
if (!background) {
// Показываем loading только если нет кеша
try {
const cached = localStorage.getItem(`${ITEMS_CACHE_KEY}_${boardId}`)
if (cached) {
setItems(JSON.parse(cached) || [])
setLoading(false)
} else {
setLoading(true)
}
} catch (err) {
setLoading(true)
}
}
setError('')
try {
const res = await authFetch(`/api/shopping/boards/${boardId}/items`, {
signal: abortController.signal
})
if (abortController.signal.aborted) return
if (res.ok) {
const data = await res.json()
if (abortController.signal.aborted) return
setItems(Array.isArray(data) ? data : [])
try {
localStorage.setItem(`${ITEMS_CACHE_KEY}_${boardId}`, JSON.stringify(data))
} catch (err) {}
} else {
setError('Ошибка загрузки товаров')
}
} catch (err) {
if (err.name === 'AbortError') return
setError('Ошибка загрузки товаров')
} finally {
if (!abortController.signal.aborted) {
setLoading(false)
}
}
}
// Загрузка досок из кэша
useEffect(() => {
try {
const cached = localStorage.getItem(BOARDS_CACHE_KEY)
if (cached) {
const data = JSON.parse(cached)
if (data.boards) setBoards(data.boards)
}
} catch (err) {}
}, [])
// Начальная загрузка
useEffect(() => {
const hasCache = hasBoardsCache()
fetchBoards(!hasCache, initialBoardId)
initialFetchDoneRef.current = true
}, [])
// Загрузка при смене доски
useEffect(() => {
if (selectedBoardId) {
fetchItems(selectedBoardId)
} else {
setItems([])
setLoading(false)
}
// Отменяем запрос при размонтировании или смене доски
return () => {
if (itemsAbortRef.current) {
itemsAbortRef.current.abort()
}
}
}, [selectedBoardId])
// Рефреш при возврате на таб
useEffect(() => {
if (isActive && !prevIsActiveRef.current && initialFetchDoneRef.current) {
fetchBoards(false)
if (selectedBoardId) fetchItems(selectedBoardId, { background: true })
}
prevIsActiveRef.current = isActive
}, [isActive])
// Рефреш по триггеру
useEffect(() => {
if (refreshTrigger > 0) {
fetchBoards(false)
if (selectedBoardId) fetchItems(selectedBoardId, { background: true })
}
}, [refreshTrigger])
// Синхронизация refs для диалогов
useEffect(() => {
selectedItemForDetailRef.current = selectedItemForDetail
}, [selectedItemForDetail])
// Закрытие диалогов кнопкой "Назад" (browser history API)
useEffect(() => {
if (selectedItemForDetail && !historyPushedForDetailRef.current) {
window.history.pushState({ modalOpen: true, type: 'shopping-detail' }, '', window.location.href)
historyPushedForDetailRef.current = true
} else if (!selectedItemForDetail) {
historyPushedForDetailRef.current = false
}
if (!selectedItemForDetail) return
const handlePopState = () => {
const currentDetail = selectedItemForDetailRef.current
if (currentDetail) {
setSelectedItemForDetail(null)
historyPushedForDetailRef.current = false
}
}
window.addEventListener('popstate', handlePopState)
return () => {
window.removeEventListener('popstate', handlePopState)
}
}, [selectedItemForDetail])
// Фильтрация и группировка на клиенте
const groupedItems = useMemo(() => {
const now = new Date()
now.setHours(0, 0, 0, 0)
const todayEnd = new Date(now)
todayEnd.setHours(23, 59, 59, 999)
const groups = {}
items.forEach(item => {
const groupKey = item.group_name || 'Остальные'
if (!groups[groupKey]) {
groups[groupKey] = { active: [], future: [] }
}
if (!item.next_show_at) {
groups[groupKey].future.push(item)
return
}
const showAt = new Date(item.next_show_at)
if (showAt > todayEnd) {
groups[groupKey].future.push(item)
return
}
groups[groupKey].active.push(item)
})
// Сортируем future по next_show_at ASC
Object.values(groups).forEach(group => {
group.future.sort((a, b) => {
if (!a.next_show_at) return 1
if (!b.next_show_at) return -1
return new Date(a.next_show_at) - new Date(b.next_show_at)
})
})
return groups
}, [items])
const [expandedFuture, setExpandedFuture] = useState({})
const handleBoardChange = (boardId) => {
setSelectedBoardId(boardId)
}
const handleBoardEdit = (boardId) => {
const id = boardId || selectedBoardId
if (!id) return
const board = boards.find(b => b.id === id)
if (board && !board.is_owner) {
openBoardActionMenu()
return
}
onNavigate('shopping-board-form', { boardId: id })
}
const handleAddBoard = () => {
onNavigate('shopping-board-form')
}
const openBoardActionMenu = () => {
setShowBoardActionMenu(true)
}
const closeBoardActionMenu = () => {
setShowBoardActionMenu(false)
}
const handleBoardArchive = async () => {
const board = boards.find(b => b.id === selectedBoardId)
if (!board) return
if (board.is_archived) {
setShowBoardActionMenu(false)
try {
const res = await authFetch(`/api/shopping/boards/${selectedBoardId}/unarchive`, {
method: 'POST'
})
if (res.ok) {
fetchBoards()
fetchItems(selectedBoardId)
}
} catch (err) {
console.error('Error unarchiving board:', err)
}
} else {
if (!window.confirm('Архивировать доску? Она переместится в архив.')) return
setShowBoardActionMenu(false)
try {
const res = await authFetch(`/api/shopping/boards/${selectedBoardId}/archive`, {
method: 'POST'
})
if (res.ok) {
fetchBoards()
}
} catch (err) {
console.error('Error archiving board:', err)
}
}
}
const handleBoardLeave = async () => {
if (!window.confirm('Покинуть доску? Вы больше не будете видеть её товары.')) return
setShowBoardActionMenu(false)
try {
const res = await authFetch(`/api/shopping/boards/${selectedBoardId}/leave`, {
method: 'POST'
})
if (res.ok) {
fetchBoards()
}
} catch (err) {
console.error('Error leaving board:', err)
}
}
const handleRefresh = () => {
if (selectedBoardId) fetchItems(selectedBoardId)
}
const handleCloseDetail = (skipHistoryBack = false) => {
if (!skipHistoryBack && historyPushedForDetailRef.current) {
window.history.back()
} else {
historyPushedForDetailRef.current = false
setSelectedItemForDetail(null)
}
}
const groupNames = useMemo(() => {
const names = Object.keys(groupedItems)
return names.sort((a, b) => {
const groupA = groupedItems[a]
const groupB = groupedItems[b]
const hasActiveA = groupA.active.length > 0
const hasActiveB = groupB.active.length > 0
if (hasActiveA && !hasActiveB) return -1
if (!hasActiveA && hasActiveB) return 1
if (a === 'Остальные') return 1
if (b === 'Остальные') return -1
return a.localeCompare(b, 'ru')
})
}, [groupedItems])
const toggleFuture = (groupName) => {
setExpandedFuture(prev => ({
...prev,
[groupName]: !prev[groupName]
}))
}
return (
<div className="shopping-list">
<div className="shopping-header">
<BoardSelector
boards={boards}
selectedBoardId={selectedBoardId}
onBoardChange={handleBoardChange}
onBoardEdit={handleBoardEdit}
onAddBoard={handleAddBoard}
loading={boardsLoading}
showBoardAction={false}
/>
<button className="shopping-close-btn" onClick={() => window.history.back()}></button>
</div>
{boards.length === 0 && !boardsLoading && (
<div className="shopping-empty">
<p>Нет досок</p>
<p className="shopping-empty-hint">Создайте доску, чтобы начать добавлять товары</p>
</div>
)}
{selectedBoardId && error && (
<LoadingError onRetry={handleRefresh} />
)}
{selectedBoardId && !error && (
<>
{loading && items.length === 0 && (
<div className="shopping-loading">
<div className="w-8 h-8 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
</div>
)}
{!loading && items.length === 0 && (
<div className="shopping-empty">
<p>Нет товаров</p>
</div>
)}
{groupNames.map(groupName => {
const group = groupedItems[groupName]
const hasActive = group.active.length > 0
const hasFuture = group.future.length > 0
const isFutureExpanded = expandedFuture[groupName]
return (
<div key={groupName} className={`project-group ${!hasActive ? 'project-group-no-tasks' : ''}`}>
<div
className={`project-group-header ${hasFuture ? 'project-group-header-clickable' : ''}`}
onClick={hasFuture ? () => toggleFuture(groupName) : undefined}
>
<h3 className={`project-group-title ${!hasActive ? 'project-group-title-empty' : ''}`}>{groupName}</h3>
{hasFuture ? (
<button
className="completed-toggle-header"
onClick={(e) => {
e.stopPropagation()
toggleFuture(groupName)
}}
title={isFutureExpanded ? 'Скрыть ожидающие' : 'Показать ожидающие'}
>
<span className="completed-toggle-icon">
{isFutureExpanded ? '▼' : '▶'}
</span>
</button>
) : (
<div className="completed-toggle-header" style={{ visibility: 'hidden', pointerEvents: 'none' }}>
<span className="completed-toggle-icon"></span>
</div>
)}
</div>
{hasActive && (
<div className="task-group">
{group.active.map(item => {
let dateDisplay = null
if (item.next_show_at) {
const itemDate = new Date(item.next_show_at)
const now = new Date()
now.setHours(0, 0, 0, 0)
const target = new Date(itemDate.getFullYear(), itemDate.getMonth(), itemDate.getDate())
if (target > now) {
dateDisplay = formatDateForDisplay(item.next_show_at)
}
}
return (
<div
key={item.id}
className="task-item"
onClick={() => setSelectedItemForDetail(item.id)}
>
<div className="task-item-content">
<div
className="task-checkmark"
onClick={(e) => {
e.stopPropagation()
setSelectedItemForDetail(item.id)
}}
title="Выполнить"
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="10" cy="10" r="9" stroke="currentColor" strokeWidth="2" fill="none" className="checkmark-circle" />
<path d="M6 10 L9 13 L14 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="checkmark-check" />
</svg>
</div>
<div className="task-name-container">
<div className="task-name-wrapper">
<div className="task-name">
{item.name}
{item.estimated_remaining > 0 && (
<span className="task-subtasks-count">
({Math.round(item.estimated_remaining * 10) / 10})
</span>
)}
</div>
{dateDisplay && (
<div className="task-next-show-date">{dateDisplay}</div>
)}
</div>
</div>
</div>
</div>
)
})}
</div>
)}
{hasFuture && isFutureExpanded && (
<div className="task-group completed-tasks">
{group.future.map(item => {
let dateDisplay = null
if (item.next_show_at) {
const itemDate = new Date(item.next_show_at)
const now = new Date()
now.setHours(0, 0, 0, 0)
const target = new Date(itemDate.getFullYear(), itemDate.getMonth(), itemDate.getDate())
if (target > now) {
dateDisplay = formatDateForDisplay(item.next_show_at)
}
}
return (
<div
key={item.id}
className="task-item"
onClick={() => setSelectedItemForDetail(item.id)}
>
<div className="task-item-content">
<div
className="task-checkmark"
onClick={(e) => {
e.stopPropagation()
setSelectedItemForDetail(item.id)
}}
title="Выполнить"
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="10" cy="10" r="9" stroke="currentColor" strokeWidth="2" fill="none" className="checkmark-circle" />
<path d="M6 10 L9 13 L14 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="checkmark-check" />
</svg>
</div>
<div className="task-name-container">
<div className="task-name-wrapper">
<div className="task-name">
{item.name}
{item.estimated_remaining > 0 && (
<span className="task-subtasks-count">
({Math.round(item.estimated_remaining * 10) / 10})
</span>
)}
</div>
{dateDisplay && (
<div className="task-next-show-date">{dateDisplay}</div>
)}
</div>
</div>
</div>
</div>
)})}
</div>
)}
</div>
)
})}
</>
)}
{/* Модалка выполнения */}
{selectedItemForDetail && (
<ShoppingItemDetail
itemId={selectedItemForDetail}
onClose={handleCloseDetail}
onRefresh={handleRefresh}
onItemCompleted={() => setToast({ message: 'Товар выполнен', type: 'success' })}
onNavigate={onNavigate}
/>
)}
{toast && (
<Toast
message={toast.message}
type={toast.type}
onClose={() => setToast(null)}
/>
)}
{showBoardActionMenu && createPortal(
<div className="wishlist-modal-overlay" style={{ zIndex: 2000 }} onClick={closeBoardActionMenu}>
<div className="wishlist-modal" onClick={(e) => e.stopPropagation()}>
<div className="wishlist-modal-header">
<h3>{boards.find(b => b.id === selectedBoardId)?.name}</h3>
</div>
<div className="wishlist-modal-actions">
{boards.find(b => b.id === selectedBoardId)?.is_archived ? (
<button className="wishlist-modal-copy" onClick={handleBoardArchive}>
Разархивировать
</button>
) : (
<button className="wishlist-modal-copy" onClick={handleBoardArchive}>
Архивировать
</button>
)}
<button className="wishlist-modal-delete" onClick={handleBoardLeave}>
Выйти
</button>
</div>
</div>
</div>,
document.body
)}
</div>
)
}
export default ShoppingList

View File

@@ -25,6 +25,23 @@
overflow: hidden;
}
.task-detail-modal.task-detail-modal-fit {
max-width: none;
width: auto;
}
.task-detail-modal-fit .task-detail-modal-content {
width: min-content;
}
.task-detail-modal-fit .task-detail-modal-content > * {
min-width: 0;
}
.task-detail-modal-fit .task-postpone-calendar {
width: max-content;
}
.task-detail-modal-header {
display: flex;
align-items: center;
@@ -157,6 +174,111 @@
border-radius: 0.25rem;
}
.shopping-item-description-card {
background: #f3f4f6;
border-radius: 10px;
padding: 0.75rem 1rem;
margin-bottom: 1rem;
display: flex;
align-items: flex-start;
gap: 0.5rem;
}
.shopping-item-description {
flex: 1;
font-size: 0.95rem;
color: #374151;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
min-width: 0;
}
.shopping-item-history-button {
background: none;
border: none;
padding: 4px;
cursor: pointer;
color: #9ca3af;
border-radius: 4px;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
margin-top: 1px;
}
.shopping-item-history-button:hover {
color: #4f46e5;
background-color: rgba(79, 70, 229, 0.1);
}
.shopping-item-description-link {
color: #3498db;
text-decoration: none;
transition: color 0.2s;
}
.shopping-item-description-link:hover {
color: #2980b9;
text-decoration: underline;
}
.shopping-item-complete-row {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.shopping-item-complete-row .progression-input-wrapper {
flex: 1;
}
.shopping-item-complete-row .progression-label {
margin-bottom: 0;
}
.shopping-item-complete-row + .task-action-left {
margin-top: 0.75rem;
}
.shopping-item-complete-button {
width: 48px;
height: 48px;
border-radius: 0.375rem;
border: none;
background: linear-gradient(135deg, #10b981, #059669);
color: white;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
transition: all 0.2s;
box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}
.shopping-item-complete-button:hover {
transform: scale(1.05);
box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
}
.shopping-item-complete-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.shopping-item-complete-spinner {
width: 20px;
height: 20px;
border: 2.5px solid rgba(255, 255, 255, 0.3);
border-top-color: white;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
.progression-section {
margin-bottom: 1.5rem;
}
@@ -200,44 +322,60 @@
.progression-controls-capsule {
position: absolute;
right: 0.375rem;
right: 0;
top: 0;
bottom: 0;
display: flex;
background: #f3f4f6;
border-radius: 9999px;
overflow: hidden;
align-items: stretch;
flex-shrink: 0;
}
.progression-control-btn {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
width: 2.375rem;
border: none;
background: transparent;
font-size: 1.125rem;
font-weight: 500;
color: #6b7280;
cursor: pointer;
transition: background 0.2s, color 0.2s;
transition: color 0.2s;
z-index: 1;
}
.progression-control-btn::after {
content: '';
position: absolute;
width: 2rem;
height: 2rem;
background: #f3f4f6;
transition: background 0.2s;
z-index: -1;
}
.progression-control-btn:hover {
background: #e5e7eb;
color: #374151;
}
.progression-control-btn:active {
.progression-control-btn:hover::after {
background: #e5e7eb;
}
.progression-control-btn:active::after {
background: #d1d5db;
}
.progression-control-minus {
border-right: 1px solid #eeeff1;
.progression-control-minus::after {
border-radius: 9999px 0 0 9999px;
right: 0;
}
.progression-control-plus {
border-left: 1px solid #eeeff1;
.progression-control-plus::after {
border-radius: 0 9999px 9999px 0;
left: 0;
}
.task-detail-divider {
@@ -464,22 +602,10 @@
font-weight: 500;
}
.task-wishlist-link-button {
background: none;
border: none;
.task-wishlist-link-name {
color: #6366f1;
font-size: 0.95rem;
font-weight: 500;
cursor: pointer;
padding: 0.25rem 0.5rem;
border-radius: 4px;
transition: all 0.2s;
text-decoration: underline;
margin-left: auto;
}
.task-wishlist-link-button:hover {
background-color: rgba(99, 102, 241, 0.1);
text-decoration: none;
}

View File

@@ -291,7 +291,7 @@ const formatTelegramMessage = (task, rewards, subtasks, selectedSubtasks, progre
})
// Функция для замены плейсхолдеров
const replacePlaceholders = (message, rewardStrings) => {
const replacePlaceholders = (message, rewardStrings, taskName, subtaskName) => {
let result = message
// Сначала защищаем экранированные плейсхолдеры
const escapedMarkers = {}
@@ -303,6 +303,12 @@ const formatTelegramMessage = (task, rewards, subtasks, selectedSubtasks, progre
result = result.replace(new RegExp(escaped.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), marker)
}
}
// Заменяем $subtaskName именем подзадачи (если задано)
if (subtaskName) {
result = result.replace(/\$subtaskName/g, subtaskName)
}
// Заменяем $name именем задачи
result = result.replace(/\$name/g, taskName || '')
// Заменяем ${0}, ${1}, и т.д.
for (let i = 0; i < 100; i++) {
const placeholder = `\${${i}}`
@@ -327,7 +333,7 @@ const formatTelegramMessage = (task, rewards, subtasks, selectedSubtasks, progre
// Формируем сообщение основной задачи
let mainTaskMessage = task.reward_message && task.reward_message.trim() !== ''
? replacePlaceholders(task.reward_message, rewardStrings)
? replacePlaceholders(task.reward_message, rewardStrings, task.name)
: task.name
// Формируем сообщения подзадач
@@ -361,7 +367,7 @@ const formatTelegramMessage = (task, rewards, subtasks, selectedSubtasks, progre
subtaskRewardStrings[reward.position] = scoreStr
})
const subtaskMessage = replacePlaceholders(subtask.task.reward_message, subtaskRewardStrings)
const subtaskMessage = replacePlaceholders(subtask.task.reward_message, subtaskRewardStrings, task.name, subtask.task.name)
subtaskMessages.push(subtaskMessage)
})
@@ -485,8 +491,9 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
throw new Error('Неверное значение')
}
payload.progression_value = parsedValue
} else {
// Если прогрессия не введена - сбрасываем в null
} else if (!autoComplete) {
// Если прогрессия не введена и нет авто-выполнения - сбрасываем в null
// При авто-выполнении бэкенд сам подставит progression_base
payload.clear_progression_value = true
}
} else {
@@ -558,7 +565,7 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
children_task_ids: Array.from(selectedSubtasks)
}
// Если есть прогрессия, отправляем значение (или progression_base, если не введено)
// Если есть прогрессия, отправляем значение (или default_progress/progression_base, если не введено)
if (taskDetail.task.progression_base != null) {
if (progressionValue.trim()) {
payload.value = parseFloat(progressionValue)
@@ -566,8 +573,8 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
throw new Error('Неверное значение')
}
} else {
// Если прогрессия не введена - используем progression_base
payload.value = taskDetail.task.progression_base
// Если прогрессия не введена - используем default_progress или progression_base
payload.value = taskDetail.task.default_progress ?? taskDetail.task.progression_base
}
}
@@ -586,13 +593,17 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
throw new Error(errorData.message || 'Ошибка при выполнении задачи')
}
const data = await response.json().catch(() => ({}))
// Показываем уведомление о выполнении
if (onTaskCompleted) {
onTaskCompleted()
}
// Обновляем список и закрываем модальное окно
if (onRefresh) {
// Если бэкенд вернул обновлённый список — передаём его, иначе делаем повторный GET
if (data.tasks && onRefresh) {
onRefresh(data.tasks)
} else if (onRefresh) {
onRefresh()
}
if (onClose) {
@@ -621,7 +632,7 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
children_task_ids: Array.from(selectedSubtasks)
}
// Если есть прогрессия, отправляем значение (или progression_base, если не введено)
// Если есть прогрессия, отправляем значение (или default_progress/progression_base, если не введено)
if (taskDetail.task.progression_base != null) {
if (progressionValue.trim()) {
payload.value = parseFloat(progressionValue)
@@ -629,8 +640,8 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
throw new Error('Неверное значение')
}
} else {
// Если прогрессия не введена - используем progression_base
payload.value = taskDetail.task.progression_base
// Если прогрессия не введена - используем default_progress или progression_base
payload.value = taskDetail.task.default_progress ?? taskDetail.task.progression_base
}
}
@@ -649,13 +660,17 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
throw new Error(errorData.message || 'Ошибка при выполнении задачи')
}
const data = await response.json().catch(() => ({}))
// Показываем уведомление о выполнении
if (onTaskCompleted) {
onTaskCompleted()
}
// Обновляем список и закрываем модальное окно
if (onRefresh) {
// Если бэкенд вернул обновлённый список — передаём его, иначе делаем повторный GET
if (data.tasks && onRefresh) {
onRefresh(data.tasks)
} else if (onRefresh) {
onRefresh()
}
if (onClose) {
@@ -718,8 +733,11 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
// Обновляем значение чекбокса при изменении taskDetail
useEffect(() => {
if (taskDetail && taskDetail.task) {
const autoCompleteValue = Boolean(taskDetail.task.auto_complete)
console.log('useEffect: Updating completeAtEndOfDay from taskDetail:', autoCompleteValue, 'task.auto_complete:', taskDetail.task.auto_complete)
// Если есть драфт, используем значение из драфта
// Иначе используем default_auto_complete как начальное значение
const autoCompleteValue = taskDetail.has_draft
? Boolean(taskDetail.task.auto_complete)
: Boolean(taskDetail.task.default_auto_complete)
setCompleteAtEndOfDay(autoCompleteValue)
} else {
setCompleteAtEndOfDay(false)
@@ -729,7 +747,7 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
const modalContent = (
<div className="task-detail-modal-overlay" onClick={onClose}>
<div className="task-detail-modal-overlay" onClick={() => onClose?.()}>
<div className="task-detail-modal" onClick={(e) => e.stopPropagation()}>
<div className="task-detail-modal-header">
<h2
@@ -761,7 +779,7 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
</>
) : 'Задача'}
</h2>
<button onClick={onClose} className="task-detail-close-button">
<button onClick={() => onClose?.()} className="task-detail-close-button">
</button>
</div>
@@ -789,17 +807,9 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
<path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"></path>
</svg>
<span className="task-wishlist-link-label">Связано с желанием:</span>
<button
onClick={() => {
if (onClose) onClose()
if (onNavigate && wishlistInfo) {
onNavigate('wishlist-detail', { wishlistId: wishlistInfo.id })
}
}}
className="task-wishlist-link-button"
>
<span className="task-wishlist-link-name">
{wishlistInfo.name}
</button>
</span>
</div>
</div>
)}
@@ -814,7 +824,7 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
step="any"
value={progressionValue}
onChange={(e) => setProgressionValue(e.target.value)}
placeholder={task.progression_base?.toString() || ''}
placeholder={(task.default_progress ?? task.progression_base)?.toString() || ''}
className="progression-input"
/>
<div className="progression-controls-capsule">
@@ -822,7 +832,8 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
type="button"
className="progression-control-btn progression-control-minus"
onClick={() => {
const current = parseFloat(progressionValue) || 0
const base = task.default_progress ?? task.progression_base ?? 1
const current = progressionValue.trim() ? parseFloat(progressionValue) : base
const step = task.progression_base || 1
setProgressionValue((current - step).toString())
}}
@@ -833,7 +844,8 @@ function TaskDetail({ taskId, onClose, onRefresh, onTaskCompleted, onNavigate })
type="button"
className="progression-control-btn progression-control-plus"
onClick={() => {
const current = parseFloat(progressionValue) || 0
const base = task.default_progress ?? task.progression_base ?? 1
const current = progressionValue.trim() ? parseFloat(progressionValue) : base
const step = task.progression_base || 1
setProgressionValue((current + step).toString())
}}

View File

@@ -3,6 +3,7 @@
max-width: 800px;
margin: 0 auto;
position: relative;
padding-bottom: 5rem;
}
.close-x-button {
@@ -48,6 +49,10 @@
margin-bottom: 1.5rem;
}
.task-form form > *:last-child {
margin-bottom: 0;
}
.form-group label {
display: block;
font-weight: 500;
@@ -227,23 +232,24 @@
}
.add-subtask-button {
padding: 0.375rem;
background: #6366f1;
color: white;
border: none;
padding: 0.5rem;
background: white;
color: #3498db;
border: 1px dashed #bae6fd;
border-radius: 0.375rem;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
min-width: 2rem;
height: 2rem;
width: 100%;
height: 2.5rem;
margin-top: 0.5rem;
}
.add-subtask-button:hover {
background: #4f46e5;
background: #e0f2fe;
border-color: #3498db;
}
.subtask-form-item {
@@ -311,9 +317,9 @@
}
.remove-subtask-button {
padding: 0.5rem;
background: #ef4444;
color: white;
padding: 0.25rem;
background: none;
color: #9ca3af;
border: none;
border-radius: 0.375rem;
cursor: pointer;
@@ -322,12 +328,12 @@
align-items: center;
justify-content: center;
flex-shrink: 0;
min-width: 2.5rem;
height: 2.5rem;
min-width: 2rem;
height: 2rem;
}
.remove-subtask-button:hover {
background: #dc2626;
color: #ef4444;
}
.error-message {
@@ -347,9 +353,7 @@
border-top: 1px solid #e5e7eb;
}
.cancel-button,
.submit-button,
.delete-button {
.cancel-button {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 0.375rem;
@@ -357,9 +361,6 @@
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.cancel-button {
background: #f3f4f6;
color: #374151;
}
@@ -368,42 +369,6 @@
background: #e5e7eb;
}
.submit-button {
background: linear-gradient(to right, #6366f1, #8b5cf6);
color: white;
flex: 1;
}
.submit-button:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}
.submit-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.delete-button {
background: #ef4444;
color: white;
padding: 0.75rem;
display: flex;
align-items: center;
justify-content: center;
min-width: 44px;
width: 44px;
}
.delete-button:hover:not(:disabled) {
background: #dc2626;
}
.delete-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.loading {
text-align: center;
padding: 3rem 1rem;
@@ -451,6 +416,57 @@
color: #ef4444;
}
/* Task type tabs */
.task-type-tabs-section {
background: #f0f9ff;
border: 1px solid #bae6fd;
border-radius: 0.5rem;
padding: 0;
overflow: hidden;
}
.task-type-tabs {
display: flex;
border-bottom: 1px solid #bae6fd;
}
.task-type-tab {
flex: 1;
padding: 0.625rem 0;
border: none;
background: transparent;
font-size: 0.875rem;
font-weight: 500;
color: #64748b;
cursor: pointer;
transition: all 0.15s ease;
position: relative;
}
.task-type-tab:not(:last-child) {
border-right: 1px solid #bae6fd;
}
.task-type-tab-active {
color: #3498db;
font-weight: 600;
background: rgba(52, 152, 219, 0.08);
}
.task-type-tab-active::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 2px;
background: #3498db;
}
.task-type-content {
padding: 1rem;
}
/* Test configuration styles */
.test-config-section {
background: #f0f9ff;
@@ -459,13 +475,23 @@
padding: 1rem;
}
.test-config-section > label {
.test-config-section > label,
.test-config-section > .subtasks-header > label {
font-size: 1rem;
font-weight: 600;
color: #3498db;
margin-bottom: 1rem !important;
}
.test-config-section > .subtasks-header {
margin-bottom: 0.5rem;
}
.test-config-section .subtask-form-item {
background: white;
border-color: #bae6fd;
}
.test-config-fields {
display: grid;
grid-template-columns: 1fr 1fr;
@@ -476,7 +502,7 @@
.test-field-group {
display: flex;
flex-direction: column;
gap: 0.25rem;
gap: 0;
}
.test-field-group label {
@@ -500,20 +526,27 @@
.test-dictionaries-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
gap: 0;
max-height: 200px;
overflow-y: auto;
padding: 0.5rem;
padding: 0.5rem 0.25rem;
background: white;
border: 1px solid #d1d5db;
border-radius: 0.375rem;
}
.test-dictionary-item {
.test-dictionaries-list > div {
margin: 0;
padding: 0;
}
label.test-dictionary-item,
.form-group label.test-dictionary-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
gap: 0.25rem;
padding: 0.4rem 0.5rem;
margin-bottom: 0;
border-radius: 0.25rem;
cursor: pointer;
transition: background-color 0.2s;
@@ -526,13 +559,15 @@
.test-dictionary-item input[type="checkbox"] {
width: 18px;
height: 18px;
flex-shrink: 0;
margin: 0;
accent-color: #3498db;
}
.test-dictionary-name {
flex: 1;
font-weight: 500;
color: #374151;
line-height: 18px;
}
.test-dictionary-count {

File diff suppressed because it is too large Load Diff

View File

@@ -319,7 +319,8 @@
border: none;
color: #6b7280;
cursor: pointer;
padding: 0.25rem;
padding: 1rem;
margin: -1rem;
border-radius: 0.25rem;
transition: all 0.2s;
display: flex;
@@ -350,8 +351,9 @@
background: white;
border-radius: 0.5rem;
width: fit-content;
max-width: 90%;
max-width: min(90%, 350px);
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.task-postpone-modal-header {
@@ -558,6 +560,21 @@
cursor: not-allowed;
}
.task-postpone-quick-button-primary {
background: #3b82f6;
color: white;
border-color: #3b82f6;
display: flex;
align-items: center;
gap: 4px;
}
.task-postpone-quick-button-primary:hover:not(:disabled) {
background: #2563eb;
border-color: #2563eb;
color: white;
}
.task-postpone-input-group {
display: flex;
gap: 0.5rem;
@@ -917,3 +934,13 @@
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}
.task-add-modal-button-purchase {
background: linear-gradient(to right, #27ae60, #229954);
color: white;
}
.task-add-modal-button-purchase:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(39, 174, 96, 0.3);
}

View File

@@ -87,6 +87,17 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
return
}
// Для задач-закупок открываем экран закупок
const isPurchase = task.purchase_config_id != null
if (isPurchase) {
onNavigate?.('purchase', {
purchaseConfigId: task.purchase_config_id,
taskId: task.id,
taskName: task.name
})
return
}
// Для обычных задач открываем диалог подтверждения
setSelectedTaskForDetail(task.id)
}
@@ -408,7 +419,19 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
}
defaultDate.setHours(0, 0, 0, 0)
setPostponeDate(formatDateToLocal(defaultDate))
const plannedStr = formatDateToLocal(defaultDate)
// Предвыбираем дату только если она не совпадает с текущей next_show_at (т.е. если чипс "По плану" будет показан)
let nextShowStr = null
if (task.next_show_at) {
const d = new Date(task.next_show_at)
d.setHours(0, 0, 0, 0)
nextShowStr = formatDateToLocal(d)
}
if (plannedStr !== nextShowStr) {
setPostponeDate(plannedStr)
} else {
setPostponeDate('')
}
}
const handlePostponeSubmit = async () => {
@@ -721,16 +744,29 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
Object.keys(groups).forEach(projectName => {
const group = groups[projectName]
// Сортируем невыполненные задачи: по completed DESC (больше завершений выше), затем по id ASC (раньше добавленные выше)
// Сортируем невыполненные задачи: автовыполнение первыми, затем по алфавиту (name ASC), затем по id ASC
group.notCompleted.sort((a, b) => {
if (b.completed !== a.completed) {
return b.completed - a.completed // DESC
// Задачи с автовыполнением (включая default_auto_complete) идут первыми
const aAuto = a.has_draft ? a.auto_complete : a.auto_complete || a.default_auto_complete
const bAuto = b.has_draft ? b.auto_complete : b.auto_complete || b.default_auto_complete
if (aAuto && !bAuto) return -1
if (!aAuto && bAuto) return 1
const nameCompare = (a.name || '').localeCompare(b.name || '')
if (nameCompare !== 0) {
return nameCompare
}
return a.id - b.id // ASC
})
// Сортируем выполненные задачи: бесконечные первыми, затем по next_show_at ASC (ранние в начале), NULL в начале
// Сортируем выполненные задачи: автовыполнение первыми, затем бесконечные, затем по next_show_at ASC (ранние в начале), NULL в начале
group.completed.sort((a, b) => {
// Задачи с автовыполнением (включая default_auto_complete) идут первыми
const aAuto = a.has_draft ? a.auto_complete : a.auto_complete || a.default_auto_complete
const bAuto = b.has_draft ? b.auto_complete : b.auto_complete || b.default_auto_complete
if (aAuto && !bAuto) return -1
if (!aAuto && bAuto) return 1
// Проверяем, является ли задача бесконечной
const hasZeroPeriodA = a.repetition_period && isZeroPeriod(a.repetition_period)
const hasZeroDateA = a.repetition_date && isZeroDate(a.repetition_date)
@@ -791,7 +827,8 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
const hasProgression = task.has_progression || task.progression_base != null
const hasSubtasks = task.subtasks_count > 0
const isTest = task.config_id != null
const showDetailOnCheckmark = !isTest
const isPurchase = task.purchase_config_id != null
const showDetailOnCheckmark = !isTest && !isPurchase
const isWishlist = task.wishlist_id != null
// Проверяем бесконечную задачу: repetition_period = 0 И (repetition_date = 0 ИЛИ отсутствует)
@@ -814,9 +851,9 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
>
<div className="task-item-content">
<div
className={`task-checkmark ${showDetailOnCheckmark ? 'task-checkmark-detail' : ''} ${task.auto_complete ? 'task-checkmark-auto-complete' : ''}`}
className={`task-checkmark ${showDetailOnCheckmark ? 'task-checkmark-detail' : ''} ${(task.has_draft ? task.auto_complete : task.auto_complete || task.default_auto_complete) ? 'task-checkmark-auto-complete' : ''}`}
onClick={(e) => handleCheckmarkClick(task, e)}
title={isTest ? 'Запустить тест' : (showDetailOnCheckmark ? 'Открыть детали' : 'Выполнить задачу')}
title={isTest ? 'Запустить тест' : (isPurchase ? 'Открыть закупки' : (showDetailOnCheckmark ? 'Открыть детали' : 'Выполнить задачу'))}
>
{isTest ? (
<svg
@@ -832,6 +869,20 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path>
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path>
</svg>
) : isPurchase ? (
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M2 7h20l-2 13a2 2 0 0 1-2 1.5H6a2 2 0 0 1-2-1.5L2 7z"></path>
<path d="M9 7V6a3 3 0 0 1 6 0v1"></path>
</svg>
) : isWishlist ? (
<>
<svg
@@ -868,7 +919,7 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
<path d="M6 10 L9 13 L14 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="checkmark-check" />
</svg>
)}
{task.auto_complete && !isTest && !isWishlist && (
{(task.has_draft ? task.auto_complete : task.auto_complete || task.default_auto_complete) && !isTest && !isWishlist && (
<svg
className="task-checkmark-auto-complete-icon"
width="16"
@@ -886,7 +937,11 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
<div className="task-name">
{task.name}
{hasSubtasks && (
<span className="task-subtasks-count">(+{task.subtasks_count})</span>
<span className="task-subtasks-count">
{task.draft_subtasks_count != null && task.draft_subtasks_count > 0
? `(${task.draft_subtasks_count}/${task.subtasks_count})`
: `(${task.subtasks_count})`}
</span>
)}
<span className="task-badge-bar">
{!isOneTime && !isInfinite && !isWishlist && (
@@ -950,8 +1005,8 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, error, onRetry
<polyline points="23 6 13.5 15.5 8.5 10.5 1 18"></polyline>
<polyline points="17 6 23 6 23 12"></polyline>
</svg>
{task.draft_progression_value != null && (
<span className="task-progression-value">{task.draft_progression_value}</span>
{(task.draft_progression_value != null || (task.has_draft ? task.auto_complete : task.auto_complete || task.default_auto_complete)) && (
<span className="task-progression-value">{task.draft_progression_value ?? task.default_progress ?? task.progression_base}</span>
)}
</span>
)}

View File

@@ -242,7 +242,7 @@
align-content: start;
overflow-y: auto;
overflow-x: hidden;
padding: 4rem 1rem 1rem 1rem;
padding: 4rem 1rem 5rem 1rem;
box-sizing: border-box;
width: 100%;
min-height: 0;
@@ -331,7 +331,7 @@
align-content: start;
overflow-y: auto;
overflow-x: hidden;
padding: 4rem 1rem 1rem 1rem;
padding: 4rem 1rem 5rem 1rem;
box-sizing: border-box;
width: 100%;
min-height: 0;

View File

@@ -1,4 +1,5 @@
import React, { useState, useEffect, useRef, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import LoadingError from './LoadingError'
import './TestWords.css'
@@ -8,7 +9,7 @@ const API_URL = '/api'
const DEFAULT_TEST_WORD_COUNT = 10
function TestWords({ onNavigate, wordCount: initialWordCount, configId: initialConfigId, maxCards: initialMaxCards, taskId: initialTaskId }) {
function TestWords({ onNavigate, wordCount: initialWordCount, configId: initialConfigId, maxCards: initialMaxCards, taskId: initialTaskId, isActive }) {
const { authFetch } = useAuth()
const wordCount = initialWordCount || DEFAULT_TEST_WORD_COUNT
const configId = initialConfigId || null
@@ -610,6 +611,7 @@ function TestWords({ onNavigate, wordCount: initialWordCount, configId: initialC
return (
<>
<div className="test-container test-container-fullscreen">
<button className="close-x-button" onClick={handleClose}>
@@ -636,11 +638,6 @@ function TestWords({ onNavigate, wordCount: initialWordCount, configId: initialC
)
})}
</div>
<div className="preview-actions">
<button className="test-start-button" onClick={handleStartTest}>
Начать
</button>
</div>
</div>
) : showResults ? (
<div className="test-results">
@@ -664,15 +661,6 @@ function TestWords({ onNavigate, wordCount: initialWordCount, configId: initialC
)
})}
</div>
<div className="results-actions">
<button
className="test-finish-button"
onClick={handleFinish}
disabled={isClosing}
>
{isClosing ? 'Завершение…' : 'Закончить'}
</button>
</div>
</div>
) : (
<div className="test-screen">
@@ -804,6 +792,43 @@ function TestWords({ onNavigate, wordCount: initialWordCount, configId: initialC
</div>
)}
</div>
{isActive && (showPreview || showResults) ? createPortal(
<div style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '0.75rem 1rem',
paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))',
background: 'linear-gradient(to top, white 60%, rgba(255,255,255,0))',
zIndex: 1500,
display: 'flex',
justifyContent: 'center',
}}>
<button
onClick={showPreview ? handleStartTest : handleFinish}
disabled={showResults && isClosing}
style={{
width: '100%',
maxWidth: '42rem',
padding: '0.875rem',
background: 'linear-gradient(to right, #10b981, #059669)',
color: 'white',
border: 'none',
borderRadius: '0.5rem',
fontSize: '1rem',
fontWeight: 600,
cursor: (showResults && isClosing) ? 'not-allowed' : 'pointer',
opacity: (showResults && isClosing) ? 0.6 : 1,
transition: 'all 0.2s',
}}
>
{showPreview ? 'Начать' : (isClosing ? 'Завершение…' : 'Завершить')}
</button>
</div>,
document.body
) : null}
</>
)
}

View File

@@ -1,14 +1,16 @@
import React, { useState } from 'react'
import React, { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import LoadingError from './LoadingError'
import { useAuth } from './auth/AuthContext'
import TaskDetail from './TaskDetail'
// Функция для форматирования скорa (аналогично formatScore из TaskDetail)
const formatScore = (num) => {
if (num === 0) return '0'
let str = num.toPrecision(4)
str = str.replace(/\.?0+$/, '')
if (str.includes('e+') || str.includes('e-')) {
const numValue = parseFloat(str)
if (Math.abs(numValue) >= 10000) {
@@ -16,7 +18,7 @@ const formatScore = (num) => {
}
return numValue.toString().replace(/\.?0+$/, '')
}
return str
}
@@ -54,7 +56,7 @@ const formatEntryText = (text, nodes) => {
const regex = new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')
if (nodesMap[i] && currentText.includes(placeholder)) {
const node = nodesMap[i]
const scoreStr = node.score >= 0
const scoreStr = node.score >= 0
? `${node.project_name}+${formatScore(node.score)}`
: `${node.project_name}-${formatScore(Math.abs(node.score))}`
currentText = currentText.replace(regex, `__NODE_${i}__`)
@@ -69,7 +71,7 @@ const formatEntryText = (text, nodes) => {
for (let i = 99; i >= 0; i--) {
if (nodesMap[i]) {
const node = nodesMap[i]
const scoreStr = node.score >= 0
const scoreStr = node.score >= 0
? `${node.project_name}+${formatScore(node.score)}`
: `${node.project_name}-${formatScore(Math.abs(node.score))}`
const regex = new RegExp(`\\$${i}(?!\\d)`, 'g')
@@ -85,12 +87,12 @@ const formatEntryText = (text, nodes) => {
// Разбиваем текст на части и создаем React элементы
const result = []
let searchIndex = 0
while (searchIndex < currentText.length) {
// Ищем следующий маркер
let foundMarker = null
let markerIndex = currentText.length
// Ищем все маркеры
for (const marker in escapedMarkers) {
const index = currentText.indexOf(marker, searchIndex)
@@ -99,14 +101,14 @@ const formatEntryText = (text, nodes) => {
foundMarker = marker
}
}
// Если нашли маркер
if (foundMarker) {
// Добавляем текст до маркера
if (markerIndex > searchIndex) {
result.push(currentText.substring(searchIndex, markerIndex))
}
// Добавляем элемент для маркера
const markerData = escapedMarkers[foundMarker]
if (markerData && markerData.type === 'node') {
@@ -117,7 +119,7 @@ const formatEntryText = (text, nodes) => {
// Это экранированный плейсхолдер
result.push(markerData)
}
searchIndex = markerIndex + foundMarker.length
} else {
// Больше маркеров нет, добавляем оставшийся текст
@@ -131,9 +133,295 @@ const formatEntryText = (text, nodes) => {
return result.length > 0 ? result : currentText
}
function TodayEntriesList({ data, loading, error, onRetry, onDelete }) {
// Модальное окно редактирования записи
function EditEntryModal({ entry, onClose, onSuccess, authFetch }) {
const [message, setMessage] = useState(() => {
// Заменяем ${N} на $N для удобного отображения
return (entry.text || '').replace(/\$\{(\d+)\}/g, '$$$1')
})
const [rewards, setRewards] = useState(() => {
if (!entry.nodes || entry.nodes.length === 0) return []
const sorted = [...entry.nodes].sort((a, b) => a.index - b.index)
return sorted.map((node, idx) => ({
position: idx,
project_name: node.project_name,
value: String(node.score)
}))
})
const [projects, setProjects] = useState([])
const [isSending, setIsSending] = useState(false)
const [error, setError] = useState(null)
const debounceTimer = useRef(null)
useEffect(() => {
const loadProjects = async () => {
try {
const response = await authFetch('/projects')
if (response.ok) {
const data = await response.json()
setProjects(Array.isArray(data) ? data : [])
}
} catch (err) {
console.error('Error loading projects:', err)
}
}
loadProjects()
}, [authFetch])
const findMaxPlaceholderIndex = (msg) => {
if (!msg) return -1
const indices = []
const matchesCurly = msg.match(/\$\{(\d+)\}/g) || []
matchesCurly.forEach(match => {
const numMatch = match.match(/\d+/)
if (numMatch) indices.push(parseInt(numMatch[0]))
})
let searchIndex = 0
while (true) {
const index = msg.indexOf('$', searchIndex)
if (index === -1) break
if (index === 0 || msg[index - 1] !== '\\') {
const afterDollar = msg.substring(index + 1)
const digitMatch = afterDollar.match(/^(\d+)/)
if (digitMatch) {
indices.push(parseInt(digitMatch[0]))
}
}
searchIndex = index + 1
}
return indices.length > 0 ? Math.max(...indices) : -1
}
// Пересчет rewards при изменении сообщения
useEffect(() => {
if (debounceTimer.current) clearTimeout(debounceTimer.current)
debounceTimer.current = setTimeout(() => {
const maxIndex = findMaxPlaceholderIndex(message)
setRewards(prevRewards => {
const currentRewards = [...prevRewards]
while (currentRewards.length > maxIndex + 1) currentRewards.pop()
while (currentRewards.length < maxIndex + 1) {
currentRewards.push({ position: currentRewards.length, project_name: '', value: '0' })
}
return currentRewards
})
}, 500)
return () => { if (debounceTimer.current) clearTimeout(debounceTimer.current) }
}, [message])
const handleRewardChange = (index, field, value) => {
const newRewards = [...rewards]
newRewards[index] = { ...newRewards[index], [field]: value }
setRewards(newRewards)
}
const buildFinalMessage = () => {
let result = message
const rewardStrings = {}
rewards.forEach((reward, index) => {
const score = parseFloat(reward.value) || 0
const projectName = reward.project_name.trim()
if (!projectName) return
const scoreStr = score >= 0
? `**${projectName}+${score}**`
: `**${projectName}${score}**`
rewardStrings[index] = scoreStr
})
for (let i = 0; i < 100; i++) {
const placeholder = `\${${i}}`
if (rewardStrings[i]) result = result.split(placeholder).join(rewardStrings[i])
}
for (let i = 99; i >= 0; i--) {
if (rewardStrings[i]) {
const regex = new RegExp(`\\$${i}(?!\\d)`, 'g')
result = result.replace(regex, rewardStrings[i])
}
}
return result
}
const isFormValid = () => {
if (rewards.length === 0) return true
return rewards.every(reward => {
const projectName = reward.project_name?.trim() || ''
const value = reward.value?.toString().trim() || ''
return projectName !== '' && value !== ''
})
}
const handleSubmit = async () => {
for (const reward of rewards) {
if (!reward.project_name.trim()) {
setError('Заполните все проекты')
return
}
}
const finalMessage = buildFinalMessage()
if (!finalMessage.trim()) {
setError('Введите сообщение')
return
}
setIsSending(true)
setError(null)
try {
const response = await authFetch(`/api/entries/${entry.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: finalMessage })
})
if (!response.ok) throw new Error('Ошибка при сохранении')
onSuccess()
} catch (err) {
console.error('Error updating entry:', err)
setError(err.message || 'Ошибка при сохранении')
} finally {
setIsSending(false)
}
}
const modalContent = (
<div className="add-entry-modal-overlay" onClick={onClose}>
<div className="add-entry-modal" onClick={(e) => e.stopPropagation()}>
<div className="add-entry-modal-header">
<h2 className="add-entry-modal-title">Редактировать запись</h2>
<button onClick={onClose} className="add-entry-close-button"></button>
</div>
<div className="add-entry-modal-content">
<div className="add-entry-field">
<label className="add-entry-label">Сообщение</label>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Используйте $0, $1 для указания проектов"
className="add-entry-textarea"
rows={3}
/>
</div>
{rewards.length > 0 && (
<div className="add-entry-rewards">
{rewards.map((reward, index) => (
<div key={index} className="add-entry-reward-item">
<span className="add-entry-reward-number">{index}</span>
<input
type="text"
value={reward.project_name}
onChange={(e) => handleRewardChange(index, 'project_name', e.target.value)}
placeholder="Проект"
className="add-entry-input add-entry-project-input"
list={`edit-entry-projects-${index}`}
/>
<datalist id={`edit-entry-projects-${index}`}>
{projects.map(p => (
<option key={p.project_id} value={p.project_name} />
))}
</datalist>
<input
type="number"
step="any"
value={reward.value}
onChange={(e) => handleRewardChange(index, 'value', e.target.value)}
placeholder="Баллы"
className="add-entry-input add-entry-score-input"
/>
</div>
))}
</div>
)}
{error && (
<div style={{ color: '#ef4444', fontSize: '0.875rem', marginBottom: '0.5rem' }}>{error}</div>
)}
<button
onClick={handleSubmit}
disabled={isSending || !isFormValid()}
className="add-entry-submit-button"
>
{isSending ? 'Сохранение...' : 'Сохранить'}
</button>
</div>
</div>
</div>
)
return typeof document !== 'undefined'
? createPortal(modalContent, document.body)
: modalContent
}
function TodayEntriesList({ data, loading, error, onRetry, onDelete, onNavigate }) {
const { authFetch } = useAuth()
const [deletingIds, setDeletingIds] = useState(new Set())
const [selectedTaskId, setSelectedTaskId] = useState(null)
const [editingEntry, setEditingEntry] = useState(null)
const [removingAutoCompleteId, setRemovingAutoCompleteId] = useState(null)
const selectedTaskIdRef = useRef(null)
const historyPushedRef = useRef(false)
// Обновляем ref при изменении selectedTaskId
useEffect(() => {
selectedTaskIdRef.current = selectedTaskId
}, [selectedTaskId])
// Управление историей браузера при открытии/закрытии TaskDetail
useEffect(() => {
if (selectedTaskId && !historyPushedRef.current) {
window.history.pushState({ modalOpen: true, type: 'task-detail-statistics' }, '', window.location.href)
historyPushedRef.current = true
} else if (!selectedTaskId) {
historyPushedRef.current = false
}
if (!selectedTaskId) return
const handlePopState = () => {
if (selectedTaskIdRef.current) {
setSelectedTaskId(null)
historyPushedRef.current = false
}
}
window.addEventListener('popstate', handlePopState)
return () => {
window.removeEventListener('popstate', handlePopState)
}
}, [selectedTaskId])
const handleOpenTaskDetail = (taskId) => {
setSelectedTaskId(taskId)
}
const handleCloseTaskDetail = (skipHistoryBack = false) => {
if (!skipHistoryBack && historyPushedRef.current) {
window.history.back()
} else {
historyPushedRef.current = false
setSelectedTaskId(null)
}
}
const handleTaskSaved = () => {
if (onDelete) onDelete()
}
const handleRemoveAutoComplete = async (taskId) => {
if (!window.confirm('Убрать автовыполнение этой задачи в конце дня?')) return
setRemovingAutoCompleteId(taskId)
try {
const response = await authFetch(`/api/tasks/${taskId}/draft`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ auto_complete: false })
})
if (!response.ok) throw new Error('Ошибка при обновлении')
if (onDelete) onDelete()
} catch (err) {
console.error('Remove auto-complete failed:', err)
alert(err.message || 'Не удалось убрать автовыполнение')
} finally {
setRemovingAutoCompleteId(null)
}
}
const handleDelete = async (entryId) => {
if (deletingIds.has(entryId)) return
@@ -147,9 +435,7 @@ function TodayEntriesList({ data, loading, error, onRetry, onDelete }) {
try {
const response = await authFetch(`/api/entries/${entryId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
headers: { 'Content-Type': 'application/json' },
})
if (!response.ok) {
@@ -158,10 +444,7 @@ function TodayEntriesList({ data, loading, error, onRetry, onDelete }) {
throw new Error(`Ошибка при удалении записи: ${response.status}`)
}
// Вызываем callback для обновления данных
if (onDelete) {
onDelete()
}
if (onDelete) onDelete()
} catch (err) {
console.error('Delete failed:', err)
alert(err.message || 'Не удалось удалить запись')
@@ -195,75 +478,150 @@ function TodayEntriesList({ data, loading, error, onRetry, onDelete }) {
}
return (
<>
<div className="mt-2 mb-6">
<div className="space-y-3">
{data.map((entry) => (
<div
key={entry.id}
className="bg-white rounded-lg p-4 shadow-sm border border-gray-200 relative group"
>
<button
onClick={() => handleDelete(entry.id)}
disabled={deletingIds.has(entry.id)}
className="absolute top-4 right-4 disabled:opacity-50 disabled:cursor-not-allowed"
style={{
color: '#6b7280',
background: 'none',
border: 'none',
cursor: 'pointer',
padding: '0.25rem',
borderRadius: '0.25rem',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '24px',
height: '24px',
transition: 'all 0.2s',
opacity: deletingIds.has(entry.id) ? 0.5 : 1,
zIndex: 10
}}
onMouseEnter={(e) => {
if (!deletingIds.has(entry.id)) {
e.currentTarget.style.backgroundColor = '#f3f4f6'
e.currentTarget.style.color = '#1f2937'
{data.map((entry) => {
const isDraft = entry.is_draft === true
return (
<div
key={isDraft ? `draft-${entry.task_id}` : entry.id}
className={`bg-white rounded-lg p-4 shadow-sm border relative group ${
isDraft ? 'border-blue-400 cursor-pointer' : 'border-gray-200 cursor-pointer'
}`}
onClick={() => {
if (isDraft) {
handleOpenTaskDetail(entry.task_id)
} else {
setEditingEntry(entry)
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent'
e.currentTarget.style.color = '#6b7280'
}}
title="Удалить запись"
>
{deletingIds.has(entry.id) ? (
<svg className="w-5 h-5 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{isDraft ? (
// Кнопка-молния с зачёркиванием — убрать автовыполнение
<button
onClick={(e) => {
e.stopPropagation()
handleRemoveAutoComplete(entry.task_id)
}}
disabled={removingAutoCompleteId === entry.task_id}
className="absolute top-4 right-4"
style={{
color: '#3b82f6',
background: 'none',
border: 'none',
cursor: 'pointer',
padding: '0.25rem',
borderRadius: '0.25rem',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '24px',
height: '24px',
transition: 'all 0.2s',
opacity: removingAutoCompleteId === entry.task_id ? 0.5 : 1,
zIndex: 10
}}
onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = '#eff6ff' }}
onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent' }}
title="Убрать автовыполнение"
>
{/* Молния с зачёркиванием */}
<svg width="16" height="16" viewBox="0 0 24 24">
<path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" fill="currentColor" />
{/* Зачёркивающая линия: белая с синей обводкой */}
<line x1="3" y1="21" x2="21" y2="3" stroke="white" strokeWidth="4" strokeLinecap="round" />
<line x1="3" y1="21" x2="21" y2="3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
</svg>
</button>
) : (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 6h18"></path>
<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
<line x1="10" y1="11" x2="10" y2="17"></line>
<line x1="14" y1="11" x2="14" y2="17"></line>
</svg>
<button
onClick={(e) => {
e.stopPropagation()
handleDelete(entry.id)
}}
disabled={deletingIds.has(entry.id)}
className="absolute top-4 right-4 disabled:opacity-50 disabled:cursor-not-allowed"
style={{
color: '#6b7280',
background: 'none',
border: 'none',
cursor: 'pointer',
padding: '0.25rem',
borderRadius: '0.25rem',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '24px',
height: '24px',
transition: 'all 0.2s',
opacity: deletingIds.has(entry.id) ? 0.5 : 1,
zIndex: 10
}}
onMouseEnter={(e) => {
if (!deletingIds.has(entry.id)) {
e.currentTarget.style.backgroundColor = '#f3f4f6'
e.currentTarget.style.color = '#1f2937'
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent'
e.currentTarget.style.color = '#6b7280'
}}
title="Удалить запись"
>
{deletingIds.has(entry.id) ? (
<svg className="w-5 h-5 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
) : (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 6h18"></path>
<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
<line x1="10" y1="11" x2="10" y2="17"></line>
<line x1="14" y1="11" x2="14" y2="17"></line>
</svg>
)}
</button>
)}
</button>
<div className="text-gray-800 whitespace-pre-wrap pr-8">
{formatEntryText(entry.text, entry.nodes)}
</div>
{entry.created_date && (
<div className="text-xs text-gray-500 mt-2">
{new Date(entry.created_date).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit'
})}
<div className="text-gray-800 whitespace-pre-wrap pr-8">
{formatEntryText(entry.text, entry.nodes)}
</div>
)}
</div>
))}
<div className="text-xs text-gray-500 mt-2">
{isDraft ? 'в конце дня' : (
entry.created_date && new Date(entry.created_date).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit'
})
)}
</div>
</div>
)
})}
</div>
</div>
{selectedTaskId && (
<TaskDetail
taskId={selectedTaskId}
onClose={handleCloseTaskDetail}
onRefresh={handleTaskSaved}
onNavigate={onNavigate}
/>
)}
{editingEntry && (
<EditEntryModal
entry={editingEntry}
onClose={() => setEditingEntry(null)}
onSuccess={() => {
setEditingEntry(null)
if (onDelete) onDelete()
}}
authFetch={authFetch}
/>
)}
</>
)
}

View File

@@ -30,6 +30,8 @@ function getLastFiveWeeks() {
return weeks.reverse() // От старой к новой
}
// Проверяет, закончилась ли уже данная ISO-неделя (текущая неделя не закончилась)
function Tracking({ onNavigate, activeTab }) {
const { authFetch } = useAuth()
const [weeks, setWeeks] = useState(() => getLastFiveWeeks())
@@ -147,7 +149,7 @@ function Tracking({ onNavigate, activeTab }) {
) : (
<div className="users-list">
{data?.users.map(user => (
<UserTrackingCard key={user.user_id} user={user} />
<UserTrackingCard key={user.user_id} user={user} selectedWeek={selectedWeek} />
))}
</div>
)}
@@ -156,7 +158,7 @@ function Tracking({ onNavigate, activeTab }) {
}
// Карточка пользователя с прогрессом
function UserTrackingCard({ user }) {
function UserTrackingCard({ user, selectedWeek }) {
// Сортируем проекты по priority (1, 2, остальные)
const sortedProjects = [...user.projects].sort((a, b) => {
const pa = a.priority ?? 99
@@ -169,10 +171,27 @@ function UserTrackingCard({ user }) {
return percent >= 100 ? 'percent-green' : 'percent-blue'
}
// Показываем (черновик) если выбранная неделя позже недели подтверждения
const showDraft = selectedWeek && (() => {
const cy = user.priorities_confirmed_year || 0
const cw = user.priorities_confirmed_week || 0
const sy = selectedWeek.year
const sw = selectedWeek.week
// Неделя не подтверждена вообще (0,0) или выбранная неделя позже подтверждённой
return sy > cy || (sy === cy && sw > cw)
})()
return (
<div className={`user-tracking-card ${user.is_current_user ? 'current-user' : ''}`}>
<div className="user-header">
<span className="user-name">{user.user_name}</span>
<span className="user-name">
{user.user_name}
{showDraft && (
<span style={{ color: '#9ca3af', fontWeight: 'normal', fontSize: '0.85em', marginLeft: '4px' }}>
(черновик)
</span>
)}
</span>
<span className={`user-total ${getPercentColorClass(totalPercent)}`}>{totalPercent.toFixed(0)}%</span>
</div>
<div className="projects-list">

View File

@@ -478,3 +478,11 @@
transform: translateY(-1px);
}
.wishlist .board-pill {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.wishlist .board-pill {
border-color: transparent;
}

View File

@@ -1,4 +1,5 @@
import React, { useState, useEffect, useRef, useMemo } from 'react'
import { createPortal } from 'react-dom'
import { useAuth } from './auth/AuthContext'
import BoardSelector from './BoardSelector'
import LoadingError from './LoadingError'
@@ -47,13 +48,16 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
const [selectedItem, setSelectedItem] = useState(null)
const [selectedWishlistForDetail, setSelectedWishlistForDetail] = useState(null)
const [currentWeekData, setCurrentWeekData] = useState(null)
const [showBoardActionMenu, setShowBoardActionMenu] = useState(false)
const fetchingRef = useRef(false)
const fetchingCompletedRef = useRef(false)
const initialFetchDoneRef = useRef(false)
const prevIsActiveRef = useRef(isActive)
const selectedBoardIdRef = useRef(getInitialBoardId())
// Обёртка для setSelectedBoardId с сохранением в localStorage
const setSelectedBoardId = (boardId) => {
selectedBoardIdRef.current = boardId
setSelectedBoardIdState(boardId)
try {
if (boardId) {
@@ -146,20 +150,20 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
setBoards(data || [])
saveBoardsToCache(data || [])
const firstActive = data?.find(b => !b.is_archived) || (data?.length > 0 ? data[0] : null)
// Проверяем, что выбранная доска существует в списке
if (selectedBoardId) {
const boardExists = data?.some(b => b.id === selectedBoardId)
if (!boardExists && data?.length > 0) {
// Сохранённая доска не существует, выбираем первую
setSelectedBoardId(data[0].id)
if (!boardExists && firstActive) {
setSelectedBoardId(firstActive.id)
}
} else if (data?.length > 0) {
} else if (firstActive) {
// Пытаемся восстановить из localStorage
const savedBoardId = getSavedBoardId()
if (savedBoardId && data.some(b => b.id === savedBoardId)) {
setSelectedBoardId(savedBoardId)
} else {
setSelectedBoardId(data[0].id)
setSelectedBoardId(firstActive.id)
}
}
}
@@ -171,69 +175,83 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
}
// Загрузка желаний выбранной доски
const fetchItems = async () => {
if (!selectedBoardId || fetchingRef.current) return
const fetchItems = async (boardId) => {
if (!boardId || fetchingRef.current) return
fetchingRef.current = true
try {
const hasDataInState = items.length > 0 || completedCount > 0
if (!hasDataInState) {
const cacheLoaded = loadItemsFromCache(selectedBoardId)
const cacheLoaded = loadItemsFromCache(boardId)
if (!cacheLoaded) {
setLoading(true)
}
}
const response = await authFetch(`${API_URL}/boards/${selectedBoardId}/items`)
const response = await authFetch(`${API_URL}/boards/${boardId}/items`)
if (!response.ok) {
throw new Error('Ошибка при загрузке желаний')
}
const data = await response.json()
const allItems = [...(data.unlocked || []), ...(data.locked || [])]
const count = data.completed_count || 0
// Проверяем, что пользователь не переключился на другую доску пока шёл запрос
if (selectedBoardIdRef.current !== boardId) return
setItems(allItems)
setCompletedCount(count)
saveItemsToCache(selectedBoardId, allItems, count)
saveItemsToCache(boardId, allItems, count)
setError('')
} catch (err) {
if (selectedBoardIdRef.current !== boardId) return
setError(err.message)
if (!loadItemsFromCache(selectedBoardId)) {
if (!loadItemsFromCache(boardId)) {
setItems([])
setCompletedCount(0)
}
} finally {
setLoading(false)
if (selectedBoardIdRef.current === boardId) {
setLoading(false)
}
fetchingRef.current = false
}
}
// Загрузка завершённых для текущей доски
const fetchCompleted = async () => {
if (fetchingCompletedRef.current || !selectedBoardId) return
const fetchCompleted = async (boardId) => {
if (fetchingCompletedRef.current || !boardId) return
fetchingCompletedRef.current = true
try {
setCompletedLoading(true)
// Используем новый API для получения завершённых на доске
const response = await authFetch(`${API_URL}/boards/${selectedBoardId}/completed`)
const response = await authFetch(`${API_URL}/boards/${boardId}/completed`)
if (!response.ok) {
const errText = await response.text()
const msg = errText || 'Ошибка при загрузке завершённых желаний'
throw new Error(msg)
}
const data = await response.json()
const completedData = Array.isArray(data) ? data : []
// Проверяем, что пользователь не переключился на другую доску пока шёл запрос
if (selectedBoardIdRef.current !== boardId) return
setCompleted(completedData)
} catch (err) {
console.error('Error fetching completed items:', err)
setCompleted([])
if (selectedBoardIdRef.current === boardId) {
setCompleted([])
}
} finally {
setCompletedLoading(false)
if (selectedBoardIdRef.current === boardId) {
setCompletedLoading(false)
}
fetchingCompletedRef.current = false
}
}
@@ -292,7 +310,7 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
}
// Загружаем свежие данные
fetchItems()
fetchItems(selectedBoardId)
}
}, [selectedBoardId])
@@ -300,13 +318,13 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
useEffect(() => {
const wasActive = prevIsActiveRef.current
prevIsActiveRef.current = isActive
if (!initialFetchDoneRef.current) return
if (isActive && !wasActive) {
fetchBoards()
if (selectedBoardId) {
fetchItems()
fetchItems(selectedBoardId)
}
}
}, [isActive])
@@ -321,9 +339,9 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
console.error('Error clearing cache:', err)
}
fetchBoards()
fetchItems()
if (completedExpanded && completedCount > 0) {
fetchCompleted()
fetchItems(selectedBoardId)
if (completedExpanded) {
fetchCompleted(selectedBoardId)
}
}
}, [refreshTrigger, selectedBoardId])
@@ -361,12 +379,13 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
}
}, [boardDeleted])
// Если текущая доска больше не существует в списке - выбираем первую
// Если текущая доска больше не существует в списке - выбираем первую неархивную
useEffect(() => {
if (boards.length > 0 && selectedBoardId) {
const boardExists = boards.some(b => b.id === selectedBoardId)
if (!boardExists) {
setSelectedBoardId(boards[0].id)
const firstActive = boards.find(b => !b.is_archived) || boards[0]
setSelectedBoardId(firstActive.id)
}
}
}, [boards, selectedBoardId])
@@ -375,53 +394,84 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
setSelectedBoardId(boardId)
}
const handleBoardEdit = () => {
const board = boards.find(b => b.id === selectedBoardId)
if (board?.is_owner) {
onNavigate?.('board-form', { boardId: selectedBoardId })
} else {
// Показать подтверждение выхода
handleLeaveBoard()
}
}
const handleLeaveBoard = async () => {
if (!window.confirm('Отвязаться от этой доски? Вы больше не будете видеть её желания.')) return
try {
const response = await authFetch(`${API_URL}/boards/${selectedBoardId}/leave`, {
method: 'POST'
})
if (response.ok) {
// Убираем доску из списка
const newBoards = boards.filter(b => b.id !== selectedBoardId)
setBoards(newBoards)
saveBoardsToCache(newBoards)
// Выбираем первую доску
if (newBoards.length > 0) {
setSelectedBoardId(newBoards[0].id)
} else {
setSelectedBoardId(null)
setItems([])
}
}
} catch (err) {
console.error('Error leaving board:', err)
const handleBoardEdit = (boardId) => {
const id = boardId || selectedBoardId
const board = boards.find(b => b.id === id)
if (board && !board.is_owner) {
openBoardActionMenu()
return
}
onNavigate?.('board-form', { boardId: id })
}
const handleAddBoard = () => {
onNavigate?.('board-form', { boardId: null })
}
const openBoardActionMenu = () => {
setShowBoardActionMenu(true)
}
const closeBoardActionMenu = () => {
setShowBoardActionMenu(false)
}
const handleBoardArchive = async () => {
const board = boards.find(b => b.id === selectedBoardId)
if (!board) return
if (board.is_archived) {
setShowBoardActionMenu(false)
try {
const res = await authFetch(`/api/wishlist/boards/${selectedBoardId}/unarchive`, {
method: 'POST'
})
if (res.ok) {
fetchBoards()
fetchItems(selectedBoardId)
}
} catch (err) {
console.error('Error unarchiving board:', err)
}
} else {
if (!window.confirm('Архивировать доску? Она переместится в архив.')) return
setShowBoardActionMenu(false)
try {
const res = await authFetch(`/api/wishlist/boards/${selectedBoardId}/archive`, {
method: 'POST'
})
if (res.ok) {
fetchBoards()
}
} catch (err) {
console.error('Error archiving board:', err)
}
}
}
const handleBoardLeave = async () => {
if (!window.confirm('Покинуть доску? Вы больше не будете видеть её желания.')) return
setShowBoardActionMenu(false)
try {
const res = await authFetch(`/api/wishlist/boards/${selectedBoardId}/leave`, {
method: 'POST'
})
if (res.ok) {
fetchBoards()
}
} catch (err) {
console.error('Error leaving board:', err)
}
}
const handleToggleCompleted = () => {
const newExpanded = !completedExpanded
setCompletedExpanded(newExpanded)
if (newExpanded && completedCount > 0) {
fetchCompleted()
fetchCompleted(selectedBoardId)
}
}
@@ -465,9 +515,9 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
}
setSelectedItem(null)
await fetchItems()
await fetchItems(selectedBoardId)
if (completedExpanded) {
await fetchCompleted()
await fetchCompleted(selectedBoardId)
}
} catch (err) {
setError(err.message)
@@ -502,8 +552,8 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
}
// Обновляем список
await fetchItems()
await fetchItems(selectedBoardId)
// Открываем форму редактирования для нового желания
onNavigate?.('wishlist-form', { wishlistId: newItem.id, boardId: selectedBoardId })
} catch (err) {
@@ -633,10 +683,24 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
<div className="wishlist-card-content">
<button
className="card-menu-button"
onClick={(e) => handleMenuClick(item, e)}
title="Меню"
onClick={(e) => {
e.stopPropagation()
onNavigate?.('wishlist-form', { wishlistId: item.id, boardId: selectedBoardId })
}}
title="Редактировать"
>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
</svg>
</button>
<div className="card-image">
@@ -680,8 +744,9 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
onBoardEdit={handleBoardEdit}
onAddBoard={handleAddBoard}
loading={boardsLoading}
showBoardAction={false}
/>
<LoadingError onRetry={() => fetchItems()} />
<LoadingError onRetry={() => fetchItems(selectedBoardId)} />
</div>
)
}
@@ -695,7 +760,10 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
onBoardChange={handleBoardChange}
onBoardEdit={handleBoardEdit}
onAddBoard={handleAddBoard}
archivedApiUrl="/api/wishlist/boards/archived"
onBoardUnarchived={() => fetchBoards()}
loading={boardsLoading}
showBoardAction={false}
/>
{/* Основной список */}
@@ -791,15 +859,41 @@ function Wishlist({ onNavigate, refreshTrigger = 0, isActive = false, initialBoa
wishlistId={selectedWishlistForDetail}
onNavigate={onNavigate}
boardId={selectedBoardId}
refreshTrigger={refreshTrigger}
onRefresh={async () => {
await fetchItems()
await fetchItems(selectedBoardId)
if (completedExpanded) {
await fetchCompleted()
await fetchCompleted(selectedBoardId)
}
}}
onClose={handleCloseDetail}
/>
)}
{showBoardActionMenu && createPortal(
<div className="wishlist-modal-overlay" style={{ zIndex: 2000 }} onClick={closeBoardActionMenu}>
<div className="wishlist-modal" onClick={(e) => e.stopPropagation()}>
<div className="wishlist-modal-header">
<h3>{boards.find(b => b.id === selectedBoardId)?.name}</h3>
</div>
<div className="wishlist-modal-actions">
{boards.find(b => b.id === selectedBoardId)?.is_archived ? (
<button className="wishlist-modal-copy" onClick={handleBoardArchive}>
Разархивировать
</button>
) : (
<button className="wishlist-modal-copy" onClick={handleBoardArchive}>
Архивировать
</button>
)}
<button className="wishlist-modal-delete" onClick={handleBoardLeave}>
Выйти
</button>
</div>
</div>
</div>,
document.body
)}
</div>
)
}

View File

@@ -9,7 +9,7 @@ import './TaskList.css'
const API_URL = '/api/wishlist'
function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, previousTab }) {
function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, previousTab, refreshTrigger = 0 }) {
const { authFetch, user } = useAuth()
const [wishlistItem, setWishlistItem] = useState(null)
const [loading, setLoading] = useState(true)
@@ -51,6 +51,12 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
}
}, [wishlistId, fetchWishlistDetail])
useEffect(() => {
if (refreshTrigger > 0 && wishlistId) {
fetchWishlistDetail()
}
}, [refreshTrigger])
const handleEdit = () => {
// Сбрасываем флаг, чтобы handleClose не вызвал history.back()
// handleTabChange заменит запись модального окна через replaceState
@@ -75,10 +81,7 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
if (onRefresh) {
onRefresh()
}
if (onNavigate) {
onNavigate('wishlist')
}
onClose?.()
closeWithHistoryCleanup()
} catch (err) {
console.error('Error completing wishlist:', err)
setToastMessage({ text: err.message || 'Ошибка при завершении', type: 'error' })
@@ -103,10 +106,7 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
if (onRefresh) {
onRefresh()
}
if (onNavigate) {
onNavigate('wishlist')
}
onClose?.()
closeWithHistoryCleanup()
} catch (err) {
console.error('Error rejecting wishlist:', err)
setToastMessage({ text: err.message || 'Ошибка при отклонении', type: 'error' })
@@ -131,8 +131,7 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
if (onRefresh) {
onRefresh()
}
fetchWishlistDetail()
onClose?.()
closeWithHistoryCleanup()
} catch (err) {
console.error('Error uncompleting wishlist:', err)
setToastMessage({ text: err.message || 'Ошибка при возобновлении желания', type: 'error' })
@@ -161,9 +160,7 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
if (onRefresh) {
onRefresh()
}
if (onNavigate) {
onNavigate('wishlist')
}
closeWithHistoryCleanup()
} catch (err) {
console.error('Error deleting wishlist:', err)
setToastMessage({ text: err.message || 'Ошибка при удалении', type: 'error' })
@@ -174,6 +171,11 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
const handleCreateTask = () => {
if (!wishlistItem || !wishlistItem.unlocked || wishlistItem.completed) return
// Сбрасываем refs чтобы popstate handler и cleanup не мешали навигации
// history.back() не вызываем — App.jsx заменит запись модала через replaceState
historyPushedForWishlistRef.current = false
wishlistIdRef.current = null
onClose?.()
onNavigate?.('task-form', { wishlistId: wishlistId })
}
@@ -230,15 +232,17 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
// закрываем модальные окна без удаления записей из истории
// App.jsx сам обработает навигацию и заменит запись task-detail на task-form через replaceState
// Запись wishlist-detail останется в истории, но экран будет закрыт
if (skipHistoryBack) {
if (skipHistoryBack === true) {
// Сохраняем флаг перед сбросом
const hadWishlistHistory = historyPushedForWishlistRef.current
// Закрываем модальные окна
historyPushedForTaskRef.current = false
selectedTaskForDetailRef.current = null
setSelectedTaskForDetail(null)
historyPushedForWishlistRef.current = false
wishlistIdRef.current = null
// Закрываем экран желания через onClose
// Навигация на task-form уже происходит в TaskDetail, поэтому не вызываем onNavigate здесь
// App.jsx обработает навигацию и заменит запись task-detail на task-form через replaceState
@@ -249,6 +253,7 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
window.history.back()
} else {
historyPushedForTaskRef.current = false
selectedTaskForDetailRef.current = null
setSelectedTaskForDetail(null)
}
}
@@ -285,27 +290,24 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
if (!wishlistId && !selectedTaskForDetail) return
const handlePopState = (event) => {
// Проверяем наличие модальных окон в DOM
const taskDetailModal = document.querySelector('.task-detail-modal-overlay')
const wishlistDetailModal = document.querySelector('.wishlist-detail-modal-overlay')
// Используем refs для получения актуального состояния
// (refs обновляются сразу в обработчике, в отличие от DOM который обновляется после рендера)
const currentTaskDetail = selectedTaskForDetailRef.current
const currentWishlistId = wishlistIdRef.current
// Сначала проверяем вложенное модальное окно TaskDetail
if (currentTaskDetail || taskDetailModal) {
if (currentTaskDetail) {
setSelectedTaskForDetail(null)
selectedTaskForDetailRef.current = null
historyPushedForTaskRef.current = false
// Возвращаем запись для WishlistDetail
if (currentWishlistId || wishlistDetailModal) {
window.history.pushState({ modalOpen: true, type: 'wishlist-detail' }, '', window.location.href)
}
// НЕ пушим запись для WishlistDetail — оригинальная запись wishlist-detail
// уже находится на текущей позиции в history stack (мы вернулись на неё после back).
// Следующий back от wishlist-detail закроет диалог желания.
return
}
// Если открыто модальное окно WishlistDetail, закрываем его
if (currentWishlistId || wishlistDetailModal) {
if (currentWishlistId) {
if (onClose) {
onClose()
} else {
@@ -323,9 +325,11 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
}
}
historyPushedForWishlistRef.current = false
wishlistIdRef.current = null
// Следующее нажатие "назад" обработается App.jsx нормально
return
}
}
window.addEventListener('popstate', handlePopState)
@@ -334,6 +338,28 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
}
}, [wishlistId, selectedTaskForDetail, onClose, onNavigate, previousTab, boardId])
// Закрытие модального окна с очисткой записей из истории
// Используется при программном закрытии (завершение, отклонение, возобновление)
const closeWithHistoryCleanup = () => {
// Считаем сколько записей нужно убрать из истории
let stepsBack = 0
if (historyPushedForTaskRef.current) stepsBack++
if (historyPushedForWishlistRef.current) stepsBack++
// Сбрасываем refs чтобы popstate handler не реагировал
historyPushedForTaskRef.current = false
historyPushedForWishlistRef.current = false
selectedTaskForDetailRef.current = null
wishlistIdRef.current = null
setSelectedTaskForDetail(null)
// Убираем записи из истории
if (stepsBack > 0) {
window.history.go(-stepsBack)
}
onClose?.()
}
const handleClose = () => {
// Если была добавлена запись в историю, удаляем её через history.back()
// Обработчик popstate закроет модальное окно
@@ -364,9 +390,7 @@ function WishlistDetail({ wishlistId, onNavigate, onRefresh, boardId, onClose, p
if (onRefresh) {
onRefresh()
}
if (onNavigate) {
onNavigate('wishlist')
}
closeWithHistoryCleanup()
}
const handleDeleteTask = async (e) => {

View File

@@ -430,12 +430,52 @@
}
.condition-form form {
padding: 1.5rem 1.5rem 0.75rem 1.5rem;
padding: 0 1.5rem 0.75rem 1.5rem;
flex: 1;
display: flex;
flex-direction: column;
}
.condition-tabs-container {
display: flex;
align-items: center;
margin-bottom: 1rem;
padding-top: 0.5rem;
}
.condition-tabs-inner {
display: flex;
gap: 0.5rem;
border-bottom: 2px solid #e0e0e0;
}
.condition-tabs-close {
margin-left: auto;
margin-right: -0.5rem;
}
.condition-tab-button {
background: none;
border: none;
padding: 0.75rem 1.25rem;
font-size: 1rem;
color: #666;
cursor: pointer;
border-bottom: 3px solid transparent;
margin-bottom: -2px;
transition: color 0.2s, border-color 0.2s;
}
.condition-tab-button:hover {
color: #3498db;
}
.condition-tab-button.active {
color: #3498db;
border-bottom-color: #3498db;
font-weight: 600;
}
.form-actions {
display: flex;
gap: 1rem;
@@ -449,38 +489,14 @@
text-align: left;
color: #666;
font-size: 0.85em;
min-height: 1.2em;
line-height: 1.2em;
}
.submit-button {
flex: 1;
padding: 0.75rem;
background: #3498db;
color: white;
border: none;
border-radius: 0.375rem;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.condition-form-submit-button {
width: 100%;
flex: none;
}
.submit-button:hover:not(:disabled) {
background: #2980b9;
transform: translateY(-1px);
}
.submit-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.cancel-button {
flex: 1;
padding: 0.75rem;

View File

@@ -1,16 +1,37 @@
import React, { useState, useEffect, useCallback, useRef } from 'react'
import { createPortal } from 'react-dom'
import Cropper from 'react-easy-crop'
import { useAuth } from './auth/AuthContext'
import Toast from './Toast'
import './Wishlist.css'
import './WishlistForm.css'
// Извлекает первый URL из текста
function extractUrl(text) {
if (!text) return ''
const match = text.match(/https?:\/\/[^\s<>"'`,;!)\]]+/i)
return match ? match[0] : text
}
const API_URL = '/api/wishlist'
const TASKS_API_URL = '/api/tasks'
const PROJECTS_API_URL = '/projects'
const WISHLIST_FORM_STATE_KEY = 'wishlistFormPendingState'
function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, boardId }) {
function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId: newTaskIdProp, boardId, isActive }) {
const { authFetch, user } = useAuth()
// newTaskId может прийти из props (через onNavigate) или из sessionStorage (через history.back)
const [newTaskId] = useState(() => {
if (newTaskIdProp) return newTaskIdProp
const stored = sessionStorage.getItem('wishlistFormNewTaskId')
if (stored) {
sessionStorage.removeItem('wishlistFormNewTaskId')
return parseInt(stored, 10)
}
return undefined
})
const [name, setName] = useState('')
const [price, setPrice] = useState('')
const [link, setLink] = useState('')
@@ -33,10 +54,18 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
const [toastMessage, setToastMessage] = useState(null)
const [loadingWishlist, setLoadingWishlist] = useState(false)
const [fetchingMetadata, setFetchingMetadata] = useState(false)
const [restoredFromSession, setRestoredFromSession] = useState(false) // Флаг восстановления из sessionStorage
const [restoredFromSession, setRestoredFromSession] = useState(() => {
// Инициализируем флаг сразу, чтобы loadWishlist не запустился до восстановления
return !!(newTaskId && sessionStorage.getItem(WISHLIST_FORM_STATE_KEY))
})
const [loadedWishlistData, setLoadedWishlistData] = useState(null) // Данные желания для последующего маппинга условий
const [imageUrlInput, setImageUrlInput] = useState('') // Ссылка на картинку для загрузки по URL
const [loadingImageFromUrl, setLoadingImageFromUrl] = useState(false)
const [newTaskConsumed, setNewTaskConsumed] = useState(false) // Флаг что newTaskId уже добавлен как цель
const [isDeleting, setIsDeleting] = useState(false)
const [isCopying, setIsCopying] = useState(false)
const [showActionMenu, setShowActionMenu] = useState(false)
const actionMenuHistoryRef = useRef(false)
const fileInputRef = useRef(null)
// Загрузка задач, проектов и саджестов групп
@@ -139,6 +168,24 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
}
}, [editConditionIndex, unlockConditions])
// Обработка кнопки "назад" для диалога ConditionForm
const showConditionFormRef = useRef(false)
const conditionClosedByPopStateRef = useRef(false)
showConditionFormRef.current = showConditionForm
useEffect(() => {
const handlePopState = () => {
if (showConditionFormRef.current) {
// Закрываем диалог — popstate уже убрал запись из стека
conditionClosedByPopStateRef.current = true
setShowConditionForm(false)
setEditingConditionIndex(null)
}
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
}, [])
// Восстановление состояния при возврате с создания задачи
useEffect(() => {
const savedState = sessionStorage.getItem(WISHLIST_FORM_STATE_KEY)
@@ -161,6 +208,9 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
const restoredConditions = state.unlockConditions || []
console.log('[WishlistForm] Restored conditions:', restoredConditions)
// Устанавливаем флаг синхронно, чтобы loadWishlist не перезаписал восстановленное состояние
setRestoredFromSession(true)
// Перезагружаем задачи, чтобы новая задача была в списке
const reloadTasks = async () => {
console.log('[WishlistForm] Reloading tasks...')
@@ -171,7 +221,7 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
const tasksData = await tasksResponse.json()
console.log('[WishlistForm] Tasks loaded:', tasksData.length)
setTasks(Array.isArray(tasksData) ? tasksData : [])
// Автоматически добавляем цель с новой задачей
console.log('[WishlistForm] pendingConditionType:', state.pendingConditionType)
if (state.pendingConditionType === 'task_completion') {
@@ -184,11 +234,11 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
display_order: restoredConditions.length,
}
console.log('[WishlistForm] New condition to add:', newCondition)
// Если редактировали существующее условие, заменяем его
if (state.editingConditionIndex !== null && state.editingConditionIndex !== undefined) {
console.log('[WishlistForm] Replacing existing condition at index:', state.editingConditionIndex)
const updatedConditions = restoredConditions.map((cond, idx) =>
const updatedConditions = restoredConditions.map((cond, idx) =>
idx === state.editingConditionIndex ? { ...newCondition, display_order: idx } : cond
)
setUnlockConditions(updatedConditions)
@@ -199,12 +249,10 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
console.log('[WishlistForm] Adding new condition, final conditions:', finalConditions)
setUnlockConditions(finalConditions)
}
setNewTaskConsumed(true)
} else {
setUnlockConditions(restoredConditions)
}
// Устанавливаем флаг, что состояние восстановлено
setRestoredFromSession(true)
}
} catch (err) {
console.error('[WishlistForm] Error reloading tasks:', err)
@@ -324,15 +372,18 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
setToastMessage({ text: 'Введите ссылку', type: 'error' })
return
}
const extracted = extractUrl(link)
setLink(extracted)
// Проверяем валидность URL
try {
new URL(link)
new URL(extracted)
} catch {
setToastMessage({ text: 'Некорректная ссылка', type: 'error' })
return
}
setFetchingMetadata(true)
try {
const response = await authFetch(`${API_URL}/metadata`, {
@@ -340,7 +391,7 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: link.trim() }),
body: JSON.stringify({ url: extracted.trim() }),
})
if (response.ok) {
@@ -442,7 +493,9 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
// Загрузка картинки по ссылке с последующим кропом
const loadImageFromUrl = async () => {
const url = imageUrlInput?.trim()
const extracted = extractUrl(imageUrlInput)
setImageUrlInput(extracted)
const url = extracted?.trim()
if (!url) {
setToastMessage({ text: 'Введите ссылку на картинку', type: 'error' })
return
@@ -543,9 +596,25 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
}
}
const openConditionForm = () => {
setShowConditionForm(true)
conditionClosedByPopStateRef.current = false
window.history.pushState({ conditionForm: true }, '', window.location.href)
}
const closeConditionForm = () => {
setShowConditionForm(false)
setEditingConditionIndex(null)
// Если закрытие через popstate — запись уже убрана, не делаем back
if (!conditionClosedByPopStateRef.current) {
window.history.back()
}
conditionClosedByPopStateRef.current = false
}
const handleAddCondition = () => {
setEditingConditionIndex(null)
setShowConditionForm(true)
openConditionForm()
}
const handleEditCondition = (index) => {
@@ -556,26 +625,24 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
return
}
setEditingConditionIndex(index)
setShowConditionForm(true)
openConditionForm()
}
const handleConditionSubmit = (condition) => {
if (editingConditionIndex !== null) {
// Редактирование существующего условия
setUnlockConditions(prev => prev.map((cond, idx) =>
setUnlockConditions(prev => prev.map((cond, idx) =>
idx === editingConditionIndex ? { ...condition, display_order: idx } : cond
))
} else {
// Добавление нового условия
setUnlockConditions([...unlockConditions, { ...condition, display_order: unlockConditions.length }])
}
setShowConditionForm(false)
setEditingConditionIndex(null)
closeConditionForm()
}
const handleConditionCancel = () => {
setShowConditionForm(false)
setEditingConditionIndex(null)
closeConditionForm()
}
const handleRemoveCondition = (index) => {
@@ -590,6 +657,9 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
// Обработчик для создания задачи из ConditionForm
const handleCreateTaskFromCondition = () => {
// Закрываем диалог цели перед переходом
setShowConditionForm(false)
// Сохранить текущее состояние формы
const stateToSave = {
name,
@@ -602,7 +672,7 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
}
console.log('[WishlistForm] Saving state and navigating to task-form:', stateToSave)
sessionStorage.setItem(WISHLIST_FORM_STATE_KEY, JSON.stringify(stateToSave))
// Навигация на форму создания задачи
const navParams = {
returnTo: 'wishlist-form',
@@ -612,6 +682,77 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
onNavigate?.('task-form', navParams)
}
const openActionMenu = () => {
setShowActionMenu(true)
window.history.pushState({ actionMenu: true }, '')
actionMenuHistoryRef.current = true
}
const closeActionMenu = () => {
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.back()
}
}
// Обработка popstate для закрытия action menu кнопкой назад
useEffect(() => {
const handlePopState = () => {
if (showActionMenu) {
actionMenuHistoryRef.current = false
setShowActionMenu(false)
}
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
}, [showActionMenu])
const handleDelete = async () => {
if (!wishlistId) return
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.go(-2)
} else {
window.history.back()
}
setIsDeleting(true)
try {
const response = await authFetch(`${API_URL}/${wishlistId}`, { method: 'DELETE' })
if (!response.ok) {
throw new Error('Ошибка при удалении')
}
} catch (err) {
console.error('Error deleting wishlist item:', err)
}
}
const handleCopy = async () => {
if (!wishlistId) return
setShowActionMenu(false)
if (actionMenuHistoryRef.current) {
actionMenuHistoryRef.current = false
window.history.go(-2)
} else {
window.history.back()
}
setIsCopying(true)
try {
const response = await authFetch(`${API_URL}/${wishlistId}/copy`, { method: 'POST' })
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(errorText || 'Ошибка при копировании')
}
} catch (err) {
console.error('Error copying wishlist item:', err)
}
}
const handleSubmit = async (e) => {
e.preventDefault()
setError('')
@@ -712,12 +853,8 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
}
resetForm()
// Возвращаемся на доску, если она была указана
if (boardId) {
onNavigate?.('wishlist', { boardId })
} else {
onNavigate?.('wishlist')
}
// Возврат назад по стеку истории
window.history.back()
} catch (err) {
setError(err.message)
} finally {
@@ -731,6 +868,7 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
}
return (
<>
<div className="wishlist-form">
<button className="close-x-button" onClick={handleCancel}>
@@ -746,15 +884,16 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
<>
<h2>{wishlistId ? 'Редактировать желание' : 'Новое желание'}</h2>
<form onSubmit={handleSubmit}>
<form id="wishlist-form-element" onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="link">Ссылка</label>
<div className="link-input-wrapper">
<input
id="link"
type="url"
type="text"
value={link}
onChange={(e) => setLink(e.target.value)}
onBlur={() => setLink(extractUrl(link))}
placeholder="https://..."
className="form-input"
disabled={fetchingMetadata}
@@ -859,9 +998,10 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
<div className="image-url-row">
<span className="image-url-label">Ссылка:</span>
<input
type="url"
type="text"
value={imageUrlInput}
onChange={(e) => setImageUrlInput(e.target.value)}
onBlur={() => setImageUrlInput(extractUrl(imageUrlInput))}
placeholder="https://..."
className="form-input image-url-input"
disabled={loadingImageFromUrl}
@@ -976,11 +1116,6 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
{error && <div className="error-message">{error}</div>}
<div className="form-actions">
<button type="submit" disabled={loading} className="submit-button">
{loading ? 'Сохранение...' : 'Сохранить'}
</button>
</div>
</form>
{showConditionForm && (
@@ -991,7 +1126,7 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
onCancel={handleConditionCancel}
editingCondition={editingConditionIndex !== null ? unlockConditions[editingConditionIndex] : null}
onCreateTask={handleCreateTaskFromCondition}
preselectedTaskId={newTaskId}
preselectedTaskId={newTaskConsumed ? undefined : newTaskId}
authFetch={authFetch}
/>
)}
@@ -1006,6 +1141,93 @@ function WishlistForm({ onNavigate, wishlistId, editConditionIndex, newTaskId, b
</>
)}
</div>
{isActive ? createPortal(
<div style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '2rem 1rem 0.75rem',
paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))',
background: 'linear-gradient(to top, white 70%, rgba(255,255,255,0))',
zIndex: 1500,
display: 'flex',
justifyContent: 'center',
gap: '0.75rem',
}}>
<button
type="submit"
form="wishlist-form-element"
disabled={loading || isDeleting || isCopying}
style={{
flex: 1,
maxWidth: '42rem',
padding: '0.875rem',
background: loading ? undefined : 'linear-gradient(to right, #10b981, #059669)',
backgroundColor: loading ? '#9ca3af' : undefined,
color: 'white',
border: 'none',
borderRadius: '0.5rem',
fontSize: '1rem',
fontWeight: 600,
cursor: (loading || isDeleting || isCopying) ? 'not-allowed' : 'pointer',
opacity: loading ? 0.6 : 1,
transition: 'all 0.2s',
}}
>
{loading ? 'Сохранение...' : 'Сохранить'}
</button>
{wishlistId && (
<button
type="button"
onClick={openActionMenu}
disabled={loading || isDeleting || isCopying}
style={{
width: '52px',
height: '52px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'transparent',
color: '#059669',
border: '2px solid #059669',
borderRadius: '0.5rem',
fontSize: '1.25rem',
fontWeight: 700,
cursor: (loading || isDeleting || isCopying) ? 'not-allowed' : 'pointer',
lineHeight: 1,
flexShrink: 0,
padding: 0,
boxSizing: 'border-box',
transition: 'all 0.2s',
}}
title="Действия"
>
</button>
)}
</div>,
document.body
) : null}
{showActionMenu && createPortal(
<div className="wishlist-modal-overlay" style={{ zIndex: 2000 }} onClick={closeActionMenu}>
<div className="wishlist-modal" onClick={(e) => e.stopPropagation()}>
<div className="wishlist-modal-header">
<h3>{name}</h3>
</div>
<div className="wishlist-modal-actions">
<button className="wishlist-modal-copy" onClick={handleCopy}>
Копировать
</button>
<button className="wishlist-modal-delete" onClick={handleDelete}>
Удалить
</button>
</div>
</div>
</div>,
document.body
)}
</>
)
}
@@ -1500,23 +1722,27 @@ function ConditionForm({ tasks, projects, onSubmit, onCancel, editingCondition,
return (
<div className="condition-form-overlay" onClick={onCancel}>
<div className="condition-form" onClick={(e) => e.stopPropagation()}>
<div className="condition-form-header">
<h3>{isEditing ? 'Редактировать цель' : 'Добавить цель'}</h3>
<button onClick={onCancel} className="condition-form-close-button">
</button>
</div>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label>Тип условия</label>
<select
value={type}
onChange={(e) => setType(e.target.value)}
className="form-input"
>
<option value="project_points">Баллы</option>
<option value="task_completion">Задача</option>
</select>
<div className="condition-tabs-container">
<div className="condition-tabs-inner">
<button
type="button"
className={`condition-tab-button ${type === 'project_points' ? 'active' : ''}`}
onClick={() => setType('project_points')}
>
Баллы
</button>
<button
type="button"
className={`condition-tab-button ${type === 'task_completion' ? 'active' : ''}`}
onClick={() => setType('task_completion')}
>
Задача
</button>
</div>
<button type="button" onClick={onCancel} className="condition-form-close-button condition-tabs-close">
</button>
</div>
{type === 'task_completion' && (
@@ -1577,14 +1803,10 @@ function ConditionForm({ tasks, projects, onSubmit, onCancel, editingCondition,
{isEditing ? 'Сохранить' : 'Добавить'}
</button>
</div>
{type === 'project_points' && (
{type === 'project_points' && calculatedWeeksText && (
<div className="calculated-weeks-info">
{calculatedWeeksText && (
<>
<span>Срок: </span>
<span style={{ fontWeight: '600' }}>{calculatedWeeksText}</span>
</>
)}
<span>Срок: </span>
<span style={{ fontWeight: '600' }}>{calculatedWeeksText}</span>
</div>
)}
</form>

View File

@@ -187,8 +187,8 @@ function WordList({ onNavigate, dictionaryId, isNewDictionary, refreshTrigger =
await fetchDictionary(newDictionaryId)
await fetchWordsForDictionary(newDictionaryId)
// Update navigation to use the new dictionary ID and name
onNavigate?.('words', { dictionaryId: newDictionaryId, dictionaryName: newDict.name })
// Update navigation to use the new dictionary ID and name (replace history entry so back goes to dictionaries)
onNavigate?.('words', { dictionaryId: newDictionaryId, dictionaryName: newDict.name }, { replace: true })
} else if (hasValidDictionary(currentDictionaryId)) {
// Update existing dictionary (rename)
const response = await authFetch(`${API_URL}/dictionaries/${currentDictionaryId}`, {

16
run.sh
View File

@@ -5,6 +5,10 @@
set -e
# Включаем BuildKit для надёжного отслеживания изменений файлов
export DOCKER_BUILDKIT=1
export COMPOSE_DOCKER_CLI_BUILD=1
# Цвета для вывода
RED='\033[0;31m'
GREEN='\033[0;32m'
@@ -42,14 +46,10 @@ if docker-compose ps | grep -q "Up"; then
echo " - Backend сервер (с пересборкой)"
echo " - Frontend приложение (с пересборкой)"
echo " - База данных"
# Пересобираем и перезапускаем веб-приложение
echo -e "${BLUE}Пересборка веб-приложения...${NC}"
docker-compose build --no-cache play-life-web
docker-compose up -d --force-recreate play-life-web
# Пересобираем и перезапускаем бэкенд
echo -e "${BLUE}Пересборка бэкенда...${NC}"
docker-compose build --no-cache backend
docker-compose up -d --force-recreate backend
# Пересобираем без кэша и перезапускаем
echo -e "${BLUE}Пересборка и перезапуск сервисов...${NC}"
docker-compose build --no-cache play-life-web backend
docker-compose up -d --force-recreate play-life-web backend
# Перезапускаем базу данных
docker-compose restart db
echo -e "${GREEN}✅ Контейнеры перезапущены${NC}"